From b383abc5a8fcb4b1058347a9b8383e773dc90cd6 Mon Sep 17 00:00:00 2001 From: Birk Skyum <74932975+birkskyum@users.noreply.github.com> Date: Thu, 27 Apr 2023 21:54:12 +0200 Subject: [PATCH 01/21] Adjust trivial links to maplibre-native (#1083) --- .github/ISSUE_TEMPLATE/config.yml | 2 +- CHANGELOG.md | 16 +-- CONTRIBUTING.md | 6 +- FORK.md | 2 +- README.md | 2 +- .../2022-10-27-rendering-modularization.md | 16 +-- metrics/ignores/platform-linux.json | 2 +- metrics/ignores/platform-macos.json | 2 +- package.json | 4 +- platform/android/CHANGELOG.md | 128 +++++++++--------- platform/android/DEVELOPING.md | 2 +- platform/android/MapboxGLAndroidSDK/README.md | 2 +- platform/android/README.md | 6 +- platform/android/RELEASE.md | 2 +- platform/darwin/README.md | 4 +- platform/ios/CONTRIBUTING.md | 4 +- platform/ios/Makefile | 2 +- .../test/MLNDocumentationGuideTests.swift | 2 +- .../darwin/test/MLNExpressionTests.mm | 30 ++-- .../darwin/test/MLNHeatmapColorTests.mm | 4 +- .../platform/darwin/test/MLNPredicateTests.mm | 4 +- .../darwin/test/MLNStyleLayerTests.mm.ejs | 2 +- platform/ios/platform/ios/CHANGELOG.md | 64 ++++----- platform/ios/platform/ios/CONTRIBUTING.md | 12 +- platform/ios/platform/ios/INSTALL.md | 2 +- platform/ios/platform/ios/README.md | 4 +- platform/ios/platform/ios/docs/pod-README.md | 4 +- platform/ios/platform/ios/jazzy.yml | 2 +- platform/ios/platform/ios/scripts/document.sh | 2 +- platform/ios/platform/ios/scripts/package.sh | 2 +- .../ios/scripts/release-notes-jazzy.md.ejs | 4 +- .../ios/scripts/update-swift-package.sh | 2 +- .../ios/platform/ios/scripts/xcpackage.sh | 2 +- platform/ios/platform/macos/CHANGELOG.md | 18 +-- platform/ios/platform/macos/INSTALL.md | 2 +- platform/ios/platform/macos/README.md | 4 +- platform/linux/README.md | 2 +- platform/node/CHANGELOG.md | 44 +++--- platform/node/README.md | 8 +- platform/qt/CHANGELOG.md | 6 +- platform/qt/README.md | 2 +- platform/windows/README.md | 2 +- test/actor/actor_ref.test.cpp | 2 +- 43 files changed, 217 insertions(+), 217 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 9d3b7328cd1..cd7d8561a41 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,7 +1,7 @@ blank_issues_enabled: true contact_links: - name: "🙏 Q&A - GitHub Discussions" - url: https://github.com/maplibre/maplibre-gl-native/discussions/categories/q-a + url: https://github.com/maplibre/maplibre-native/discussions/categories/q-a about: If you have a question about using MapLibre Native - name: "💬 Chat with us on Slack" url: https://slack.openstreetmap.us/ diff --git a/CHANGELOG.md b/CHANGELOG.md index bdb02f5827b..d8bd7062a44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,15 +5,15 @@ ### ✨ New features - *...Add new stuff here...* -- [windows] Added windows build support for core applications and node [#707](https://github.com/maplibre/maplibre-gl-native/pull/707) -- [core] Add `ClientOptions` to configure client information [#365](https://github.com/maplibre/maplibre-gl-native/pull/365). -- [node] Add workflow to create node binary releases for Ubuntu 20.04 x64 and MacOS 12 x64/arm64 [#378](https://github.com/maplibre/maplibre-gl-native/pull/378), [#459](https://github.com/maplibre/maplibre-gl-native/pull/459). +- [windows] Added windows build support for core applications and node [#707](https://github.com/maplibre/maplibre-native/pull/707) +- [core] Add `ClientOptions` to configure client information [#365](https://github.com/maplibre/maplibre-native/pull/365). +- [node] Add workflow to create node binary releases for Ubuntu 20.04 x64 and MacOS 12 x64/arm64 [#378](https://github.com/maplibre/maplibre-native/pull/378), [#459](https://github.com/maplibre/maplibre-native/pull/459). ### ✨ Technical Improvements - *...Add new stuff here...* -- Bump [maplibre-native-base](https://github.com/maplibre/maplibre-native-base) from 2.0.0 to 2.1.1 ([#397](https://github.com/maplibre/maplibre-gl-native/pull/397), [#406](https://github.com/maplibre/maplibre-gl-native/pull/406)) -- Bump [wagyu](https://github.com/mapbox/wagyu) from 0.4.3 to 0.5.0 [#398](https://github.com/maplibre/maplibre-gl-native/pull/398) +- Bump [maplibre-native-base](https://github.com/maplibre/maplibre-native-base) from 2.0.0 to 2.1.1 ([#397](https://github.com/maplibre/maplibre-native/pull/397), [#406](https://github.com/maplibre/maplibre-native/pull/406)) +- Bump [wagyu](https://github.com/mapbox/wagyu) from 0.4.3 to 0.5.0 [#398](https://github.com/maplibre/maplibre-native/pull/398) - Bump [eternal](https://github.com/mapbox/eternal.git) from 1.0.0 to 1.0.1 - Bump [protozero](https://github.com/mapbox/protozero.git) from 1.7.0 to 1.7.1 - Bump [vector-tile](https://github.com/mapbox/vector-tile.git) from 1.0.3 to 1.0.4 @@ -25,9 +25,9 @@ ### 🐞 Bug fixes - *...Add new stuff here...* -- [core] Fix memory access violation exception in vector_tile_data.cpp [#632](https://github.com/maplibre/maplibre-gl-native/pull/632) -- [iOS] Fix a bug where the compass was determined to be misplaced when hidden [#498](https://github.com/maplibre/maplibre-gl-native/pull/498). -- [core] `MaptilerFileSource` renamed to `MBTilesFileSource` [#198](https://github.com/maplibre/maplibre-gl-native/pull/198). +- [core] Fix memory access violation exception in vector_tile_data.cpp [#632](https://github.com/maplibre/maplibre-native/pull/632) +- [iOS] Fix a bug where the compass was determined to be misplaced when hidden [#498](https://github.com/maplibre/maplibre-native/pull/498). +- [core] `MaptilerFileSource` renamed to `MBTilesFileSource` [#198](https://github.com/maplibre/maplibre-native/pull/198). ## maps-v1.6.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b8577ff5d24..efe31aaa6d4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,13 +2,13 @@ ## Documentation -- For a high-level overview of MapLibre Native, check out the [MapLibre Native Markdown Book](https://maplibre.org/maplibre-gl-native/docs/book/). +- For a high-level overview of MapLibre Native, check out the [MapLibre Native Markdown Book](https://maplibre.org/maplibre-native/docs/book/). - See [`DEVELOPING.md`](DEVELOPING.md) for getting started with development. ## Source code checkout ```bash -git clone --recurse-submodules https://github.com/maplibre/maplibre-gl-native.git +git clone --recurse-submodules https://github.com/maplibre/maplibre-native.git ``` ## Building @@ -31,7 +31,7 @@ If you want to contribute code: 1. Please familiarize yourself with the installation process of your chosen platform. -1. Ensure that existing [pull requests](https://github.com/maplibre/maplibre-gl-native/pulls) and [issues](https://github.com/maplibre/maplibre-gl-native/issues) don’t already cover your contribution or question. +1. Ensure that existing [pull requests](https://github.com/maplibre/maplibre-native/pulls) and [issues](https://github.com/maplibre/maplibre-native/issues) don’t already cover your contribution or question. 1. Pull requests are gladly accepted. If there are any changes that developers using one of the GL SDKs should be aware of, please update the **main** section of the relevant `CHANGELOG.md`. diff --git a/FORK.md b/FORK.md index eff1760444e..7eae33e2487 100644 --- a/FORK.md +++ b/FORK.md @@ -16,4 +16,4 @@ Beside merging in platform specific SDKs, the following changes were made compar We'd like to acknowledge the amazing work Mapbox has contributed to open source. The open source community is sad to part ways with them, but we simultaneously feel grateful for everything they already contributed. We're proud to develop on the shoulders of giants, thank you Mapbox 🙇🏽‍♀️. -Please keep in mind: Unauthorized backports are the biggest threat to the MapLibre project. It is unacceptable to backport code from any Mapbox project with a non-free license. If you are unsure about this issue, [please ask](https://github.com/maplibre/maplibre-gl-native/discussions)! +Please keep in mind: Unauthorized backports are the biggest threat to the MapLibre project. It is unacceptable to backport code from any Mapbox project with a non-free license. If you are unsure about this issue, [please ask](https://github.com/maplibre/maplibre-native/discussions)! diff --git a/README.md b/README.md index 40989db2b95..484c9f4206b 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ To get started with MapLibre Native, go to your platform below. ## Documentation -The documentation of MapLibre Native is a work in progress. To get an architectural overview and to learn about the current state of the project and its path forward read the [MapLibre Native Markdown Book](https://maplibre.org/maplibre-gl-native/docs/book/). See below for platform-specific documentation. +The documentation of MapLibre Native is a work in progress. To get an architectural overview and to learn about the current state of the project and its path forward read the [MapLibre Native Markdown Book](https://maplibre.org/maplibre-native/docs/book/). See below for platform-specific documentation. ## Platforms diff --git a/design-proposals/2022-10-27-rendering-modularization.md b/design-proposals/2022-10-27-rendering-modularization.md index 20867ec0cc8..08b1bdf6b91 100644 --- a/design-proposals/2022-10-27-rendering-modularization.md +++ b/design-proposals/2022-10-27-rendering-modularization.md @@ -53,7 +53,7 @@ It is useful to split our goals into three sections to articulate what this prop 1. Developers should be able to continue using the OpenGL renderer with this refactor. 2. The resulting binary from the modularized refactor should not increase more than 5% when compiled. 3. The modularization refactor should be visually identical to the current implementation when using OpenGL. All existing render tests should pass, and developers that continue to use this library with an OpenGL renderer should not experience any visual degradation such as artifacts. -4. After refactor, the startup time for applications built with this library should not increase. This will be measured by the startup time of [this](https://github.com/maplibre/maplibre-gl-native/blob/main/platform/ios/platform/ios/iosapp%20UITests/iosapp_UITests.swift) iOS test app. +4. After refactor, the startup time for applications built with this library should not increase. This will be measured by the startup time of [this](https://github.com/maplibre/maplibre-native/blob/main/platform/ios/platform/ios/iosapp%20UITests/iosapp_UITests.swift) iOS test app. 5. When implemented with a given style and set of tilesets, the compiled library should not decrease the rendering frame rate. 6. This refactor will not introduce data loading or other bottlenecks that will negatively impact rendering performance. 7. Developers currently using this library will not see any breaking API changes, and will be able to seamlessly upgrade versions. @@ -75,7 +75,7 @@ The shaders need a representation visible outside the toolkit and we need to cha Individual shaders are represented by an object class with massive amounts of template logic and a minimum of in-line comments. They’re opaque from the outside and only controllable through vector tile data and styles. -The [render_raster_layer](https://github.com/maplibre/maplibre-gl-native/blob/main/src/mbgl/renderer/layers/render_raster_layer.cpp), as an example, asks for the instantiation of (eventually) RasterProgram. Rather than having the source for the program, that then pokes into a compressed chunk of memory that contains the source, which is then uncompressed and fed into OpenGL for compilation. +The [render_raster_layer](https://github.com/maplibre/maplibre-native/blob/main/src/mbgl/renderer/layers/render_raster_layer.cpp), as an example, asks for the instantiation of (eventually) RasterProgram. Rather than having the source for the program, that then pokes into a compressed chunk of memory that contains the source, which is then uncompressed and fed into OpenGL for compilation. All of this makes sense in context, but is completely inaccessible outside the toolkit and rather incomprehensible when making changes. @@ -134,9 +134,9 @@ Modern graphics pipelines use more than one pass to create a visual representati Without getting too deep into specifics, early rendering passes allow the developer to use the power of the rasterizer for their own data. Later rendering passes are typically used to decorate the map with effects. #### The way it is now: -The [low level rendering logic](https://github.com/maplibre/maplibre-gl-native/blob/main/src/mbgl/renderer/renderer_impl.cpp) in the toolkit seems to only support one explicit rendering pass. +The [low level rendering logic](https://github.com/maplibre/maplibre-native/blob/main/src/mbgl/renderer/renderer_impl.cpp) in the toolkit seems to only support one explicit rendering pass. -However, there is the [RenderPass](https://github.com/maplibre/maplibre-gl-native/blob/main/src/mbgl/gl/render_pass.hpp) so some notion of this exists in the toolkit, but it's not clear how complete that is. It may depend on ordering to work things out, rather than the explicit command buffer filling and fences we would use in a more modern approach. +However, there is the [RenderPass](https://github.com/maplibre/maplibre-native/blob/main/src/mbgl/gl/render_pass.hpp) so some notion of this exists in the toolkit, but it's not clear how complete that is. It may depend on ordering to work things out, rather than the explicit command buffer filling and fences we would use in a more modern approach. In any case, we need this filled out more explicitly for the render targets. @@ -205,7 +205,7 @@ In WhirlyGlobe we’ve always called out separate objects for drawing certain ki Which is to say that Drawable is a good concept which can encapsulate a lot of complexity. So much so that it eventually encapsulates ALL the complexity, at least at that level of rendering. It’s a good interface between the things that construct geometry and the things that render geometry. -To keep the Drawable somewhat manageable, we added the concept of a Drawable Builder. This is an object that you throw geometry at in a somewhat disordered way and it emits Drawables when you’re done. MapLibre's [Buckets](https://github.com/maplibre/maplibre-gl-native/blob/main/src/mbgl/renderer/bucket.hpp) are similar, but not quite the same. Perhaps they'll be adaptable. We'll see. +To keep the Drawable somewhat manageable, we added the concept of a Drawable Builder. This is an object that you throw geometry at in a somewhat disordered way and it emits Drawables when you’re done. MapLibre's [Buckets](https://github.com/maplibre/maplibre-native/blob/main/src/mbgl/renderer/bucket.hpp) are similar, but not quite the same. Perhaps they'll be adaptable. We'll see. Drawables and Builders have a subclass for each supported rendering SDK. One mistake we won’t bring over is using multiple inheritance for that. You’re welcome. @@ -221,7 +221,7 @@ Builders will be used primarily by Layers to emit Drawables for rendering. This is a big topic because it gets to the very heart of the critical changes we want to make to the toolkit. There are a couple of different categories that are revealing and we'll use some examples. -Most commonly there are *render layers*. These are individual classes that know how to render, for instance, the [fill layer](https://github.com/maplibre/maplibre-gl-native/blob/main/src/mbgl/renderer/layers/render_fill_layer.cpp). You'll see a bunch of these that start with "render" and end with "layer". +Most commonly there are *render layers*. These are individual classes that know how to render, for instance, the [fill layer](https://github.com/maplibre/maplibre-native/blob/main/src/mbgl/renderer/layers/render_fill_layer.cpp). You'll see a bunch of these that start with "render" and end with "layer". What's going on here is that the toolkit has broken out a bunch of features from a tile, consolidated them together in a Bucket and then handed them off to a Layer to render. Sure enough, if you look in the render_*_layer you can see it doing just that. @@ -230,7 +230,7 @@ Now it's not redoing the work of consolidation each frame, but it is doing a lot - This is more specific logic than we'd want to see in a rendering loop. Remember, this runs every frame. - If your data is not in tile form, it's going to be hard to render. -That last one is really interesting and we can find an example in MapLibre Native itself. Look to the [Render Location Indicator Layer](https://github.com/maplibre/maplibre-gl-native/blob/main/src/mbgl/renderer/layers/render_location_indicator_layer.cpp). Here's where this approach trips up... rolls down the hill... into a pile of broken glass. You can feel the developers' pain in this module. +That last one is really interesting and we can find an example in MapLibre Native itself. Look to the [Render Location Indicator Layer](https://github.com/maplibre/maplibre-native/blob/main/src/mbgl/renderer/layers/render_location_indicator_layer.cpp). Here's where this approach trips up... rolls down the hill... into a pile of broken glass. You can feel the developers' pain in this module. If you're not familiar with real time rendering toolkits, I'll put it this way. Managing the logic for a location puck that updates every time the user moves should not involve direct OpenGL calls. It should be abstracted, at least a little. @@ -319,7 +319,7 @@ Every real time rendering toolkit has a main rendering loop or something like it On iOS this runs on the main thread and on Android this runs on its own separate thread. You might think the latter is better, but it has its own problems (gesture lag). In any case, MapLibre Native handles both just fine. -The toolkit's main rendering "loop" lives in [renderer_impl](https://github.com/maplibre/maplibre-gl-native/blob/main/src/mbgl/renderer/renderer_impl.cpp) and it's worth a look. It serves as a central point to begin examining the real time rendering. +The toolkit's main rendering "loop" lives in [renderer_impl](https://github.com/maplibre/maplibre-native/blob/main/src/mbgl/renderer/renderer_impl.cpp) and it's worth a look. It serves as a central point to begin examining the real time rendering. As you might suspect, the rendering loop logic and implementation are heavily influenced by OpenGL. diff --git a/metrics/ignores/platform-linux.json b/metrics/ignores/platform-linux.json index de5bf88d9b5..613d87c6c13 100644 --- a/metrics/ignores/platform-linux.json +++ b/metrics/ignores/platform-linux.json @@ -1,5 +1,5 @@ { - "render-tests/icon-text-fit/enlargen-both": "Not working for unknown reason: https://github.com/maplibre/maplibre-gl-native/issues/355", + "render-tests/icon-text-fit/enlargen-both": "Not working for unknown reason: https://github.com/maplibre/maplibre-native/issues/355", "render-tests/fill-opacity/zoom-and-property-function-pattern": "Flaky on Linux: https://github.com/mapbox/mapbox-gl-native/issues/15322", "render-tests/fill-pattern/literal": "Flaky on Linux: https://github.com/mapbox/mapbox-gl-native/issues/14423", "render-tests/fill-pattern/opacity": "Flaky on Linux: https://github.com/mapbox/mapbox-gl-native/issues/14870", diff --git a/metrics/ignores/platform-macos.json b/metrics/ignores/platform-macos.json index 8c1bd921e9f..4dd90d8bd32 100644 --- a/metrics/ignores/platform-macos.json +++ b/metrics/ignores/platform-macos.json @@ -1,5 +1,5 @@ { - "render-tests/icon-image/icon-sdf-non-sdf-one-layer": "Failing on GitHub runner for unknown reason https://github.com/maplibre/maplibre-gl-native/issues/377", + "render-tests/icon-image/icon-sdf-non-sdf-one-layer": "Failing on GitHub runner for unknown reason https://github.com/maplibre/maplibre-native/issues/377", "render-tests/regressions/mapbox-gl-js#5642": "Failing with mbgl-render-test", "render-tests/regressions/mapbox-gl-js#7066": "Failing with mbgl-render-test" } diff --git a/package.json b/package.json index 096ff723bd6..98ff0794147 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "types": "platform/node/index.d.ts", "repository": { "type": "git", - "url": "git+https://github.com/maplibre/maplibre-gl-native.git" + "url": "git+https://github.com/maplibre/maplibre-native.git" }, "license": "BSD-2-Clause", "dependencies": { @@ -69,7 +69,7 @@ "binary": { "module_name": "mbgl", "module_path": "./lib/{node_abi}", - "host": "https://github.com/maplibre/maplibre-gl-native/releases/download/", + "host": "https://github.com/maplibre/maplibre-native/releases/download/", "remote_path": "node-v{version}", "package_name": "{node_abi}-{platform}-{arch}-{configuration}.tar.gz" } diff --git a/platform/android/CHANGELOG.md b/platform/android/CHANGELOG.md index 36ba53ead49..c84fb54d3d5 100644 --- a/platform/android/CHANGELOG.md +++ b/platform/android/CHANGELOG.md @@ -1,16 +1,16 @@ # Changelog for the MapLibre Maps SDK for Android -MapLibre welcomes participation and contributions from everyone. Please read [`Contributing Guide`](https://github.com/maplibre/maplibre-gl-native/blob/main/CONTRIBUTING.md) to get started. +MapLibre welcomes participation and contributions from everyone. Please read [`Contributing Guide`](https://github.com/maplibre/maplibre-native/blob/main/CONTRIBUTING.md) to get started. ## main ### ✨ Features and improvements -* Change to a more natural fling animation and allow setting `flingThreshold` and `flingAnimationBaseTime` in `UiSettings` ([#963](https://github.com/maplibre/maplibre-gl-native/pull/963)) +* Change to a more natural fling animation and allow setting `flingThreshold` and `flingAnimationBaseTime` in `UiSettings` ([#963](https://github.com/maplibre/maplibre-native/pull/963)) ### 🐞 Bug fixes -* Fix regression in CameraUpdateFactory#zoomOut ([#1035](https://github.com/maplibre/maplibre-gl-native/pull/1035)) +* Fix regression in CameraUpdateFactory#zoomOut ([#1035](https://github.com/maplibre/maplibre-native/pull/1035)) ### ⛵ Dependencies @@ -18,20 +18,20 @@ MapLibre welcomes participation and contributions from everyone. Please read [`C ### 🐞 Bug fixes -* `MapboxFusedLocationEngineImpl` constructor made public to create custom `LocationEngineProvider`([#850](https://github.com/maplibre/maplibre-gl-native/pull/850)) +* `MapboxFusedLocationEngineImpl` constructor made public to create custom `LocationEngineProvider`([#850](https://github.com/maplibre/maplibre-native/pull/850)) ## 10.0.1 - February 22, 2023 ### 🐞 Bug fixes -* Fixed regression with `RasterSource` native code throwing an exception expecting bound after switching to `FloatArray` ([#830](https://github.com/maplibre/maplibre-gl-native/pull/830)). -* `LocationEngineProxy` was made public so that the migration path suggested in the 10.0.0 changelog for those wanting to use GMS Location Services can actually be implemented ([#832](https://github.com/maplibre/maplibre-gl-native/pull/830)). +* Fixed regression with `RasterSource` native code throwing an exception expecting bound after switching to `FloatArray` ([#830](https://github.com/maplibre/maplibre-native/pull/830)). +* `LocationEngineProxy` was made public so that the migration path suggested in the 10.0.0 changelog for those wanting to use GMS Location Services can actually be implemented ([#832](https://github.com/maplibre/maplibre-native/pull/830)). ## 10.0.0 - February 15, 2023 ### ✨ Features and improvements -* 💥 Breaking: Changed resourcePrefix to `maplibre_` from `mapbox_` ([#647](https://github.com/maplibre/maplibre-gl-native/pull/647)) and renamed resources accordingly. Note that this is a breaking change since the names of public resources were renamed as well. Replaced Mapbox logo with MapLibre logo. +* 💥 Breaking: Changed resourcePrefix to `maplibre_` from `mapbox_` ([#647](https://github.com/maplibre/maplibre-native/pull/647)) and renamed resources accordingly. Note that this is a breaking change since the names of public resources were renamed as well. Replaced Mapbox logo with MapLibre logo. > To migrate: > If you use any of the public Android resources, you will get an error that they can not be found. Replace the prefix of each, e.g. `R.style.mapbox_LocationComponent` -> `R.style.maplibre_LocationComponent`. @@ -48,12 +48,12 @@ MapLibre welcomes participation and contributions from everyone. Please read [`C > locationComponent.activateLocationComponent(options) > ``` -* 💥 Breaking: the `LocationEngine` implemented with Google Location Services has been removed to make MapLibre Native for Android fully FLOSS ([#379](https://github.com/maplibre/maplibre-gl-native/issues/379)). +* 💥 Breaking: the `LocationEngine` implemented with Google Location Services has been removed to make MapLibre Native for Android fully FLOSS ([#379](https://github.com/maplibre/maplibre-native/issues/379)). > To migrate: - > Include the source code of the removed [`GoogleLocationEngineImpl`](https://github.com/maplibre/maplibre-gl-native/blob/4a34caab7593f4f1b6d8c09c06a5e25d7c6cfc43/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/engine/GoogleLocationEngineImpl.java) in your source tree. + > Include the source code of the removed [`GoogleLocationEngineImpl`](https://github.com/maplibre/maplibre-native/blob/4a34caab7593f4f1b6d8c09c06a5e25d7c6cfc43/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/engine/GoogleLocationEngineImpl.java) in your source tree. > - > Pass an instance of `LocationEngine` based on `GoogleLocationEngineImpl` to `LocationComponentActivationOptions.Builder.locationEngine` (this was done in a now removed [`LocationEngineProvider`](https://github.com/maplibre/maplibre-gl-native/blob/68d58d6f6f453d5c6cc0fa92fcc6c6cfe0cf967f/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/engine/LocationEngineProvider.java#L59) class): + > Pass an instance of `LocationEngine` based on `GoogleLocationEngineImpl` to `LocationComponentActivationOptions.Builder.locationEngine` (this was done in a now removed [`LocationEngineProvider`](https://github.com/maplibre/maplibre-native/blob/68d58d6f6f453d5c6cc0fa92fcc6c6cfe0cf967f/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/engine/LocationEngineProvider.java#L59) class): > ```kotlin > val locationEngine = LocationEngineProxy(GoogleLocationEngineImpl(context)) > val options = LocationComponentActivationOptions.builder(context, style).locationEngine(locationEngine).build() @@ -62,95 +62,95 @@ MapLibre welcomes participation and contributions from everyone. Please read [`C * 💥 Breaking: The static `LocationEngineResult.extractResult` can no longer extract a `LocationEngineResult` from a Google Play intent. - > To migrate, include and use the [previous implementation](https://github.com/maplibre/maplibre-gl-native/blob/ea234edf67bb3aec75f077e15c1c30c99756b926/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/engine/LocationEngineResult.java#L97) in your source tree. + > To migrate, include and use the [previous implementation](https://github.com/maplibre/maplibre-native/blob/ea234edf67bb3aec75f077e15c1c30c99756b926/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/engine/LocationEngineResult.java#L97) in your source tree. -* Improve Kotlinification of LatLng ([#742](https://github.com/maplibre/maplibre-gl-native/issues)) -* Increment minSdkVersion from 14 to 21, as it covers 99.2%% of the newer devices since 2014 and lessens the backward compatibility burden ([#630](https://github.com/maplibre/maplibre-gl-native/pull/630)) +* Improve Kotlinification of LatLng ([#742](https://github.com/maplibre/maplibre-native/issues)) +* Increment minSdkVersion from 14 to 21, as it covers 99.2%% of the newer devices since 2014 and lessens the backward compatibility burden ([#630](https://github.com/maplibre/maplibre-native/pull/630)) ### 🐞 Bug fixes -* Catches NaN for onMove event ([621](https://github.com/maplibre/maplibre-gl-native/pull/621)) -* `BitmapUtils.mergeBitmap` was deprecated, `BitmapUtils.mergeBitmaps` is a new method that does not offset views rendered on top of snapshots ([#733](https://github.com/maplibre/maplibre-gl-native/issues/733)) -* Fixed a crash when native code was accessing the LatLngBounds class [#655](https://github.com/maplibre/maplibre-gl-native/pull/) +* Catches NaN for onMove event ([621](https://github.com/maplibre/maplibre-native/pull/621)) +* `BitmapUtils.mergeBitmap` was deprecated, `BitmapUtils.mergeBitmaps` is a new method that does not offset views rendered on top of snapshots ([#733](https://github.com/maplibre/maplibre-native/issues/733)) +* Fixed a crash when native code was accessing the LatLngBounds class [#655](https://github.com/maplibre/maplibre-native/pull/) ### ⛵ Dependencies -* Revert "Revert "Gradle update"" - Update Gradle from v3 to v7 ([#619](https://github.com/maplibre/maplibre-gl-native/pull/619)) +* Revert "Revert "Gradle update"" - Update Gradle from v3 to v7 ([#619](https://github.com/maplibre/maplibre-native/pull/619)) ## 9.6.0 - December 18, 2022 ### ✨ Features and improvements -* Add missing header guards ([#543](https://github.com/maplibre/maplibre-gl-native/pull/543)) -* Removing unused versions sdk ([#515](https://github.com/maplibre/maplibre-gl-native/pull/515)) -* (tag: node-v5.0.1-pre.0) Upgrade libs and remove Jetifier ([#218](https://github.com/maplibre/maplibre-gl-native/pull/218)) -* Migrate examples in android TestApp to Kotlin ([#416](https://github.com/maplibre/maplibre-gl-native/pull/416)) -* Add ClientOptions to be able to pass around client name and version ([#365](https://github.com/maplibre/maplibre-gl-native/pull/365)) -* Use maplibre docs for more links ([#354](https://github.com/maplibre/maplibre-gl-native/pull/354)) -* Use the MapLibre style spec docs website ([#353](https://github.com/maplibre/maplibre-gl-native/pull/353)) -* Refresh iOS & Android build docs ([5f679b55b](https://github.com/maplibre/maplibre-gl-native/commit/5f679b55b)) -* Qt build improvements and documentation ([#277](https://github.com/maplibre/maplibre-gl-native/pull/277)) -* Replace Mapbox with MapLibre in README titles ([#297](https://github.com/maplibre/maplibre-gl-native/pull/297)) -* Rename MaptilerFileSource to MBTilesFileSource ([#198](https://github.com/maplibre/maplibre-gl-native/pull/198)) -* Changed missed MapBox reference to MapLibre ([#253](https://github.com/maplibre/maplibre-gl-native/pull/253)) -* Implement map projection functionality ([#254](https://github.com/maplibre/maplibre-gl-native/pull/254)) -* chore: rename master -> main in CI and scripts ([#246](https://github.com/maplibre/maplibre-gl-native/pull/246)) -* Feature - Bring back node support ([#217](https://github.com/maplibre/maplibre-gl-native/pull/217)) -* Remove obsolete CI configurations ([#219](https://github.com/maplibre/maplibre-gl-native/pull/219)) +* Add missing header guards ([#543](https://github.com/maplibre/maplibre-native/pull/543)) +* Removing unused versions sdk ([#515](https://github.com/maplibre/maplibre-native/pull/515)) +* (tag: node-v5.0.1-pre.0) Upgrade libs and remove Jetifier ([#218](https://github.com/maplibre/maplibre-native/pull/218)) +* Migrate examples in android TestApp to Kotlin ([#416](https://github.com/maplibre/maplibre-native/pull/416)) +* Add ClientOptions to be able to pass around client name and version ([#365](https://github.com/maplibre/maplibre-native/pull/365)) +* Use maplibre docs for more links ([#354](https://github.com/maplibre/maplibre-native/pull/354)) +* Use the MapLibre style spec docs website ([#353](https://github.com/maplibre/maplibre-native/pull/353)) +* Refresh iOS & Android build docs ([5f679b55b](https://github.com/maplibre/maplibre-native/commit/5f679b55b)) +* Qt build improvements and documentation ([#277](https://github.com/maplibre/maplibre-native/pull/277)) +* Replace Mapbox with MapLibre in README titles ([#297](https://github.com/maplibre/maplibre-native/pull/297)) +* Rename MaptilerFileSource to MBTilesFileSource ([#198](https://github.com/maplibre/maplibre-native/pull/198)) +* Changed missed MapBox reference to MapLibre ([#253](https://github.com/maplibre/maplibre-native/pull/253)) +* Implement map projection functionality ([#254](https://github.com/maplibre/maplibre-native/pull/254)) +* chore: rename master -> main in CI and scripts ([#246](https://github.com/maplibre/maplibre-native/pull/246)) +* Feature - Bring back node support ([#217](https://github.com/maplibre/maplibre-native/pull/217)) +* Remove obsolete CI configurations ([#219](https://github.com/maplibre/maplibre-native/pull/219)) ### 🐞 Bug fixes -* Fixes potential NaN when calling `NativeMapView::nativeMoveBy` ([#501](https://github.com/maplibre/maplibre-gl-native/pull/501)) -* Fix android ci workflows ([#476](https://github.com/maplibre/maplibre-gl-native/pull/476)) -* Fix typo in geo.cpp ([#412](https://github.com/maplibre/maplibre-gl-native/pull/412)) -* Fix render tests ([#351](https://github.com/maplibre/maplibre-gl-native/pull/351)) -* fix shiftY calculation typo ([#285](https://github.com/maplibre/maplibre-gl-native/pull/285)) -* [msvc] Fix warnings, mainly casting to smaller types ([#270](https://github.com/maplibre/maplibre-gl-native/pull/270)) -* Fix street label appearance while animating near zoom level threshhold ([#267](https://github.com/maplibre/maplibre-gl-native/pull/267)) +* Fixes potential NaN when calling `NativeMapView::nativeMoveBy` ([#501](https://github.com/maplibre/maplibre-native/pull/501)) +* Fix android ci workflows ([#476](https://github.com/maplibre/maplibre-native/pull/476)) +* Fix typo in geo.cpp ([#412](https://github.com/maplibre/maplibre-native/pull/412)) +* Fix render tests ([#351](https://github.com/maplibre/maplibre-native/pull/351)) +* fix shiftY calculation typo ([#285](https://github.com/maplibre/maplibre-native/pull/285)) +* [msvc] Fix warnings, mainly casting to smaller types ([#270](https://github.com/maplibre/maplibre-native/pull/270)) +* Fix street label appearance while animating near zoom level threshhold ([#267](https://github.com/maplibre/maplibre-native/pull/267)) ### ⛵ Dependencies -* Bump semver from 7.3.7 to 7.3.8 in /platform/android ([#530](https://github.com/maplibre/maplibre-gl-native/pull/530)) -* Bump to JDK 11 in android CI and generate Gradle Wrapper ([#474](https://github.com/maplibre/maplibre-gl-native/pull/474)) -* Bump ejs from 3.1.7 to 3.1.8 in /platform/android ([#470](https://github.com/maplibre/maplibre-gl-native/pull/470)) -* Upgrade Gradle from 3.6.3 to 3.6.4 ([#456](https://github.com/maplibre/maplibre-gl-native/pull/456)) -* Bump semver from 5.7.1 to 7.3.7 in /platform/android ([#461](https://github.com/maplibre/maplibre-gl-native/pull/461)) -* Bump pixelmatch from 4.0.2 to 5.3.0 in /platform/android ([#460](https://github.com/maplibre/maplibre-gl-native/pull/460)) -* Bump esm from 3.1.0 to 3.2.25 in /platform/android ([#463](https://github.com/maplibre/maplibre-gl-native/pull/463)) -* Bump ejs from 2.7.4 to 3.1.7 in /platform/android ([#299](https://github.com/maplibre/maplibre-gl-native/pull/299)) -* Bump lodash from 4.17.19 to 4.17.21 in /platform/android ([#195](https://github.com/maplibre/maplibre-gl-native/pull/195)) +* Bump semver from 7.3.7 to 7.3.8 in /platform/android ([#530](https://github.com/maplibre/maplibre-native/pull/530)) +* Bump to JDK 11 in android CI and generate Gradle Wrapper ([#474](https://github.com/maplibre/maplibre-native/pull/474)) +* Bump ejs from 3.1.7 to 3.1.8 in /platform/android ([#470](https://github.com/maplibre/maplibre-native/pull/470)) +* Upgrade Gradle from 3.6.3 to 3.6.4 ([#456](https://github.com/maplibre/maplibre-native/pull/456)) +* Bump semver from 5.7.1 to 7.3.7 in /platform/android ([#461](https://github.com/maplibre/maplibre-native/pull/461)) +* Bump pixelmatch from 4.0.2 to 5.3.0 in /platform/android ([#460](https://github.com/maplibre/maplibre-native/pull/460)) +* Bump esm from 3.1.0 to 3.2.25 in /platform/android ([#463](https://github.com/maplibre/maplibre-native/pull/463)) +* Bump ejs from 2.7.4 to 3.1.7 in /platform/android ([#299](https://github.com/maplibre/maplibre-native/pull/299)) +* Bump lodash from 4.17.19 to 4.17.21 in /platform/android ([#195](https://github.com/maplibre/maplibre-native/pull/195)) ## 9.5.2 - December 02, 2021 ### Bug Fixes -* raster layers stopped working in Android [#161](https://github.com/maplibre/maplibre-gl-native/pull/161) -* remove Mapbox's in favor of MapLibre in attribution dialog [#160](https://github.com/maplibre/maplibre-gl-native/pull/160) -* queryRenderedFeatures returns wrong results - issue #184, [#147](https://github.com/maplibre/maplibre-gl-native/pull/174) +* raster layers stopped working in Android [#161](https://github.com/maplibre/maplibre-native/pull/161) +* remove Mapbox's in favor of MapLibre in attribution dialog [#160](https://github.com/maplibre/maplibre-native/pull/160) +* queryRenderedFeatures returns wrong results - issue #184, [#147](https://github.com/maplibre/maplibre-native/pull/174) ## 9.5.1 - September 06, 2021 ### Bug Fixes -* Invalid tile url template for MapLibre style [#107](https://github.com/maplibre/maplibre-gl-native/pull/107) -* Crash when inflating view on Android [#130](https://github.com/maplibre/maplibre-gl-native/pull/130) +* Invalid tile url template for MapLibre style [#107](https://github.com/maplibre/maplibre-native/pull/107) +* Crash when inflating view on Android [#130](https://github.com/maplibre/maplibre-native/pull/130) ### Other -* Fix perf regression in cached tiles of tile pyramid [#129](https://github.com/maplibre/maplibre-gl-native/pull/129) -* Upgrade to newest protozero [#148](https://github.com/maplibre/maplibre-gl-native/pull/148) -* Change NativeMapView.resizeView to use 0 instead of throwing IllegalArgumentException [#151](https://github.com/maplibre/maplibre-gl-native/pull/151) +* Fix perf regression in cached tiles of tile pyramid [#129](https://github.com/maplibre/maplibre-native/pull/129) +* Upgrade to newest protozero [#148](https://github.com/maplibre/maplibre-native/pull/148) +* Change NativeMapView.resizeView to use 0 instead of throwing IllegalArgumentException [#151](https://github.com/maplibre/maplibre-native/pull/151) ## 9.5.0 - June 29, 2021 ### Features -* Replacing hardcoded configuration with configurable API and removing Mapbox assets and dependencies [#90](https://github.com/maplibre/maplibre-gl-native/pull/90) +* Replacing hardcoded configuration with configurable API and removing Mapbox assets and dependencies [#90](https://github.com/maplibre/maplibre-native/pull/90) ### Other -* Migration from bintray [#77](https://github.com/maplibre/maplibre-gl-native/pull/77) +* Migration from bintray [#77](https://github.com/maplibre/maplibre-native/pull/77) ## 9.4.2 - May 6, 2021 @@ -162,17 +162,17 @@ Switching from mapbox-java libraries to [maplibre fork](https://github.com/mapli ### Bug Fixes -* Fixed an issue where symbols flickered when zooming out. [#16](https://github.com/maplibre/maplibre-gl-native/issues/16) +* Fixed an issue where symbols flickered when zooming out. [#16](https://github.com/maplibre/maplibre-native/issues/16) * Fixes crash caused by NullPointerException MapKeyListener [#464](https://github.com/mapbox/mapbox-gl-native-android/issues/464), cherry picked from [#466](https://github.com/mapbox/mapbox-gl-native-android/pull/466) * Fixed an issue where GPS puck keeps previous value when enabled. [#462]https://github.com/mapbox/mapbox-gl-native-android/issues/462, cherry picked from [#470](https://github.com/mapbox/mapbox-gl-native-android/pull/470) -* Not changing location camera mode while disabled. [#24](https://github.com/maplibre/maplibre-gl-native/issues/24) -* Symbol layer flickering after zooming out. [#16](https://github.com/maplibre/maplibre-gl-native/issues/16) -* Avoid throwing null pointer exception on slow initialization [#22](https://github.com/maplibre/maplibre-gl-native/issues/22) +* Not changing location camera mode while disabled. [#24](https://github.com/maplibre/maplibre-native/issues/24) +* Symbol layer flickering after zooming out. [#16](https://github.com/maplibre/maplibre-native/issues/16) +* Avoid throwing null pointer exception on slow initialization [#22](https://github.com/maplibre/maplibre-native/issues/22) ### Other * mapbox-gl-js submodule has been replaced with maplibre-gl-js -* Removed Telemetry [#7](https://github.com/maplibre/maplibre-gl-native/pull/7) +* Removed Telemetry [#7](https://github.com/maplibre/maplibre-native/pull/7) ## 9.3.0 - January 6, 2021 diff --git a/platform/android/DEVELOPING.md b/platform/android/DEVELOPING.md index 7bd056d8be4..b49abc357b6 100644 --- a/platform/android/DEVELOPING.md +++ b/platform/android/DEVELOPING.md @@ -65,7 +65,7 @@ final draft of the C++14 standard. More information in [DEVELOPING.md](../../DEV * node * `JAVA_HOME="/Applications/Android Studio.app/Contents/jre/Contents/Home"` * `ANDROID_SDK_ROOT=~/Library/Android/sdk` - * In Android Studio, go to Tools > [SDK Manager](https://developer.android.com/studio/projects/install-ndk#specific-version) to install CMake and the specific NDK version specified in [`dependencies.gradle`](https://github.com/maplibre/maplibre-gl-native/blob/main/platform/android/gradle/dependencies.gradle). + * In Android Studio, go to Tools > [SDK Manager](https://developer.android.com/studio/projects/install-ndk#specific-version) to install CMake and the specific NDK version specified in [`dependencies.gradle`](https://github.com/maplibre/maplibre-native/blob/main/platform/android/gradle/dependencies.gradle). Open `platform/android` with Android Studio. diff --git a/platform/android/MapboxGLAndroidSDK/README.md b/platform/android/MapboxGLAndroidSDK/README.md index 70b2f96183f..9fb68f1f78c 100644 --- a/platform/android/MapboxGLAndroidSDK/README.md +++ b/platform/android/MapboxGLAndroidSDK/README.md @@ -2,4 +2,4 @@ This is the MapLibre Native API for Android doccumentation. -Visit [https://maplibre.org/maplibre-gl-native/docs/book/android/getting-started-guide.html](https://maplibre.org/maplibre-gl-native/docs/book/android/getting-started-guide.html) to view the Getting Started Guide for MapLibre Native for Android. \ No newline at end of file +Visit [https://maplibre.org/maplibre-native/docs/book/android/getting-started-guide.html](https://maplibre.org/maplibre-native/docs/book/android/getting-started-guide.html) to view the Getting Started Guide for MapLibre Native for Android. \ No newline at end of file diff --git a/platform/android/README.md b/platform/android/README.md index 25d4c4c4956..49e45809647 100644 --- a/platform/android/README.md +++ b/platform/android/README.md @@ -1,16 +1,16 @@ # MapLibre Native for Android -[![GitHub Action build status](https://github.com/maplibre/maplibre-gl-native/workflows/android-ci/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/android-ci.yml) [![GitHub Action build status](https://github.com/maplibre/maplibre-gl-native/workflows/android-release/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/android-release.yml) +[![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/android-ci/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/android-ci.yml) [![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/android-release/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/android-release.yml) MapLibre Native for Android is a library for embedding interactive map views with scalable, customizable vector maps onto Android devices. ## Getting Started -Visit [https://maplibre.org/maplibre-gl-native/docs/book/android/getting-started-guide.html](https://maplibre.org/maplibre-gl-native/docs/book/android/getting-started-guide.html) to view the Getting Started Guide for MapLibre Native for Android. +Visit [https://maplibre.org/maplibre-native/docs/book/android/getting-started-guide.html](https://maplibre.org/maplibre-native/docs/book/android/getting-started-guide.html) to view the Getting Started Guide for MapLibre Native for Android. ## Documentation -Visit [https://maplibre.org/maplibre-gl-native/android/api/](https://maplibre.org/maplibre-gl-native/android/api/) to view the current API reference Javadoc files for MapLibre Native for Android. +Visit [https://maplibre.org/maplibre-native/android/api/](https://maplibre.org/maplibre-native/android/api/) to view the current API reference Javadoc files for MapLibre Native for Android. ## Contributing diff --git a/platform/android/RELEASE.md b/platform/android/RELEASE.md index 7c519231aac..46fa193d067 100644 --- a/platform/android/RELEASE.md +++ b/platform/android/RELEASE.md @@ -14,6 +14,6 @@ To make an Android release, do the following: * You need write access to push the tag, e.g. `git push --atomic origin main android-v9.6.0` * Once the tag is pushed, you can run the `release-android.yml` workflow - * Go to https://github.com/maplibre/maplibre-gl-native/actions + * Go to https://github.com/maplibre/maplibre-native/actions * Press `android-release` * Press `Run workflow` from the tag you pushed diff --git a/platform/darwin/README.md b/platform/darwin/README.md index e3253d6f923..20ace3780a8 100644 --- a/platform/darwin/README.md +++ b/platform/darwin/README.md @@ -3,8 +3,8 @@ The code in the Darwin platform targets Apple platforms but is not specific to iOS or macOS. This code is not distributed as an SDK in itself, but is required by iOS and macOS builds of MapLibre Native and ultimately by the -[MapLibre Maps SDK for iOS](https://github.com/maplibre/maplibre-gl-native/tree/main/platform/ios) -and [MapLibre Maps SDK for macOS](https://github.com/maplibre/maplibre-gl-native/tree/main/platform/macos). +[MapLibre Maps SDK for iOS](https://github.com/maplibre/maplibre-native/tree/main/platform/ios) +and [MapLibre Maps SDK for macOS](https://github.com/maplibre/maplibre-native/tree/main/platform/macos). These files depend on the Foundation and Core Foundation frameworks but do not depend on iOS- or macOS–specific frameworks, such as UIKit or AppKit. Any diff --git a/platform/ios/CONTRIBUTING.md b/platform/ios/CONTRIBUTING.md index bf8a40d6cdc..bd75a222cb1 100644 --- a/platform/ios/CONTRIBUTING.md +++ b/platform/ios/CONTRIBUTING.md @@ -1,12 +1,12 @@ # Contributing -If you have a usage question for a product built on MapLibre Native (such as our iOS or Android SDKs), please create a discussion thread on [GitHub Discussions](https://github.com/maplibre/maplibre-gl-native/discussions/categories/q-a). +If you have a usage question for a product built on MapLibre Native (such as our iOS or Android SDKs), please create a discussion thread on [GitHub Discussions](https://github.com/maplibre/maplibre-native/discussions/categories/q-a). If you want to contribute code: 1. Please familiarize yourself with the [install process](./INSTALL.md). -1. Ensure that existing [pull requests](https://github.com/maplibre/maplibre-gl-native/pulls?q=is%3Aopen+is%3Apr+label%3AiOS) and [issues](https://github.com/maplibre/maplibre-gl-native/issues?q=is%3Aopen+is%3Aissue+label%3AiOS) don’t already cover your contribution or question. +1. Ensure that existing [pull requests](https://github.com/maplibre/maplibre-native/pulls?q=is%3Aopen+is%3Apr+label%3AiOS) and [issues](https://github.com/maplibre/maplibre-native/issues?q=is%3Aopen+is%3Aissue+label%3AiOS) don’t already cover your contribution or question. 2. Pull requests are gladly accepted. If there are any changes that developers using one of the GL SDKs should be aware of, please update the **main** section of the [iOS changelog](platform/ios/CHANGELOG.md) or [macOS changelog](platform/macos/CHANGELOG.md). diff --git a/platform/ios/Makefile b/platform/ios/Makefile index faf9b590e11..5b54b84697c 100644 --- a/platform/ios/Makefile +++ b/platform/ios/Makefile @@ -7,7 +7,7 @@ export DEV_TEAM ?= "" # When only the dependencies in the package.json are installed # Node.js will error when running a script from the root scripts directory # Getting rid of the duplicate package.json file is an open issue -# https://github.com/maplibre/maplibre-gl-native/issues/657 +# https://github.com/maplibre/maplibre-native/issues/657 export NODE_PATH = ../../node_modules diff --git a/platform/ios/platform/darwin/test/MLNDocumentationGuideTests.swift b/platform/ios/platform/darwin/test/MLNDocumentationGuideTests.swift index 47b29c52e7e..d475546ad09 100644 --- a/platform/ios/platform/darwin/test/MLNDocumentationGuideTests.swift +++ b/platform/ios/platform/darwin/test/MLNDocumentationGuideTests.swift @@ -263,7 +263,7 @@ class MLNDocumentationGuideTests: XCTestCase, MLNMapViewDelegate { let yellow = NSExpression(forConstantValue: UIColor.yellow) - XCTExpectFailure("Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331") + XCTExpectFailure("Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331") layer.circleColor = NSExpression(forMLNMatchingKey: type, in: [earthquake:orange, explosion:red, quarryBlast:yellow], default: defaultColor) diff --git a/platform/ios/platform/darwin/test/MLNExpressionTests.mm b/platform/ios/platform/darwin/test/MLNExpressionTests.mm index 61ecfefb282..00cb840308e 100644 --- a/platform/ios/platform/darwin/test/MLNExpressionTests.mm +++ b/platform/ios/platform/darwin/test/MLNExpressionTests.mm @@ -291,7 +291,7 @@ - (void)testVariableExpressionObject { { NSDictionary *context = @{@"loremIpsum": MLNConstantExpression(@"Lorem ipsum dolor sit amet")}; #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionWithFormat:@"MLN_LET('loremIpsum', 'Lorem ipsum dolor sit amet', uppercase($loremIpsum))", context]; NSExpression *compatibilityExpression = [NSExpression expressionWithFormat:@"FUNCTION(uppercase($loremIpsum), 'mgl_expressionWithContext:', %@)", context]; @@ -627,7 +627,7 @@ - (void)testArithmeticExpressionObject { } { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionForFunction:@"mgl_round:" arguments:@[MLNConstantExpression(@1.5)]]; NSArray *jsonExpression = @[@"round", @1.5]; @@ -670,7 +670,7 @@ - (void)testTrigonometricExpressionObject { } { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionForFunction:@"mgl_log2:" arguments:@[MLNConstantExpression(@1024)]]; NSArray *jsonExpression = @[@"log2", @1024]; @@ -756,7 +756,7 @@ - (void)testShapeDistanceExpressionObject { MLNPointAnnotation *point = [[MLNPointAnnotation alloc] init]; point.coordinate = CLLocationCoordinate2DMake(1, -1); #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionForFunction:@"mgl_distanceFrom:" arguments:@[MLNConstantExpression(point)]]; NSArray *jsonExpression = @[@"distance", @{@"type": @"Point", @"coordinates": @[@-1, @1]}]; @@ -771,7 +771,7 @@ - (void)testStringFormattingExpressionObject { { NSExpression *expression = [NSExpression expressionWithFormat:@"FUNCTION('Old', 'stringByAppendingString:', 'MacDonald')"]; #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *aftermarketExpression = [NSExpression expressionWithFormat:@"mgl_join({'Old', 'MacDonald'})"]; NSArray *jsonExpression = @[@"concat", @"Old", @"MacDonald"]; @@ -877,7 +877,7 @@ - (void)testTypeConversionExpressionObject { } { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionWithFormat:@"MLN_FUNCTION('to-color', x, y, z)"]; NSArray *jsonExpression = @[@"to-color", @[@"get", @"x"], @[@"get", @"y"], @[@"get", @"z"]]; @@ -904,7 +904,7 @@ - (void)testTypeConversionExpressionObject { - (void)testInterpolationExpressionObject { { NSDictionary *stops = @{@0: MLNConstantExpression(@100), @10: MLNConstantExpression(@200)}; - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); NSExpression *expression = [NSExpression expressionWithFormat:@"mgl_interpolate:withCurveType:parameters:stops:(x, 'linear', nil, %@)", stops]; NSExpression *compatibilityExpression = [NSExpression expressionWithFormat:@"FUNCTION(x, 'mgl_interpolateWithCurveType:parameters:stops:', 'linear', nil, %@)", stops]; NSArray *jsonExpression = @[@"interpolate", @[@"linear"], @[@"get", @"x"], @0, @100, @10, @200]; @@ -957,7 +957,7 @@ - (void)testInterpolationExpressionObject { - (void)testMatchExpressionObject { { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionWithFormat:@"MLN_MATCH(2 - 1, %@, %@, %@, %@, 'default')", MLNConstantExpression(@1), MLNConstantExpression(@"one"), @@ -998,7 +998,7 @@ - (void)testMatchExpressionObject { - (void)testCoalesceExpressionObject { { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionWithFormat:@"mgl_coalesce(%@)", @[[NSExpression expressionForKeyPath:@"x"], @@ -1038,7 +1038,7 @@ - (void)testConditionalExpressionObject { } { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionWithFormat:@"MLN_IF(%@, %@, %@)", [NSExpression expressionWithFormat:@"%@", [NSPredicate predicateWithFormat:@"1 = 2"]], @@ -1131,7 +1131,7 @@ - (void)testLookupExpressionObject { } { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionForFunction:@"mgl_does:have:" arguments:@[[NSExpression expressionForEvaluatedObject], @@ -1194,7 +1194,7 @@ - (void)testFormatExpressionObject { fontNames:@[] fontScale:nil]; #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionWithFormat:@"mgl_attributed:(%@, %@, %@, %@)", MLNConstantExpression(attribute1), @@ -1326,7 +1326,7 @@ - (void)testFormatExpressionObject { - (void)testGenericExpressionObject { { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [NSExpression expressionWithFormat:@"MLN_FUNCTION('random', 1, 2, 3, 4, 5)"]; NSArray *jsonExpression = @[@"random", @1, @2, @3, @4, @5]; @@ -1397,7 +1397,7 @@ - (void)testLocalization { NSExpression *original = [NSExpression expressionForConstantValue:attributedExpression]; #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *coalesceExpression = [NSExpression expressionWithFormat:@"mgl_coalesce({%K, %K})", @"name_en", @"name"]; MLNAttributedExpression *expectedAttributedExpression = [MLNAttributedExpression attributedExpression:coalesceExpression attributes:@{}]; @@ -1527,7 +1527,7 @@ - (void)testConvenienceInitializers { } { #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *expression = [[NSExpression expressionForConstantValue:@"Old"] mgl_expressionByAppendingExpression:[NSExpression expressionForConstantValue:@"MacDonald"]]; diff --git a/platform/ios/platform/darwin/test/MLNHeatmapColorTests.mm b/platform/ios/platform/darwin/test/MLNHeatmapColorTests.mm index ecc24e43ef2..0206b967cff 100644 --- a/platform/ios/platform/darwin/test/MLNHeatmapColorTests.mm +++ b/platform/ios/platform/darwin/test/MLNHeatmapColorTests.mm @@ -34,7 +34,7 @@ - (void)testProperties { constantExpression = [NSExpression expressionWithFormat:@"%@", [MLNColor redColor]]; NSExpression *constantExpression2 = [NSExpression expressionWithFormat:@"%@", [MLNColor blueColor]]; #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif NSExpression *functionExpression = [NSExpression expressionWithFormat:@"mgl_step:from:stops:($heatmapDensity, %@, %@)", constantExpression, @{@12: constantExpression2}]; layer.heatmapColor = functionExpression; @@ -43,7 +43,7 @@ - (void)testProperties { @"Setting heatmapColor to an expression depending on $heatmapDensity should update heatmap-color."); XCTAssertEqual(rawLayer->getHeatmapColor().evaluate(12.0), mbgl::Color::blue(), @"Setting heatmapColor to an expression depending on $heatmapDensity should update heatmap-color."); - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); XCTAssertEqualObjects(layer.heatmapColor, functionExpression, @"heatmapColor should round-trip expressions depending on $heatmapDensity."); diff --git a/platform/ios/platform/darwin/test/MLNPredicateTests.mm b/platform/ios/platform/darwin/test/MLNPredicateTests.mm index 60edd8b97a4..1f4ddc845ed 100644 --- a/platform/ios/platform/darwin/test/MLNPredicateTests.mm +++ b/platform/ios/platform/darwin/test/MLNPredicateTests.mm @@ -315,7 +315,7 @@ - (void)testComparisonPredicates { NSArray *expected = @[@"in", @"📍", @[@"literal", @"Pinole"]]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"'📍' IN 'Pinole'"]; #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif XCTAssertEqualObjects(predicate.mgl_jsonExpressionObject, expected); XCTAssertEqualObjects([NSPredicate predicateWithMLNJSONObject:expected], predicate); @@ -447,7 +447,7 @@ - (void)testComparisonPredicatesWithOptions { NSArray *jsonExpression = @[@"==", @[@"get", @"a"], @"b", @[@"collator", @{@"case-sensitive": @NO, @"diacritic-sensitive": @YES}]]; XCTAssertEqualObjects(predicate.mgl_jsonExpressionObject, jsonExpression); #if TARGET_OS_IPHONE - XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-gl-native/issues/331"); + XCTExpectFailure(@"Awaiting unit test refactoring for https://github.com/maplibre/maplibre-native/issues/331"); #endif [self testSymmetryWithPredicate:predicate mustRoundTrip:NO]; diff --git a/platform/ios/platform/darwin/test/MLNStyleLayerTests.mm.ejs b/platform/ios/platform/darwin/test/MLNStyleLayerTests.mm.ejs index cd57bd273d1..225f3212860 100644 --- a/platform/ios/platform/darwin/test/MLNStyleLayerTests.mm.ejs +++ b/platform/ios/platform/darwin/test/MLNStyleLayerTests.mm.ejs @@ -92,7 +92,7 @@ attributes:@{}]; constantExpression = [NSExpression mgl_expressionForAttributedExpressions:@[[NSExpression expressionForConstantValue:attributedConstantExpression]]]; <% } -%> - XCTExpectFailure(@"Awaiting unit test refactoring https://github.com/maplibre/maplibre-gl-native/issues/421"); + XCTExpectFailure(@"Awaiting unit test refactoring https://github.com/maplibre/maplibre-native/issues/421"); NSExpression *functionExpression = [NSExpression expressionWithFormat:@"mgl_step:from:stops:($zoomLevel, %@, %@)", constantExpression, @{@18: constantExpression}]; layer.<%- objCName(property) %> = functionExpression; diff --git a/platform/ios/platform/ios/CHANGELOG.md b/platform/ios/platform/ios/CHANGELOG.md index dcc3caf91f3..c7141dcb0c8 100644 --- a/platform/ios/platform/ios/CHANGELOG.md +++ b/platform/ios/platform/ios/CHANGELOG.md @@ -1,65 +1,65 @@ # Changelog for MapLibre Native for iOS -MapLibre welcomes participation and contributions from everyone. Please read [`Contributing Guide`](https://github.com/maplibre/maplibre-gl-native/blob/master/CONTRIBUTING.md) to get started. +MapLibre welcomes participation and contributions from everyone. Please read [`Contributing Guide`](https://github.com/maplibre/maplibre-native/blob/master/CONTRIBUTING.md) to get started. ## main -* 💥 Breaking: Changed the prefix of files, classes, methods, variables and everything from `MGL` to `MLN`. ([#919](https://github.com/maplibre/maplibre-gl-native/pull/919)). +* 💥 Breaking: Changed the prefix of files, classes, methods, variables and everything from `MGL` to `MLN`. ([#919](https://github.com/maplibre/maplibre-native/pull/919)). > To migrate: > Change all your `MGL` prefixes to `MLN`. If you are using `NSKeyedArchiver` or similar mechanishm to save the state, the app may crash after this change when trying to unarchive the state using old names of the classes. You need to clean the saved state of the app and save it using new classes. ## 5.13.0 - January 05, 2023 -* Fix missing attribution [#236](https://github.com/maplibre/maplibre-gl-native/pull/236) -* Fix logging format strings [#266](https://github.com/maplibre/maplibre-gl-native/pull/266) -* Implement map projection functionality [#254](https://github.com/maplibre/maplibre-gl-native/pull/254) -* Fix warnings, mainly casting to smaller types [#270](https://github.com/maplibre/maplibre-gl-native/pull/270) +* Fix missing attribution [#236](https://github.com/maplibre/maplibre-native/pull/236) +* Fix logging format strings [#266](https://github.com/maplibre/maplibre-native/pull/266) +* Implement map projection functionality [#254](https://github.com/maplibre/maplibre-native/pull/254) +* Fix warnings, mainly casting to smaller types [#270](https://github.com/maplibre/maplibre-native/pull/270) * Remove an unused static library (savings of 97 KB from iOS binary) -* Add ClientOptions to be able to pass around client name and version [#365](https://github.com/maplibre/maplibre-gl-native/pull/365) -* Remove account from xcconfig [#382](https://github.com/maplibre/maplibre-gl-native/pull/382) -* Remove observation of key-path [#380](https://github.com/maplibre/maplibre-gl-native/pull/380) -* Fix for "NSExpression function is forbidden" [#411](https://github.com/maplibre/maplibre-gl-native/pull/411) -* Xcode 14 compatibility [#494](https://github.com/maplibre/maplibre-gl-native/pull/494) [#599](https://github.com/maplibre/maplibre-gl-native/pull/599) +* Add ClientOptions to be able to pass around client name and version [#365](https://github.com/maplibre/maplibre-native/pull/365) +* Remove account from xcconfig [#382](https://github.com/maplibre/maplibre-native/pull/382) +* Remove observation of key-path [#380](https://github.com/maplibre/maplibre-native/pull/380) +* Fix for "NSExpression function is forbidden" [#411](https://github.com/maplibre/maplibre-native/pull/411) +* Xcode 14 compatibility [#494](https://github.com/maplibre/maplibre-native/pull/494) [#599](https://github.com/maplibre/maplibre-native/pull/599) ## 5.12.2 - December 02, 2021 ### Improvements -* Exposes the windowBit value from zlib in the compress/decompress helper utils [#147](https://github.com/maplibre/maplibre-gl-native/pull/147) -* Fix camera paddings reset on map view gestures performing [#188](https://github.com/maplibre/maplibre-gl-native/pull/188) +* Exposes the windowBit value from zlib in the compress/decompress helper utils [#147](https://github.com/maplibre/maplibre-native/pull/147) +* Fix camera paddings reset on map view gestures performing [#188](https://github.com/maplibre/maplibre-native/pull/188) ## 5.12.1 - September 06, 2021 ### Bug Fixes -* ScaleBar enhancements [#120](https://github.com/maplibre/maplibre-gl-native/pull/120), [#121](https://github.com/maplibre/maplibre-gl-native/pull/121) -* Invalid tile url template for MapLibre style [#107](https://github.com/maplibre/maplibre-gl-native/pull/107) -* Address crash when localFontFamilyName is nil [#109](https://github.com/maplibre/maplibre-gl-native/pull/109) -* Fix for annotations stuttering and drifting when panning [#113](https://github.com/maplibre/maplibre-gl-native/pull/113) -* Adjust local glyphs [#122](https://github.com/maplibre/maplibre-gl-native/pull/122) -* Return correct Mapbox TileServerOptions [#132](https://github.com/maplibre/maplibre-gl-native/pull/132) +* ScaleBar enhancements [#120](https://github.com/maplibre/maplibre-native/pull/120), [#121](https://github.com/maplibre/maplibre-native/pull/121) +* Invalid tile url template for MapLibre style [#107](https://github.com/maplibre/maplibre-native/pull/107) +* Address crash when localFontFamilyName is nil [#109](https://github.com/maplibre/maplibre-native/pull/109) +* Fix for annotations stuttering and drifting when panning [#113](https://github.com/maplibre/maplibre-native/pull/113) +* Adjust local glyphs [#122](https://github.com/maplibre/maplibre-native/pull/122) +* Return correct Mapbox TileServerOptions [#132](https://github.com/maplibre/maplibre-native/pull/132) ### Other -* Fix perf regression in cached tiles of tile pyramid [#129](https://github.com/maplibre/maplibre-gl-native/pull/129) -* Upgrade to newest protozero [#148](https://github.com/maplibre/maplibre-gl-native/pull/148) -* Fix build for Xcode 12.5 & 13-beta. [#153](https://github.com/maplibre/maplibre-gl-native/pull/153) +* Fix perf regression in cached tiles of tile pyramid [#129](https://github.com/maplibre/maplibre-native/pull/129) +* Upgrade to newest protozero [#148](https://github.com/maplibre/maplibre-native/pull/148) +* Fix build for Xcode 12.5 & 13-beta. [#153](https://github.com/maplibre/maplibre-native/pull/153) ## 5.12.0 - June 29, 2021 ### Features -* Added allowScrollGesturesDuringRotateOrZoom [#60](https://github.com/maplibre/maplibre-gl-native/pull/62) -* Replacing hardcoded configuration with configurable API and removing Mapbox assets and dependencies [#90](https://github.com/maplibre/maplibre-gl-native/pull/90) +* Added allowScrollGesturesDuringRotateOrZoom [#60](https://github.com/maplibre/maplibre-native/pull/62) +* Replacing hardcoded configuration with configurable API and removing Mapbox assets and dependencies [#90](https://github.com/maplibre/maplibre-native/pull/90) ### Bug Fixes -* Fix map stuttering by switching render call to use setNeedsDisplay [#60](https://github.com/maplibre/maplibre-gl-native/pull/60) -* Dispatch to main queue, rather than global [#64](https://github.com/maplibre/maplibre-gl-native/pull/64) -* Use DisplayLink to prevent crashes in willResignActive [#68](https://github.com/maplibre/maplibre-gl-native/pull/68) -* Ignore sizing and positioning for hidden elements in assertions [#80](https://github.com/maplibre/maplibre-gl-native/pull/80) -* Disable map snapshots by default [#83](https://github.com/maplibre/maplibre-gl-native/pull/83) +* Fix map stuttering by switching render call to use setNeedsDisplay [#60](https://github.com/maplibre/maplibre-native/pull/60) +* Dispatch to main queue, rather than global [#64](https://github.com/maplibre/maplibre-native/pull/64) +* Use DisplayLink to prevent crashes in willResignActive [#68](https://github.com/maplibre/maplibre-native/pull/68) +* Ignore sizing and positioning for hidden elements in assertions [#80](https://github.com/maplibre/maplibre-native/pull/80) +* Disable map snapshots by default [#83](https://github.com/maplibre/maplibre-native/pull/83) ## 5.11.0 - March 12, 2021 @@ -76,14 +76,14 @@ MapLibre welcomes participation and contributions from everyone. Please read [`C ### Bug Fixes * Fixed an issue that caused a crash when custom location managers did not implement `MLNLocationManager.accuracyAuthorization`. (cherry pick from [#474](https://github.com/mapbox/mapbox-gl-native-ios/pull/474)) -* Fixed an issue where symbols flickered when zooming out. [#16](https://github.com/maplibre/maplibre-gl-native/issues/16) +* Fixed an issue where symbols flickered when zooming out. [#16](https://github.com/maplibre/maplibre-native/issues/16) * Benchmark app updated and fixes to the latest xcode version -* iOS performance improvements [#44](https://github.com/maplibre/maplibre-gl-native/pull/44) +* iOS performance improvements [#44](https://github.com/maplibre/maplibre-native/pull/44) ### Other * mapbox-gl-js submodule has been replaced with maplibre-gl-js -* Removed Mapbox Mobile Events and Telemetry [#7](https://github.com/maplibre/maplibre-gl-native/pull/7) +* Removed Mapbox Mobile Events and Telemetry [#7](https://github.com/maplibre/maplibre-native/pull/7) ## 5.10.0 - January 6, 2021 diff --git a/platform/ios/platform/ios/CONTRIBUTING.md b/platform/ios/platform/ios/CONTRIBUTING.md index 7ab136459d8..205307f080e 100644 --- a/platform/ios/platform/ios/CONTRIBUTING.md +++ b/platform/ios/platform/ios/CONTRIBUTING.md @@ -60,7 +60,7 @@ The products of these build commands can be found in the `build/ios/pkg` folder ## Documentation -We are moving away from the legacy Jazzy documentation towards Apple's documentation generator [DocC](https://developer.apple.com/documentation/docc). DocC has great Xcode intergration. See the [open issues](https://github.com/maplibre/maplibre-gl-native/issues?q=is%3Aissue+is%3Aopen+label%3Aios+label%3Adocumentation) if you want to help. +We are moving away from the legacy Jazzy documentation towards Apple's documentation generator [DocC](https://developer.apple.com/documentation/docc). DocC has great Xcode intergration. See the [open issues](https://github.com/maplibre/maplibre-native/issues?q=is%3Aissue+is%3Aopen+label%3Aios+label%3Adocumentation) if you want to help. - For a general introduction to DocC, including for example a demonstration of the custom Markdown that DocC uses that allows for cross-linking, see this WWDC video: https://developer.apple.com/videos/play/wwdc2021/10166/ - For instructions of how to write a tutorial in DooC format: https://developer.apple.com/documentation/docc/building-an-interactive-tutorial @@ -70,14 +70,14 @@ The most convenient way to generate the DocC based documentation locally is usin ### Jazzy Documentation -The code samples in the header files & [iOS API Documentation](https://maplibre.org/maplibre-gl-native/ios/api/) are generated by a unit test. +The code samples in the header files & [iOS API Documentation](https://maplibre.org/maplibre-native/ios/api/) are generated by a unit test. An example of auto generated documentation is the unit test [MLNDocumentationExampleTests.swift](../darwin/test/MLNDocumentationExampleTests.swift) which generates styling examples in the `.h` file for styling either a -[Circle](https://maplibre.org/maplibre-gl-native/ios/api/Classes/MLNCircleStyleLayer.html), -[Heatmap](https://maplibre.org/maplibre-gl-native/ios/api/Classes/MLNHeatmapStyleLayer.html), or -[Line](https://maplibre.org/maplibre-gl-native/ios/api/Classes/MLNLineStyleLayer.html). For more details see [Adding a code example](DEVELOPING.md#adding-a-code-example). +[Circle](https://maplibre.org/maplibre-native/ios/api/Classes/MLNCircleStyleLayer.html), +[Heatmap](https://maplibre.org/maplibre-native/ios/api/Classes/MLNHeatmapStyleLayer.html), or +[Line](https://maplibre.org/maplibre-native/ios/api/Classes/MLNLineStyleLayer.html). For more details see [Adding a code example](DEVELOPING.md#adding-a-code-example). Use `make` to update API documentation: @@ -101,7 +101,7 @@ To add any Objective-C type, constant, or member to the iOS SDK’s public inter 1. Ensure that the symbol is pure Objective-C and does not rely on any language features specific to Objective-C++ or the C11 dialect of C – so no namespaced types or classes named with emoji! 🙃 Most projects that depend on this SDK are either written in pure Objective-C (GNU99 dialect) or Swift, which cannot yet bridge C++ types. 1. Name the symbol according to [Cocoa naming conventions](https://developer.apple.com/library/prerelease/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html#//apple_ref/doc/uid/10000146i). Use the `MLN` class prefix to avoid conflicts with client code. If the symbol has an analogue in MapKit, name the symbol according to MapKit. -1. Provide full documentation comments. We use [jazzy](https://github.com/realm/jazzy/) to produce the documentation found in the SDK distribution and [on the website for this SDK](https://maplibre.org/maplibre-gl-native/ios/api/). We also recognize that many developers rely on Xcode’s Quick Help feature. jazzy supports Markdown formatting; however, Quick Help supports only [HeaderDoc](https://developer.apple.com/legacy/library/documentation/DeveloperTools/Conceptual/HeaderDoc/intro/intro.html) syntax and a subset of Doxygen syntax. For hyperlinks, use HTML syntax, which is recognized by both tools. +1. Provide full documentation comments. We use [jazzy](https://github.com/realm/jazzy/) to produce the documentation found in the SDK distribution and [on the website for this SDK](https://maplibre.org/maplibre-native/ios/api/). We also recognize that many developers rely on Xcode’s Quick Help feature. jazzy supports Markdown formatting; however, Quick Help supports only [HeaderDoc](https://developer.apple.com/legacy/library/documentation/DeveloperTools/Conceptual/HeaderDoc/intro/intro.html) syntax and a subset of Doxygen syntax. For hyperlinks, use HTML syntax, which is recognized by both tools. ### Making a type or constant public diff --git a/platform/ios/platform/ios/INSTALL.md b/platform/ios/platform/ios/INSTALL.md index 20753619f15..56d5a834b2c 100644 --- a/platform/ios/platform/ios/INSTALL.md +++ b/platform/ios/platform/ios/INSTALL.md @@ -57,7 +57,7 @@ If you wish to deploy on attached hardware, you need to setup your Apple Develop 1. Clone the git repository: ```bash - git clone --recurse-submodules https://github.com/maplibre/maplibre-gl-native.git + git clone --recurse-submodules https://github.com/maplibre/maplibre-native.git cd maplibre-gl-native ``` Note that you must check out the project's git submodules to build. If you did not include `--recurse-submodules` in the clone, you can later run `git submodule update --init`. diff --git a/platform/ios/platform/ios/README.md b/platform/ios/platform/ios/README.md index 2e38cfe5c65..e5ca9bf58ab 100644 --- a/platform/ios/platform/ios/README.md +++ b/platform/ios/platform/ios/README.md @@ -1,6 +1,6 @@ # MapLibre Native for iOS -[![GitHub Action build status](https://github.com/maplibre/maplibre-gl-native/workflows/ios-ci/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/ios-ci.yml) [![GitHub Action build status](https://github.com/maplibre/maplibre-gl-native/workflows/ios-release/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/ios-release.yml) +[![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/ios-ci/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/ios-ci.yml) [![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/ios-release/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/ios-release.yml) A library based on [MapLibre Native](https://github.com/maplibre/maplibre-gl-native) for embedding interactive map views with scalable, customizable vector maps into Cocoa Touch applications on iOS using Objective-C, Swift, or Interface Builder. @@ -18,7 +18,7 @@ A library based on [MapLibre Native](https://github.com/maplibre/maplibre-gl-nat ## Documentation -- [MapLibre Native for iOS API Reference](https://maplibre.org/maplibre-gl-native/ios/api/) +- [MapLibre Native for iOS API Reference](https://maplibre.org/maplibre-native/ios/api/) ## Contributing diff --git a/platform/ios/platform/ios/docs/pod-README.md b/platform/ios/platform/ios/docs/pod-README.md index 00de86535b4..891939193b9 100644 --- a/platform/ios/platform/ios/docs/pod-README.md +++ b/platform/ios/platform/ios/docs/pod-README.md @@ -2,7 +2,7 @@ MapLibre Native for iOS is an open-source framework for embedding interactive map views with scalable, customizable vector maps into Cocoa Touch applications on iOS 9.0 and above using Objective-C, Swift, or Interface Builder. It takes stylesheets that conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-gl-js-docs/style-spec/), applies them to vector tiles that conform to the [Mapbox Vector Tile Specification](https://docs.mapbox.com/data/tilesets/guides/vector-tiles-standards/), and renders them using OpenGL. -For more information, check out the [MapLibre Native for iOS repository](https://github.com/maplibre/maplibre-gl-native) and the [full changelog](https://github.com/maplibre/maplibre-gl-native/blob/main/platform/ios/platform/ios/CHANGELOG.md) online. +For more information, check out the [MapLibre Native for iOS repository](https://github.com/maplibre/maplibre-gl-native) and the [full changelog](https://github.com/maplibre/maplibre-native/blob/main/platform/ios/platform/ios/CHANGELOG.md) online. [![](https://raw.githubusercontent.com/mapbox/mapbox-gl-native-ios/master/platform/ios/docs/img/screenshot.png)]() @@ -94,4 +94,4 @@ class ViewController: UIViewController { Full API documentation is included in this package, within the `documentation` folder. -We welcome your [bug reports, feature requests, and contributions](https://github.com/maplibre/maplibre-gl-native/issues). +We welcome your [bug reports, feature requests, and contributions](https://github.com/maplibre/maplibre-native/issues). diff --git a/platform/ios/platform/ios/jazzy.yml b/platform/ios/platform/ios/jazzy.yml index 627a2964504..5b568f9ba11 100644 --- a/platform/ios/platform/ios/jazzy.yml +++ b/platform/ios/platform/ios/jazzy.yml @@ -2,7 +2,7 @@ module: MapLibre author: MapLibre Contributors author_url: https://maplibre.org/ github_url: https://github.com/maplibre/maplibre-gl-native -copyright: '[License](https://github.com/maplibre/maplibre-gl-native/blob/main/platform/ios/LICENSE.md)' +copyright: '[License](https://github.com/maplibre/maplibre-native/blob/main/platform/ios/LICENSE.md)' head: | diff --git a/platform/ios/platform/ios/scripts/document.sh b/platform/ios/platform/ios/scripts/document.sh index 3203052ec94..726f7f06f7f 100755 --- a/platform/ios/platform/ios/scripts/document.sh +++ b/platform/ios/platform/ios/scripts/document.sh @@ -45,7 +45,7 @@ jazzy \ --module-version ${SHORT_VERSION} \ --readme ${README} \ --documentation="platform/{darwin,ios}/docs/guides/*.md" \ - --root-url https://maplibre.org/maplibre-gl-native/ios/api/ \ + --root-url https://maplibre.org/maplibre-native/ios/api/ \ --theme ${THEME} \ --head "${CUSTOM_HEAD}" \ --output ${OUTPUT} \ diff --git a/platform/ios/platform/ios/scripts/package.sh b/platform/ios/platform/ios/scripts/package.sh index 3614c550d7a..fed5ea0b792 100755 --- a/platform/ios/platform/ios/scripts/package.sh +++ b/platform/ios/platform/ios/scripts/package.sh @@ -59,7 +59,7 @@ fi step "Recording library version…" VERSION="${OUTPUT}"/version.txt -echo -n "https://github.com/maplibre/maplibre-gl-native/commit/" > ${VERSION} +echo -n "https://github.com/maplibre/maplibre-native/commit/" > ${VERSION} HASH=`git log | head -1 | awk '{ print $2 }' | cut -c 1-10` && true echo -n "maplibre-gl-native-ios " echo ${HASH} diff --git a/platform/ios/platform/ios/scripts/release-notes-jazzy.md.ejs b/platform/ios/platform/ios/scripts/release-notes-jazzy.md.ejs index 27730ec4e67..ed865084c2b 100644 --- a/platform/ios/platform/ios/scripts/release-notes-jazzy.md.ejs +++ b/platform/ios/platform/ios/scripts/release-notes-jazzy.md.ejs @@ -4,7 +4,7 @@ MapLibre Native for iOS is an open-source framework for embedding interactive ma ![MapLibre Native for iOS screenshots](img/screenshot.png) -We welcome your [bug reports, feature requests, and contributions](https://github.com/maplibre/maplibre-gl-native/issues). +We welcome your [bug reports, feature requests, and contributions](https://github.com/maplibre/maplibre-native/issues). ## Changes in version <%-CURRENTVERSION%> @@ -18,4 +18,4 @@ We welcome your [bug reports, feature requests, and contributions](https://githu <%-release.changelog%> <% }) -%> -See the [full changelog](https://github.com/maplibre/maplibre-gl-native/blob/main/platform/ios/platform/ios/CHANGELOG.md) for previous releases. +See the [full changelog](https://github.com/maplibre/maplibre-native/blob/main/platform/ios/platform/ios/CHANGELOG.md) for previous releases. diff --git a/platform/ios/platform/ios/scripts/update-swift-package.sh b/platform/ios/platform/ios/scripts/update-swift-package.sh index ca6619aef84..f106a71c115 100755 --- a/platform/ios/platform/ios/scripts/update-swift-package.sh +++ b/platform/ios/platform/ios/scripts/update-swift-package.sh @@ -26,7 +26,7 @@ PUBLISH_VERSION="5.11.0" BINARY_DIRECTORY='/Volumes/Data/Temp/maplibre' PUBLISH_PRE_FLAG='' S3_DISTRIBUTION=false -MAPBOX_ZIP_FILE_URL="https://github.com/maplibre/maplibre-gl-native/releases/download/ios-v5.11.0/Mapbox-5.11.0.zip" +MAPBOX_ZIP_FILE_URL="https://github.com/maplibre/maplibre-native/releases/download/ios-v5.11.0/Mapbox-5.11.0.zip" MAPBOX_ZIP_FILE="Mapbox-5.11.0.zip" DIST_GITHUB_TOKEN="PUT YOUR TOKEN HERE:" diff --git a/platform/ios/platform/ios/scripts/xcpackage.sh b/platform/ios/platform/ios/scripts/xcpackage.sh index d1d35f94d8d..3740ea31680 100755 --- a/platform/ios/platform/ios/scripts/xcpackage.sh +++ b/platform/ios/platform/ios/scripts/xcpackage.sh @@ -41,7 +41,7 @@ mkdir -p ${BINOUT} step "Recording library version…" VERSION="${OUTPUT}"/version.txt -echo -n "https://github.com/maplibre/maplibre-gl-native/commit/" > ${VERSION} +echo -n "https://github.com/maplibre/maplibre-native/commit/" > ${VERSION} HASH=`git log | head -1 | awk '{ print $2 }' | cut -c 1-10` && true echo -n "maplibre-gl-native-ios " echo ${HASH} diff --git a/platform/ios/platform/macos/CHANGELOG.md b/platform/ios/platform/macos/CHANGELOG.md index d5d3b0cd8a3..6c0f6374c6c 100644 --- a/platform/ios/platform/macos/CHANGELOG.md +++ b/platform/ios/platform/macos/CHANGELOG.md @@ -1,26 +1,26 @@ # Changelog for Mapbox Maps SDK for macOS -MapLibre welcomes participation and contributions from everyone. Please read [`Contributing Guide`](https://github.com/maplibre/maplibre-gl-native/blob/main/CONTRIBUTING.md) to get started. +MapLibre welcomes participation and contributions from everyone. Please read [`Contributing Guide`](https://github.com/maplibre/maplibre-native/blob/main/CONTRIBUTING.md) to get started. ## 0.19.1 - September 06, 2021 ### Bug Fixes -* Invalid tile url template for MapLibre style [#107](https://github.com/maplibre/maplibre-gl-native/pull/107) -* Adjust local glyphs [#122](https://github.com/maplibre/maplibre-gl-native/pull/122) -* Return correct Mapbox TileServerOptions [#132](https://github.com/maplibre/maplibre-gl-native/pull/132) +* Invalid tile url template for MapLibre style [#107](https://github.com/maplibre/maplibre-native/pull/107) +* Adjust local glyphs [#122](https://github.com/maplibre/maplibre-native/pull/122) +* Return correct Mapbox TileServerOptions [#132](https://github.com/maplibre/maplibre-native/pull/132) ### Other -* Fix perf regression in cached tiles of tile pyramid [#129](https://github.com/maplibre/maplibre-gl-native/pull/129) -* Upgrade to newest protozero [#148](https://github.com/maplibre/maplibre-gl-native/pull/148) -* Fix build for Xcode 12.5 & 13-beta. [#153](https://github.com/maplibre/maplibre-gl-native/pull/153) +* Fix perf regression in cached tiles of tile pyramid [#129](https://github.com/maplibre/maplibre-native/pull/129) +* Upgrade to newest protozero [#148](https://github.com/maplibre/maplibre-native/pull/148) +* Fix build for Xcode 12.5 & 13-beta. [#153](https://github.com/maplibre/maplibre-native/pull/153) ## 0.19.0 - June 29, 2021 ### Features -* Replacing hardcoded configuration with configurable API and removing Mapbox assets and dependencies [#90](https://github.com/maplibre/maplibre-gl-native/pull/90) +* Replacing hardcoded configuration with configurable API and removing Mapbox assets and dependencies [#90](https://github.com/maplibre/maplibre-native/pull/90) ## 0.18.0 - March 12, 2021 @@ -31,7 +31,7 @@ MapLibre welcomes participation and contributions from everyone. Please read [`C ### Other * mapbox-gl-js submodule has been replaced with maplibre-gl-js -* Removed Mapbox Mobile Events and Telemetry [#7](https://github.com/maplibre/maplibre-gl-native/pull/7) +* Removed Mapbox Mobile Events and Telemetry [#7](https://github.com/maplibre/maplibre-native/pull/7) ## 0.17.0 - January 6, 2021 diff --git a/platform/ios/platform/macos/INSTALL.md b/platform/ios/platform/macos/INSTALL.md index 2810e0e56f8..ff4fa23aa4e 100644 --- a/platform/ios/platform/macos/INSTALL.md +++ b/platform/ios/platform/macos/INSTALL.md @@ -38,7 +38,7 @@ To build the SDK from source: 1. Clone the git repository: ```bash - git clone https://github.com/maplibre/maplibre-gl-native.git + git clone https://github.com/maplibre/maplibre-native.git cd maplibre-gl-native ``` Note that this repository uses Git submodules. They'll be automatically checked out when you first run a `make` command, diff --git a/platform/ios/platform/macos/README.md b/platform/ios/platform/macos/README.md index 8a4b85fee4a..a563d2afd35 100644 --- a/platform/ios/platform/macos/README.md +++ b/platform/ios/platform/macos/README.md @@ -1,9 +1,9 @@ # MapLibre Native for macOS > **Note** -> https://github.com/maplibre/maplibre-gl-native/pull/995 introduced OpenGL ES 3.0 shaders which are not supported by macOS without workarounds. That means that while the [Metal backend implementation](https://github.com/maplibre/maplibre-gl-native/blob/main/design-proposals/2022-11-29-metal-port.md) is underway, builds from the `main` branch will not work on macOS. Use the `opengl-2` branch in the meantime. +> https://github.com/maplibre/maplibre-native/pull/995 introduced OpenGL ES 3.0 shaders which are not supported by macOS without workarounds. That means that while the [Metal backend implementation](https://github.com/maplibre/maplibre-native/blob/main/design-proposals/2022-11-29-metal-port.md) is underway, builds from the `main` branch will not work on macOS. Use the `opengl-2` branch in the meantime. -[![GitHub Action build status](https://github.com/maplibre/maplibre-gl-native/workflows/macos-ci/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/macos-ci.yml) [![GitHub Action build status](https://github.com/maplibre/maplibre-gl-native/workflows/macos-release/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/macos-release.yml) +[![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/macos-ci/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/macos-ci.yml) [![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/macos-release/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/macos-release.yml) Put interactive, scalable world maps into your native Cocoa application with MapLibre Native for macOS. diff --git a/platform/linux/README.md b/platform/linux/README.md index 49352bf7388..585938d46c8 100644 --- a/platform/linux/README.md +++ b/platform/linux/README.md @@ -34,7 +34,7 @@ apt install libjpeg-turbo8 libicu66 First, clone the repository. This repository uses git submodules, which are also required to build the project. ```bash -git clone --recurse-submodules -j8 https://github.com/maplibre/maplibre-gl-native.git +git clone --recurse-submodules -j8 https://github.com/maplibre/maplibre-native.git cd maplibre-gl-native ``` diff --git a/platform/node/CHANGELOG.md b/platform/node/CHANGELOG.md index 85c3bcf6556..a9217440249 100644 --- a/platform/node/CHANGELOG.md +++ b/platform/node/CHANGELOG.md @@ -3,42 +3,42 @@ ### ✨ New features - *...Add new stuff here...* -* Make Node Map object options "request" property optional by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/904 +* Make Node Map object options "request" property optional by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/904 ### 🐞 Bug fixes - *...Add new stuff here...* -* Compile Node targets without -std=c++11 option by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/926 +* Compile Node targets without -std=c++11 option by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/926 # 5.2.0 -* Adjust Typings for Node Platform by @etnav in https://github.com/maplibre/maplibre-gl-native/pull/871 -* Node platform improvements (added setSize and a new render call without render options object) by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/891 -* Move node ci+release to self hosted Ubuntu arm64 by @acalcutt in https://github.com/maplibre/maplibre-gl-native/pull/873 -* Add windows support by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/707 -* Add Typings for Node Platform by @KiwiKilian in https://github.com/maplibre/maplibre-gl-native/pull/766 -* Upgrade nan for node 19.x support by @mnutt in https://github.com/maplibre/maplibre-gl-native/pull/853 -* Improve node docs with available platforms by @KiwiKilian in https://github.com/maplibre/maplibre-gl-native/pull/786 -* Avoid implicit casts by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/787 -* Update node (ubuntu-20.04, arm64) docker build workflow by @acalcutt in https://github.com/maplibre/maplibre-gl-native/pull/804 -* Move module.cmake out of mapbox/cmake-node-module by @acalcutt in https://github.com/maplibre/maplibre-gl-native/pull/821 -* Add mbgl-compiler-options to Node targets by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/826 -* Avoid implicit casts and make code more portable by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/716 -* Use `*_t` and `*_v` trait helpers from C++17 STL by @louwers in https://github.com/maplibre/maplibre-gl-native/pull/731 -* Avoid implicit casts and portable printf with size_t by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/722 +* Adjust Typings for Node Platform by @etnav in https://github.com/maplibre/maplibre-native/pull/871 +* Node platform improvements (added setSize and a new render call without render options object) by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/891 +* Move node ci+release to self hosted Ubuntu arm64 by @acalcutt in https://github.com/maplibre/maplibre-native/pull/873 +* Add windows support by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/707 +* Add Typings for Node Platform by @KiwiKilian in https://github.com/maplibre/maplibre-native/pull/766 +* Upgrade nan for node 19.x support by @mnutt in https://github.com/maplibre/maplibre-native/pull/853 +* Improve node docs with available platforms by @KiwiKilian in https://github.com/maplibre/maplibre-native/pull/786 +* Avoid implicit casts by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/787 +* Update node (ubuntu-20.04, arm64) docker build workflow by @acalcutt in https://github.com/maplibre/maplibre-native/pull/804 +* Move module.cmake out of mapbox/cmake-node-module by @acalcutt in https://github.com/maplibre/maplibre-native/pull/821 +* Add mbgl-compiler-options to Node targets by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/826 +* Avoid implicit casts and make code more portable by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/716 +* Use `*_t` and `*_v` trait helpers from C++17 STL by @louwers in https://github.com/maplibre/maplibre-native/pull/731 +* Avoid implicit casts and portable printf with size_t by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/722 # 5.1.1 -* Fix memory access violation exception in vector_tile_data.cpp by @tdcosta100 in https://github.com/maplibre/maplibre-gl-native/pull/632 +* Fix memory access violation exception in vector_tile_data.cpp by @tdcosta100 in https://github.com/maplibre/maplibre-native/pull/632 # 5.1.0 * First Maplibre Native Node Stable Release -* Node workflow - build linux arm64 in a container #520 https://github.com/maplibre/maplibre-gl-native/pull/590 +* Node workflow - build linux arm64 in a container #520 https://github.com/maplibre/maplibre-native/pull/590 # 5.0.1 -* Exclude Node 19 (ABI 111) because it breaks the node build by @acalcutt in https://github.com/maplibre/maplibre-gl-native/pull/542 -* Fix mode switch not working in node version by @acalcutt in https://github.com/maplibre/maplibre-gl-native/pull/415 -* Node release workflow by @acalcutt in https://github.com/maplibre/maplibre-gl-native/pull/378 https://github.com/maplibre/maplibre-gl-native/pull/459 https://github.com/maplibre/maplibre-gl-native/pull/505 https://github.com/maplibre/maplibre-gl-native/pull/512 https://github.com/maplibre/maplibre-gl-native/pull/514 +* Exclude Node 19 (ABI 111) because it breaks the node build by @acalcutt in https://github.com/maplibre/maplibre-native/pull/542 +* Fix mode switch not working in node version by @acalcutt in https://github.com/maplibre/maplibre-native/pull/415 +* Node release workflow by @acalcutt in https://github.com/maplibre/maplibre-native/pull/378 https://github.com/maplibre/maplibre-native/pull/459 https://github.com/maplibre/maplibre-native/pull/505 https://github.com/maplibre/maplibre-native/pull/512 https://github.com/maplibre/maplibre-native/pull/514 * Add support for [image expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-image). ([#15877](https://github.com/mapbox/mapbox-gl-native/pull/15877)) * [Breaking] Remove node 10 support. v5.0.1-pre.0 of the node package can be used a compatibility version. -* Bring back node support by @jutaz in https://github.com/maplibre/maplibre-gl-native/pull/217 +* Bring back node support by @jutaz in https://github.com/maplibre/maplibre-native/pull/217 # 5.0.0 * No longer supporting source-compile fallback ([#15748](https://github.com/mapbox/mapbox-gl-native/pull/15748)) diff --git a/platform/node/README.md b/platform/node/README.md index f41844ba7bb..327ef88b5e9 100644 --- a/platform/node/README.md +++ b/platform/node/README.md @@ -1,7 +1,7 @@ # @maplibre/maplibre-gl-native [![Version](https://img.shields.io/npm/v/@maplibre/maplibre-gl-native?style=flat)](https://www.npmjs.com/package/@maplibre/maplibre-gl-native) -[![node-ci](https://github.com/maplibre/maplibre-gl-native/actions/workflows/node-ci.yml/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/node-ci.yml) +[![node-ci](https://github.com/maplibre/maplibre-native/actions/workflows/node-ci.yml/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/node-ci.yml) ## Installing @@ -19,7 +19,7 @@ Run: npm install @maplibre/maplibre-gl-native ``` -Further platforms might work [with additional libraries installed](https://github.com/maplibre/maplibre-gl-native/tree/main/platform/linux#prerequisites). +Further platforms might work [with additional libraries installed](https://github.com/maplibre/maplibre-native/tree/main/platform/linux#prerequisites). ## Testing @@ -139,7 +139,7 @@ If you omit the `request` method, the `map` object will use the default internal } ``` -The `kind` is an enum and defined in [`mbgl.Resource`](https://github.com/maplibre/maplibre-gl-native/blob/main/include/mbgl/storage/resource.hpp): +The `kind` is an enum and defined in [`mbgl.Resource`](https://github.com/maplibre/maplibre-native/blob/main/include/mbgl/storage/resource.hpp): ```json { @@ -230,7 +230,7 @@ Stylesheets are free to use any protocols, but your implementation of `request` ## Listening for log events -The module imported with `require('maplibre-gl-native')` inherits from [`EventEmitter`](https://nodejs.org/api/events.html), and the `NodeLogObserver` will push log events to this. Log messages can have [`class`](https://github.com/maplibre/maplibre-gl-native/blob/node-v2.1.0/include/mbgl/platform/event.hpp#L43-L60), [`severity`](https://github.com/maplibre/maplibre-gl-native/blob/node-v2.1.0/include/mbgl/platform/event.hpp#L17-L23), `code` ([HTTP status codes](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)), and `text` parameters. +The module imported with `require('maplibre-gl-native')` inherits from [`EventEmitter`](https://nodejs.org/api/events.html), and the `NodeLogObserver` will push log events to this. Log messages can have [`class`](https://github.com/maplibre/maplibre-native/blob/node-v2.1.0/include/mbgl/platform/event.hpp#L43-L60), [`severity`](https://github.com/maplibre/maplibre-native/blob/node-v2.1.0/include/mbgl/platform/event.hpp#L17-L23), `code` ([HTTP status codes](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)), and `text` parameters. ```js var mbgl = require('@maplibre/maplibre-gl-native'); diff --git a/platform/qt/CHANGELOG.md b/platform/qt/CHANGELOG.md index 68b05c973d9..5900dc6393d 100644 --- a/platform/qt/CHANGELOG.md +++ b/platform/qt/CHANGELOG.md @@ -4,7 +4,7 @@ ### ✨ New features -- Support for GeoJSON feature collections using std::list ([#541](https://github.com/maplibre/maplibre-gl-native/pull/541)). +- Support for GeoJSON feature collections using std::list ([#541](https://github.com/maplibre/maplibre-native/pull/541)). - Based on Qt 6.5.0 ### 🐞 Bug fixes @@ -22,5 +22,5 @@ ### ✨ New features - Full Qt5 and Qt6 support for macOS, Linux, Windows, iOS and Android. -- Rename to `QMapLibreGL` ([#338](https://github.com/maplibre/maplibre-gl-native/pull/338)). -- Build user agent based on `ClientOptions`, if available ([#365](https://github.com/maplibre/maplibre-gl-native/pull/365)). +- Rename to `QMapLibreGL` ([#338](https://github.com/maplibre/maplibre-native/pull/338)). +- Build user agent based on `ClientOptions`, if available ([#365](https://github.com/maplibre/maplibre-native/pull/365)). diff --git a/platform/qt/README.md b/platform/qt/README.md index 750fa9eeb2c..66e23864564 100644 --- a/platform/qt/README.md +++ b/platform/qt/README.md @@ -1,6 +1,6 @@ # MapLibre Native for Qt -[![GitHub Action build status](https://github.com/maplibre/maplibre-gl-native/workflows/qt-ci/badge.svg)](https://github.com/maplibre/maplibre-gl-native/actions/workflows/qt-ci.yml) +[![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/qt-ci/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/qt-ci.yml) This is a community maintained MapLibre SDK for usage in Qt apps. Both Qt5 (minimal 5.6) and Qt6 are supported. diff --git a/platform/windows/README.md b/platform/windows/README.md index 67a18eeb3c8..757bf303308 100644 --- a/platform/windows/README.md +++ b/platform/windows/README.md @@ -15,7 +15,7 @@ To install the required Visual Studio components, open Visual Studio Installer a Open `x64 Native Tools Command Prompt for VS 2022` and then clone the repository: ```cmd -git clone --recurse-submodules -j8 https://github.com/maplibre/maplibre-gl-native.git +git clone --recurse-submodules -j8 https://github.com/maplibre/maplibre-native.git cd maplibre-gl-native ``` diff --git a/test/actor/actor_ref.test.cpp b/test/actor/actor_ref.test.cpp index 66ed7237724..59917060317 100644 --- a/test/actor/actor_ref.test.cpp +++ b/test/actor/actor_ref.test.cpp @@ -104,7 +104,7 @@ TEST(ActorRef, AskOnDestroyedActor) { // the problem is that the ActorRef has a pointer to the actor // whose memory is managed by AspiringActor, which has been destroyed // mitigation would require getting rid of the raw pointer - // See https://github.com/maplibre/maplibre-gl-native/issues/876 + // See https://github.com/maplibre/maplibre-native/issues/876 // auto result = ref.ask(&TestActorRef::receive); // EXPECT_ANY_THROW(result.get()); From e4501c789d76ed335939d2fa7632b8089307665a Mon Sep 17 00:00:00 2001 From: Bart Louwers Date: Thu, 27 Apr 2023 22:08:02 +0200 Subject: [PATCH 02/21] Create security policy (#1080) --- SECURITY.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000000..05a48f0ebd5 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,8 @@ +# Security Policy + +To report a vulnerability in MapLibre Native, create a [security advisory](https://github.com/maplibre/maplibre-gl-native/security/advisories/new). +You will be able to privately discuss the issue with the maintainers of MapLibre Native and we can collaborate on a fix. + +We highly appreciate your reports, but we do not pay out bug bounties at this time. + +We will acknowledge your report in our newsletter with your consent. From 401cd790b4b5d109b355314ab640ac6aa19e1c86 Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Thu, 27 Apr 2023 15:29:18 -0700 Subject: [PATCH 03/21] warnings --- src/mbgl/gl/drawable_gl_builder.cpp | 10 +++++++--- src/mbgl/gl/vertex_attribute_gl.cpp | 4 ++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/mbgl/gl/drawable_gl_builder.cpp b/src/mbgl/gl/drawable_gl_builder.cpp index fb329408d6e..843e2abf386 100644 --- a/src/mbgl/gl/drawable_gl_builder.cpp +++ b/src/mbgl/gl/drawable_gl_builder.cpp @@ -24,9 +24,13 @@ void DrawableGLBuilder::init() { if (auto colorAttr = attrs.getOrAdd("a_color")) { std::size_t index = 0; for (const auto& color : impl->colors) { - const auto comp = util::convert(color.toArray()); - const auto norm = gfx::VertexAttribute::float4{comp[0]/255.f,comp[1]/255.f,comp[2]/255.f,comp[3]}; - colorAttr->set(index++, norm); + const auto comp = color.toArray(); + colorAttr->set(index++, gfx::VertexAttribute::float4 { + static_cast(comp[0]/255.0), + static_cast(comp[1]/255.0), + static_cast(comp[2]/255.0), + static_cast(comp[3]), + }); } } diff --git a/src/mbgl/gl/vertex_attribute_gl.cpp b/src/mbgl/gl/vertex_attribute_gl.cpp index efbe5277526..e8f7affbc80 100644 --- a/src/mbgl/gl/vertex_attribute_gl.cpp +++ b/src/mbgl/gl/vertex_attribute_gl.cpp @@ -116,7 +116,7 @@ const std::vector& VertexAttributeGL::getRaw(platform::GLenum type std::fill(rawData.begin(), rawData.end(), 0); if (!rawData.empty()) { - std::uint8_t* outPtr = &rawData[0]; + std::uint8_t* outPtr = rawData.data(); for (std::size_t i = 0; i < count; ++i) { if (!get(items[i], type, outPtr)) { // throw? @@ -143,7 +143,7 @@ namespace { template <> void applyUniform(GLint, const gfx::VertexAttribute::float4& ) { } template <> void applyUniform(GLint, const gfx::VertexAttribute::matf3& ) { } template <> void applyUniform(GLint location, const gfx::VertexAttribute::matf4& value) { - MBGL_CHECK_ERROR(glUniformMatrix4fv(location, 1, GL_FALSE, &value[0])); + MBGL_CHECK_ERROR(glUniformMatrix4fv(location, 1, GL_FALSE, value.data())); } } From 95c7e3818d1d8a7390a66c135d0cdbd962d9780f Mon Sep 17 00:00:00 2001 From: Tadej Novak Date: Fri, 28 Apr 2023 00:34:38 +0200 Subject: [PATCH 04/21] [cmake] Use MLN prefix instead of MBGL (#1054) Co-authored-by: Bart Louwers --- .github/actions/qt5-build/entrypoint.sh | 6 +- .github/actions/qt6-build/entrypoint.sh | 6 +- .github/workflows/android-ci-pull.yml | 2 +- .github/workflows/android-ci.yml | 2 +- .github/workflows/linux-ci.yml | 2 +- .github/workflows/qt-ci.yml | 12 +- BUILD.bazel | 2 +- CHANGELOG.md | 7 +- CMakeLists.txt | 82 +++++------ CONTRIBUTING.md | 4 +- DEVELOPING.md | 2 +- benchmark/CMakeLists.txt | 4 +- expression-test/CMakeLists.txt | 4 +- platform/android/Makefile | 128 +++++++++--------- platform/glfw/CMakeLists.txt | 10 +- platform/ios/ios-test-runners.cmake | 8 +- platform/ios/ios.cmake | 10 +- platform/ios/scripts/standalone.cmake | 4 +- platform/linux/linux.cmake | 18 +-- platform/macos/macos.cmake | 2 +- platform/node/CMakeLists.txt | 2 +- platform/node/DEVELOPING.md | 2 +- platform/node/cmake/module.cmake | 2 +- platform/qt/QMapLibreGLConfig.cmake.in | 2 +- platform/qt/README.md | 2 +- platform/qt/qt.cmake | 74 +++++----- .../scripts/configure_Qt5_Android_static.sh | 6 +- platform/qt/scripts/configure_Qt5_Linux.sh | 2 +- platform/qt/scripts/configure_Qt5_Windows.ps1 | 2 +- .../scripts/configure_Qt5_Windows_static.ps1 | 6 +- .../qt/scripts/configure_Qt5_iOS_static.sh | 6 +- platform/qt/scripts/configure_Qt5_macOS.sh | 2 +- .../qt/scripts/configure_Qt5_macOS_static.sh | 6 +- platform/qt/scripts/configure_Qt6_Windows.ps1 | 2 +- platform/qt/scripts/configure_Qt6_macOS.sh | 2 +- .../qt/scripts/configure_Qt6_macOS_static.sh | 6 +- platform/windows/README.md | 8 +- platform/windows/windows.cmake | 18 +-- test/CMakeLists.txt | 22 +-- vendor/csscolorparser.cmake | 2 +- vendor/nunicode.cmake | 2 +- vendor/parsedate.cmake | 2 +- vendor/sqlite.cmake | 4 +- 43 files changed, 249 insertions(+), 248 deletions(-) diff --git a/.github/actions/qt5-build/entrypoint.sh b/.github/actions/qt5-build/entrypoint.sh index 5aa2f884e98..6add42fe807 100755 --- a/.github/actions/qt5-build/entrypoint.sh +++ b/.github/actions/qt5-build/entrypoint.sh @@ -15,8 +15,8 @@ cmake ../source/ \ -DCMAKE_C_COMPILER_LAUNCHER="ccache" \ -DCMAKE_CXX_COMPILER_LAUNCHER="ccache" \ -DCMAKE_INSTALL_PREFIX=../install \ - -DMBGL_WITH_QT=ON \ - -DMBGL_QT_DEPLOYMENT=ON \ - -DMBGL_QT_LIBRARY_ONLY=ON + -DMLN_WITH_QT=ON \ + -DMLN_QT_DEPLOYMENT=ON \ + -DMLN_QT_LIBRARY_ONLY=ON ninja ninja install diff --git a/.github/actions/qt6-build/entrypoint.sh b/.github/actions/qt6-build/entrypoint.sh index 8dfd07c364e..8dce4ec6309 100755 --- a/.github/actions/qt6-build/entrypoint.sh +++ b/.github/actions/qt6-build/entrypoint.sh @@ -13,9 +13,9 @@ qt-cmake ../source/ \ -DCMAKE_C_COMPILER_LAUNCHER="ccache" \ -DCMAKE_CXX_COMPILER_LAUNCHER="ccache" \ -DCMAKE_INSTALL_PREFIX=../install \ - -DMBGL_WITH_QT=ON \ - -DMBGL_QT_DEPLOYMENT=ON \ - -DMBGL_QT_LIBRARY_ONLY=ON + -DMLN_WITH_QT=ON \ + -DMLN_QT_DEPLOYMENT=ON \ + -DMLN_QT_LIBRARY_ONLY=ON ninja ninja install cd ../install diff --git a/.github/workflows/android-ci-pull.yml b/.github/workflows/android-ci-pull.yml index df1e127e1ea..f2c9d960a9d 100644 --- a/.github/workflows/android-ci-pull.yml +++ b/.github/workflows/android-ci-pull.yml @@ -37,7 +37,7 @@ jobs: JOBS: 8 BUILDTYPE: Debug IS_LOCAL_DEVELOPMENT: false - MBGL_ANDROID_STL: c++_static + MLN_ANDROID_STL: c++_static steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/android-ci.yml b/.github/workflows/android-ci.yml index 4d97e693bc9..8d350a1aae1 100644 --- a/.github/workflows/android-ci.yml +++ b/.github/workflows/android-ci.yml @@ -34,7 +34,7 @@ jobs: JOBS: 8 BUILDTYPE: Debug IS_LOCAL_DEVELOPMENT: false - MBGL_ANDROID_STL: c++_static + MLN_ANDROID_STL: c++_static steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/linux-ci.yml b/.github/workflows/linux-ci.yml index c54b224eb2a..440be7ad94b 100644 --- a/.github/workflows/linux-ci.yml +++ b/.github/workflows/linux-ci.yml @@ -48,7 +48,7 @@ jobs: - name: Build Maplibre GL Core run: | cmake --version - cmake -B build -GNinja -DCMAKE_BUILD_TYPE=Debug -DMBGL_WITH_CLANG_TIDY=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DMBGL_WITH_COVERAGE=ON + cmake -B build -GNinja -DCMAKE_BUILD_TYPE=Debug -DMLN_WITH_CLANG_TIDY=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DMLN_WITH_COVERAGE=ON cmake --build build --target mbgl-core mbgl-test-runner mbgl-render-test-runner - name: Archive mbgl-test-runner diff --git a/.github/workflows/qt-ci.yml b/.github/workflows/qt-ci.yml index 5e3b7501d62..a377eaf91c1 100644 --- a/.github/workflows/qt-ci.yml +++ b/.github/workflows/qt-ci.yml @@ -194,9 +194,9 @@ jobs: -DCMAKE_INSTALL_PREFIX="../install" \ -DCMAKE_OSX_DEPLOYMENT_TARGET="${DEPLOYMENT_TARGET}" \ -DCMAKE_OSX_ARCHITECTURES="${DEPLOYMENT_ARCH}" \ - -DMBGL_WITH_QT=ON \ - -DMBGL_QT_DEPLOYMENT=ON \ - -DMBGL_QT_LIBRARY_ONLY=ON + -DMLN_WITH_QT=ON \ + -DMLN_QT_DEPLOYMENT=ON \ + -DMLN_QT_LIBRARY_ONLY=ON ninja ninja install @@ -221,9 +221,9 @@ jobs: -DCMAKE_C_COMPILER_LAUNCHER="ccache.exe" \ -DCMAKE_CXX_COMPILER_LAUNCHER="ccache.exe" \ -DCMAKE_INSTALL_PREFIX="../install" \ - -DMBGL_WITH_QT=ON \ - -DMBGL_QT_DEPLOYMENT=ON \ - -DMBGL_QT_LIBRARY_ONLY=ON + -DMLN_WITH_QT=ON \ + -DMLN_QT_DEPLOYMENT=ON \ + -DMLN_QT_LIBRARY_ONLY=ON ninja.exe ninja.exe install diff --git a/BUILD.bazel b/BUILD.bazel index dbb228827d9..ce601ad5ad1 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -26,7 +26,7 @@ cc_library( "src", ], local_defines = [ - r"MBGL_VERSION_REV=\"standalone\"", + r"MLN_VERSION_REV=\"standalone\"", ], visibility = ["//visibility:public"], deps = [ diff --git a/CHANGELOG.md b/CHANGELOG.md index d8bd7062a44..d9386628043 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,10 @@ ### ✨ New features - *...Add new stuff here...* -- [windows] Added windows build support for core applications and node [#707](https://github.com/maplibre/maplibre-native/pull/707) -- [core] Add `ClientOptions` to configure client information [#365](https://github.com/maplibre/maplibre-native/pull/365). -- [node] Add workflow to create node binary releases for Ubuntu 20.04 x64 and MacOS 12 x64/arm64 [#378](https://github.com/maplibre/maplibre-native/pull/378), [#459](https://github.com/maplibre/maplibre-native/pull/459). +- [core] All CMake properties are now prefixed `MLN_*` [1054](https://github.com/maplibre/maplibre-gl-native/pull/1054). +- [windows] Added windows build support for core applications and node [#707](https://github.com/maplibre/maplibre-gl-native/pull/707) +- [core] Add `ClientOptions` to configure client information [#365](https://github.com/maplibre/maplibre-gl-native/pull/365). +- [node] Add workflow to create node binary releases for Ubuntu 20.04 x64 and MacOS 12 x64/arm64 [#378](https://github.com/maplibre/maplibre-gl-native/pull/378), [#459](https://github.com/maplibre/maplibre-gl-native/pull/459). ### ✨ Technical Improvements diff --git a/CMakeLists.txt b/CMakeLists.txt index 49905a6343c..09236d50475 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,18 +1,18 @@ cmake_minimum_required(VERSION 3.10 FATAL_ERROR) -option(MBGL_WITH_CORE_ONLY "Build only the core bits, no platform code" OFF) -option(MBGL_WITH_CLANG_TIDY "Build with clang-tidy checks enabled" OFF) -option(MBGL_WITH_COVERAGE "Enable code coverage collection" OFF) -option(MBGL_WITH_QT "Build MapLibre Native Qt bindings" OFF) +option(MLN_WITH_CORE_ONLY "Build only the core bits, no platform code" OFF) +option(MLN_WITH_CLANG_TIDY "Build with clang-tidy checks enabled" OFF) +option(MLN_WITH_COVERAGE "Enable code coverage collection" OFF) +option(MLN_WITH_QT "Build MapLibre Native Qt bindings" OFF) option(MLN_WITH_NODE "Build MapLibre Native Node.js bindings" OFF) -option(MBGL_WITH_SANITIZER "Use [address|thread|undefined] here" OFF) -option(MBGL_WITH_RTTI "Compile with runtime type information" OFF) -option(MBGL_WITH_OPENGL "Build with OpenGL renderer" ON) -option(MBGL_WITH_EGL "Build with EGL renderer" OFF) -option(MBGL_WITH_OSMESA "Build with OSMesa (Software) renderer" OFF) -option(MBGL_WITH_WERROR "Make all compilation warnings errors" ON) +option(MLN_WITH_SANITIZER "Use [address|thread|undefined] here" OFF) +option(MLN_WITH_RTTI "Compile with runtime type information" OFF) +option(MLN_WITH_OPENGL "Build with OpenGL renderer" ON) +option(MLN_WITH_EGL "Build with EGL renderer" OFF) +option(MLN_WITH_OSMESA "Build with OSMesa (Software) renderer" OFF) +option(MLN_WITH_WERROR "Make all compilation warnings errors" ON) -if (MBGL_WITH_CLANG_TIDY) +if (MLN_WITH_CLANG_TIDY) find_program(CLANG_TIDY_COMMAND NAMES clang-tidy) if(NOT CLANG_TIDY_COMMAND) message(FATAL_ERROR "ENABLE_CLANG_TIDY is ON but clang-tidy is not found!") @@ -25,11 +25,11 @@ if (MBGL_WITH_CLANG_TIDY) set(CLANG_TIDY_COMMAND "${CLANG_TIDY_COMMAND};--extra-arg=-Wno-error=unknown-warning-option") endif() -if (MBGL_WITH_QT AND NOT CMAKE_OSX_DEPLOYMENT_TARGET) +if (MLN_WITH_QT AND NOT CMAKE_OSX_DEPLOYMENT_TARGET) set(CMAKE_OSX_DEPLOYMENT_TARGET 13.0) endif() -if(WIN32 AND NOT MBGL_WITH_QT) +if(WIN32 AND NOT MLN_WITH_QT) set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_LIST_DIR}/platform/windows/custom-toolchain.cmake) endif() @@ -58,35 +58,35 @@ set(UBSAN_BLACKLIST ${PROJECT_SOURCE_DIR}/scripts/ubsan.blacklist) target_compile_options( mbgl-compiler-options INTERFACE - $<$:--coverage> - $<$:-DSANITIZE> - $<$:-fno-omit-frame-pointer> - $<$:-fno-optimize-sibling-calls> - $<$:-fsanitize=address> - $<$:-fsanitize=thread> - $<$:-fsanitize=implicit-conversion, + $<$:--coverage> + $<$:-DSANITIZE> + $<$:-fno-omit-frame-pointer> + $<$:-fno-optimize-sibling-calls> + $<$:-fsanitize=address> + $<$:-fsanitize=thread> + $<$:-fsanitize=implicit-conversion, -fsanitize-blacklist=${UBSAN_BLACKLIST}> - $<$:-fsanitize=undefined, + $<$:-fsanitize=undefined, -fsanitize-blacklist=${UBSAN_BLACKLIST}> - $<$:-fsanitize=unsigned-integer-overflow, + $<$:-fsanitize=unsigned-integer-overflow, -fsanitize-blacklist=${UBSAN_BLACKLIST}> - $<$:-fsanitize=nullability, + $<$:-fsanitize=nullability, -fsanitize-blacklist=${UBSAN_BLACKLIST}> - $<$:-fsanitize=float-divide-by-zero, + $<$:-fsanitize=float-divide-by-zero, -fsanitize-blacklist=${UBSAN_BLACKLIST}> $<$:-fembed-bitcode> - $<$,$,$>>>:-fno-rtti> + $<$,$,$>>>:-fno-rtti> $<$,$>>:-Wall> $<$,$>>:-Wshadow> $<$,$>>:-Wextra> - $<$,$>,$>:-Werror> + $<$,$>,$>:-Werror> $<$,$>:-Wno-error=tautological-constant-compare> $<$:-Wno-error=maybe-uninitialized> $<$:-Wno-error=return-type> $<$:-Wno-error=unknown-pragmas> - $<$,$>>:-Wno-error=deprecated-declarations> - $<$,$>>:-Wno-error=unused-parameter> - $<$,$>>:-Wno-error=unused-property-ivar> + $<$,$>>:-Wno-error=deprecated-declarations> + $<$,$>>:-Wno-error=unused-parameter> + $<$,$>>:-Wno-error=unused-property-ivar> $<$:/utf-8> $<$:/WX> # all warnings as errors $<$:/EHsc> # exceptions @@ -100,10 +100,10 @@ target_compile_options( target_link_libraries( mbgl-compiler-options INTERFACE - $<$:--coverage> - $<$:-fsanitize=address> - $<$:-fsanitize=thread> - $<$:-fsanitize=undefined> + $<$:--coverage> + $<$:-fsanitize=address> + $<$:-fsanitize=thread> + $<$:-fsanitize=undefined> ) cmake_policy(SET CMP0063 NEW) @@ -124,7 +124,7 @@ set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_MINSIZEREL ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON) set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) -if(MBGL_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") +if(MLN_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") add_library(mbgl-core OBJECT) else() add_library(mbgl-core STATIC) @@ -871,7 +871,7 @@ list(APPEND SRC_FILES ${PROJECT_SOURCE_DIR}/src/mbgl/util/work_request.cpp ) -if(MBGL_WITH_OPENGL) +if(MLN_WITH_OPENGL) message(STATUS "Configuring GL-Native with OpenGL renderer backend") target_compile_definitions( mbgl-core @@ -984,7 +984,7 @@ target_sources( ${SRC_FILES} ) -if (MBGL_WITH_CLANG_TIDY) +if (MLN_WITH_CLANG_TIDY) set_target_properties(mbgl-core PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() @@ -999,18 +999,18 @@ if(EXISTS ${PROJECT_SOURCE_DIR}/.git/HEAD) --short=8 HEAD WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - OUTPUT_VARIABLE MBGL_VERSION_REV + OUTPUT_VARIABLE MLN_VERSION_REV OUTPUT_STRIP_TRAILING_WHITESPACE ) else() - set(MBGL_VERSION_REV 00000000) + set(MLN_VERSION_REV 00000000) endif() set_source_files_properties( ${PROJECT_SOURCE_DIR}/src/mbgl/util/version.cpp PROPERTIES COMPILE_DEFINITIONS - MBGL_VERSION_REV="${MBGL_VERSION_REV}" + MBGL_VERSION_REV="${MLN_VERSION_REV}" ) target_include_directories( @@ -1110,13 +1110,13 @@ add_library( Mapbox::Map ALIAS mbgl-core ) -if(MBGL_WITH_CORE_ONLY) +if(MLN_WITH_CORE_ONLY) return() endif() include(${PROJECT_SOURCE_DIR}/scripts/license.cmake) -if(MBGL_WITH_QT) +if(MLN_WITH_QT) include(${PROJECT_SOURCE_DIR}/platform/qt/qt.cmake) elseif(CMAKE_SYSTEM_NAME STREQUAL Android) include(${PROJECT_SOURCE_DIR}/platform/android/android.cmake) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index efe31aaa6d4..b7936f8684e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,11 +17,11 @@ MapLibre Native shares a single C++ core library with all platforms. To build it To build, run the following from the root directory ```bash -cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DMBGL_WITH_CORE_ONLY=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DMBGL_WITH_COVERAGE=ON +cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DMLN_WITH_CORE_ONLY=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DMLN_WITH_COVERAGE=ON ``` `CMAKE_BUILD_TYPE=Debug` will build debug artifacts. You can opt to omit it if that is not necessary. -`MBGL_WITH_CORE_ONLY=ON` will build only the core libraries. +`MLN_WITH_CORE_ONLY=ON` will build only the core libraries. Built artifacts should be available on `build` folder. diff --git a/DEVELOPING.md b/DEVELOPING.md index 2d6ffed3e4c..a92594ba23a 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -76,7 +76,7 @@ or any of the platform make files: * iOS developers can use [Xcode](https://developer.apple.com/support/debugging/). See also [Advanced Debugging with Xcode and LLDB](https://developer.apple.com/videos/play/wwdc2018/412/). ## Static Analysis -We use [`clang-tidy`](https://clang.llvm.org/extra/clang-tidy/) for static analysis and run it on CI for each pull request. If you want to run it locally use `-DMBGL_WITH_CLANG_TIDY=ON` CMake option and just run regular build. For the list of enabled checks please see: +We use [`clang-tidy`](https://clang.llvm.org/extra/clang-tidy/) for static analysis and run it on CI for each pull request. If you want to run it locally use `-DMLN_WITH_CLANG_TIDY=ON` CMake option and just run regular build. For the list of enabled checks please see: [`.clang-tidy`](.clang-tidy) and [`test/.clang-tidy`](test/.clang-tidy)(for tests we are less strict and use different set of checks). ## Logging in C++ diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt index 8b6d28f5940..7ffb01cdb81 100644 --- a/benchmark/CMakeLists.txt +++ b/benchmark/CMakeLists.txt @@ -52,11 +52,11 @@ if(CMAKE_SYSTEM_NAME STREQUAL Darwin) endif() # Needed for testing private classes -get_target_property(MBGL_CORE_PRIVATE_LIBRARIES mbgl-core LINK_LIBRARIES) +get_target_property(MLN_CORE_PRIVATE_LIBRARIES mbgl-core LINK_LIBRARIES) target_link_libraries( mbgl-benchmark - PRIVATE ${MBGL_CORE_PRIVATE_LIBRARIES} mbgl-vendor-benchmark mbgl-compiler-options + PRIVATE ${MLN_CORE_PRIVATE_LIBRARIES} mbgl-vendor-benchmark mbgl-compiler-options PUBLIC mbgl-core ) diff --git a/expression-test/CMakeLists.txt b/expression-test/CMakeLists.txt index 19597520586..c6a2f5b9195 100644 --- a/expression-test/CMakeLists.txt +++ b/expression-test/CMakeLists.txt @@ -34,10 +34,10 @@ target_link_libraries( set_property(TARGET mbgl-expression-test PROPERTY FOLDER Executables) -string(RANDOM LENGTH 5 ALPHABET 0123456789 MBGL_EXPRESSION_TEST_SEED) +string(RANDOM LENGTH 5 ALPHABET 0123456789 MLN_EXPRESSION_TEST_SEED) add_test( NAME mbgl-expression-test - COMMAND mbgl-expression-test -s --seed=${MBGL_EXPRESSION_TEST_SEED} + COMMAND mbgl-expression-test -s --seed=${MLN_EXPRESSION_TEST_SEED} WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} ) diff --git a/platform/android/Makefile b/platform/android/Makefile index fd108eba1be..81bc2dc97b0 100644 --- a/platform/android/Makefile +++ b/platform/android/Makefile @@ -31,23 +31,23 @@ endif #### Android targets ########################################################### -MBGL_ANDROID_ABIS = arm-v7;armeabi-v7a -MBGL_ANDROID_ABIS += arm-v8;arm64-v8a -MBGL_ANDROID_ABIS += x86;x86 -MBGL_ANDROID_ABIS += x86-64;x86_64 - -MBGL_ANDROID_LOCAL_WORK_DIR = /data/local/tmp/core-tests -MBGL_ANDROID_LOCAL_BENCHMARK_DIR = /data/local/tmp/benchmark -MBGL_ANDROID_LIBDIR = lib$(if $(filter arm-v8 x86-64,$1),64) -MBGL_ANDROID_DALVIKVM = dalvikvm$(if $(filter arm-v8 x86-64,$1),64,32) -MBGL_ANDROID_APK_SUFFIX = $(if $(filter Release,$(BUILDTYPE)),release,debug) -MBGL_ANDROID_CORE_TEST_DIR = MapboxGLAndroidSDK/.externalNativeBuild/cmake/$(buildtype)/$2/core-tests -MBGL_ANDROID_BENCHMARK_DIR = MapboxGLAndroidSDK/.externalNativeBuild/cmake/$(buildtype)/$2/benchmark -MBGL_ANDROID_STL ?= c++_static +MLN_ANDROID_ABIS = arm-v7;armeabi-v7a +MLN_ANDROID_ABIS += arm-v8;arm64-v8a +MLN_ANDROID_ABIS += x86;x86 +MLN_ANDROID_ABIS += x86-64;x86_64 + +MLN_ANDROID_LOCAL_WORK_DIR = /data/local/tmp/core-tests +MLN_ANDROID_LOCAL_BENCHMARK_DIR = /data/local/tmp/benchmark +MLN_ANDROID_LIBDIR = lib$(if $(filter arm-v8 x86-64,$1),64) +MLN_ANDROID_DALVIKVM = dalvikvm$(if $(filter arm-v8 x86-64,$1),64,32) +MLN_ANDROID_APK_SUFFIX = $(if $(filter Release,$(BUILDTYPE)),release,debug) +MLN_ANDROID_CORE_TEST_DIR = MapboxGLAndroidSDK/.externalNativeBuild/cmake/$(buildtype)/$2/core-tests +MLN_ANDROID_BENCHMARK_DIR = MapboxGLAndroidSDK/.externalNativeBuild/cmake/$(buildtype)/$2/benchmark +MLN_ANDROID_STL ?= c++_static SOCKET_TIMEOUT = 360000 CONNECTION_TIMEOUT = 360000 -MBGL_ANDROID_GRADLE = ./gradlew --parallel --max-workers=$(JOBS) -Pmapbox.buildtype=$(buildtype) -Pmapbox.stl=$(MBGL_ANDROID_STL) -Dorg.gradle.internal.http.socketTimeout=$(SOCKET_TIMEOUT) -Dorg.gradle.internal.http.connectionTimeout=$(CONNECTION_TIMEOUT) -MBGL_ANDROID_GRADLE_SINGLE_JOB = ./gradlew --parallel --max-workers=1 -Pmapbox.buildtype=$(buildtype) -Pmapbox.stl=$(MBGL_ANDROID_STL) -Dorg.gradle.internal.http.socketTimeout=$(SOCKET_TIMEOUT) -Dorg.gradle.internal.http.connectionTimeout=$(CONNECTION_TIMEOUT) +MLN_ANDROID_GRADLE = ./gradlew --parallel --max-workers=$(JOBS) -Pmapbox.buildtype=$(buildtype) -Pmapbox.stl=$(MLN_ANDROID_STL) -Dorg.gradle.internal.http.socketTimeout=$(SOCKET_TIMEOUT) -Dorg.gradle.internal.http.connectionTimeout=$(CONNECTION_TIMEOUT) +MLN_ANDROID_GRADLE_SINGLE_JOB = ./gradlew --parallel --max-workers=1 -Pmapbox.buildtype=$(buildtype) -Pmapbox.stl=$(MLN_ANDROID_STL) -Dorg.gradle.internal.http.socketTimeout=$(SOCKET_TIMEOUT) -Dorg.gradle.internal.http.connectionTimeout=$(CONNECTION_TIMEOUT) # Generate code based on the style specification .PHONY: android-style-code @@ -61,51 +61,51 @@ define ANDROID_RULES .PHONY: android-test-lib-$1 android-test-lib-$1: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 -Pmapbox.with_test=true :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 -Pmapbox.with_test=true :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) .PHONY: android-benchmark-$1 android-benchmark-$1: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 -Pmapbox.with_benchmark=true :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 -Pmapbox.with_benchmark=true :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) # Build SDK for for specified abi .PHONY: android-lib-$1 android-lib-$1: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDK:assemble$(BUILDTYPE) + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDK:assemble$(BUILDTYPE) # Build test app and SDK for for specified abi .PHONY: android-$1 android-$1: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) # Build the core test for specified abi .PHONY: android-core-test-$1 android-core-test-$1: android-test-lib-$1 # Compile main sources and extract the classes (using the test app to get all transitive dependencies in one place) - mkdir -p $(MBGL_ANDROID_CORE_TEST_DIR) - unzip -o MapboxGLAndroidSDKTestApp/build/outputs/apk/$(buildtype)/MapboxGLAndroidSDKTestApp-$(MBGL_ANDROID_APK_SUFFIX).apk classes.dex -d $(MBGL_ANDROID_CORE_TEST_DIR) + mkdir -p $(MLN_ANDROID_CORE_TEST_DIR) + unzip -o MapboxGLAndroidSDKTestApp/build/outputs/apk/$(buildtype)/MapboxGLAndroidSDKTestApp-$(MLN_ANDROID_APK_SUFFIX).apk classes.dex -d $(MLN_ANDROID_CORE_TEST_DIR) run-android-core-test-$1-%: android-core-test-$1 # Ensure clean state on the device - adb shell "rm -Rf $(MBGL_ANDROID_LOCAL_WORK_DIR) && mkdir -p $(MBGL_ANDROID_LOCAL_WORK_DIR)/test && mkdir -p $(MBGL_ANDROID_LOCAL_WORK_DIR)/scripts/style-spec-reference" + adb shell "rm -Rf $(MLN_ANDROID_LOCAL_WORK_DIR) && mkdir -p $(MLN_ANDROID_LOCAL_WORK_DIR)/test && mkdir -p $(MLN_ANDROID_LOCAL_WORK_DIR)/scripts/style-spec-reference" # Push all needed files to the device - adb push $(MBGL_ANDROID_CORE_TEST_DIR)/classes.dex $(MBGL_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 - adb push MapboxGLAndroidSDK/build/intermediates/intermediate-jars/$(buildtype)/jni/$2/libmapbox-gl.so $(MBGL_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 - adb push test/fixtures $(MBGL_ANDROID_LOCAL_WORK_DIR)/test > /dev/null 2>&1 - adb push scripts/style-spec-reference/v8.json $(MBGL_ANDROID_LOCAL_WORK_DIR)/scripts/style-spec-reference > /dev/null 2>&1 - adb push MapboxGLAndroidSDK/build/intermediates/cmake/$(buildtype)/obj/$2/mbgl-test $(MBGL_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 + adb push $(MLN_ANDROID_CORE_TEST_DIR)/classes.dex $(MLN_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 + adb push MapboxGLAndroidSDK/build/intermediates/intermediate-jars/$(buildtype)/jni/$2/libmapbox-gl.so $(MLN_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 + adb push test/fixtures $(MLN_ANDROID_LOCAL_WORK_DIR)/test > /dev/null 2>&1 + adb push scripts/style-spec-reference/v8.json $(MLN_ANDROID_LOCAL_WORK_DIR)/scripts/style-spec-reference > /dev/null 2>&1 + adb push MapboxGLAndroidSDK/build/intermediates/cmake/$(buildtype)/obj/$2/mbgl-test $(MLN_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 # Create gtest filter for skipped tests. $(eval SKIPPED_TESTS := -$(shell sed -n '/#\|^$$/!p' tests/skipped.txt | sed ':a;$!N;s/\n/:/g;ta')) # Kick off the tests - adb shell "export LD_LIBRARY_PATH=$(MBGL_ANDROID_LOCAL_WORK_DIR) && cd $(MBGL_ANDROID_LOCAL_WORK_DIR) && chmod +x mbgl-test && ./mbgl-test --class_path=$(MBGL_ANDROID_LOCAL_WORK_DIR)/classes.dex --gtest_filter=$$*:$(SKIPPED_TESTS)" + adb shell "export LD_LIBRARY_PATH=$(MLN_ANDROID_LOCAL_WORK_DIR) && cd $(MLN_ANDROID_LOCAL_WORK_DIR) && chmod +x mbgl-test && ./mbgl-test --class_path=$(MLN_ANDROID_LOCAL_WORK_DIR)/classes.dex --gtest_filter=$$*:$(SKIPPED_TESTS)" # Gather the results and unpack them - adb shell "cd $(MBGL_ANDROID_LOCAL_WORK_DIR) && tar -cvzf results.tgz test/fixtures/* > /dev/null 2>&1" - adb pull $(MBGL_ANDROID_LOCAL_WORK_DIR)/results.tgz $(MBGL_ANDROID_CORE_TEST_DIR)/ > /dev/null 2>&1 - rm -rf $(MBGL_ANDROID_CORE_TEST_DIR)/results && mkdir -p $(MBGL_ANDROID_CORE_TEST_DIR)/results - tar -xzf $(MBGL_ANDROID_CORE_TEST_DIR)/results.tgz --strip-components=2 -C $(MBGL_ANDROID_CORE_TEST_DIR)/results + adb shell "cd $(MLN_ANDROID_LOCAL_WORK_DIR) && tar -cvzf results.tgz test/fixtures/* > /dev/null 2>&1" + adb pull $(MLN_ANDROID_LOCAL_WORK_DIR)/results.tgz $(MLN_ANDROID_CORE_TEST_DIR)/ > /dev/null 2>&1 + rm -rf $(MLN_ANDROID_CORE_TEST_DIR)/results && mkdir -p $(MLN_ANDROID_CORE_TEST_DIR)/results + tar -xzf $(MLN_ANDROID_CORE_TEST_DIR)/results.tgz --strip-components=2 -C $(MLN_ANDROID_CORE_TEST_DIR)/results # Run the core test for specified abi .PHONY: run-android-core-test-$1 @@ -116,47 +116,47 @@ run-android-core-test-$1: run-android-core-test-$1-* run-android-benchmark-$1: run-android-benchmark-$1-* run-android-benchmark-$1-%: android-benchmark-$1 - mkdir -p $(MBGL_ANDROID_BENCHMARK_DIR) - unzip -o MapboxGLAndroidSDKTestApp/build/outputs/apk/$(buildtype)/MapboxGLAndroidSDKTestApp-$(MBGL_ANDROID_APK_SUFFIX).apk classes.dex -d $(MBGL_ANDROID_BENCHMARK_DIR) + mkdir -p $(MLN_ANDROID_BENCHMARK_DIR) + unzip -o MapboxGLAndroidSDKTestApp/build/outputs/apk/$(buildtype)/MapboxGLAndroidSDKTestApp-$(MLN_ANDROID_APK_SUFFIX).apk classes.dex -d $(MLN_ANDROID_BENCHMARK_DIR) # Delete old test folder and create new one - adb shell "rm -Rf $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) && mkdir -p $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/benchmark && mkdir -p $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/test" + adb shell "rm -Rf $(MLN_ANDROID_LOCAL_BENCHMARK_DIR) && mkdir -p $(MLN_ANDROID_LOCAL_BENCHMARK_DIR)/benchmark && mkdir -p $(MLN_ANDROID_LOCAL_BENCHMARK_DIR)/test" # Push compiled java sources, test data and executable to device - adb push $(MBGL_ANDROID_BENCHMARK_DIR)/classes.dex $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 - adb push MapboxGLAndroidSDK/build/intermediates/intermediate-jars/$(buildtype)/jni/$2/libmapbox-gl.so $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 - adb push benchmark/fixtures $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/benchmark > /dev/null 2>&1 - adb push test/fixtures $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/test > /dev/null 2>&1 - adb push MapboxGLAndroidSDK/build/intermediates/cmake/$(buildtype)/obj/$2/mbgl-benchmark $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 + adb push $(MLN_ANDROID_BENCHMARK_DIR)/classes.dex $(MLN_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 + adb push MapboxGLAndroidSDK/build/intermediates/intermediate-jars/$(buildtype)/jni/$2/libmapbox-gl.so $(MLN_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 + adb push benchmark/fixtures $(MLN_ANDROID_LOCAL_BENCHMARK_DIR)/benchmark > /dev/null 2>&1 + adb push test/fixtures $(MLN_ANDROID_LOCAL_BENCHMARK_DIR)/test > /dev/null 2>&1 + adb push MapboxGLAndroidSDK/build/intermediates/cmake/$(buildtype)/obj/$2/mbgl-benchmark $(MLN_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 # Run benchmark. Number of benchmark iterations can be set by run-android-benchmark-N parameter. - adb shell "export LD_LIBRARY_PATH=$(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) && cd $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) && chmod +x mbgl-benchmark && ./mbgl-benchmark --class_path=$(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/classes.dex --benchmark_repetitions=$$* --benchmark_format=json --benchmark_out=results.json" + adb shell "export LD_LIBRARY_PATH=$(MLN_ANDROID_LOCAL_BENCHMARK_DIR) && cd $(MLN_ANDROID_LOCAL_BENCHMARK_DIR) && chmod +x mbgl-benchmark && ./mbgl-benchmark --class_path=$(MLN_ANDROID_LOCAL_BENCHMARK_DIR)/classes.dex --benchmark_repetitions=$$* --benchmark_format=json --benchmark_out=results.json" # Pull results.json from the device - rm -rf $(MBGL_ANDROID_BENCHMARK_DIR)/results && mkdir -p $(MBGL_ANDROID_BENCHMARK_DIR)/results - adb pull $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/results.json $(MBGL_ANDROID_BENCHMARK_DIR)/results > /dev/null 2>&1 + rm -rf $(MLN_ANDROID_BENCHMARK_DIR)/results && mkdir -p $(MLN_ANDROID_BENCHMARK_DIR)/results + adb pull $(MLN_ANDROID_LOCAL_BENCHMARK_DIR)/results.json $(MLN_ANDROID_BENCHMARK_DIR)/results > /dev/null 2>&1 # Run the test app on connected android device with specified abi .PHONY: run-android-$1 run-android-$1: -adb uninstall com.mapbox.mapboxsdk.testapp 2> /dev/null - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:install$(BUILDTYPE) && adb shell am start -n com.mapbox.mapboxsdk.testapp/.activity.FeatureOverviewActivity + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:install$(BUILDTYPE) && adb shell am start -n com.mapbox.mapboxsdk.testapp/.activity.FeatureOverviewActivity # Build test app instrumentation tests apk and test app apk for specified abi .PHONY: android-ui-test-$1 android-ui-test-$1: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:assembleDebug :MapboxGLAndroidSDKTestApp:assembleAndroidTest + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:assembleDebug :MapboxGLAndroidSDKTestApp:assembleAndroidTest # Run test app instrumentation tests on a connected android device or emulator with specified abi .PHONY: run-android-ui-test-$1 run-android-ui-test-$1: -adb uninstall com.mapbox.mapboxsdk.testapp 2> /dev/null - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest # Run Java Instrumentation tests on a connected android device or emulator with specified abi and test filter run-android-ui-test-$1-%: -adb uninstall com.mapbox.mapboxsdk.testapp 2> /dev/null - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class="$$*" + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class="$$*" # Symbolicate native stack trace with the specified abi .PHONY: android-ndk-stack-$1 @@ -174,7 +174,7 @@ run-android-render-test-$1: $(BUILD_DEPS) cp -r metrics/integration MapboxGLAndroidSDKTestApp/src/main/assets cp platform/node/test/ignores.json MapboxGLAndroidSDKTestApp/src/main/assets/integration/ignores.json # run RenderTest.java to generate static map images - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class="com.mapbox.mapboxsdk.testapp.render.RenderTest" + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class="com.mapbox.mapboxsdk.testapp.render.RenderTest" # pull generated images from the device adb pull "`adb shell 'printenv EXTERNAL_STORAGE' | tr -d '\r'`/mapbox/render" build/render-test # copy expected result and run pixelmatch @@ -189,7 +189,7 @@ define ANDROID_RULES_INVOKER $(call ANDROID_RULES,$(word 1,$1),$(word 2,$1)) endef -$(foreach abi,$(MBGL_ANDROID_ABIS),$(eval $(call ANDROID_RULES_INVOKER,$(subst ;, ,$(abi))))) +$(foreach abi,$(MLN_ANDROID_ABIS),$(eval $(call ANDROID_RULES_INVOKER,$(subst ;, ,$(abi))))) # Build the Android SDK and test app with abi set to arm-v7 .PHONY: android @@ -211,20 +211,20 @@ run-android-ui-test-%: run-android-ui-test-arm-v7-% # Run Java Unit tests on the JVM of the development machine executing this .PHONY: run-android-unit-test run-android-unit-test: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:testDebugUnitTest --info + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:testDebugUnitTest --info run-android-unit-test-%: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:testDebugUnitTest --info --tests "$*" + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:testDebugUnitTest --info --tests "$*" # Builds a release package of the Android SDK .PHONY: apackage apackage: make android-lib-arm-v7 && make android-lib-arm-v8 && make android-lib-x86 && make android-lib-x86-64 - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=all assemble$(BUILDTYPE) + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=all assemble$(BUILDTYPE) # Build test app instrumentation tests apk and test app apk for all abi's .PHONY: android-ui-test android-ui-test: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=all :MapboxGLAndroidSDKTestApp:assembleDebug :MapboxGLAndroidSDKTestApp:assembleAndroidTest + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=all :MapboxGLAndroidSDKTestApp:assembleDebug :MapboxGLAndroidSDKTestApp:assembleAndroidTest #Run instrumentations tests on MicroSoft App Center, ${devices} can be "xiaomi","huawei","OnePlus","htc" .PHONY: run-android-test-app-center @@ -234,7 +234,7 @@ run-android-test-app-center: # Uploads the compiled Android SDK to Maven Central Staging .PHONY: run-android-publish run-android-publish: - $(MBGL_ANDROID_GRADLE_SINGLE_JOB) -Pmapbox.abis=all :MapboxGLAndroidSDK:publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepository + $(MLN_ANDROID_GRADLE_SINGLE_JOB) -Pmapbox.abis=all :MapboxGLAndroidSDK:publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepository # Dump system graphics information for the test app .PHONY: android-gfxinfo @@ -248,32 +248,32 @@ android-check : android-ktlint android-checkstyle android-lint-sdk android-lint- # Runs checkstyle on the java code .PHONY: android-checkstyle android-checkstyle: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:checkstyle :MapboxGLAndroidSDKTestApp:checkstyle + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:checkstyle :MapboxGLAndroidSDKTestApp:checkstyle # Runs checkstyle on the kotlin code .PHONY: android-ktlint android-ktlint: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none checkstyle + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none checkstyle # Runs lint on the Android SDK java code .PHONY: android-lint-sdk android-lint-sdk: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:lint + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:lint # Runs lint on the Android test app java code .PHONY: android-lint-test-app android-lint-test-app: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDKTestApp:lint + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDKTestApp:lint # Generates javadoc from the Android SDK .PHONY: android-javadoc android-javadoc: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:javadocrelease + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:javadocrelease # Generates LICENSE.md file based on all Android project dependencies .PHONY: android-license android-license: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:licenseReleaseReport + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:licenseReleaseReport python scripts/generate-license.py # Symbolicate ndk stack traces for the arm-v7 abi @@ -283,22 +283,22 @@ android-ndk-stack: android-ndk-stack-arm-v7 # Updates Android's vendor submodules .PHONY: android-update-vendor android-update-vendor: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none updateVendorSubmodules + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none updateVendorSubmodules # Run android nitpick script .PHONY: run-android-nitpick run-android-nitpick: android-update-vendor - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none androidNitpick + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none androidNitpick # Creates a dependency graph using Graphviz .PHONY: android-graph android-graph: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:generateDependencyGraphMapboxLibraries + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:generateDependencyGraphMapboxLibraries # Lists tasks .PHONY: list-tasks list-tasks: - $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=all tasks + $(MLN_ANDROID_GRADLE) -Pmapbox.abis=all tasks #### Miscellaneous targets ##################################################### diff --git a/platform/glfw/CMakeLists.txt b/platform/glfw/CMakeLists.txt index 721c727cf55..bbfb88afeb6 100644 --- a/platform/glfw/CMakeLists.txt +++ b/platform/glfw/CMakeLists.txt @@ -1,8 +1,8 @@ find_package(OpenGL REQUIRED) if(WIN32) - if(MBGL_WITH_OSMESA) - message(WARNING "mbgl-glfw does not work with -DMBGL_WITH_OSMESA=ON. If you want to build this target, don't use this option.") + if(MLN_WITH_OSMESA) + message(WARNING "mbgl-glfw does not work with -DMLN_WITH_OSMESA=ON. If you want to build this target, don't use this option.") return() endif() @@ -29,7 +29,7 @@ set_property( PROPERTY COMPILE_DEFINITIONS MAPBOX_PUCK_ASSETS_PATH=\"${PROJECT_SOURCE_DIR}/platform/glfw/assets/\" ) -if(MBGL_WITH_OPENGL) +if(MLN_WITH_OPENGL) target_sources( mbgl-glfw PRIVATE ${PROJECT_SOURCE_DIR}/platform/glfw/glfw_gl_backend.cpp @@ -40,7 +40,7 @@ if(MBGL_WITH_OPENGL) ) endif() -if(MBGL_WITH_EGL) +if(MLN_WITH_EGL) target_compile_definitions( mbgl-glfw PRIVATE MBGL_WITH_EGL=1 @@ -94,7 +94,7 @@ target_link_libraries( Mapbox::Base::cheap-ruler-cpp ) -if(NOT WIN32 AND MBGL_WITH_OPENGL) +if(NOT WIN32 AND MLN_WITH_OPENGL) target_link_libraries( mbgl-glfw PRIVATE OpenGL::GL diff --git a/platform/ios/ios-test-runners.cmake b/platform/ios/ios-test-runners.cmake index 6e94d25d6a5..94d2ad7bd3b 100644 --- a/platform/ios/ios-test-runners.cmake +++ b/platform/ios/ios-test-runners.cmake @@ -1,8 +1,8 @@ -if(MBGL_IOS_RENDER_TEST) +if(MLN_IOS_RENDER_TEST) include(${PROJECT_SOURCE_DIR}/vendor/zip-archive.cmake) initialize_ios_target(mbgl-vendor-zip-archive) - if(MBGL_WITH_OPENGL) + if(MLN_WITH_OPENGL) message(STATUS "Setting up test data for iOS render test with OpenGL renderer") set(PREPARE_CMD "${PROJECT_SOURCE_DIR}/render-test/ios/setup_test_data.sh") endif() @@ -87,7 +87,7 @@ if(MBGL_IOS_RENDER_TEST) set_target_properties(RenderTestAppTests PROPERTIES XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO") endif() -if(MBGL_IOS_UNIT_TEST) +if(MLN_IOS_UNIT_TEST) execute_process(COMMAND ditto ${PROJECT_SOURCE_DIR}/test/fixtures ${CMAKE_CURRENT_BINARY_DIR}/test-data/test/fixtures) execute_process( COMMAND @@ -159,7 +159,7 @@ if(MBGL_IOS_UNIT_TEST) set_target_properties(UnitTestsAppTests PROPERTIES XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO") endif() -if(MBGL_IOS_BENCHMARK) +if(MLN_IOS_BENCHMARK) execute_process(COMMAND ditto ${PROJECT_SOURCE_DIR}/benchmark/fixtures ${CMAKE_CURRENT_BINARY_DIR}/benchmark-data/benchmark/fixtures) execute_process( COMMAND diff --git a/platform/ios/ios.cmake b/platform/ios/ios.cmake index ecc97577894..2d6bcaa0c07 100644 --- a/platform/ios/ios.cmake +++ b/platform/ios/ios.cmake @@ -1,5 +1,5 @@ -option(MBGL_WITH_IOS_CCACHE "Enable ccache for iOS" OFF) -option(MBGL_IOS_RENDER_TEST "Include render tests" ON) +option(MLN_WITH_IOS_CCACHE "Enable ccache for iOS" OFF) +option(MLN_IOS_RENDER_TEST "Include render tests" ON) if(NOT DEFINED IOS_DEPLOYMENT_TARGET) set(IOS_DEPLOYMENT_TARGET "12.0") @@ -22,7 +22,7 @@ endmacro() set_target_properties(mbgl-core PROPERTIES XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES) -if(MBGL_WITH_OPENGL) +if(MLN_WITH_OPENGL) target_compile_definitions( mbgl-core PUBLIC GLES_SILENCE_DEPRECATION GLES_SILENCE_DEPRECATION @@ -91,10 +91,10 @@ target_include_directories( ) include(${PROJECT_SOURCE_DIR}/vendor/icu.cmake) -if(MBGL_WITH_IOS_CCACHE) +if(MLN_WITH_IOS_CCACHE) include(${PROJECT_SOURCE_DIR}/platform/ios/ccache.cmake) endif() -if(MBGL_WITH_OPENGL) +if(MLN_WITH_OPENGL) include(${PROJECT_SOURCE_DIR}/platform/ios/ios-test-runners.cmake) endif() diff --git a/platform/ios/scripts/standalone.cmake b/platform/ios/scripts/standalone.cmake index b8bcbfa03f3..fb0ae5e5959 100644 --- a/platform/ios/scripts/standalone.cmake +++ b/platform/ios/scripts/standalone.cmake @@ -1,9 +1,9 @@ include(cmake/mason.cmake) # include once for every platform to get all dependency defines -set(MBGL_PLATFORM "android") +set(MLN_PLATFORM "android") include(cmake/mason-dependencies.cmake) -set(MBGL_PLATFORM "ios") +set(MLN_PLATFORM "ios") include(cmake/mason-dependencies.cmake) get_cmake_property(_VARS VARIABLES) diff --git a/platform/linux/linux.cmake b/platform/linux/linux.cmake index 307948ac67c..800509a9eb9 100644 --- a/platform/linux/linux.cmake +++ b/platform/linux/linux.cmake @@ -1,5 +1,5 @@ -option(MBGL_WITH_X11 "Build with X11 Support" ON) -option(MBGL_WITH_WAYLAND "Build with Wayland Support" OFF) +option(MLN_WITH_X11 "Build with X11 Support" ON) +option(MLN_WITH_WAYLAND "Build with Wayland Support" OFF) find_package(CURL REQUIRED) find_package(ICU OPTIONAL_COMPONENTS i18n) @@ -7,7 +7,7 @@ find_package(ICU OPTIONAL_COMPONENTS uc) find_package(JPEG REQUIRED) find_package(PNG REQUIRED) find_package(PkgConfig REQUIRED) -if (MBGL_WITH_X11) +if (MLN_WITH_X11) find_package(X11 REQUIRED) endif () find_package(Threads REQUIRED) @@ -57,7 +57,7 @@ target_sources( ${PROJECT_SOURCE_DIR}/platform/linux/src/gl_functions.cpp ) -if(MBGL_WITH_EGL) +if(MLN_WITH_EGL) find_package(OpenGL REQUIRED EGL) target_sources( mbgl-core @@ -69,7 +69,7 @@ if(MBGL_WITH_EGL) PRIVATE OpenGL::EGL ) - if (MBGL_WITH_WAYLAND) + if (MLN_WITH_WAYLAND) target_compile_definitions(mbgl-core PUBLIC EGL_NO_X11 MESA_EGL_NO_X11_HEADERS @@ -107,7 +107,7 @@ include(${PROJECT_SOURCE_DIR}/vendor/sqlite.cmake) if(NOT ${ICU_FOUND} OR "${ICU_VERSION}" VERSION_LESS 62.0) message(STATUS "ICU not found or too old, using builtin.") - set(MBGL_USE_BUILTIN_ICU TRUE) + set(MLN_USE_BUILTIN_ICU TRUE) include(${PROJECT_SOURCE_DIR}/vendor/icu.cmake) set_source_files_properties( @@ -126,9 +126,9 @@ target_link_libraries( ${LIBUV_LIBRARIES} ${X11_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} - $<$>:ICU::i18n> - $<$>:ICU::uc> - $<$:mbgl-vendor-icu> + $<$>:ICU::i18n> + $<$>:ICU::uc> + $<$:mbgl-vendor-icu> PNG::PNG mbgl-vendor-nunicode mbgl-vendor-sqlite diff --git a/platform/macos/macos.cmake b/platform/macos/macos.cmake index 105c60f7f24..a141bcddd3a 100644 --- a/platform/macos/macos.cmake +++ b/platform/macos/macos.cmake @@ -11,7 +11,7 @@ set_target_properties(mbgl-core PROPERTIES XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH[vari set_target_properties(mbgl-core PROPERTIES XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES) -if(MBGL_WITH_OPENGL) +if(MLN_WITH_OPENGL) find_package(OpenGL REQUIRED) target_compile_definitions( diff --git a/platform/node/CMakeLists.txt b/platform/node/CMakeLists.txt index ce58a72e3e4..68767b15b5a 100644 --- a/platform/node/CMakeLists.txt +++ b/platform/node/CMakeLists.txt @@ -71,7 +71,7 @@ target_link_libraries( # FIXME: Node bindings only run fully on Linux now because it requires libuv RunLoop (which is the default on Linux). Also, Sanitizer will # not work here because node will do a dlopen(), which is not currently supported. -if(CMAKE_SYSTEM_NAME STREQUAL Linux AND NOT MBGL_WITH_SANITIZER) +if(CMAKE_SYSTEM_NAME STREQUAL Linux AND NOT MLN_WITH_SANITIZER) add_test(NAME mbgl-node-memory COMMAND npm run test-memory WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) add_test(NAME mbgl-node-test COMMAND npm run test WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) endif() diff --git a/platform/node/DEVELOPING.md b/platform/node/DEVELOPING.md index c370af5301d..0bb201f8039 100644 --- a/platform/node/DEVELOPING.md +++ b/platform/node/DEVELOPING.md @@ -48,7 +48,7 @@ To compile the Node.js bindings and install module dependencies, from the reposi #### MacOS ```bash -cmake . -B build -G Ninja -DMLN_WITH_NODE=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_BUILD_TYPE=Debug -DMBGL_WITH_COVERAGE=ON +cmake . -B build -G Ninja -DMLN_WITH_NODE=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_BUILD_TYPE=Debug -DMLN_WITH_COVERAGE=ON ``` #### Linux diff --git a/platform/node/cmake/module.cmake b/platform/node/cmake/module.cmake index 2dca7d29456..23d609ab892 100644 --- a/platform/node/cmake/module.cmake +++ b/platform/node/cmake/module.cmake @@ -211,7 +211,7 @@ function(add_node_module NAME) ) if(WIN32) - if(MBGL_WITH_OSMESA) + if(MLN_WITH_OSMESA) get_filename_component(_OUTPUT_PATH "${_OUTPUT_PATH}" DIRECTORY "${CMAKE_CURRENT_SOURCE_PATH}") add_custom_command( diff --git a/platform/qt/QMapLibreGLConfig.cmake.in b/platform/qt/QMapLibreGLConfig.cmake.in index dc44d5c4a1b..d3ae5c80b9c 100644 --- a/platform/qt/QMapLibreGLConfig.cmake.in +++ b/platform/qt/QMapLibreGLConfig.cmake.in @@ -6,7 +6,7 @@ find_dependency(Qt@QT_VERSION_MAJOR@ find_dependency(Qt@QT_VERSION_MAJOR@ COMPONENTS Network @REQUIRED_QT_VERSION@) -if(@MBGL_QT_STATIC@ AND NOT @MBGL_QT_INSIDE_PLUGIN@ AND NOT @MBGL_QT_WITH_INTERNAL_SQLITE@) +if(@MLN_QT_STATIC@ AND NOT @MLN_QT_INSIDE_PLUGIN@ AND NOT @MLN_QT_WITH_INTERNAL_SQLITE@) find_dependency(Qt@QT_VERSION_MAJOR@ COMPONENTS Sql @REQUIRED_QT_VERSION@) endif() diff --git a/platform/qt/README.md b/platform/qt/README.md index 66e23864564..7a2e0718344 100644 --- a/platform/qt/README.md +++ b/platform/qt/README.md @@ -33,7 +33,7 @@ cmake ../maplibre-gl-native/ \ -GNinja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX= \ - -DMBGL_WITH_QT=ON + -DMLN_WITH_QT=ON ninja ninja install ``` diff --git a/platform/qt/qt.cmake b/platform/qt/qt.cmake index 35c6395e033..c00211562c8 100644 --- a/platform/qt/qt.cmake +++ b/platform/qt/qt.cmake @@ -1,16 +1,16 @@ message(STATUS "Configuring GL-Native with Qt bindings") -file(READ "${PROJECT_SOURCE_DIR}/platform/qt/VERSION" MBGL_QT_VERSION) -string(REGEX REPLACE "\n" "" MBGL_QT_VERSION "${MBGL_QT_VERSION}") # get rid of the newline at the end -set(MBGL_QT_VERSION_COMPATIBILITY 2.0.0) -message(STATUS "Version ${MBGL_QT_VERSION}") - -option(MBGL_QT_LIBRARY_ONLY "Build only libraries" OFF) -option(MBGL_QT_STATIC "Build MapLibre GL Qt bindings staticly" OFF) -option(MBGL_QT_INSIDE_PLUGIN "Build QMapLibreGL as OBJECT library, so it can be bundled into separate single plugin lib." OFF) -option(MBGL_QT_WITH_HEADLESS "Build MapLibre GL Qt with headless support" ON) -option(MBGL_QT_WITH_INTERNAL_SQLITE "Build MapLibre GL Qt bindings with internal sqlite" OFF) -option(MBGL_QT_DEPLOYMENT "Autogenerate files necessary for deployment" OFF) +file(READ "${PROJECT_SOURCE_DIR}/platform/qt/VERSION" MLN_QT_VERSION) +string(REGEX REPLACE "\n" "" MLN_QT_VERSION "${MLN_QT_VERSION}") # get rid of the newline at the end +set(MLN_QT_VERSION_COMPATIBILITY 2.0.0) +message(STATUS "Version ${MLN_QT_VERSION}") + +option(MLN_QT_LIBRARY_ONLY "Build only libraries" OFF) +option(MLN_QT_STATIC "Build MapLibre GL Qt bindings staticly" OFF) +option(MLN_QT_INSIDE_PLUGIN "Build QMapLibreGL as OBJECT library, so it can be bundled into separate single plugin lib." OFF) +option(MLN_QT_WITH_HEADLESS "Build MapLibre GL Qt with headless support" ON) +option(MLN_QT_WITH_INTERNAL_SQLITE "Build MapLibre GL Qt bindings with internal sqlite" OFF) +option(MLN_QT_DEPLOYMENT "Autogenerate files necessary for deployment" OFF) find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED) find_package(Qt${QT_VERSION_MAJOR} @@ -18,14 +18,14 @@ find_package(Qt${QT_VERSION_MAJOR} Network REQUIRED) -if(NOT MBGL_QT_LIBRARY_ONLY) +if(NOT MLN_QT_LIBRARY_ONLY) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED) if (Qt6_FOUND) find_package(Qt${QT_VERSION_MAJOR}OpenGLWidgets REQUIRED) endif() endif() -if(NOT MBGL_QT_WITH_INTERNAL_SQLITE) +if(NOT MLN_QT_WITH_INTERNAL_SQLITE) find_package(Qt${QT_VERSION_MAJOR}Sql REQUIRED) else() message(STATUS "Using internal sqlite") @@ -33,8 +33,8 @@ else() endif() if(CMAKE_SYSTEM_NAME STREQUAL "Linux") - option(MBGL_QT_WITH_INTERNAL_ICU "Build MapLibre GL Qt bindings with internal ICU" OFF) - if(NOT MBGL_QT_WITH_INTERNAL_ICU) + option(MLN_QT_WITH_INTERNAL_ICU "Build MapLibre GL Qt bindings with internal ICU" OFF) + if(NOT MLN_QT_WITH_INTERNAL_ICU) find_package(ICU COMPONENTS uc REQUIRED) else() message(STATUS "Using internal ICU") @@ -87,10 +87,10 @@ target_sources( ${PROJECT_SOURCE_DIR}/platform/default/src/mbgl/storage/offline_database.cpp ${PROJECT_SOURCE_DIR}/platform/default/src/mbgl/storage/offline_download.cpp ${PROJECT_SOURCE_DIR}/platform/default/src/mbgl/storage/online_file_source.cpp - ${PROJECT_SOURCE_DIR}/platform/$,default/src/mbgl/storage/sqlite3.cpp,qt/src/mbgl/sqlite3.cpp> + ${PROJECT_SOURCE_DIR}/platform/$,default/src/mbgl/storage/sqlite3.cpp,qt/src/mbgl/sqlite3.cpp> ${PROJECT_SOURCE_DIR}/platform/default/src/mbgl/util/compression.cpp ${PROJECT_SOURCE_DIR}/platform/default/src/mbgl/util/monotonic_timer.cpp - $<$:${PROJECT_SOURCE_DIR}/platform/qt/src/mbgl/headless_backend_qt.cpp> + $<$:${PROJECT_SOURCE_DIR}/platform/qt/src/mbgl/headless_backend_qt.cpp> ${PROJECT_SOURCE_DIR}/platform/qt/src/mbgl/async_task.cpp ${PROJECT_SOURCE_DIR}/platform/qt/src/mbgl/async_task_impl.hpp ${PROJECT_SOURCE_DIR}/platform/qt/src/mbgl/gl_functions.cpp @@ -138,8 +138,8 @@ target_link_libraries( Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Gui Qt${QT_VERSION_MAJOR}::Network - $,mbgl-vendor-sqlite,Qt${QT_VERSION_MAJOR}::Sql> - $<$:$,mbgl-vendor-icu,ICU::uc>> + $,mbgl-vendor-sqlite,Qt${QT_VERSION_MAJOR}::Sql> + $<$:$,mbgl-vendor-icu,ICU::uc>> mbgl-vendor-nunicode ) @@ -156,9 +156,9 @@ set(qmaplibregl_headers ${PROJECT_SOURCE_DIR}/platform/qt/include/QMapLibreGL/Utils ) -if (MBGL_QT_INSIDE_PLUGIN) +if (MLN_QT_INSIDE_PLUGIN) add_library(qmaplibregl OBJECT) -elseif(MBGL_QT_STATIC) +elseif(MLN_QT_STATIC) add_library(qmaplibregl STATIC) else() add_library(qmaplibregl SHARED) @@ -193,21 +193,21 @@ set_target_properties( AUTOMOC ON EXPORT_NAME QMapLibreGL OUTPUT_NAME QMapLibreGL - VERSION ${MBGL_QT_VERSION} - SOVERSION ${MBGL_QT_VERSION_COMPATIBILITY} + VERSION ${MLN_QT_VERSION} + SOVERSION ${MLN_QT_VERSION_COMPATIBILITY} PUBLIC_HEADER "${qmaplibregl_headers}" ) if (Qt6_FOUND AND COMMAND qt_enable_autogen_tool) qt_enable_autogen_tool(qmaplibregl "moc" ON) endif() -if (APPLE AND NOT MBGL_QT_STATIC AND NOT MBGL_QT_INSIDE_PLUGIN) +if (APPLE AND NOT MLN_QT_STATIC AND NOT MLN_QT_INSIDE_PLUGIN) set_target_properties( qmaplibregl PROPERTIES FRAMEWORK ON FRAMEWORK_VERSION A MACOSX_FRAMEWORK_IDENTIFIER org.maplibre.QMapLibreGL - MACOSX_FRAMEWORK_BUNDLE_VERSION ${MBGL_QT_VERSION} - MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${MBGL_QT_VERSION} + MACOSX_FRAMEWORK_BUNDLE_VERSION ${MLN_QT_VERSION} + MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${MLN_QT_VERSION} ) target_include_directories( qmaplibregl @@ -227,7 +227,7 @@ configure_package_config_file( CMAKE_INSTALL_LIBDIR NO_CHECK_REQUIRED_COMPONENTS_MACRO) write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/QMapLibreGLConfigVersion.cmake - VERSION ${MBGL_QT_VERSION} + VERSION ${MLN_QT_VERSION} COMPATIBILITY AnyNewerVersion) install(EXPORT QMapLibreGLTargets @@ -248,7 +248,7 @@ install( COMPONENT development ) -if(MBGL_QT_DEPLOYMENT) +if(MLN_QT_DEPLOYMENT) install(FILES ${PROJECT_SOURCE_DIR}/LICENSE.md DESTINATION .) endif() @@ -281,18 +281,18 @@ target_link_libraries( $ ) # Do not use generator expressions for cleaner output -if (MBGL_QT_STATIC AND NOT MBGL_QT_INSIDE_PLUGIN) +if (MLN_QT_STATIC AND NOT MLN_QT_INSIDE_PLUGIN) target_link_libraries( qmaplibregl PUBLIC - $<$>:Qt${QT_VERSION_MAJOR}::Sql> + $<$>:Qt${QT_VERSION_MAJOR}::Sql> $<$,$>>:z> ) endif() -if (MBGL_QT_STATIC OR MBGL_QT_INSIDE_PLUGIN) +if (MLN_QT_STATIC OR MLN_QT_INSIDE_PLUGIN) # Don't add import/export into public header because we don't build shared library. - # In case on MBGL_QT_INSIDE_PLUGIN it's always OBJECT library and bundled into one + # In case on MLN_QT_INSIDE_PLUGIN it's always OBJECT library and bundled into one # single Qt plugin lib. target_compile_definitions( qmaplibregl @@ -312,7 +312,7 @@ install(TARGETS qmaplibregl PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/QMapLibreGL" ) -if(NOT MBGL_QT_LIBRARY_ONLY) +if(NOT MLN_QT_LIBRARY_ONLY) add_executable( mbgl-qt ${PROJECT_SOURCE_DIR}/platform/qt/app/main.cpp @@ -396,21 +396,21 @@ if(NOT MBGL_QT_LIBRARY_ONLY) endif() endif() -find_program(MBGL_QDOC NAMES qdoc) +find_program(MLN_QDOC NAMES qdoc) -if(MBGL_QDOC) +if(MLN_QDOC) add_custom_target(mbgl-qt-docs) add_custom_command( TARGET mbgl-qt-docs PRE_BUILD COMMAND - ${MBGL_QDOC} + ${MLN_QDOC} ${PROJECT_SOURCE_DIR}/platform/qt/config.qdocconf -outputdir ${CMAKE_BINARY_DIR}/docs ) endif() -if(NOT MBGL_QT_LIBRARY_ONLY) +if(NOT MLN_QT_LIBRARY_ONLY) add_test(NAME mbgl-test-runner COMMAND mbgl-test-runner WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) endif() diff --git a/platform/qt/scripts/configure_Qt5_Android_static.sh b/platform/qt/scripts/configure_Qt5_Android_static.sh index f0692a0c52b..a9377addde6 100755 --- a/platform/qt/scripts/configure_Qt5_Android_static.sh +++ b/platform/qt/scripts/configure_Qt5_Android_static.sh @@ -25,9 +25,9 @@ cmake "$1" \ -DANDROID_ABI="$4" \ -DANDROID_NATIVE_API_LEVEL=21 \ -G Ninja \ --DMBGL_WITH_QT=ON \ --DMBGL_QT_STATIC=ON \ --DMBGL_QT_LIBRARY_ONLY=ON \ +-DMLN_WITH_QT=ON \ +-DMLN_QT_STATIC=ON \ +-DMLN_QT_LIBRARY_ONLY=ON \ -DCMAKE_CXX_FLAGS_RELEASE=-g0 \ -DCMAKE_INSTALL_PREFIX="$2" \ -DCMAKE_FIND_ROOT_PATH="$3/android" \ diff --git a/platform/qt/scripts/configure_Qt5_Linux.sh b/platform/qt/scripts/configure_Qt5_Linux.sh index 43d54a8eb85..a86a9560836 100755 --- a/platform/qt/scripts/configure_Qt5_Linux.sh +++ b/platform/qt/scripts/configure_Qt5_Linux.sh @@ -13,5 +13,5 @@ fi cmake "$1" \ -G Ninja \ -DCMAKE_BUILD_TYPE="RelWithDebInfo" \ - -DMBGL_WITH_QT=ON \ + -DMLN_WITH_QT=ON \ -DCMAKE_INSTALL_PREFIX="$2" diff --git a/platform/qt/scripts/configure_Qt5_Windows.ps1 b/platform/qt/scripts/configure_Qt5_Windows.ps1 index 62cf0b6ccc9..850a136b2bd 100644 --- a/platform/qt/scripts/configure_Qt5_Windows.ps1 +++ b/platform/qt/scripts/configure_Qt5_Windows.ps1 @@ -5,4 +5,4 @@ cmake -S "$path" ` -GNinja ` -DCMAKE_BUILD_TYPE="Release" ` -DCMAKE_INSTALL_PREFIX="$install" ` - -DMBGL_WITH_QT=ON + -DMLN_WITH_QT=ON diff --git a/platform/qt/scripts/configure_Qt5_Windows_static.ps1 b/platform/qt/scripts/configure_Qt5_Windows_static.ps1 index 060ca364450..75eae572053 100644 --- a/platform/qt/scripts/configure_Qt5_Windows_static.ps1 +++ b/platform/qt/scripts/configure_Qt5_Windows_static.ps1 @@ -5,6 +5,6 @@ cmake -S "$path" ` -GNinja ` -DCMAKE_BUILD_TYPE="Release" ` -DCMAKE_INSTALL_PREFIX="$install" ` - -DMBGL_WITH_QT=ON ` - -DMBGL_QT_STATIC=ON ` - -DMBGL_QT_LIBRARY_ONLY=ON + -DMLN_WITH_QT=ON ` + -DMLN_QT_STATIC=ON ` + -DMLN_QT_LIBRARY_ONLY=ON diff --git a/platform/qt/scripts/configure_Qt5_iOS_static.sh b/platform/qt/scripts/configure_Qt5_iOS_static.sh index 14b5f8b1eaa..3d113aea6d2 100755 --- a/platform/qt/scripts/configure_Qt5_iOS_static.sh +++ b/platform/qt/scripts/configure_Qt5_iOS_static.sh @@ -21,9 +21,9 @@ cmake "$1" \ -DCMAKE_CONFIGURATION_TYPES="Release;Debug" \ -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" \ -DCMAKE_OSX_DEPLOYMENT_TARGET="12.0" \ - -DMBGL_WITH_QT=ON \ - -DMBGL_QT_STATIC=ON \ - -DMBGL_QT_LIBRARY_ONLY=ON \ + -DMLN_WITH_QT=ON \ + -DMLN_QT_STATIC=ON \ + -DMLN_QT_LIBRARY_ONLY=ON \ -DCMAKE_INSTALL_PREFIX="$2" \ -DCMAKE_FIND_ROOT_PATH="$3/ios" \ -DCMAKE_PREFIX_PATH="$3/ios" diff --git a/platform/qt/scripts/configure_Qt5_macOS.sh b/platform/qt/scripts/configure_Qt5_macOS.sh index abcdd805514..f079ed20200 100755 --- a/platform/qt/scripts/configure_Qt5_macOS.sh +++ b/platform/qt/scripts/configure_Qt5_macOS.sh @@ -14,5 +14,5 @@ cmake "$1" \ -G Ninja \ -DCMAKE_BUILD_TYPE="RelWithDebInfo" \ -DCMAKE_OSX_DEPLOYMENT_TARGET="10.13" \ - -DMBGL_WITH_QT=ON \ + -DMLN_WITH_QT=ON \ -DCMAKE_INSTALL_PREFIX="$2" diff --git a/platform/qt/scripts/configure_Qt5_macOS_static.sh b/platform/qt/scripts/configure_Qt5_macOS_static.sh index fd030309db1..bd014a8e35a 100755 --- a/platform/qt/scripts/configure_Qt5_macOS_static.sh +++ b/platform/qt/scripts/configure_Qt5_macOS_static.sh @@ -14,7 +14,7 @@ cmake "$1" \ -G Ninja \ -DCMAKE_BUILD_TYPE="RelWithDebInfo" \ -DCMAKE_OSX_DEPLOYMENT_TARGET="10.13" \ - -DMBGL_WITH_QT=ON \ - -DMBGL_QT_STATIC=ON \ - -DMBGL_QT_LIBRARY_ONLY=ON \ + -DMLN_WITH_QT=ON \ + -DMLN_QT_STATIC=ON \ + -DMLN_QT_LIBRARY_ONLY=ON \ -DCMAKE_INSTALL_PREFIX="$2" diff --git a/platform/qt/scripts/configure_Qt6_Windows.ps1 b/platform/qt/scripts/configure_Qt6_Windows.ps1 index d9653eba5e5..2190b1b7416 100644 --- a/platform/qt/scripts/configure_Qt6_Windows.ps1 +++ b/platform/qt/scripts/configure_Qt6_Windows.ps1 @@ -5,4 +5,4 @@ qt-cmake -S "$path" ` -GNinja ` -DCMAKE_BUILD_TYPE="Release" ` -DCMAKE_INSTALL_PREFIX="$install" ` - -DMBGL_WITH_QT=ON + -DMLN_WITH_QT=ON diff --git a/platform/qt/scripts/configure_Qt6_macOS.sh b/platform/qt/scripts/configure_Qt6_macOS.sh index 8b5feb04a75..b535ba127d7 100755 --- a/platform/qt/scripts/configure_Qt6_macOS.sh +++ b/platform/qt/scripts/configure_Qt6_macOS.sh @@ -15,5 +15,5 @@ qt-cmake "$1" \ -DCMAKE_BUILD_TYPE="RelWithDebInfo" \ -DCMAKE_OSX_DEPLOYMENT_TARGET="10.14" \ -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" \ - -DMBGL_WITH_QT=ON \ + -DMLN_WITH_QT=ON \ -DCMAKE_INSTALL_PREFIX="$2" diff --git a/platform/qt/scripts/configure_Qt6_macOS_static.sh b/platform/qt/scripts/configure_Qt6_macOS_static.sh index 714204fc21c..08a440eb896 100755 --- a/platform/qt/scripts/configure_Qt6_macOS_static.sh +++ b/platform/qt/scripts/configure_Qt6_macOS_static.sh @@ -15,7 +15,7 @@ qt-cmake "$1" \ -DCMAKE_BUILD_TYPE="RelWithDebInfo" \ -DCMAKE_OSX_DEPLOYMENT_TARGET="10.14" \ -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" \ - -DMBGL_WITH_QT=ON \ - -DMBGL_QT_STATIC=ON \ - -DMBGL_QT_LIBRARY_ONLY=ON \ + -DMLN_WITH_QT=ON \ + -DMLN_QT_STATIC=ON \ + -DMLN_QT_LIBRARY_ONLY=ON \ -DCMAKE_INSTALL_PREFIX="$2" diff --git a/platform/windows/README.md b/platform/windows/README.md index 757bf303308..ba942e3e454 100644 --- a/platform/windows/README.md +++ b/platform/windows/README.md @@ -34,13 +34,13 @@ It will take some time to build and install all components on which Maplibre dep To configure build with EGL support (ANGLE libraries will be build), use the following command: ```cmd -cmake . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DMBGL_WITH_EGL=ON +cmake . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DMLN_WITH_EGL=ON ``` To configure build with OSMesa (software rendering), use the following command: ``` -cmake . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DMBGL_WITH_OSMESA=ON +cmake . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DMLN_WITH_OSMESA=ON ``` **WARNING:** as OSMesa doesn't have static libraries, it's necessary to copy `libglapi.dll`, `libGLESv3.dll` and `osmesa.dll` from `platform\windows\vendor\mesa3d\` to executable/dll directory you want to use, otherwise it won't run. @@ -64,11 +64,11 @@ cmake . -B build The same can be done with alternative configure commands: ```cmd -cmake . -B build -DMBGL_WITH_EGL=ON +cmake . -B build -DMLN_WITH_EGL=ON ``` or ```cmd -cmake . -B build -DMBGL_WITH_OSMESA=ON +cmake . -B build -DMLN_WITH_OSMESA=ON ``` Once configure is done, open the file `build\Mapbox GL Native.sln`. Build the target `ALL_BUILD` to build all targets, or pick a specific target. Don't forget to pick a build configuration (`Release`, `RelWithDebInfo`, `MinSizeRel` or `Debug`), otherwise the project will be built with default configuration (`Debug`). diff --git a/platform/windows/windows.cmake b/platform/windows/windows.cmake index 2db7de33c39..5357275d2f0 100644 --- a/platform/windows/windows.cmake +++ b/platform/windows/windows.cmake @@ -1,6 +1,6 @@ -if(MBGL_WITH_EGL) +if(MLN_WITH_EGL) set(_RENDERER EGL) -elseif(MBGL_WITH_OSMESA) +elseif(MLN_WITH_OSMESA) set(_RENDERER OSMesa) else() set(_RENDERER OpenGL) @@ -74,7 +74,7 @@ target_compile_definitions( CURL_STATICLIB ) -if(MBGL_WITH_EGL) +if(MLN_WITH_EGL) find_package(unofficial-angle CONFIG REQUIRED) target_sources( mbgl-core @@ -93,7 +93,7 @@ if(MBGL_WITH_EGL) unofficial::angle::libEGL unofficial::angle::libGLESv3 ) -elseif(MBGL_WITH_OSMESA) +elseif(MLN_WITH_OSMESA) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) list(APPEND CMAKE_PREFIX_PATH ${CMAKE_CURRENT_LIST_DIR}/vendor/mesa3d) @@ -153,7 +153,7 @@ include(${PROJECT_SOURCE_DIR}/vendor/sqlite.cmake) if(NOT ${ICU_FOUND} OR "${ICU_VERSION}" VERSION_LESS 62.0) message(STATUS "ICU not found or too old, using builtin.") - set(MBGL_USE_BUILTIN_ICU TRUE) + set(MLN_USE_BUILTIN_ICU TRUE) include(${PROJECT_SOURCE_DIR}/vendor/icu.cmake) set_source_files_properties( @@ -171,10 +171,10 @@ target_link_libraries( ${JPEG_LIBRARIES} ${LIBUV_LIBRARIES} dlfcn-win32::dl - $<$>:ICU::data> - $<$>:ICU::i18n> - $<$>:ICU::uc> - $<$:mbgl-vendor-icu> + $<$>:ICU::data> + $<$>:ICU::i18n> + $<$>:ICU::uc> + $<$:mbgl-vendor-icu> PNG::PNG mbgl-vendor-nunicode mbgl-vendor-sqlite diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 6407cb5299a..47c866a9ddd 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -113,7 +113,7 @@ add_library( # MapSnapshotter uses headless backend that is rendering image on a background thread. QT / macOS adaptation for headless backend creates # new window and updates it's parameters, which is not allowed since macOS mohave 10.14. Following block disables snapshotter unit tests for # QT on macOS. https://github.com/mapbox/mapbox-gl-native/issues/16267 -if(NOT (MBGL_WITH_QT AND CMAKE_SYSTEM_NAME STREQUAL Darwin)) +if(NOT (MLN_WITH_QT AND CMAKE_SYSTEM_NAME STREQUAL Darwin)) target_sources( mbgl-test PRIVATE @@ -121,7 +121,7 @@ if(NOT (MBGL_WITH_QT AND CMAKE_SYSTEM_NAME STREQUAL Darwin)) ) endif() -if(MBGL_WITH_OPENGL) +if(MLN_WITH_OPENGL) target_sources( mbgl-test PRIVATE @@ -142,9 +142,9 @@ endif() if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL Android AND ANDROID_NATIVE_API_LEVEL VERSION_LESS 24) message("Target platform does not support HTTP tests or dependencies not found.") - set(MBGL_TEST_HAS_TEST_SERVER 0) + set(MLN_TEST_HAS_TEST_SERVER 0) else() - set(MBGL_TEST_HAS_TEST_SERVER 1) + set(MLN_TEST_HAS_TEST_SERVER 1) target_sources( mbgl-test PRIVATE ${PROJECT_SOURCE_DIR}/test/src/mbgl/test/http_server.cpp @@ -164,14 +164,14 @@ else() endif() if(NOT DEFINED ENV{CI}) - set(MBGL_TEST_BUILD_ON_CI 0) + set(MLN_TEST_BUILD_ON_CI 0) else() - set(MBGL_TEST_BUILD_ON_CI 1) + set(MLN_TEST_BUILD_ON_CI 1) endif() target_compile_definitions( mbgl-test - PRIVATE TEST_HAS_SERVER=${MBGL_TEST_HAS_TEST_SERVER} CI_BUILD=${MBGL_TEST_BUILD_ON_CI} + PRIVATE TEST_HAS_SERVER=${MLN_TEST_HAS_TEST_SERVER} CI_BUILD=${MLN_TEST_BUILD_ON_CI} ) target_include_directories( @@ -210,12 +210,12 @@ if(CMAKE_SYSTEM_NAME STREQUAL Darwin) endif() # Needed for testing private classes -get_target_property(MBGL_CORE_PRIVATE_LIBRARIES mbgl-core LINK_LIBRARIES) +get_target_property(MLN_CORE_PRIVATE_LIBRARIES mbgl-core LINK_LIBRARIES) target_link_libraries( mbgl-test PRIVATE - ${MBGL_CORE_PRIVATE_LIBRARIES} + ${MLN_CORE_PRIVATE_LIBRARIES} Mapbox::Base::Extras::args Mapbox::Base::pixelmatch-cpp mbgl-compiler-options @@ -238,6 +238,6 @@ endif() set_property(TARGET mbgl-test PROPERTY FOLDER Core) -if (MBGL_WITH_CLANG_TIDY) +if (MLN_WITH_CLANG_TIDY) set_target_properties(mbgl-test PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() \ No newline at end of file +endif() diff --git a/vendor/csscolorparser.cmake b/vendor/csscolorparser.cmake index c8ce21719d0..c2c954fc4b9 100644 --- a/vendor/csscolorparser.cmake +++ b/vendor/csscolorparser.cmake @@ -2,7 +2,7 @@ if(TARGET mbgl-vendor-csscolorparser) return() endif() -if(MBGL_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") +if(MLN_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") add_library(mbgl-vendor-csscolorparser OBJECT) else() add_library(mbgl-vendor-csscolorparser STATIC) diff --git a/vendor/nunicode.cmake b/vendor/nunicode.cmake index 8940d60dbb1..60f63c188a6 100644 --- a/vendor/nunicode.cmake +++ b/vendor/nunicode.cmake @@ -2,7 +2,7 @@ if(TARGET mbgl-vendor-nunicode) return() endif() -if(MBGL_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") +if(MLN_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") add_library(mbgl-vendor-nunicode OBJECT) else() add_library(mbgl-vendor-nunicode STATIC) diff --git a/vendor/parsedate.cmake b/vendor/parsedate.cmake index c57c1f86945..d5565a4150b 100644 --- a/vendor/parsedate.cmake +++ b/vendor/parsedate.cmake @@ -2,7 +2,7 @@ if(TARGET mbgl-vendor-parsedate) return() endif() -if(MBGL_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") +if(MLN_WITH_QT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0") add_library(mbgl-vendor-parsedate OBJECT) else() add_library(mbgl-vendor-parsedate STATIC) diff --git a/vendor/sqlite.cmake b/vendor/sqlite.cmake index 9c7e6128589..716b767e5c4 100644 --- a/vendor/sqlite.cmake +++ b/vendor/sqlite.cmake @@ -8,9 +8,9 @@ add_library( ) include(CheckSymbolExists) -check_symbol_exists("strerror_r" "string.h" MBGL_SQLITE3_HAVE_STRERROR_R) +check_symbol_exists("strerror_r" "string.h" MLN_SQLITE3_HAVE_STRERROR_R) -if(MBGL_SQLITE3_HAVE_STRERROR_R) +if(MLN_SQLITE3_HAVE_STRERROR_R) target_compile_definitions( mbgl-vendor-sqlite PRIVATE HAVE_STRERROR_R From 4c01b7ef1f19964167070c3ea008780b8df72182 Mon Sep 17 00:00:00 2001 From: tdcosta100 Date: Fri, 28 Apr 2023 12:51:46 -0300 Subject: [PATCH 05/21] Revert GLES3 changes for OSMesa in Windows (#1079) --- platform/node/cmake/module.cmake | 2 +- platform/windows/FindOSMesa.cmake | 18 +++++++++--------- platform/windows/README.md | 2 +- platform/windows/windows.cmake | 4 ++-- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/platform/node/cmake/module.cmake b/platform/node/cmake/module.cmake index 23d609ab892..7e41e617d48 100644 --- a/platform/node/cmake/module.cmake +++ b/platform/node/cmake/module.cmake @@ -218,7 +218,7 @@ function(add_node_module NAME) TARGET ${_TARGET} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "${PROJECT_SOURCE_DIR}/platform/windows/vendor/mesa3d/${_ARCH}/libglapi.dll" "${_OUTPUT_PATH}" - COMMAND ${CMAKE_COMMAND} -E copy "${PROJECT_SOURCE_DIR}/platform/windows/vendor/mesa3d/${_ARCH}/libGLESv3.dll" "${_OUTPUT_PATH}" + COMMAND ${CMAKE_COMMAND} -E copy "${PROJECT_SOURCE_DIR}/platform/windows/vendor/mesa3d/${_ARCH}/libGLESv2.dll" "${_OUTPUT_PATH}" COMMAND ${CMAKE_COMMAND} -E copy "${PROJECT_SOURCE_DIR}/platform/windows/vendor/mesa3d/${_ARCH}/osmesa.dll" "${_OUTPUT_PATH}" ) endif() diff --git a/platform/windows/FindOSMesa.cmake b/platform/windows/FindOSMesa.cmake index be1c5eb5ddf..66f8eca4033 100644 --- a/platform/windows/FindOSMesa.cmake +++ b/platform/windows/FindOSMesa.cmake @@ -16,10 +16,10 @@ else() endif() find_library(OSMesa_osmesa_LIBRARY NAMES osmesa PATHS ${OSMesa_DIR}/lib PATH_SUFFIXES ${_ARCH} NO_DEFAULT_PATH) -find_library(OSMesa_libGLESv3_LIBRARY NAMES libGLESv3 PATHS ${OSMesa_DIR}/lib PATH_SUFFIXES ${_ARCH} NO_DEFAULT_PATH) +find_library(OSMesa_libGLESv2_LIBRARY NAMES libGLESv2 PATHS ${OSMesa_DIR}/lib PATH_SUFFIXES ${_ARCH} NO_DEFAULT_PATH) find_file(OSMesa_osmesa_LIBRARY_DLL NAMES osmesa.dll PATHS ${OSMesa_DIR} PATH_SUFFIXES ${_ARCH} NO_DEFAULT_PATH) -find_file(OSMesa_libGLESv3_LIBRARY_DLL NAMES libGLESv3.dll PATHS ${OSMesa_DIR} PATH_SUFFIXES ${_ARCH} NO_DEFAULT_PATH) +find_file(OSMesa_libGLESv2_LIBRARY_DLL NAMES libGLESv2.dll PATHS ${OSMesa_DIR} PATH_SUFFIXES ${_ARCH} NO_DEFAULT_PATH) unset(_ARCH) @@ -29,18 +29,18 @@ include(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(OSMesa REQUIRED_VARS OSMesa_osmesa_LIBRARY - OSMesa_libGLESv3_LIBRARY + OSMesa_libGLESv2_LIBRARY OSMesa_INCLUDE_DIR) # Hide internal variables -mark_as_advanced(OSMesa_INCLUDE_DIR OSMesa_osmesa_LIBRARY OSMesa_libGLESv3_LIBRARY) +mark_as_advanced(OSMesa_INCLUDE_DIR OSMesa_osmesa_LIBRARY OSMesa_libGLESv2_LIBRARY) # Set standard variables if(OSMesa_FOUND) set(OSMesa_INCLUDE_DIRS "${OSMesa_INCLUDE_DIR}") set(OSMesa_LIBRARIES "${OSMesa_osmesa_LIBRARY}" - "${OSMesa_libGLESv3_LIBRARY}" + "${OSMesa_libGLESv2_LIBRARY}" ) add_library(OSMesa::osmesa SHARED IMPORTED) @@ -53,13 +53,13 @@ if(OSMesa_FOUND) IMPORTED_LOCATION ${OSMesa_osmesa_LIBRARY_DLL} ) - add_library(OSMesa::libGLESv3 SHARED IMPORTED) + add_library(OSMesa::libGLESv2 SHARED IMPORTED) set_target_properties( - OSMesa::libGLESv3 + OSMesa::libGLESv2 PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${OSMesa_INCLUDE_DIRS} - IMPORTED_IMPLIB ${OSMesa_libGLESv3_LIBRARY} - IMPORTED_LOCATION ${OSMesa_libGLESv3_LIBRARY_DLL} + IMPORTED_IMPLIB ${OSMesa_libGLESv2_LIBRARY} + IMPORTED_LOCATION ${OSMesa_libGLESv2_LIBRARY_DLL} ) endif() diff --git a/platform/windows/README.md b/platform/windows/README.md index ba942e3e454..c6f8c083ea4 100644 --- a/platform/windows/README.md +++ b/platform/windows/README.md @@ -43,7 +43,7 @@ To configure build with OSMesa (software rendering), use the following command: cmake . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DMLN_WITH_OSMESA=ON ``` -**WARNING:** as OSMesa doesn't have static libraries, it's necessary to copy `libglapi.dll`, `libGLESv3.dll` and `osmesa.dll` from `platform\windows\vendor\mesa3d\` to executable/dll directory you want to use, otherwise it won't run. +**WARNING:** as OSMesa doesn't have static libraries, it's necessary to copy `libglapi.dll`, `libGLESv2.dll` and `osmesa.dll` from `platform\windows\vendor\mesa3d\` to executable/dll directory you want to use, otherwise it won't run. ## Building diff --git a/platform/windows/windows.cmake b/platform/windows/windows.cmake index 5357275d2f0..63274adc1e6 100644 --- a/platform/windows/windows.cmake +++ b/platform/windows/windows.cmake @@ -91,7 +91,7 @@ if(MLN_WITH_EGL) mbgl-core PRIVATE unofficial::angle::libEGL - unofficial::angle::libGLESv3 + unofficial::angle::libGLESv2 ) elseif(MLN_WITH_OSMESA) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) @@ -114,7 +114,7 @@ elseif(MLN_WITH_OSMESA) mbgl-core PRIVATE OSMesa::osmesa - OSMesa::libGLESv3 + OSMesa::libGLESv2 ) else() find_package(OpenGL REQUIRED) From 76f07631bfd030f7134182c735da8fac1347f242 Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Fri, 28 Apr 2023 12:12:56 -0700 Subject: [PATCH 06/21] Evaluate and apply color --- include/mbgl/gfx/drawable.hpp | 4 ++ include/mbgl/gfx/drawable_builder.hpp | 6 ++ include/mbgl/gfx/vertex_attribute.hpp | 38 ++++++++++--- include/mbgl/gl/drawable_gl.hpp | 14 ++++- include/mbgl/renderer/change_request.hpp | 36 ++++++++++-- src/mbgl/gfx/drawable_builder.cpp | 8 ++- src/mbgl/gl/drawable_gl.cpp | 7 +++ src/mbgl/gl/drawable_gl_builder.cpp | 23 +++++--- src/mbgl/renderer/change_request.cpp | 8 ++- src/mbgl/renderer/render_orchestrator.cpp | 6 ++ src/mbgl/renderer/render_orchestrator.hpp | 2 + src/mbgl/renderer/renderer_impl.cpp | 3 +- .../style/layers/background_layer_impl.cpp | 55 +++++++++++++------ .../style/layers/background_layer_impl.hpp | 14 +++++ 14 files changed, 179 insertions(+), 45 deletions(-) diff --git a/include/mbgl/gfx/drawable.hpp b/include/mbgl/gfx/drawable.hpp index 1d26fcee549..51cc9341862 100644 --- a/include/mbgl/gfx/drawable.hpp +++ b/include/mbgl/gfx/drawable.hpp @@ -11,6 +11,7 @@ namespace mbgl { +class Color; class PaintParameters; namespace gfx { @@ -71,6 +72,9 @@ class Drawable { /// Get the tweakers attached to this drawable const std::vector& getTweakers() const { return tweakers; } + // Reset a single color attribute for all vertexes + virtual void resetColor(const Color&) = 0; + protected: util::SimpleIdentity uniqueID; gfx::ShaderProgramBasePtr shader; diff --git a/include/mbgl/gfx/drawable_builder.hpp b/include/mbgl/gfx/drawable_builder.hpp index 567c7422022..4a759adf543 100644 --- a/include/mbgl/gfx/drawable_builder.hpp +++ b/include/mbgl/gfx/drawable_builder.hpp @@ -60,6 +60,11 @@ class DrawableBuilder { const Color& getColor() const; void setColor(const Color& value); + enum class ColorMode { PerDrawable, PerVertex }; + /// Set how the color value is used + /// This should not be changed while a build is in progress + void setColorMode(ColorMode mode) { colorMode = mode; } + DepthMaskType getDepthType() const { return depthType; } void setDepthType(DepthMaskType value) { depthType = value; } @@ -98,6 +103,7 @@ class DrawableBuilder { DrawablePtr currentDrawable; std::vector drawables; std::vector tweakers; + ColorMode colorMode = ColorMode::PerVertex; struct Impl; std::unique_ptr impl; diff --git a/include/mbgl/gfx/vertex_attribute.hpp b/include/mbgl/gfx/vertex_attribute.hpp index 5daedc5e7cc..c8df1d680eb 100644 --- a/include/mbgl/gfx/vertex_attribute.hpp +++ b/include/mbgl/gfx/vertex_attribute.hpp @@ -70,16 +70,38 @@ class VertexAttribute { const ElementType& get(std::size_t i) const { return items[i]; } + void reserve(std::size_t count) { items.reserve(count); } + template const ElementType& set(std::size_t i, T value) { - dirty = true; // need to rebuild the raw data next time - items.resize(std::max(items.size(), i + 1)); + if (items.size() < i + 1) { + items.resize(std::max(items.size(), i + 1)); + setDirty(); // need to rebuild the raw data next time + } + if (!isDirty()) { + if (std::holds_alternative(items[i])) { + // TODO: epsilon for floats? + if (std::get(items[i]) != value) { + setDirty(); + } + } else { + // different types + setDirty(); + } + } return items[i] = value; } - bool getDirty() const { return dirty; } - void clearDirty() { - dirty = false; + void clear() { + if (!items.empty()) { + setDirty(); + } + items.clear(); + } + + bool isDirty() const { return dirty; } + void setDirty() { + dirty = true; rawData.clear(); } @@ -159,8 +181,10 @@ class VertexAttributeArray { } /// Indicates whether any values have changed - bool isDirty() const; - void resetDirty(); + bool isDirty() const { + return std::any_of(attrs.begin(), attrs.end(), + [](const auto& kv){ return kv.second && kv.second->isDirty(); }); + } using ResolveDelegate = std::function; /// Call the provided delegate with each value, providing the override if one exists. diff --git a/include/mbgl/gl/drawable_gl.hpp b/include/mbgl/gl/drawable_gl.hpp index ea18a7a00a1..2de566a74bb 100644 --- a/include/mbgl/gl/drawable_gl.hpp +++ b/include/mbgl/gl/drawable_gl.hpp @@ -2,11 +2,11 @@ #include #include +#include #include namespace mbgl { - namespace gfx { class IndexBuffer; @@ -43,7 +43,17 @@ class DrawableGL : public gfx::Drawable { const gfx::UniqueVertexBufferResource& getBuffer() const; const gfx::IndexBuffer& getIndexBuffer() const; - + + /// Reset a single color attribute for all vertexes + void resetColor(const Color&) override; + + static gfx::VertexAttribute::float4 colorAttrValue(const Color& color) { + const auto components = color.toArray(); + return { static_cast(components[0]/255.0), + static_cast(components[1]/255.0), + static_cast(components[2]/255.0), + static_cast(components[3]) }; + } protected: class Impl; const std::unique_ptr impl; diff --git a/include/mbgl/renderer/change_request.hpp b/include/mbgl/renderer/change_request.hpp index 3b2ddcc9974..6539818adec 100644 --- a/include/mbgl/renderer/change_request.hpp +++ b/include/mbgl/renderer/change_request.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -34,6 +35,17 @@ using ChangeRequestPtr = std::shared_ptr; using UniqueChangeRequest = std::unique_ptr; using UniqueChangeRequestVec = std::vector; +/** + Base for drawable-related change requests + */ +class DrawableRefChangeRequest : public ChangeRequest { +protected: + DrawableRefChangeRequest(util::SimpleIdentity id) : drawableID(id) { } + DrawableRefChangeRequest(const DrawableRefChangeRequest&) = default; + + util::SimpleIdentity drawableID; +}; + /** Add a new drawable to the scene @@ -57,16 +69,30 @@ class AddDrawableRequest : public ChangeRequest { /** Remove a drawable from the scene */ -class RemoveDrawableRequest : public ChangeRequest { +class RemoveDrawableRequest : public DrawableRefChangeRequest { public: - RemoveDrawableRequest(util::SimpleIdentity drawableId_) : drawableId(drawableId_) { } - RemoveDrawableRequest(const RemoveDrawableRequest& other) : drawableId(other.drawableId) { } + RemoveDrawableRequest(util::SimpleIdentity id) : DrawableRefChangeRequest(id) { } + RemoveDrawableRequest(const RemoveDrawableRequest&) = default; + + void execute(RenderOrchestrator &) override; +}; + + +/** + Change the color of all vertexes + */ +class ResetColorRequest : public DrawableRefChangeRequest { +public: + ResetColorRequest(util::SimpleIdentity id, Color color) : + DrawableRefChangeRequest(id), + newColor(color) + { } + ResetColorRequest(const ResetColorRequest& other) = default; void execute(RenderOrchestrator &) override; protected: - util::SimpleIdentity drawableId; + Color newColor; }; - } // namespace mbgl diff --git a/src/mbgl/gfx/drawable_builder.cpp b/src/mbgl/gfx/drawable_builder.cpp index 4424aa515e6..3e457fe79ef 100644 --- a/src/mbgl/gfx/drawable_builder.cpp +++ b/src/mbgl/gfx/drawable_builder.cpp @@ -69,14 +69,18 @@ void DrawableBuilder::addTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1 impl->vertices.emplace_back(Impl::VT({{{ x1, y1 }}})); impl->vertices.emplace_back(Impl::VT({{{ x2, y2 }}})); impl->indexes.emplace_back(n, n+1, n+2); - impl->colors.insert(impl->colors.end(), 3, impl->currentColor); + if (colorMode == ColorMode::PerVertex) { + impl->colors.insert(impl->colors.end(), 3, impl->currentColor); + } } void DrawableBuilder::appendTriangle(int16_t x0, int16_t y0) { const auto n = (uint16_t)impl->vertices.elements(); impl->vertices.emplace_back(Impl::VT({{{ x0, y0 }}})); impl->indexes.emplace_back(n-2, n-1, n); - impl->colors.emplace_back(impl->currentColor); + if (colorMode == ColorMode::PerVertex) { + impl->colors.emplace_back(impl->currentColor); + } } void DrawableBuilder::addQuad(int16_t x0, int16_t y0, int16_t x1, int16_t y1) { diff --git a/src/mbgl/gl/drawable_gl.cpp b/src/mbgl/gl/drawable_gl.cpp index 20f8ae4184d..009c5bae92e 100644 --- a/src/mbgl/gl/drawable_gl.cpp +++ b/src/mbgl/gl/drawable_gl.cpp @@ -68,5 +68,12 @@ void DrawableGL::setVertexArray(gl::VertexArray&& vertexArray_, impl->indexBuffer = std::move(indexBuffer_); } +void DrawableGL::resetColor(const Color& newColor) { + if (auto* colorAttr = impl->vertexAttributes.get("a_color")) { + colorAttr->clear(); + colorAttr->set(0, colorAttrValue(newColor)); + } +} + } // namespace gl } // namespace mbgl diff --git a/src/mbgl/gl/drawable_gl_builder.cpp b/src/mbgl/gl/drawable_gl_builder.cpp index 843e2abf386..c3c682fe009 100644 --- a/src/mbgl/gl/drawable_gl_builder.cpp +++ b/src/mbgl/gl/drawable_gl_builder.cpp @@ -22,15 +22,20 @@ void DrawableGLBuilder::init() { } } if (auto colorAttr = attrs.getOrAdd("a_color")) { - std::size_t index = 0; - for (const auto& color : impl->colors) { - const auto comp = color.toArray(); - colorAttr->set(index++, gfx::VertexAttribute::float4 { - static_cast(comp[0]/255.0), - static_cast(comp[1]/255.0), - static_cast(comp[2]/255.0), - static_cast(comp[3]), - }); + // We should have either a single color or one per vertex. Otherwise, + // the color mode was probably changed after vertexes were added. + if (impl->colors.size() > 1 && impl->colors.size() != impl->vertices.elements()) { + impl->colors.clear(); + } + + if (impl->colors.empty()) { + colorAttr->set(0, DrawableGL::colorAttrValue(getColor())); + } else { + std::size_t index = 0; + colorAttr->reserve(impl->colors.size()); + for (const auto& color : impl->colors) { + colorAttr->set(index++, DrawableGL::colorAttrValue(color)); + } } } diff --git a/src/mbgl/renderer/change_request.cpp b/src/mbgl/renderer/change_request.cpp index 7b80b76042c..da7a4ad55a8 100644 --- a/src/mbgl/renderer/change_request.cpp +++ b/src/mbgl/renderer/change_request.cpp @@ -8,7 +8,13 @@ void AddDrawableRequest::execute(RenderOrchestrator &orchestrator) { } void RemoveDrawableRequest::execute(RenderOrchestrator &orchestrator) { - orchestrator.removeDrawable(drawableId); + orchestrator.removeDrawable(drawableID); +} + +void ResetColorRequest::execute(RenderOrchestrator &orchestrator) { + if (auto& drawable = orchestrator.getDrawable(drawableID)) { + drawable->resetColor(newColor); + } } } // namespace mbgl diff --git a/src/mbgl/renderer/render_orchestrator.cpp b/src/mbgl/renderer/render_orchestrator.cpp index 3ee944a33dc..2fb88aba93b 100644 --- a/src/mbgl/renderer/render_orchestrator.cpp +++ b/src/mbgl/renderer/render_orchestrator.cpp @@ -751,6 +751,12 @@ void RenderOrchestrator::removeDrawable(const util::SimpleIdentity& drawableId) drawables.erase(drawableId); } +const gfx::DrawablePtr noDrawable; +const gfx::DrawablePtr& RenderOrchestrator::getDrawable(const util::SimpleIdentity& id) { + const auto hit = drawables.find(id); + return (hit != drawables.end()) ? hit->second : noDrawable; +} + void RenderOrchestrator::updateLayers(gfx::ShaderRegistry& shaders, const TransformState& state, const PropertyEvaluationParameters& evalParameters) { diff --git a/src/mbgl/renderer/render_orchestrator.hpp b/src/mbgl/renderer/render_orchestrator.hpp index 82b96ba6819..fbc0347d673 100644 --- a/src/mbgl/renderer/render_orchestrator.hpp +++ b/src/mbgl/renderer/render_orchestrator.hpp @@ -95,6 +95,8 @@ class RenderOrchestrator final : public GlyphManagerObserver, void addDrawable(gfx::DrawablePtr); void removeDrawable(const util::SimpleIdentity& drawableId); + const gfx::DrawablePtr& getDrawable(const util::SimpleIdentity&); + void updateLayers(gfx::ShaderRegistry&, const TransformState&, const PropertyEvaluationParameters&); diff --git a/src/mbgl/renderer/renderer_impl.cpp b/src/mbgl/renderer/renderer_impl.cpp index ba31d7d6ab0..99bd8b48fe9 100644 --- a/src/mbgl/renderer/renderer_impl.cpp +++ b/src/mbgl/renderer/renderer_impl.cpp @@ -118,7 +118,8 @@ void Renderer::Impl::render(const RenderTree& renderTree) { auto& shader = drawable.getShader(); // Generate a vertex array object for the drawable state, if necessary - if (shader && !drawableGL.getVertexArray().isValid()) { + if (shader && (!drawableGL.getVertexArray().isValid() || + drawableGL.getVertexAttributes().isDirty())) { const auto usage = gfx::BufferUsageType::StaticDraw; // Build index buffer diff --git a/src/mbgl/style/layers/background_layer_impl.cpp b/src/mbgl/style/layers/background_layer_impl.cpp index 7b1d9da2e50..3dd87e96f5f 100644 --- a/src/mbgl/style/layers/background_layer_impl.cpp +++ b/src/mbgl/style/layers/background_layer_impl.cpp @@ -18,10 +18,10 @@ namespace style { BackgroundLayer::Impl::Impl(const Impl& other) : Layer::Impl(other), - shader(other.shader), + tileDrawables(other.tileDrawables), + lastColor(other.lastColor), paint(other.paint) { - // mutex, drawables, stats not copied } bool BackgroundLayer::Impl::hasLayoutDifference(const Layer::Impl&) const { @@ -46,17 +46,18 @@ void BackgroundLayer::Impl::layerAdded(gfx::ShaderRegistry& shaders, } void BackgroundLayer::Impl::layerRemoved(UniqueChangeRequestVec& changes) const { + // TODO: This isn't happening on style change, so old tile drawables are being left active + // Remove everything decltype(tileDrawables) localDrawables; { std::unique_lock guard(mutex); localDrawables = std::move(tileDrawables); } - - for (auto& kv : localDrawables) { - auto& drawable = kv.second; - changes.emplace_back(std::make_unique(drawable->getId())); - } + + removeDrawables( + localDrawables.cbegin(), localDrawables.cend(), changes, + [](auto& ii) { return ii->second->getId(); }); } void BackgroundLayer::Impl::update(const TransformState& state, @@ -64,8 +65,10 @@ void BackgroundLayer::Impl::update(const TransformState& state, UniqueChangeRequestVec& changes) const { std::unique_lock guard(mutex); - const auto uneval = paint.untransitioned(); - const auto eval = uneval.evaluate(evalParameters); + if (!unevaluated) { + unevaluated = paint.untransitioned(); + } + const auto evaluated = unevaluated->evaluate(evalParameters); //const auto passes = eval.get() == 0.0f // ? RenderPass::None @@ -79,13 +82,25 @@ void BackgroundLayer::Impl::update(const TransformState& state, //getCrossfade(evaluatedProperties).t != 1; std::optional color; - if (eval.get().from.empty()) { - const auto opacity = eval.get(); + if (evaluated.get().from.empty()) { + const auto opacity = evaluated.get(); if (opacity > 0.0f) { - color = eval.get() * eval.get(); + color = evaluated.get() * evaluated.get(); } } + // If the result is transparent or missing, just remove any existing drawables and stop + if (!color) { + removeDrawables( + tileDrawables.cbegin(), tileDrawables.cend(), changes, + [](auto& ii) { return ii->second->getId(); }); + tileDrawables.clear(); + return; + } + + const bool colorChange = (color != lastColor); + lastColor = color; + const auto zoom = state.getIntegerZoom(); const auto tileCover = util::tileCover(state, zoom); @@ -99,21 +114,24 @@ void BackgroundLayer::Impl::update(const TransformState& state, // For each existing tile drawable... for (auto iter = tileDrawables.begin(); iter != tileDrawables.end(); ) { + const auto& drawable = iter->second; + // Has this tile dropped out of the cover set? if (newTileIDs.find(iter->first) == newTileIDs.end()) { // remove it - const auto& drawable = iter->second; changes.emplace_back(std::make_unique(drawable->getId())); //Log::Warning(Event::General, "Removing drawable for " + util::toString(iter->first) + " total " + std::to_string(stats.tileDrawablesRemoved+1)); iter = tileDrawables.erase(iter); ++stats.tileDrawablesRemoved; - } else { - ++iter; + continue; } - } + ++iter; - if (!color) { - return; + // If the color evaluated to a new value, emit a change request updating all vertexes of + // the existing drawable to the new color. + if (colorChange) { + changes.emplace_back(std::make_unique(drawable->getId(), *color)); + } } std::unique_ptr builder; @@ -134,6 +152,7 @@ void BackgroundLayer::Impl::update(const TransformState& state, builder->setShader(shader); builder->addTweaker(std::make_shared()); // generally shared across drawables builder->setColor(*color); + builder->setColorMode(gfx::DrawableBuilder::ColorMode::PerDrawable); builder->setDepthType(gfx::DepthMaskType::ReadWrite); } diff --git a/src/mbgl/style/layers/background_layer_impl.hpp b/src/mbgl/style/layers/background_layer_impl.hpp index 1408f7adb5f..d22dd1dc523 100644 --- a/src/mbgl/style/layers/background_layer_impl.hpp +++ b/src/mbgl/style/layers/background_layer_impl.hpp @@ -1,5 +1,7 @@ #pragma once +#include +#include #include #include #include @@ -43,15 +45,27 @@ class BackgroundLayer::Impl : public Layer::Impl { UniqueChangeRequestVec&) const override; private: + // Add a deletion change request for each drawable in a collection + template + static void removeDrawables(T beg, const T end, UniqueChangeRequestVec& changes, + std::function f) { + for (; beg != end; ++beg) { + changes.emplace_back(std::make_unique(f(beg))); + } + } + mutable std::mutex mutex; mutable gfx::ShaderProgramBasePtr shader; mutable std::unordered_map tileDrawables; + mutable std::optional lastColor; mutable struct Stats { size_t tileDrawablesAdded = 0; size_t tileDrawablesRemoved = 0; } stats; + mutable std::optional unevaluated; + public: BackgroundPaintProperties::Transitionable paint; From 49ecfde1ab929acbab38780ea3a20088aebc1640 Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Fri, 28 Apr 2023 12:30:32 -0700 Subject: [PATCH 07/21] Missing include --- include/mbgl/gfx/vertex_attribute.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/include/mbgl/gfx/vertex_attribute.hpp b/include/mbgl/gfx/vertex_attribute.hpp index c8df1d680eb..f2338d25e23 100644 --- a/include/mbgl/gfx/vertex_attribute.hpp +++ b/include/mbgl/gfx/vertex_attribute.hpp @@ -2,6 +2,7 @@ #include +#include #include #include #include From 98c24bf4230439880fda0058fbed0e15ed4ac2a9 Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Fri, 28 Apr 2023 15:07:03 -0700 Subject: [PATCH 08/21] Eliminate GL drawable/builder dependencies from generic background layer --- include/mbgl/gfx/drawable.hpp | 7 +++- include/mbgl/gfx/drawable_builder.hpp | 10 ++++-- include/mbgl/gl/drawable_gl.hpp | 2 +- include/mbgl/gl/drawable_gl_builder.hpp | 6 ++-- src/mbgl/gfx/context.hpp | 11 ++++++ src/mbgl/gfx/drawable.cpp | 3 +- src/mbgl/gfx/drawable_builder.cpp | 7 ++-- src/mbgl/gl/context.cpp | 18 +++++++--- src/mbgl/gl/context.hpp | 3 ++ src/mbgl/gl/drawable_gl.cpp | 5 +-- src/mbgl/gl/drawable_gl_builder.cpp | 4 +-- src/mbgl/renderer/render_orchestrator.cpp | 5 +-- src/mbgl/renderer/render_orchestrator.hpp | 1 + src/mbgl/renderer/renderer.cpp | 9 +++-- src/mbgl/style/layer_impl.hpp | 5 ++- .../style/layers/background_layer_impl.cpp | 36 ++++++++++++------- .../style/layers/background_layer_impl.hpp | 4 ++- 17 files changed, 97 insertions(+), 39 deletions(-) diff --git a/include/mbgl/gfx/drawable.hpp b/include/mbgl/gfx/drawable.hpp index 51cc9341862..cb0a96c89d0 100644 --- a/include/mbgl/gfx/drawable.hpp +++ b/include/mbgl/gfx/drawable.hpp @@ -27,7 +27,7 @@ using DrawableTweakerPtr = std::shared_ptr; class Drawable { protected: - Drawable(); + Drawable(std::string name); public: virtual ~Drawable() = default; @@ -37,6 +37,10 @@ class Drawable { /// Draw the drawable virtual void draw(const PaintParameters &) const = 0; + /// Drawable name is used for debugging and troubleshooting + const std::string& getName() const { return name; } + void setName(std::string value) { name = std::move(value); } + /// Which shader to use when rendering this drawable const gfx::ShaderProgramBasePtr& getShader() const { return shader; } void setShader(gfx::ShaderProgramBasePtr value) { shader = std::move(value); } @@ -76,6 +80,7 @@ class Drawable { virtual void resetColor(const Color&) = 0; protected: + std::string name; util::SimpleIdentity uniqueID; gfx::ShaderProgramBasePtr shader; mat4 matrix; //= matrix::identity4(); diff --git a/include/mbgl/gfx/drawable_builder.hpp b/include/mbgl/gfx/drawable_builder.hpp index 4a759adf543..5af3a921bf2 100644 --- a/include/mbgl/gfx/drawable_builder.hpp +++ b/include/mbgl/gfx/drawable_builder.hpp @@ -24,7 +24,7 @@ using ShaderProgramBasePtr = std::shared_ptr; */ class DrawableBuilder { protected: - DrawableBuilder(); + DrawableBuilder(std::string name); public: virtual ~DrawableBuilder(); @@ -75,6 +75,10 @@ class DrawableBuilder { /// Get the vertex attributes that override default values in the shader program virtual const gfx::VertexAttributeArray& getVertexAttributes() const = 0; + /// Set the name given to new drawables + void setDrawableName(std::string value) { drawableName = std::move(value); } + + /// Set the matrix applied to new drawables void setMatrix(mat4 value) { matrix = value; } /// Add a triangle @@ -90,12 +94,14 @@ class DrawableBuilder { protected: /// Create an instance of the appropriate drawable type - virtual DrawablePtr createDrawable() const = 0; + virtual DrawablePtr createDrawable(std::string name) const = 0; /// Setup the SDK-specific aspects after all the values are present virtual void init() = 0; protected: + std::string name; + std::string drawableName; DrawPriority drawPriority = 0; DepthMaskType depthType = DepthMaskType::ReadOnly; gfx::ShaderProgramBasePtr shader; diff --git a/include/mbgl/gl/drawable_gl.hpp b/include/mbgl/gl/drawable_gl.hpp index 2de566a74bb..18da71d5144 100644 --- a/include/mbgl/gl/drawable_gl.hpp +++ b/include/mbgl/gl/drawable_gl.hpp @@ -22,7 +22,7 @@ class VertexArray; class DrawableGL : public gfx::Drawable { public: - DrawableGL(); + DrawableGL(std::string name); ~DrawableGL() override; void draw(const PaintParameters &) const override; diff --git a/include/mbgl/gl/drawable_gl_builder.hpp b/include/mbgl/gl/drawable_gl_builder.hpp index 50014874273..5ab1166732c 100644 --- a/include/mbgl/gl/drawable_gl_builder.hpp +++ b/include/mbgl/gl/drawable_gl_builder.hpp @@ -11,16 +11,16 @@ namespace gl { */ class DrawableGLBuilder final : public gfx::DrawableBuilder { public: - DrawableGLBuilder() { + DrawableGLBuilder(std::string name) : gfx::DrawableBuilder(std::move(name)) { } ~DrawableGLBuilder() override = default; - + const gfx::VertexAttributeArray& getVertexAttributes() const override { return vertexAttributes; } void setVertexAttributes(const VertexAttributeArrayGL& value) { vertexAttributes = value; } void setVertexAttributes(VertexAttributeArrayGL&& value) { vertexAttributes = std::move(value); } protected: - gfx::DrawablePtr createDrawable() const override; + gfx::DrawablePtr createDrawable(std::string name) const override; /// Setup the SDK-specific aspects after all the values are present void init() override; diff --git a/src/mbgl/gfx/context.hpp b/src/mbgl/gfx/context.hpp index 0df79265ba3..a9dc4a1f753 100644 --- a/src/mbgl/gfx/context.hpp +++ b/src/mbgl/gfx/context.hpp @@ -17,9 +17,14 @@ class ProgramParameters; namespace gfx { class Drawable; +class DrawableBuilder; +class DrawableTweaker; class OffscreenTexture; class ShaderProgramBase; +using DrawablePtr = std::shared_ptr; +using UniqueDrawableBuilder = std::unique_ptr; +using DrawableTweakerPtr = std::shared_ptr; using ShaderProgramBasePtr = std::shared_ptr; @@ -98,6 +103,12 @@ class Context { public: /// Activate the shader, vertex attributes, etc., specified by the drawable virtual bool setupDraw(const PaintParameters&, const gfx::Drawable&) = 0; + + /// Create a new drawable builder + virtual UniqueDrawableBuilder createDrawableBuilder(std::string name) = 0; + + /// Create a new drawable tweaker + virtual DrawableTweakerPtr createDrawableTweaker() = 0; }; } // namespace gfx diff --git a/src/mbgl/gfx/drawable.cpp b/src/mbgl/gfx/drawable.cpp index 1fc6e5c2a42..2c1b5043cba 100644 --- a/src/mbgl/gfx/drawable.cpp +++ b/src/mbgl/gfx/drawable.cpp @@ -5,7 +5,8 @@ namespace mbgl { namespace gfx { -Drawable::Drawable() : +Drawable::Drawable(std::string name_) : + name(name_), matrix(matrix::identity4()), depthType(DepthMaskType::ReadOnly) { diff --git a/src/mbgl/gfx/drawable_builder.cpp b/src/mbgl/gfx/drawable_builder.cpp index 3e457fe79ef..3bf0dbd59fc 100644 --- a/src/mbgl/gfx/drawable_builder.cpp +++ b/src/mbgl/gfx/drawable_builder.cpp @@ -4,8 +4,9 @@ namespace mbgl { namespace gfx { -DrawableBuilder::DrawableBuilder() - : impl(std::make_unique()) { +DrawableBuilder::DrawableBuilder(std::string name_) : + name(std::move(name_)), + impl(std::make_unique()) { } DrawableBuilder::~DrawableBuilder() = default; @@ -19,7 +20,7 @@ void DrawableBuilder::setColor(const Color& value) { DrawablePtr DrawableBuilder::getCurrentDrawable(bool createIfNone) { if (!currentDrawable && createIfNone) { - currentDrawable = createDrawable(); + currentDrawable = createDrawable(drawableName.empty() ? name : drawableName); } return currentDrawable; } diff --git a/src/mbgl/gl/context.cpp b/src/mbgl/gl/context.cpp index cafaf4697b0..1a968c07c8a 100644 --- a/src/mbgl/gl/context.cpp +++ b/src/mbgl/gl/context.cpp @@ -1,15 +1,17 @@ #include +#include +#include #include +#include +#include +#include #include #include -#include #include -#include +#include #include #include -#include #include -#include #include #include #include @@ -471,6 +473,14 @@ bool Context::setupDraw(const PaintParameters& parameters, const gfx::Drawable& } } +gfx::UniqueDrawableBuilder Context::createDrawableBuilder(std::string name) { + return std::make_unique(std::move(name)); +} + +gfx::DrawableTweakerPtr Context::createDrawableTweaker() { + return std::make_shared(); +} + void Context::clear(std::optional color, std::optional depth, std::optional stencil) { diff --git a/src/mbgl/gl/context.hpp b/src/mbgl/gl/context.hpp index 0301e0ce2ae..de2c99916d2 100644 --- a/src/mbgl/gl/context.hpp +++ b/src/mbgl/gl/context.hpp @@ -121,6 +121,9 @@ class Context final : public gfx::Context { bool setupDraw(const PaintParameters&, const gfx::Drawable&) override; + gfx::UniqueDrawableBuilder createDrawableBuilder(std::string name) override; + gfx::DrawableTweakerPtr createDrawableTweaker() override; + private: RendererBackend& backend; bool cleanupOnDestruction = true; diff --git a/src/mbgl/gl/drawable_gl.cpp b/src/mbgl/gl/drawable_gl.cpp index 009c5bae92e..cdfd1ee376d 100644 --- a/src/mbgl/gl/drawable_gl.cpp +++ b/src/mbgl/gl/drawable_gl.cpp @@ -5,8 +5,9 @@ namespace mbgl { namespace gl { -DrawableGL::DrawableGL() - : impl(std::make_unique()) { +DrawableGL::DrawableGL(std::string name) : + Drawable(std::move(name)), + impl(std::make_unique()) { } DrawableGL::~DrawableGL() { diff --git a/src/mbgl/gl/drawable_gl_builder.cpp b/src/mbgl/gl/drawable_gl_builder.cpp index c3c682fe009..979d39808ba 100644 --- a/src/mbgl/gl/drawable_gl_builder.cpp +++ b/src/mbgl/gl/drawable_gl_builder.cpp @@ -7,8 +7,8 @@ namespace mbgl { namespace gl { -gfx::DrawablePtr DrawableGLBuilder::createDrawable() const { - return std::make_shared(); +gfx::DrawablePtr DrawableGLBuilder::createDrawable(std::string name) const { + return std::make_shared(std::move(name)); }; void DrawableGLBuilder::init() { diff --git a/src/mbgl/renderer/render_orchestrator.cpp b/src/mbgl/renderer/render_orchestrator.cpp index 2fb88aba93b..4c89bbf711e 100644 --- a/src/mbgl/renderer/render_orchestrator.cpp +++ b/src/mbgl/renderer/render_orchestrator.cpp @@ -758,6 +758,7 @@ const gfx::DrawablePtr& RenderOrchestrator::getDrawable(const util::SimpleIdenti } void RenderOrchestrator::updateLayers(gfx::ShaderRegistry& shaders, + gfx::Context& context, const TransformState& state, const PropertyEvaluationParameters& evalParameters) { std::vector> changes; @@ -766,11 +767,11 @@ void RenderOrchestrator::updateLayers(gfx::ShaderRegistry& shaders, kv.second->layerRemoved(changes); } for (auto& kv : layersAdded) { - kv.second->layerAdded(shaders, state, evalParameters, changes); + kv.second->layerAdded(shaders, context, state, evalParameters, changes); } for (auto& impl : *layerImpls) { - impl->update(state, evalParameters, changes); + impl->update(context, state, evalParameters, changes); } addChanges(changes); diff --git a/src/mbgl/renderer/render_orchestrator.hpp b/src/mbgl/renderer/render_orchestrator.hpp index fbc0347d673..fc412390ef1 100644 --- a/src/mbgl/renderer/render_orchestrator.hpp +++ b/src/mbgl/renderer/render_orchestrator.hpp @@ -98,6 +98,7 @@ class RenderOrchestrator final : public GlyphManagerObserver, const gfx::DrawablePtr& getDrawable(const util::SimpleIdentity&); void updateLayers(gfx::ShaderRegistry&, + gfx::Context&, const TransformState&, const PropertyEvaluationParameters&); diff --git a/src/mbgl/renderer/renderer.cpp b/src/mbgl/renderer/renderer.cpp index 5eed7317a5d..a8640c4afcc 100644 --- a/src/mbgl/renderer/renderer.cpp +++ b/src/mbgl/renderer/renderer.cpp @@ -1,12 +1,13 @@ #include +#include +#include +#include #include #include #include #include #include -#include -#include namespace mbgl { @@ -46,7 +47,9 @@ void Renderer::render(const std::shared_ptr& updateParameters) const auto& state = renderTreeParameters.transformParams.state; if (impl->staticData && impl->staticData->shaders) { - impl->orchestrator.updateLayers(*impl->staticData->shaders, state, evalParameters); + auto& context = impl->backend.getContext(); + auto& shaders = *impl->staticData->shaders; + impl->orchestrator.updateLayers(shaders, context, state, evalParameters); } impl->render(*renderTree); diff --git a/src/mbgl/style/layer_impl.hpp b/src/mbgl/style/layer_impl.hpp index ba3e7189e7a..f1726ead81d 100644 --- a/src/mbgl/style/layer_impl.hpp +++ b/src/mbgl/style/layer_impl.hpp @@ -23,6 +23,7 @@ using UniqueChangeRequest = std::unique_ptr; using UniqueChangeRequestVec = std::vector; namespace gfx { +class Context; class ShaderRegistry; } // namespace gfx @@ -60,11 +61,13 @@ class Layer::Impl { virtual void populateFontStack(std::set& fontStack) const; /// Generate any changes needed by the layer - virtual void update(const TransformState&, + virtual void update(gfx::Context&, + const TransformState&, const PropertyEvaluationParameters&, UniqueChangeRequestVec&) const { } virtual void layerAdded(gfx::ShaderRegistry&, + gfx::Context&, const TransformState&, const PropertyEvaluationParameters&, UniqueChangeRequestVec&) const { } diff --git a/src/mbgl/style/layers/background_layer_impl.cpp b/src/mbgl/style/layers/background_layer_impl.cpp index 3dd87e96f5f..b59fb4c7ac3 100644 --- a/src/mbgl/style/layers/background_layer_impl.cpp +++ b/src/mbgl/style/layers/background_layer_impl.cpp @@ -1,12 +1,13 @@ #include #include +#include #include -#include -#include #include #include -#include +//#include +//#include +#include #include #include #include @@ -30,19 +31,27 @@ bool BackgroundLayer::Impl::hasLayoutDifference(const Layer::Impl&) const { constexpr auto shaderName = "background_generic"; +struct ShaderHack final : public gfx::ShaderProgramBase { + static constexpr std::string_view Name{"GenericGLShader"}; + const std::string_view typeName() const noexcept override { return Name; } + const gfx::VertexAttributeArray& getUniforms() const override { return *dummy; } + const gfx::VertexAttributeArray& getVertexAttributes() const override { return *dummy; } + gfx::VertexAttributeArray& mutableUniforms() override { return *dummy; } + gfx::VertexAttributeArray& mutableVertexAttributes() override { return *dummy; } + gfx::VertexAttributeArray* dummy = nullptr; +}; + void BackgroundLayer::Impl::layerAdded(gfx::ShaderRegistry& shaders, - const TransformState& state, - const PropertyEvaluationParameters& evalParameters, - UniqueChangeRequestVec& changes) const { + gfx::Context&, + const TransformState&, + const PropertyEvaluationParameters&, + UniqueChangeRequestVec&) const { { std::unique_lock guard(mutex); if (!shader) { - shader = shaders.get(shaderName); + shader = shaders.get(shaderName); } } - - // Add all the tiles - update(state, evalParameters, changes); } void BackgroundLayer::Impl::layerRemoved(UniqueChangeRequestVec& changes) const { @@ -60,7 +69,8 @@ void BackgroundLayer::Impl::layerRemoved(UniqueChangeRequestVec& changes) const [](auto& ii) { return ii->second->getId(); }); } -void BackgroundLayer::Impl::update(const TransformState& state, +void BackgroundLayer::Impl::update(gfx::Context& context, + const TransformState& state, const PropertyEvaluationParameters& evalParameters, UniqueChangeRequestVec& changes) const { std::unique_lock guard(mutex); @@ -148,9 +158,9 @@ void BackgroundLayer::Impl::update(const TransformState& state, // We actually need to build things, so set up a builder if we haven't already if (!builder) { - builder = std::make_unique(); // from GL-specific code via virtual method on ...Context? + builder = context.createDrawableBuilder("background"); builder->setShader(shader); - builder->addTweaker(std::make_shared()); // generally shared across drawables + builder->addTweaker(context.createDrawableTweaker()); builder->setColor(*color); builder->setColorMode(gfx::DrawableBuilder::ColorMode::PerDrawable); builder->setDepthType(gfx::DepthMaskType::ReadWrite); diff --git a/src/mbgl/style/layers/background_layer_impl.hpp b/src/mbgl/style/layers/background_layer_impl.hpp index d22dd1dc523..80bba1d9c55 100644 --- a/src/mbgl/style/layers/background_layer_impl.hpp +++ b/src/mbgl/style/layers/background_layer_impl.hpp @@ -34,13 +34,15 @@ class BackgroundLayer::Impl : public Layer::Impl { void stringifyLayout(rapidjson::Writer&) const override; void layerAdded(gfx::ShaderRegistry&, + gfx::Context&, const TransformState&, const PropertyEvaluationParameters&, UniqueChangeRequestVec&) const override; void layerRemoved(UniqueChangeRequestVec&) const override; /// Generate any changes needed by the layer - void update(const TransformState&, + void update(gfx::Context&, + const TransformState&, const PropertyEvaluationParameters&, UniqueChangeRequestVec&) const override; From 0622f002e65248cbebf0cdbaafb73bf4e2f7f50d Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Fri, 28 Apr 2023 15:26:35 -0700 Subject: [PATCH 09/21] warnings --- include/mbgl/gfx/drawable_builder.hpp | 2 +- include/mbgl/gl/drawable_gl_builder.hpp | 2 +- src/mbgl/gfx/drawable_builder.cpp | 2 +- src/mbgl/gl/drawable_gl_builder.cpp | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/include/mbgl/gfx/drawable_builder.hpp b/include/mbgl/gfx/drawable_builder.hpp index 5af3a921bf2..f0468957b85 100644 --- a/include/mbgl/gfx/drawable_builder.hpp +++ b/include/mbgl/gfx/drawable_builder.hpp @@ -94,7 +94,7 @@ class DrawableBuilder { protected: /// Create an instance of the appropriate drawable type - virtual DrawablePtr createDrawable(std::string name) const = 0; + virtual DrawablePtr createDrawable() const = 0; /// Setup the SDK-specific aspects after all the values are present virtual void init() = 0; diff --git a/include/mbgl/gl/drawable_gl_builder.hpp b/include/mbgl/gl/drawable_gl_builder.hpp index 5ab1166732c..c14e405a552 100644 --- a/include/mbgl/gl/drawable_gl_builder.hpp +++ b/include/mbgl/gl/drawable_gl_builder.hpp @@ -20,7 +20,7 @@ class DrawableGLBuilder final : public gfx::DrawableBuilder { void setVertexAttributes(VertexAttributeArrayGL&& value) { vertexAttributes = std::move(value); } protected: - gfx::DrawablePtr createDrawable(std::string name) const override; + gfx::DrawablePtr createDrawable() const override; /// Setup the SDK-specific aspects after all the values are present void init() override; diff --git a/src/mbgl/gfx/drawable_builder.cpp b/src/mbgl/gfx/drawable_builder.cpp index 3bf0dbd59fc..9616dcb20f6 100644 --- a/src/mbgl/gfx/drawable_builder.cpp +++ b/src/mbgl/gfx/drawable_builder.cpp @@ -20,7 +20,7 @@ void DrawableBuilder::setColor(const Color& value) { DrawablePtr DrawableBuilder::getCurrentDrawable(bool createIfNone) { if (!currentDrawable && createIfNone) { - currentDrawable = createDrawable(drawableName.empty() ? name : drawableName); + currentDrawable = createDrawable(); } return currentDrawable; } diff --git a/src/mbgl/gl/drawable_gl_builder.cpp b/src/mbgl/gl/drawable_gl_builder.cpp index 979d39808ba..cba40f83f35 100644 --- a/src/mbgl/gl/drawable_gl_builder.cpp +++ b/src/mbgl/gl/drawable_gl_builder.cpp @@ -7,8 +7,8 @@ namespace mbgl { namespace gl { -gfx::DrawablePtr DrawableGLBuilder::createDrawable(std::string name) const { - return std::make_shared(std::move(name)); +gfx::DrawablePtr DrawableGLBuilder::createDrawable() const { + return std::make_shared(drawableName.empty() ? name : drawableName); }; void DrawableGLBuilder::init() { From 2281330fb073ebd07a6381cd64231c2e7d24e5bc Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Fri, 28 Apr 2023 15:28:40 -0700 Subject: [PATCH 10/21] warnings --- include/mbgl/gl/drawable_gl_builder.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/mbgl/gl/drawable_gl_builder.hpp b/include/mbgl/gl/drawable_gl_builder.hpp index c14e405a552..88f37572262 100644 --- a/include/mbgl/gl/drawable_gl_builder.hpp +++ b/include/mbgl/gl/drawable_gl_builder.hpp @@ -11,7 +11,7 @@ namespace gl { */ class DrawableGLBuilder final : public gfx::DrawableBuilder { public: - DrawableGLBuilder(std::string name) : gfx::DrawableBuilder(std::move(name)) { + DrawableGLBuilder(std::string name_) : gfx::DrawableBuilder(std::move(name_)) { } ~DrawableGLBuilder() override = default; From 3977838344312bee4aa28e6bf16af9d99c73a1ae Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Fri, 28 Apr 2023 15:44:14 -0700 Subject: [PATCH 11/21] warnings --- src/mbgl/gl/drawable_gl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mbgl/gl/drawable_gl.cpp b/src/mbgl/gl/drawable_gl.cpp index cdfd1ee376d..904fbf6aaf5 100644 --- a/src/mbgl/gl/drawable_gl.cpp +++ b/src/mbgl/gl/drawable_gl.cpp @@ -5,8 +5,8 @@ namespace mbgl { namespace gl { -DrawableGL::DrawableGL(std::string name) : - Drawable(std::move(name)), +DrawableGL::DrawableGL(std::string name_) : + Drawable(std::move(name_)), impl(std::make_unique()) { } From 7308c3501b202d5d9241ba05c7bf4c4235c8265b Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Fri, 28 Apr 2023 15:59:03 -0700 Subject: [PATCH 12/21] missing includes --- src/mbgl/gfx/context.hpp | 3 +++ src/mbgl/gl/context.hpp | 2 -- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mbgl/gfx/context.hpp b/src/mbgl/gfx/context.hpp index a9dc4a1f753..ae02c98c2c8 100644 --- a/src/mbgl/gfx/context.hpp +++ b/src/mbgl/gfx/context.hpp @@ -9,6 +9,9 @@ #include #include +#include +#include + namespace mbgl { class PaintParameters; diff --git a/src/mbgl/gl/context.hpp b/src/mbgl/gl/context.hpp index de2c99916d2..71fcf9c471b 100644 --- a/src/mbgl/gl/context.hpp +++ b/src/mbgl/gl/context.hpp @@ -17,10 +17,8 @@ #include -#include #include #include -#include namespace mbgl { namespace gl { From 403a12bd1b4b61680b869344eaad70b1ec740825 Mon Sep 17 00:00:00 2001 From: Birk Skyum <74932975+birkskyum@users.noreply.github.com> Date: Mon, 1 May 2023 09:41:26 +0200 Subject: [PATCH 13/21] Update paths from maplibre-gl-native to maplibre-native (#1090) --- .github/workflows/node-ci-mac.yml | 10 ++++----- .github/workflows/node-ci.yml | 10 ++++----- .github/workflows/node-release.yml | 10 ++++----- .github/workflows/qt-ci.yml | 22 +++++++++---------- CHANGELOG.md | 8 +++---- CMakeLists.txt | 2 +- README.md | 2 +- SECURITY.md | 2 +- .../2022-10-27-rendering-modularization.md | 2 +- docs/doxygen/MAINPAGE.md | 2 +- docs/doxygen/footer.html | 2 +- docs/mdbook/src/introduction.md | 2 +- platform/android/DEVELOPING.md | 2 +- .../android/gradle/artifact-settings.gradle | 4 ++-- platform/ios/CHANGELOG.md | 8 +++---- platform/ios/platform/ios/INSTALL.md | 6 ++--- platform/ios/platform/ios/README.md | 4 ++-- platform/ios/platform/ios/docs/pod-README.md | 2 +- platform/ios/platform/ios/jazzy.yml | 2 +- .../platform/ios/scripts/deploy-packages.sh | 2 +- .../ios/scripts/deploy-swift-package.sh | 2 +- platform/ios/platform/ios/scripts/publish.sh | 2 +- .../ios/scripts/update-swift-package.sh | 2 +- platform/ios/platform/macos/INSTALL.md | 2 +- .../platform/macos/scripts/deploy-packages.sh | 2 +- platform/linux/README.md | 6 ++--- platform/qt/README.md | 2 +- .../scripts/configure_Qt5_Android_static.sh | 2 +- platform/qt/scripts/configure_Qt5_Linux.sh | 2 +- .../qt/scripts/configure_Qt5_iOS_static.sh | 2 +- platform/qt/scripts/configure_Qt5_macOS.sh | 2 +- .../qt/scripts/configure_Qt5_macOS_static.sh | 2 +- platform/qt/scripts/configure_Qt6_macOS.sh | 2 +- .../qt/scripts/configure_Qt6_macOS_static.sh | 2 +- platform/windows/README.md | 6 ++--- qt_attribution.json | 2 +- 36 files changed, 72 insertions(+), 72 deletions(-) diff --git a/.github/workflows/node-ci-mac.yml b/.github/workflows/node-ci-mac.yml index 934389e88e6..92dc0ec2ef2 100644 --- a/.github/workflows/node-ci-mac.yml +++ b/.github/workflows/node-ci-mac.yml @@ -169,7 +169,7 @@ jobs: ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }}-${{ github.ref }} ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }} - - name: Configure maplibre-gl-native (MacOS) + - name: Configure maplibre-native (MacOS) if: runner.os == 'MacOS' run: | cmake . -B build \ @@ -177,7 +177,7 @@ jobs: -DCMAKE_BUILD_TYPE=${{ env.BUILDTYPE }} \ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ - - name: Configure maplibre-gl-native (Linux) + - name: Configure maplibre-native (Linux) if: runner.os == 'Linux' run: | cmake . -B build \ @@ -205,7 +205,7 @@ jobs: key: | ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }}-${{ hashFiles( '.git/modules/platform/windows/vendor/vcpkg/HEAD' ) }}-${{ hashFiles( 'platform/windows/Get-VendorPackages.ps1' ) }} - - name: Configure maplibre-gl-native (Windows) + - name: Configure maplibre-native (Windows) if: runner.os == 'Windows' run: | cmake . -B build \ @@ -213,12 +213,12 @@ jobs: -DCMAKE_BUILD_TYPE=${{ env.BUILDTYPE }} \ -DCMAKE_CXX_COMPILER_LAUNCHER=sccache - - name: Build maplibre-gl-native (MacOS/Linux) + - name: Build maplibre-native (MacOS/Linux) if: runner.os == 'MacOS' || runner.os == 'Linux' run: | cmake --build build -j $(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null) - - name: Build maplibre-gl-native (Windows) + - name: Build maplibre-native (Windows) if: runner.os == 'Windows' run: | cmake --build build diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index ea171b2e174..d018098bf75 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -168,7 +168,7 @@ jobs: ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }}-${{ github.ref }} ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }} - - name: Configure maplibre-gl-native (MacOS) + - name: Configure maplibre-native (MacOS) if: runner.os == 'MacOS' run: | cmake . -B build \ @@ -177,7 +177,7 @@ jobs: -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ -DMLN_WITH_NODE=ON - - name: Configure maplibre-gl-native (Linux) + - name: Configure maplibre-native (Linux) if: runner.os == 'Linux' run: | cmake . -B build \ @@ -206,7 +206,7 @@ jobs: key: | ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }}-${{ hashFiles( '.git/modules/platform/windows/vendor/vcpkg/HEAD' ) }}-${{ hashFiles( 'platform/windows/Get-VendorPackages.ps1' ) }} - - name: Configure maplibre-gl-native (Windows) + - name: Configure maplibre-native (Windows) if: runner.os == 'Windows' run: | cmake . -B build \ @@ -215,12 +215,12 @@ jobs: -DCMAKE_CXX_COMPILER_LAUNCHER=sccache \ -DMLN_WITH_NODE=ON - - name: Build maplibre-gl-native (MacOS/Linux) + - name: Build maplibre-native (MacOS/Linux) if: runner.os == 'MacOS' || runner.os == 'Linux' run: | cmake --build build -j $(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null) - - name: Build maplibre-gl-native (Windows) + - name: Build maplibre-native (Windows) if: runner.os == 'Windows' run: | cmake --build build diff --git a/.github/workflows/node-release.yml b/.github/workflows/node-release.yml index 4fdd6382a88..54cf6a8bb7f 100644 --- a/.github/workflows/node-release.yml +++ b/.github/workflows/node-release.yml @@ -164,7 +164,7 @@ jobs: ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }}-${{ github.ref }} ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }} - - name: Configure maplibre-gl-native (MacOS) + - name: Configure maplibre-native (MacOS) if: runner.os == 'MacOS' run: | cmake . -B build \ @@ -172,7 +172,7 @@ jobs: -DCMAKE_BUILD_TYPE=${{ env.BUILDTYPE }} \ -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ - - name: Configure maplibre-gl-native (Linux) + - name: Configure maplibre-native (Linux) if: runner.os == 'Linux' run: | cmake . -B build \ @@ -200,7 +200,7 @@ jobs: key: | ${{ matrix.runs-on }}-${{ env.BUILDTYPE }}-${{ github.job }}-${{ hashFiles( '.git/modules/platform/windows/vendor/vcpkg/HEAD' ) }}-${{ hashFiles( 'platform/windows/Get-VendorPackages.ps1' ) }} - - name: Configure maplibre-gl-native (Windows) + - name: Configure maplibre-native (Windows) if: runner.os == 'Windows' run: | cmake . -B build \ @@ -208,12 +208,12 @@ jobs: -DCMAKE_BUILD_TYPE=${{ env.BUILDTYPE }} \ -DCMAKE_CXX_COMPILER_LAUNCHER=sccache - - name: Build maplibre-gl-native (MacOS/Linux) + - name: Build maplibre-native (MacOS/Linux) if: runner.os == 'MacOS' || runner.os == 'Linux' run: | cmake --build build -j $(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null) - - name: Build maplibre-gl-native (Windows) + - name: Build maplibre-native (Windows) if: runner.os == 'Windows' run: | cmake --build build diff --git a/.github/workflows/qt-ci.yml b/.github/workflows/qt-ci.yml index a377eaf91c1..143983c9153 100644 --- a/.github/workflows/qt-ci.yml +++ b/.github/workflows/qt-ci.yml @@ -182,7 +182,7 @@ jobs: with: key: Qt_${{ matrix.name }}_${{ matrix.qt_version }} - - name: Build maplibre-gl-native (macOS) + - name: Build maplibre-native (macOS) if: runner.os == 'macOS' && matrix.qt_target == 'desktop' run: | mkdir build && cd build @@ -200,15 +200,15 @@ jobs: ninja ninja install - - name: Build maplibre-gl-native (Linux, Qt5) + - name: Build maplibre-native (Linux, Qt5) if: runner.os == 'Linux' && matrix.qt_version == '5.15.2' uses: ./source/.github/actions/qt5-build - - name: Build maplibre-gl-native (Linux, Qt6) + - name: Build maplibre-native (Linux, Qt6) if: runner.os == 'Linux' && matrix.qt_version != '5.15.2' uses: ./source/.github/actions/qt6-build - - name: Build maplibre-gl-native (Windows) + - name: Build maplibre-native (Windows) if: runner.os == 'Windows' shell: bash run: | @@ -240,14 +240,14 @@ jobs: QT_VERSION: ${{ matrix.qt_version }} run: | pushd install - tar cjvf ../maplibre-gl-native_${QT_ARCH}_Qt${QT_VERSION}.tar.bz2 * + tar cjvf ../maplibre-native_${QT_ARCH}_Qt${QT_VERSION}.tar.bz2 * popd - name: Upload artifacts uses: actions/upload-artifact@v3 with: - name: maplibre-gl-native_${{ matrix.name }}_Qt${{ matrix.qt_version }} - path: maplibre-gl-native_${{ matrix.name }}_Qt${{ matrix.qt_version }}.tar.bz2 + name: maplibre-native_${{ matrix.name }}_Qt${{ matrix.qt_version }} + path: maplibre-native_${{ matrix.name }}_Qt${{ matrix.qt_version }}.tar.bz2 test-tarball: needs: build @@ -277,7 +277,7 @@ jobs: - name: Download artifacts uses: actions/download-artifact@v3 with: - name: maplibre-gl-native_${{ matrix.name }}_Qt${{ matrix.qt_version }} + name: maplibre-native_${{ matrix.name }}_Qt${{ matrix.qt_version }} - name: Download Qt uses: jurplel/install-qt-action@v3 @@ -296,7 +296,7 @@ jobs: - name: Build test app run: | mkdir install && cd install - tar xf ../maplibre-gl-native_${QT_ARCH}_Qt${QT_VERSION}.tar.bz2 + tar xf ../maplibre-native_${QT_ARCH}_Qt${QT_VERSION}.tar.bz2 cd .. export CMAKE_PREFIX_PATH=$PWD/install mkdir build && cd build @@ -320,7 +320,7 @@ jobs: - name: Download artifacts uses: actions/download-artifact@v3 with: - name: maplibre-gl-native_${{ matrix.name }}_Qt${{ matrix.qt_version }} + name: maplibre-native_${{ matrix.name }}_Qt${{ matrix.qt_version }} - name: Name tarball env: @@ -328,7 +328,7 @@ jobs: TAG_PLATFORM: ${{ matrix.name }} QT_VERSION: ${{ matrix.qt_version }} run: | - mv maplibre-gl-native_${TAG_PLATFORM}_Qt${QT_VERSION}.tar.bz2 QMapLibreGL_${TAG_NAME//qt-/}_Qt${QT_VERSION}_${TAG_PLATFORM}.tar.bz2 + mv maplibre-native_${TAG_PLATFORM}_Qt${QT_VERSION}.tar.bz2 QMapLibreGL_${TAG_NAME//qt-/}_Qt${QT_VERSION}_${TAG_PLATFORM}.tar.bz2 - name: Release uses: ncipollo/release-action@v1 diff --git a/CHANGELOG.md b/CHANGELOG.md index d9386628043..738686f8241 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,10 +5,10 @@ ### ✨ New features - *...Add new stuff here...* -- [core] All CMake properties are now prefixed `MLN_*` [1054](https://github.com/maplibre/maplibre-gl-native/pull/1054). -- [windows] Added windows build support for core applications and node [#707](https://github.com/maplibre/maplibre-gl-native/pull/707) -- [core] Add `ClientOptions` to configure client information [#365](https://github.com/maplibre/maplibre-gl-native/pull/365). -- [node] Add workflow to create node binary releases for Ubuntu 20.04 x64 and MacOS 12 x64/arm64 [#378](https://github.com/maplibre/maplibre-gl-native/pull/378), [#459](https://github.com/maplibre/maplibre-gl-native/pull/459). +- [core] All CMake properties are now prefixed `MLN_*` [1054](https://github.com/maplibre/maplibre-native/pull/1054). +- [windows] Added windows build support for core applications and node [#707](https://github.com/maplibre/maplibre-native/pull/707) +- [core] Add `ClientOptions` to configure client information [#365](https://github.com/maplibre/maplibre-native/pull/365). +- [node] Add workflow to create node binary releases for Ubuntu 20.04 x64 and MacOS 12 x64/arm64 [#378](https://github.com/maplibre/maplibre-native/pull/378), [#459](https://github.com/maplibre/maplibre-native/pull/459). ### ✨ Technical Improvements diff --git a/CMakeLists.txt b/CMakeLists.txt index 09236d50475..630cd7ad68e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1099,7 +1099,7 @@ set_target_properties( mbgl-core PROPERTIES INTERFACE_MAPBOX_NAME "Mapbox GL Native" - INTERFACE_MAPBOX_URL "https://github.com/maplibre/maplibre-gl-native" + INTERFACE_MAPBOX_URL "https://github.com/maplibre/maplibre-native" INTERFACE_MAPBOX_AUTHOR "Mapbox" INTERFACE_MAPBOX_LICENSE ${PROJECT_SOURCE_DIR}/LICENSE.md ) diff --git a/README.md b/README.md index 484c9f4206b..4ff96062e03 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ MapLibre Native is being actively developed. Our big goal for 2023 is to modular Your help in preparing the codebase for the latest graphics backends is more than welcome. Feel free to reach out if you are interested in joining the effort! - Check out the [news](https://maplibre.org/news/) on MapLibre's website. -- See the [Design Proposals](https://github.com/louwers/maplibre-gl-native/tree/main/design-proposals) that have been accepted and are being worked on, the most recent ones being the [Rendering Modularization Design Proposal](design-proposals/2022-10-27-rendering-modularization.md) and the [Metal Port Design Proposal](design-proposals/2022-11-29-metal-port.md). +- See the [Design Proposals](https://github.com/maplibre/maplibre-native/tree/main/design-proposals) that have been accepted and are being worked on, the most recent ones being the [Rendering Modularization Design Proposal](design-proposals/2022-10-27-rendering-modularization.md) and the [Metal Port Design Proposal](design-proposals/2022-11-29-metal-port.md). ## Contributing diff --git a/SECURITY.md b/SECURITY.md index 05a48f0ebd5..83b6a19c82d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,6 +1,6 @@ # Security Policy -To report a vulnerability in MapLibre Native, create a [security advisory](https://github.com/maplibre/maplibre-gl-native/security/advisories/new). +To report a vulnerability in MapLibre Native, create a [security advisory](https://github.com/maplibre/maplibre-native/security/advisories/new). You will be able to privately discuss the issue with the maintainers of MapLibre Native and we can collaborate on a fix. We highly appreciate your reports, but we do not pay out bug bounties at this time. diff --git a/design-proposals/2022-10-27-rendering-modularization.md b/design-proposals/2022-10-27-rendering-modularization.md index 08b1bdf6b91..92af862849e 100644 --- a/design-proposals/2022-10-27-rendering-modularization.md +++ b/design-proposals/2022-10-27-rendering-modularization.md @@ -42,7 +42,7 @@ It is useful to split our goals into three sections to articulate what this prop ### Core Functionality 1. Shader (program) code will be implemented in a modular fashion, such that replacement of any given shader can happen without impacting other shaders. -2. Shader (program) code may no longer be compiled from the [webgl source](https://github.com/maplibre/maplibre-gl-js/tree/main/src/shaders), and should be organized within the maplibre-gl-native repo (as a compile time option). +2. Shader (program) code may no longer be compiled from the [webgl source](https://github.com/maplibre/maplibre-gl-js/tree/main/src/shaders), and should be organized within the maplibre-native repo (as a compile time option). 3. Layer rendering logic should be replaceable at the dev level. All the necessary support should be exposed and a developer should be able to take over representation of any given layer. 4. Developers should be able to associate specific styles with specific layer rendering. The style sheet should be able to call out the type of representation it would like beyond the default. 5. Developers should be able to add new visual representations fed by existing geometry types. Such as data display driven by tile sets or animated markers. diff --git a/docs/doxygen/MAINPAGE.md b/docs/doxygen/MAINPAGE.md index 9f95e9ab6ed..d8e5ecd9ce6 100644 --- a/docs/doxygen/MAINPAGE.md +++ b/docs/doxygen/MAINPAGE.md @@ -2,4 +2,4 @@ This is the documentation of the public C++ API of MapLibre Native Core. You would normally only use this API if you are a contributor to one of the platform specific APIs. If you want to intergrate use MapLibre Native in your project, you are better served by [documentation specific to your platform](https://maplibre.org/projects/maplibre-native/), unless you are interested in the internals of MapLibre Native. -The source code can be found [on GitHub](https://github.com/maplibre/maplibre-gl-native) (the `include` directory contains the public API). +The source code can be found [on GitHub](https://github.com/maplibre/maplibre-native) (the `include` directory contains the public API). diff --git a/docs/doxygen/footer.html b/docs/doxygen/footer.html index 924bcfaf43c..e324c86b647 100644 --- a/docs/doxygen/footer.html +++ b/docs/doxygen/footer.html @@ -4,7 +4,7 @@ diff --git a/docs/mdbook/src/introduction.md b/docs/mdbook/src/introduction.md index 9740223c7fb..1d723ffbd33 100644 --- a/docs/mdbook/src/introduction.md +++ b/docs/mdbook/src/introduction.md @@ -1,5 +1,5 @@ # Introduction -*[MapLibre Native](https://github.com/maplibre/maplibre-gl-native)* is a community led fork of *Mapbox GL Native*. It's a C++ library that powers +*[MapLibre Native](https://github.com/maplibre/maplibre-native)* is a community led fork of *Mapbox GL Native*. It's a C++ library that powers vector maps in native applications on multiple platforms by taking stylesheets that conform to the *MapLibre Style Specification,* a fork of the Mapbox Style Specification. Since it is derived from Mapbox's original work it also uses *Mapbox Vector Tile Specification* as its choice of vector tile format. diff --git a/platform/android/DEVELOPING.md b/platform/android/DEVELOPING.md index b49abc357b6..6593a472eec 100644 --- a/platform/android/DEVELOPING.md +++ b/platform/android/DEVELOPING.md @@ -27,7 +27,7 @@ $ ./gradlew formatKotlin Clone the git repository and pull in submodules: ```bash -git clone git@github.com:maplibre/maplibre-gl-native.git +git clone git@github.com:maplibre/maplibre-native.git git submodule update --init --recursive cd platform/android ``` diff --git a/platform/android/gradle/artifact-settings.gradle b/platform/android/gradle/artifact-settings.gradle index 8adb21b97a8..63fd1f57c36 100644 --- a/platform/android/gradle/artifact-settings.gradle +++ b/platform/android/gradle/artifact-settings.gradle @@ -5,8 +5,8 @@ ext { mapLibreArtifactDescription = 'MapLibre Maps SDK for Android' mapLibreDeveloperName = 'MapLibre' mapLibreDeveloperId = 'maplibre' - mapLibreArtifactUrl = 'https://github.com/maplibre/maplibre-gl-native' - mapLibreArtifactScmUrl = 'scm:git@github.com:maplibre/maplibre-gl-native.git' + mapLibreArtifactUrl = 'https://github.com/maplibre/maplibre-native' + mapLibreArtifactScmUrl = 'scm:git@github.com:maplibre/maplibre-native.git' mapLibreArtifactLicenseName = 'BSD' mapLibreArtifactLicenseUrl = 'https://opensource.org/licenses/BSD-2-Clause' versionName = project.hasProperty('VERSION_NAME') ? project.property('VERSION_NAME') : System.getenv('VERSION_NAME') diff --git a/platform/ios/CHANGELOG.md b/platform/ios/CHANGELOG.md index 0078d59308b..2466f8b3b38 100644 --- a/platform/ios/CHANGELOG.md +++ b/platform/ios/CHANGELOG.md @@ -2,7 +2,7 @@ Each MapLibre Native SDK has a separate changelog that highlights changes relevant to their respective platforms: -* [MapLibre Maps SDK for Android](../../platform/android/CHANGELOG.md) -* [MapLibre Maps SDK for iOS](platform/ios/CHANGELOG.md) -* [MapLibre Maps SDK for macOS](platform/macos/CHANGELOG.md) -* [node-maplibre-gl-native](../../platform/node/CHANGELOG.md) +* [MapLibre Native for Android](../../platform/android/CHANGELOG.md) +* [MapLibre Native for iOS](platform/ios/CHANGELOG.md) +* [MapLibre Native for macOS](platform/macos/CHANGELOG.md) +* [MapLibre Native for Node](../../platform/node/CHANGELOG.md) diff --git a/platform/ios/platform/ios/INSTALL.md b/platform/ios/platform/ios/INSTALL.md index 56d5a834b2c..e86cdb9773b 100644 --- a/platform/ios/platform/ios/INSTALL.md +++ b/platform/ios/platform/ios/INSTALL.md @@ -40,8 +40,8 @@ Before building, follow these steps to install prerequisites: ### Build the iOS Demo App ``` -git clone --recurse-submodules git@github.com:maplibre/maplibre-gl-native.git -cd maplibre-gl-native/platform/ios +git clone --recurse-submodules git@github.com:maplibre/maplibre-native.git +cd maplibre-native/platform/ios make iproj ``` @@ -58,7 +58,7 @@ If you wish to deploy on attached hardware, you need to setup your Apple Develop 1. Clone the git repository: ```bash git clone --recurse-submodules https://github.com/maplibre/maplibre-native.git - cd maplibre-gl-native + cd maplibre-native ``` Note that you must check out the project's git submodules to build. If you did not include `--recurse-submodules` in the clone, you can later run `git submodule update --init`. 1. Run `make iframework BUILDTYPE=Release`. The packaging script will produce a `build/ios/pkg/` folder containing: diff --git a/platform/ios/platform/ios/README.md b/platform/ios/platform/ios/README.md index e5ca9bf58ab..b67311a3dbb 100644 --- a/platform/ios/platform/ios/README.md +++ b/platform/ios/platform/ios/README.md @@ -2,7 +2,7 @@ [![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/ios-ci/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/ios-ci.yml) [![GitHub Action build status](https://github.com/maplibre/maplibre-native/workflows/ios-release/badge.svg)](https://github.com/maplibre/maplibre-native/actions/workflows/ios-release.yml) -A library based on [MapLibre Native](https://github.com/maplibre/maplibre-gl-native) for embedding interactive map views with scalable, customizable vector maps into Cocoa Touch applications on iOS using Objective-C, Swift, or Interface Builder. +A library based on [MapLibre Native](https://github.com/maplibre/maplibre-native) for embedding interactive map views with scalable, customizable vector maps into Cocoa Touch applications on iOS using Objective-C, Swift, or Interface Builder. * [Learn about custom builds](INSTALL.md) @@ -12,7 +12,7 @@ A library based on [MapLibre Native](https://github.com/maplibre/maplibre-gl-nat 1. To add a package dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter its repository URL. You can also navigate to your target’s General pane, and in the “Frameworks, Libraries, and Embedded Content” section, click the + button, select Add Other, and choose Add Package Dependency. -2. Either add MapLibre GitHub distribution URL (https://github.com/maplibre/maplibre-gl-native-distribution) or search for `maplibre-gl-native` package. +2. Either add MapLibre GitHub distribution URL (https://github.com/maplibre/maplibre-gl-native-distribution) or search for `maplibre-native` package. 3. Choose "next". Xcode should clone the distribution repository and download the binaries. diff --git a/platform/ios/platform/ios/docs/pod-README.md b/platform/ios/platform/ios/docs/pod-README.md index 891939193b9..93c202aade7 100644 --- a/platform/ios/platform/ios/docs/pod-README.md +++ b/platform/ios/platform/ios/docs/pod-README.md @@ -2,7 +2,7 @@ MapLibre Native for iOS is an open-source framework for embedding interactive map views with scalable, customizable vector maps into Cocoa Touch applications on iOS 9.0 and above using Objective-C, Swift, or Interface Builder. It takes stylesheets that conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-gl-js-docs/style-spec/), applies them to vector tiles that conform to the [Mapbox Vector Tile Specification](https://docs.mapbox.com/data/tilesets/guides/vector-tiles-standards/), and renders them using OpenGL. -For more information, check out the [MapLibre Native for iOS repository](https://github.com/maplibre/maplibre-gl-native) and the [full changelog](https://github.com/maplibre/maplibre-native/blob/main/platform/ios/platform/ios/CHANGELOG.md) online. +For more information, check out the [MapLibre Native for iOS repository](https://github.com/maplibre/maplibre-native) and the [full changelog](https://github.com/maplibre/maplibre-native/blob/main/platform/ios/platform/ios/CHANGELOG.md) online. [![](https://raw.githubusercontent.com/mapbox/mapbox-gl-native-ios/master/platform/ios/docs/img/screenshot.png)]() diff --git a/platform/ios/platform/ios/jazzy.yml b/platform/ios/platform/ios/jazzy.yml index 5b568f9ba11..51686270167 100644 --- a/platform/ios/platform/ios/jazzy.yml +++ b/platform/ios/platform/ios/jazzy.yml @@ -1,7 +1,7 @@ module: MapLibre author: MapLibre Contributors author_url: https://maplibre.org/ -github_url: https://github.com/maplibre/maplibre-gl-native +github_url: https://github.com/maplibre/maplibre-native copyright: '[License](https://github.com/maplibre/maplibre-native/blob/main/platform/ios/LICENSE.md)' head: | diff --git a/platform/ios/platform/ios/scripts/deploy-packages.sh b/platform/ios/platform/ios/scripts/deploy-packages.sh index 79353b556fa..f318058b868 100755 --- a/platform/ios/platform/ios/scripts/deploy-packages.sh +++ b/platform/ios/platform/ios/scripts/deploy-packages.sh @@ -46,7 +46,7 @@ buildPackageStyle() { } export GITHUB_USER=maplibre -export GITHUB_REPO=maplibre-gl-native +export GITHUB_REPO=maplibre-native export BUILDTYPE=Release export PACKAGE_FORMAT=xcframework diff --git a/platform/ios/platform/ios/scripts/deploy-swift-package.sh b/platform/ios/platform/ios/scripts/deploy-swift-package.sh index ebd5dc39d10..70cd969eb44 100755 --- a/platform/ios/platform/ios/scripts/deploy-swift-package.sh +++ b/platform/ios/platform/ios/scripts/deploy-swift-package.sh @@ -17,7 +17,7 @@ function finish { >&2 echo -en "\033[0m"; } trap finish EXIT export GITHUB_USER=maplibre -export GITHUB_REPO=maplibre-gl-native +export GITHUB_REPO=maplibre-native export BUILDTYPE=Release export DISTRIBUTION_GITHUB_REPO=https://api.github.com/repos/maplibre/maplibre-gl-native-distribution diff --git a/platform/ios/platform/ios/scripts/publish.sh b/platform/ios/platform/ios/scripts/publish.sh index 3160d4042bc..d8b5840dcca 100755 --- a/platform/ios/platform/ios/scripts/publish.sh +++ b/platform/ios/platform/ios/scripts/publish.sh @@ -18,7 +18,7 @@ else PUBLISH_STYLE="" fi -GITHUB_REPO=${GITHUB_REPO:-'maplibre-gl-native'} +GITHUB_REPO=${GITHUB_REPO:-'maplibre-native'} # # zip diff --git a/platform/ios/platform/ios/scripts/update-swift-package.sh b/platform/ios/platform/ios/scripts/update-swift-package.sh index f106a71c115..840c77af80b 100755 --- a/platform/ios/platform/ios/scripts/update-swift-package.sh +++ b/platform/ios/platform/ios/scripts/update-swift-package.sh @@ -17,7 +17,7 @@ rm -f Package.swift cp platform/ios/scripts/swift_package_template.swift Package.swift export GITHUB_USER=maplibre -export GITHUB_REPO=maplibre-gl-native +export GITHUB_REPO=maplibre-native export BUILDTYPE=Release export DISTRIBUTION_GITHUB_REPO=https://api.github.com/repos/maplibre/maplibre-gl-native-distribution diff --git a/platform/ios/platform/macos/INSTALL.md b/platform/ios/platform/macos/INSTALL.md index ff4fa23aa4e..c2e56bce47a 100644 --- a/platform/ios/platform/macos/INSTALL.md +++ b/platform/ios/platform/macos/INSTALL.md @@ -39,7 +39,7 @@ To build the SDK from source: 1. Clone the git repository: ```bash git clone https://github.com/maplibre/maplibre-native.git - cd maplibre-gl-native + cd maplibre-native ``` Note that this repository uses Git submodules. They'll be automatically checked out when you first run a `make` command, but are not updated automatically. We recommended that you run `git submodule update` after pulling down new commits to diff --git a/platform/ios/platform/macos/scripts/deploy-packages.sh b/platform/ios/platform/macos/scripts/deploy-packages.sh index 2cf92b96f61..f45b1387c03 100755 --- a/platform/ios/platform/macos/scripts/deploy-packages.sh +++ b/platform/ios/platform/macos/scripts/deploy-packages.sh @@ -77,7 +77,7 @@ publish() { } export GITHUB_USER=maplibre -export GITHUB_REPO=maplibre-gl-native +export GITHUB_REPO=maplibre-native export BUILDTYPE=Release diff --git a/platform/linux/README.md b/platform/linux/README.md index 585938d46c8..f755d3d49e6 100644 --- a/platform/linux/README.md +++ b/platform/linux/README.md @@ -35,7 +35,7 @@ First, clone the repository. This repository uses git submodules, which are also ```bash git clone --recurse-submodules -j8 https://github.com/maplibre/maplibre-native.git -cd maplibre-gl-native +cd maplibre-native ``` To create the build, run the following commands. @@ -45,7 +45,7 @@ cmake . -B build -G Ninja -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_C_COMPILE cmake --build build -j $(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null) ``` -If all went well, there should now be a `maplibre-gl-native/build/bin/mbgl-render` binary that you can run to generate map tile images. To test that it is working properly, run the following command. +If all went well, there should now be a `maplibre-native/build/bin/mbgl-render` binary that you can run to generate map tile images. To test that it is working properly, run the following command. ```bash ./build/bin/mbgl-render --style https://raw.githubusercontent.com/maplibre/demotiles/gh-pages/style.json --output out.png @@ -150,7 +150,7 @@ For the purposes of this exercise, you can use the `zurich_switzerland.mbtiles` Note that this style is totally inadequate for any real use beyond testing your custom setup. Don't forget to replace the source URL `"mbtiles:///path/to/zurich_switzerland.mbtiles"` with the actual path to your mbtiles file. -From your `maplibre-gl-native/` dir, run the following command. +From your `maplibre-native/` dir, run the following command. ```bash ./build/bin/mbgl-render --style /path/to/style.json --output out.png diff --git a/platform/qt/README.md b/platform/qt/README.md index 7a2e0718344..81c18376fc9 100644 --- a/platform/qt/README.md +++ b/platform/qt/README.md @@ -29,7 +29,7 @@ A minimal set of commands to build and install is ```shell mkdir build && cd build -cmake ../maplibre-gl-native/ \ +cmake ../maplibre-native/ \ -GNinja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX= \ diff --git a/platform/qt/scripts/configure_Qt5_Android_static.sh b/platform/qt/scripts/configure_Qt5_Android_static.sh index a9377addde6..42d8729b15e 100755 --- a/platform/qt/scripts/configure_Qt5_Android_static.sh +++ b/platform/qt/scripts/configure_Qt5_Android_static.sh @@ -1,7 +1,7 @@ #!/bin/bash if [[ -z ${1+x} ]]; then - echo "Error: Pass the path to maplibre-gl-native as first argument" 1>&2 + echo "Error: Pass the path to maplibre-native as first argument" 1>&2 exit 1 fi diff --git a/platform/qt/scripts/configure_Qt5_Linux.sh b/platform/qt/scripts/configure_Qt5_Linux.sh index a86a9560836..c671461b9d0 100755 --- a/platform/qt/scripts/configure_Qt5_Linux.sh +++ b/platform/qt/scripts/configure_Qt5_Linux.sh @@ -1,7 +1,7 @@ #!/bin/bash if [[ -z ${1+x} ]]; then - echo "Error: Pass the path to maplibre-gl-native as first argument" 1>&2 + echo "Error: Pass the path to maplibre-native as first argument" 1>&2 exit 1 fi diff --git a/platform/qt/scripts/configure_Qt5_iOS_static.sh b/platform/qt/scripts/configure_Qt5_iOS_static.sh index 3d113aea6d2..8310b5fdfb2 100755 --- a/platform/qt/scripts/configure_Qt5_iOS_static.sh +++ b/platform/qt/scripts/configure_Qt5_iOS_static.sh @@ -1,7 +1,7 @@ #!/bin/bash if [[ -z ${1+x} ]]; then - echo "Error: Pass the path to maplibre-gl-native as first argument" 1>&2 + echo "Error: Pass the path to maplibre-native as first argument" 1>&2 exit 1 fi diff --git a/platform/qt/scripts/configure_Qt5_macOS.sh b/platform/qt/scripts/configure_Qt5_macOS.sh index f079ed20200..b1db79dc399 100755 --- a/platform/qt/scripts/configure_Qt5_macOS.sh +++ b/platform/qt/scripts/configure_Qt5_macOS.sh @@ -1,7 +1,7 @@ #!/bin/bash if [[ -z ${1+x} ]]; then - echo "Error: Pass the path to maplibre-gl-native as first argument" 1>&2 + echo "Error: Pass the path to maplibre-native as first argument" 1>&2 exit 1 fi diff --git a/platform/qt/scripts/configure_Qt5_macOS_static.sh b/platform/qt/scripts/configure_Qt5_macOS_static.sh index bd014a8e35a..df63de25279 100755 --- a/platform/qt/scripts/configure_Qt5_macOS_static.sh +++ b/platform/qt/scripts/configure_Qt5_macOS_static.sh @@ -1,7 +1,7 @@ #!/bin/bash if [[ -z ${1+x} ]]; then - echo "Error: Pass the path to maplibre-gl-native as first argument" 1>&2 + echo "Error: Pass the path to maplibre-native as first argument" 1>&2 exit 1 fi diff --git a/platform/qt/scripts/configure_Qt6_macOS.sh b/platform/qt/scripts/configure_Qt6_macOS.sh index b535ba127d7..c105191b7c4 100755 --- a/platform/qt/scripts/configure_Qt6_macOS.sh +++ b/platform/qt/scripts/configure_Qt6_macOS.sh @@ -1,7 +1,7 @@ #!/bin/bash if [[ -z ${1+x} ]]; then - echo "Error: Pass the path to maplibre-gl-native as first argument" 1>&2 + echo "Error: Pass the path to maplibre-native as first argument" 1>&2 exit 1 fi diff --git a/platform/qt/scripts/configure_Qt6_macOS_static.sh b/platform/qt/scripts/configure_Qt6_macOS_static.sh index 08a440eb896..43f48ac2e8a 100755 --- a/platform/qt/scripts/configure_Qt6_macOS_static.sh +++ b/platform/qt/scripts/configure_Qt6_macOS_static.sh @@ -1,7 +1,7 @@ #!/bin/bash if [[ -z ${1+x} ]]; then - echo "Error: Pass the path to maplibre-gl-native as first argument" 1>&2 + echo "Error: Pass the path to maplibre-native as first argument" 1>&2 exit 1 fi diff --git a/platform/windows/README.md b/platform/windows/README.md index c6f8c083ea4..917787f1268 100644 --- a/platform/windows/README.md +++ b/platform/windows/README.md @@ -16,7 +16,7 @@ Open `x64 Native Tools Command Prompt for VS 2022` and then clone the repository ```cmd git clone --recurse-submodules -j8 https://github.com/maplibre/maplibre-native.git -cd maplibre-gl-native +cd maplibre-native ``` ## Configuring @@ -75,7 +75,7 @@ Once configure is done, open the file `build\Mapbox GL Native.sln`. Build the ta ## Testing -If all went well and target `mbgl-render` or `ALL_BUILD` was chosen, there should now be a `maplibre-gl-native\build\bin\mbgl-render.exe` binary that you can run to generate map tile images. To test that it is working properly, run the following command. +If all went well and target `mbgl-render` or `ALL_BUILD` was chosen, there should now be a `maplibre-native\build\bin\mbgl-render.exe` binary that you can run to generate map tile images. To test that it is working properly, run the following command. ```cmd .\build\bin\mbgl-render.exe --style https://raw.githubusercontent.com/maplibre/demotiles/gh-pages/style.json --output out.png @@ -172,7 +172,7 @@ For the purposes of this exercise, you can use the `zurich_switzerland.mbtiles` Note that this style is totally inadequate for any real use beyond testing your custom setup. Don't forget to replace the source URL `"mbtiles:///path/to/zurich_switzerland.mbtiles"` with the actual path to your mbtiles file. -From your `maplibre-gl-native/` dir, run the following command. +From your `maplibre-native/` dir, run the following command. ```cmd .\build\bin\mbgl-render --style path\to\style.json --output out.png diff --git a/qt_attribution.json b/qt_attribution.json index be7b093c2c6..6abf25504cc 100644 --- a/qt_attribution.json +++ b/qt_attribution.json @@ -5,7 +5,7 @@ "QtUsage": "Used in the MapLibre backend of Qt Location.", "Description": "MapLibre Native is a community led fork derived from mapbox-gl-native.", - "Homepage": "https://github.com/maplibre/maplibre-gl-native", + "Homepage": "https://github.com/maplibre/maplibre-native", "LicenseId": "BSD-2-Clause", "License": "BSD 2-Clause License", "LicenseFile": "LICENSE.md", From 539d827970f5d8edc56a70e5cb9837a44b1ddd5b Mon Sep 17 00:00:00 2001 From: Tim Sylvester Date: Mon, 1 May 2023 07:51:07 -0700 Subject: [PATCH 14/21] Move generic shader lookup to context virtual --- src/mbgl/gfx/context.hpp | 4 ++++ src/mbgl/gl/context.cpp | 6 ++++++ src/mbgl/gl/context.hpp | 2 ++ src/mbgl/style/layers/background_layer_impl.cpp | 14 ++------------ 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/mbgl/gfx/context.hpp b/src/mbgl/gfx/context.hpp index ae02c98c2c8..e047ec29b6e 100644 --- a/src/mbgl/gfx/context.hpp +++ b/src/mbgl/gfx/context.hpp @@ -24,6 +24,7 @@ class DrawableBuilder; class DrawableTweaker; class OffscreenTexture; class ShaderProgramBase; +class ShaderRegistry; using DrawablePtr = std::shared_ptr; using UniqueDrawableBuilder = std::unique_ptr; @@ -112,6 +113,9 @@ class Context { /// Create a new drawable tweaker virtual DrawableTweakerPtr createDrawableTweaker() = 0; + + /// Get the generic shader with the specified name + virtual gfx::ShaderProgramBasePtr getGenericShader(gfx::ShaderRegistry&, const std::string& name) = 0; }; } // namespace gfx diff --git a/src/mbgl/gl/context.cpp b/src/mbgl/gl/context.cpp index 1a968c07c8a..81a59b0d869 100644 --- a/src/mbgl/gl/context.cpp +++ b/src/mbgl/gl/context.cpp @@ -1,4 +1,6 @@ #include + +#include #include #include #include @@ -481,6 +483,10 @@ gfx::DrawableTweakerPtr Context::createDrawableTweaker() { return std::make_shared(); } +gfx::ShaderProgramBasePtr Context::getGenericShader(gfx::ShaderRegistry& shaders, const std::string& name) { + return shaders.get(name); +} + void Context::clear(std::optional color, std::optional depth, std::optional stencil) { diff --git a/src/mbgl/gl/context.hpp b/src/mbgl/gl/context.hpp index 71fcf9c471b..14f9d6be7dc 100644 --- a/src/mbgl/gl/context.hpp +++ b/src/mbgl/gl/context.hpp @@ -122,6 +122,8 @@ class Context final : public gfx::Context { gfx::UniqueDrawableBuilder createDrawableBuilder(std::string name) override; gfx::DrawableTweakerPtr createDrawableTweaker() override; + gfx::ShaderProgramBasePtr getGenericShader(gfx::ShaderRegistry&, const std::string& name) override; + private: RendererBackend& backend; bool cleanupOnDestruction = true; diff --git a/src/mbgl/style/layers/background_layer_impl.cpp b/src/mbgl/style/layers/background_layer_impl.cpp index b59fb4c7ac3..6fa0064f49d 100644 --- a/src/mbgl/style/layers/background_layer_impl.cpp +++ b/src/mbgl/style/layers/background_layer_impl.cpp @@ -31,25 +31,15 @@ bool BackgroundLayer::Impl::hasLayoutDifference(const Layer::Impl&) const { constexpr auto shaderName = "background_generic"; -struct ShaderHack final : public gfx::ShaderProgramBase { - static constexpr std::string_view Name{"GenericGLShader"}; - const std::string_view typeName() const noexcept override { return Name; } - const gfx::VertexAttributeArray& getUniforms() const override { return *dummy; } - const gfx::VertexAttributeArray& getVertexAttributes() const override { return *dummy; } - gfx::VertexAttributeArray& mutableUniforms() override { return *dummy; } - gfx::VertexAttributeArray& mutableVertexAttributes() override { return *dummy; } - gfx::VertexAttributeArray* dummy = nullptr; -}; - void BackgroundLayer::Impl::layerAdded(gfx::ShaderRegistry& shaders, - gfx::Context&, + gfx::Context& context, const TransformState&, const PropertyEvaluationParameters&, UniqueChangeRequestVec&) const { { std::unique_lock guard(mutex); if (!shader) { - shader = shaders.get(shaderName); + shader = context.getGenericShader(shaders, shaderName); } } } From 71f6da27228c6b95ccd0e5d9e7229eba41724012 Mon Sep 17 00:00:00 2001 From: Bart Louwers Date: Mon, 1 May 2023 16:57:37 +0200 Subject: [PATCH 15/21] Add clang-format (#1086) Co-authored-by: mwilsnd --- .clang-format | 18 + .pre-commit-config.yaml | 7 + DEVELOPING.md | 15 + benchmark/api/query.benchmark.cpp | 21 +- benchmark/api/render.benchmark.cpp | 50 +- .../function/camera_function.benchmark.cpp | 22 +- .../function/composite_function.benchmark.cpp | 21 +- .../function/source_function.benchmark.cpp | 19 +- benchmark/parse/filter.benchmark.cpp | 2 +- benchmark/parse/tile_mask.benchmark.cpp | 21 +- benchmark/parse/vector_tile.benchmark.cpp | 3 +- .../benchmark/stub_geometry_tile_feature.hpp | 23 +- .../storage/offline_database.benchmark.cpp | 40 +- benchmark/util/tilecover.benchmark.cpp | 46 +- bin/offline.cpp | 123 +- bin/render.cpp | 32 +- expression-test/expression_test_logger.cpp | 21 +- expression-test/expression_test_logger.hpp | 8 +- expression-test/expression_test_parser.cpp | 79 +- expression-test/expression_test_parser.hpp | 7 +- expression-test/expression_test_runner.cpp | 44 +- expression-test/expression_test_runner.hpp | 6 +- expression-test/main.cpp | 24 +- expression-test/test_runner_common.cpp | 4 +- include/mbgl/actor/actor.hpp | 63 +- include/mbgl/actor/actor_ref.hpp | 31 +- include/mbgl/actor/aspiring_actor.hpp | 43 +- include/mbgl/actor/established_actor.hpp | 56 +- include/mbgl/actor/mailbox.hpp | 5 +- include/mbgl/actor/message.hpp | 41 +- include/mbgl/actor/scheduler.hpp | 21 +- include/mbgl/annotation/annotation.hpp | 16 +- include/mbgl/gfx/backend.hpp | 10 +- include/mbgl/gfx/backend_scope.hpp | 9 +- include/mbgl/gfx/renderable.hpp | 8 +- include/mbgl/gfx/renderer_backend.hpp | 15 +- include/mbgl/gfx/shader.hpp | 44 +- include/mbgl/gfx/shader_registry.hpp | 237 ++- include/mbgl/gl/custom_layer.hpp | 37 +- include/mbgl/gl/custom_layer_factory.hpp | 3 +- include/mbgl/gl/renderable_resource.hpp | 4 +- include/mbgl/gl/renderer_backend.hpp | 14 +- include/mbgl/i18n/collator.hpp | 4 +- .../layermanager/background_layer_factory.hpp | 3 +- .../layermanager/circle_layer_factory.hpp | 3 +- .../fill_extrusion_layer_factory.hpp | 7 +- .../mbgl/layermanager/fill_layer_factory.hpp | 7 +- .../layermanager/heatmap_layer_factory.hpp | 6 +- .../layermanager/hillshade_layer_factory.hpp | 3 +- include/mbgl/layermanager/layer_factory.hpp | 23 +- include/mbgl/layermanager/layer_manager.hpp | 44 +- .../mbgl/layermanager/line_layer_factory.hpp | 3 +- .../layermanager/raster_layer_factory.hpp | 3 +- .../layermanager/symbol_layer_factory.hpp | 3 +- include/mbgl/map/bound_options.hpp | 17 +- include/mbgl/map/camera.hpp | 77 +- include/mbgl/map/map.hpp | 31 +- include/mbgl/map/map_observer.hpp | 2 +- include/mbgl/map/map_options.hpp | 2 +- include/mbgl/map/mode.hpp | 12 +- include/mbgl/map/projection_mode.hpp | 17 +- include/mbgl/math/log2.hpp | 3 +- include/mbgl/platform/gl_functions.hpp | 511 ++--- include/mbgl/platform/settings.hpp | 5 +- include/mbgl/renderer/renderer.hpp | 34 +- include/mbgl/renderer/renderer_frontend.hpp | 1 - include/mbgl/renderer/renderer_observer.hpp | 2 +- include/mbgl/renderer/renderer_state.hpp | 5 +- include/mbgl/shaders/gl/background.hpp | 3 +- .../mbgl/shaders/gl/background_pattern.hpp | 3 +- include/mbgl/shaders/gl/circle.hpp | 3 +- include/mbgl/shaders/gl/clipping_mask.hpp | 3 +- include/mbgl/shaders/gl/collision_box.hpp | 3 +- include/mbgl/shaders/gl/collision_circle.hpp | 3 +- include/mbgl/shaders/gl/debug.hpp | 3 +- include/mbgl/shaders/gl/fill.hpp | 3 +- include/mbgl/shaders/gl/fill_extrusion.hpp | 3 +- .../shaders/gl/fill_extrusion_pattern.hpp | 3 +- include/mbgl/shaders/gl/fill_outline.hpp | 3 +- .../mbgl/shaders/gl/fill_outline_pattern.hpp | 3 +- include/mbgl/shaders/gl/fill_pattern.hpp | 3 +- include/mbgl/shaders/gl/heatmap.hpp | 3 +- include/mbgl/shaders/gl/heatmap_texture.hpp | 3 +- include/mbgl/shaders/gl/hillshade.hpp | 3 +- include/mbgl/shaders/gl/hillshade_prepare.hpp | 3 +- include/mbgl/shaders/gl/line.hpp | 3 +- include/mbgl/shaders/gl/line_gradient.hpp | 3 +- include/mbgl/shaders/gl/line_pattern.hpp | 3 +- include/mbgl/shaders/gl/line_sdf.hpp | 3 +- include/mbgl/shaders/gl/prelude.hpp | 3 +- include/mbgl/shaders/gl/raster.hpp | 3 +- include/mbgl/shaders/gl/symbol_icon.hpp | 3 +- include/mbgl/shaders/gl/symbol_sdf_icon.hpp | 3 +- include/mbgl/shaders/gl/symbol_sdf_text.hpp | 3 +- .../mbgl/shaders/gl/symbol_text_and_icon.hpp | 3 +- include/mbgl/shaders/shader_source.hpp | 6 +- include/mbgl/storage/database_file_source.hpp | 84 +- include/mbgl/storage/file_source.hpp | 25 +- include/mbgl/storage/file_source_manager.hpp | 20 +- include/mbgl/storage/offline.hpp | 77 +- include/mbgl/storage/resource.hpp | 22 +- include/mbgl/storage/resource_options.hpp | 3 +- include/mbgl/storage/response.hpp | 24 +- .../mbgl/style/color_ramp_property_value.hpp | 11 +- include/mbgl/style/conversion.hpp | 12 +- .../conversion/color_ramp_property_value.hpp | 5 +- include/mbgl/style/conversion/coordinate.hpp | 6 +- include/mbgl/style/conversion/function.hpp | 9 +- .../mbgl/style/conversion/property_value.hpp | 23 +- include/mbgl/style/conversion/source.hpp | 4 +- include/mbgl/style/conversion_impl.hpp | 215 +- include/mbgl/style/expression/assertion.hpp | 6 +- include/mbgl/style/expression/at.hpp | 19 +- .../style/expression/boolean_operator.hpp | 20 +- include/mbgl/style/expression/case.hpp | 7 +- include/mbgl/style/expression/coalesce.hpp | 23 +- include/mbgl/style/expression/coercion.hpp | 8 +- include/mbgl/style/expression/collator.hpp | 1 + .../style/expression/collator_expression.hpp | 16 +- include/mbgl/style/expression/comparison.hpp | 16 +- include/mbgl/style/expression/distance.hpp | 4 +- include/mbgl/style/expression/dsl.hpp | 48 +- include/mbgl/style/expression/error.hpp | 14 +- include/mbgl/style/expression/expression.hpp | 116 +- .../style/expression/format_expression.hpp | 17 +- .../expression/format_section_override.hpp | 54 +- include/mbgl/style/expression/formatted.hpp | 20 +- include/mbgl/style/expression/interpolate.hpp | 12 +- .../mbgl/style/expression/interpolator.hpp | 44 +- include/mbgl/style/expression/let.hpp | 28 +- include/mbgl/style/expression/literal.hpp | 25 +- include/mbgl/style/expression/match.hpp | 3 +- .../mbgl/style/expression/parsing_context.hpp | 65 +- include/mbgl/style/expression/type.hpp | 23 +- include/mbgl/style/expression/value.hpp | 31 +- include/mbgl/style/filter.hpp | 19 +- include/mbgl/style/image.hpp | 3 +- include/mbgl/style/layer.hpp | 70 +- include/mbgl/style/layer_properties.hpp | 8 +- include/mbgl/style/position.hpp | 18 +- include/mbgl/style/property_expression.hpp | 9 +- include/mbgl/style/property_value.hpp | 51 +- include/mbgl/style/rotation.hpp | 3 +- include/mbgl/style/source.hpp | 37 +- .../style/sources/custom_geometry_source.hpp | 9 +- include/mbgl/style/sources/geojson_source.hpp | 6 +- include/mbgl/style/sources/image_source.hpp | 6 +- include/mbgl/style/sources/raster_source.hpp | 11 +- include/mbgl/style/sources/vector_source.hpp | 10 +- include/mbgl/style/style.hpp | 10 +- include/mbgl/style/style_property.hpp | 11 +- include/mbgl/style/transition_options.hpp | 10 +- include/mbgl/style/types.hpp | 4 +- include/mbgl/style/undefined.hpp | 8 +- include/mbgl/tile/tile_id.hpp | 105 +- include/mbgl/util/bitmask_operations.hpp | 9 +- include/mbgl/util/char_array_buffer.hpp | 26 +- include/mbgl/util/chrono.hpp | 14 +- include/mbgl/util/color.hpp | 22 +- include/mbgl/util/compression.hpp | 7 +- include/mbgl/util/constants.hpp | 18 +- include/mbgl/util/convert.hpp | 7 +- include/mbgl/util/default_style.hpp | 2 +- include/mbgl/util/enum.hpp | 37 +- include/mbgl/util/event.hpp | 4 +- include/mbgl/util/exception.hpp | 36 +- include/mbgl/util/feature.hpp | 18 +- include/mbgl/util/geo.hpp | 92 +- include/mbgl/util/geometry.hpp | 34 +- include/mbgl/util/ignore.hpp | 9 +- include/mbgl/util/image.hpp | 70 +- include/mbgl/util/immutable.hpp | 65 +- include/mbgl/util/indexed_tuple.hpp | 22 +- include/mbgl/util/interpolate.hpp | 59 +- include/mbgl/util/logging.hpp | 39 +- include/mbgl/util/noncopyable.hpp | 13 +- include/mbgl/util/platform.hpp | 2 +- include/mbgl/util/projection.hpp | 43 +- include/mbgl/util/range.hpp | 3 +- include/mbgl/util/run_loop.hpp | 14 +- include/mbgl/util/size.hpp | 23 +- include/mbgl/util/string.hpp | 5 +- include/mbgl/util/thread.hpp | 30 +- include/mbgl/util/tile_server_options.hpp | 564 +++--- include/mbgl/util/tileset.hpp | 18 +- include/mbgl/util/traits.hpp | 28 +- include/mbgl/util/unitbezier.hpp | 49 +- include/mbgl/util/work_task.hpp | 7 +- include/mbgl/util/work_task_impl.hpp | 11 +- .../src/cpp/android_renderer_backend.cpp | 11 +- .../src/cpp/android_renderer_backend.hpp | 4 +- .../src/cpp/android_renderer_frontend.cpp | 68 +- .../src/cpp/android_renderer_frontend.hpp | 13 +- .../src/cpp/annotation/marker.hpp | 3 - .../src/cpp/annotation/multi_point.hpp | 24 +- .../src/cpp/annotation/polygon.cpp | 6 +- .../src/cpp/annotation/polygon.hpp | 1 - .../src/cpp/annotation/polyline.cpp | 4 +- .../src/cpp/annotation/polyline.hpp | 1 - .../src/cpp/asset_manager.hpp | 4 +- .../src/cpp/asset_manager_file_source.cpp | 31 +- .../src/cpp/asset_manager_file_source.hpp | 8 +- .../src/cpp/connectivity_listener.cpp | 55 +- .../src/cpp/connectivity_listener.hpp | 2 - .../src/cpp/conversion/collection.cpp | 6 +- .../src/cpp/conversion/collection.hpp | 6 +- .../src/cpp/conversion/color.cpp | 6 +- .../src/cpp/conversion/color.hpp | 2 +- .../src/cpp/conversion/constant.cpp | 32 +- .../src/cpp/conversion/constant.hpp | 2 +- .../src/cpp/conversion/conversion.hpp | 12 +- .../src/cpp/file_source.cpp | 119 +- .../src/cpp/file_source.hpp | 33 +- .../src/cpp/geojson/feature.cpp | 34 +- .../src/cpp/geojson/feature_collection.cpp | 8 +- .../src/cpp/geojson/geometry.cpp | 38 +- .../src/cpp/geojson/geometry_collection.cpp | 13 +- .../src/cpp/geojson/geometry_collection.hpp | 3 +- .../src/cpp/geojson/line_string.cpp | 15 +- .../src/cpp/geojson/line_string.hpp | 3 +- .../src/cpp/geojson/multi_line_string.cpp | 19 +- .../src/cpp/geojson/multi_line_string.hpp | 3 +- .../src/cpp/geojson/multi_point.cpp | 10 +- .../src/cpp/geojson/multi_polygon.cpp | 10 +- .../src/cpp/geojson/point.cpp | 15 +- .../src/cpp/geojson/polygon.cpp | 15 +- .../src/cpp/geojson/polygon.hpp | 10 +- .../src/cpp/geojson/util.hpp | 6 +- .../src/cpp/geometry/lat_lng.hpp | 3 - .../src/cpp/geometry/lat_lng_bounds.cpp | 4 +- .../src/cpp/geometry/lat_lng_bounds.hpp | 2 - .../src/cpp/geometry/lat_lng_quad.cpp | 33 +- .../src/cpp/geometry/lat_lng_quad.hpp | 2 - .../src/cpp/graphics/pointf.hpp | 2 - .../src/cpp/graphics/rectf.hpp | 2 - .../src/cpp/gson/json_array.cpp | 10 +- .../src/cpp/gson/json_element.cpp | 49 +- .../src/cpp/gson/json_object.cpp | 25 +- .../src/cpp/http_file_source.cpp | 81 +- .../src/cpp/i18n/collator.cpp | 59 +- .../src/cpp/i18n/collator_jni.hpp | 4 - .../src/cpp/i18n/number_format.cpp | 34 +- .../MapboxGLAndroidSDK/src/cpp/java/util.hpp | 12 +- .../MapboxGLAndroidSDK/src/cpp/java_types.cpp | 62 +- .../MapboxGLAndroidSDK/src/cpp/java_types.hpp | 70 +- .../MapboxGLAndroidSDK/src/cpp/jni_native.cpp | 4 +- .../MapboxGLAndroidSDK/src/cpp/logger.cpp | 4 +- .../MapboxGLAndroidSDK/src/cpp/logger.hpp | 8 +- .../src/cpp/logging_android.cpp | 4 +- .../src/cpp/map/camera_position.cpp | 21 +- .../MapboxGLAndroidSDK/src/cpp/map/image.cpp | 28 +- .../src/cpp/map_renderer.cpp | 54 +- .../src/cpp/map_renderer.hpp | 5 +- .../src/cpp/map_renderer_runnable.cpp | 15 +- .../src/cpp/map_renderer_runnable.hpp | 5 +- .../src/cpp/native_map_view.cpp | 345 ++-- .../src/cpp/native_map_view.hpp | 73 +- .../src/cpp/offline/offline_manager.cpp | 224 ++- .../src/cpp/offline/offline_manager.hpp | 53 +- .../src/cpp/offline/offline_region.cpp | 178 +- .../src/cpp/offline/offline_region.hpp | 41 +- .../cpp/offline/offline_region_definition.cpp | 102 +- .../cpp/offline/offline_region_definition.hpp | 20 +- .../src/cpp/offline/offline_region_error.cpp | 8 +- .../src/cpp/offline/offline_region_status.cpp | 24 +- .../src/cpp/snapshotter/map_snapshot.cpp | 45 +- .../src/cpp/snapshotter/map_snapshot.hpp | 17 +- .../src/cpp/snapshotter/map_snapshotter.cpp | 19 +- .../src/cpp/snapshotter/map_snapshotter.hpp | 5 +- .../src/cpp/style/android_conversion.hpp | 35 +- .../src/cpp/style/conversion/filter.cpp | 12 +- .../src/cpp/style/conversion/position.cpp | 15 +- .../src/cpp/style/conversion/position.hpp | 6 +- .../style/conversion/property_expression.hpp | 3 +- .../cpp/style/conversion/property_value.hpp | 6 +- .../style/conversion/transition_options.cpp | 16 +- .../style/conversion/transition_options.hpp | 11 +- .../cpp/style/conversion/url_or_tileset.cpp | 8 +- .../cpp/style/conversion/url_or_tileset.hpp | 2 +- .../src/cpp/style/formatted.cpp | 6 +- .../src/cpp/style/formatted.hpp | 19 +- .../src/cpp/style/layers/background_layer.cpp | 260 +-- .../src/cpp/style/layers/background_layer.hpp | 4 +- .../src/cpp/style/layers/circle_layer.cpp | 519 ++--- .../src/cpp/style/layers/circle_layer.hpp | 4 +- .../src/cpp/style/layers/custom_layer.cpp | 98 +- .../src/cpp/style/layers/custom_layer.hpp | 4 +- .../cpp/style/layers/fill_extrusion_layer.cpp | 413 ++-- .../cpp/style/layers/fill_extrusion_layer.hpp | 4 +- .../src/cpp/style/layers/fill_layer.cpp | 381 ++-- .../src/cpp/style/layers/fill_layer.hpp | 4 +- .../src/cpp/style/layers/heatmap_layer.cpp | 293 +-- .../src/cpp/style/layers/heatmap_layer.hpp | 4 +- .../src/cpp/style/layers/hillshade_layer.cpp | 329 +-- .../src/cpp/style/layers/hillshade_layer.hpp | 4 +- .../src/cpp/style/layers/layer.cpp | 278 +-- .../src/cpp/style/layers/layer.hpp | 4 +- .../src/cpp/style/layers/layer_manager.cpp | 9 +- .../src/cpp/style/layers/layer_manager.hpp | 11 +- .../src/cpp/style/layers/line_layer.cpp | 597 +++--- .../src/cpp/style/layers/line_layer.hpp | 4 +- .../style/layers/location_indicator_layer.cpp | 507 ++--- .../style/layers/location_indicator_layer.hpp | 5 +- .../src/cpp/style/layers/raster_layer.cpp | 411 ++-- .../src/cpp/style/layers/raster_layer.hpp | 4 +- .../src/cpp/style/layers/symbol_layer.cpp | 1155 +++++------ .../src/cpp/style/layers/symbol_layer.hpp | 4 +- .../src/cpp/style/light.cpp | 82 +- .../src/cpp/style/light.hpp | 2 - .../src/cpp/style/position.cpp | 7 +- .../style/sources/custom_geometry_source.cpp | 314 +-- .../style/sources/custom_geometry_source.hpp | 5 +- .../src/cpp/style/sources/geojson_source.cpp | 335 ++-- .../src/cpp/style/sources/geojson_source.hpp | 15 +- .../src/cpp/style/sources/image_source.cpp | 110 +- .../cpp/style/sources/raster_dem_source.cpp | 84 +- .../src/cpp/style/sources/raster_source.cpp | 82 +- .../src/cpp/style/sources/source.cpp | 323 +-- .../src/cpp/style/sources/source.hpp | 10 +- .../src/cpp/style/sources/unknown_source.cpp | 27 +- .../src/cpp/style/sources/vector_source.cpp | 104 +- .../src/cpp/style/sources/vector_source.hpp | 5 +- .../src/cpp/style/transition_options.cpp | 11 +- .../src/cpp/style/transition_options.hpp | 5 +- .../src/cpp/style/value.cpp | 148 +- .../src/cpp/style/value.hpp | 12 +- .../src/cpp/text/local_glyph_rasterizer.cpp | 39 +- .../src/cpp/util/default_style.cpp | 19 +- .../src/cpp/util/default_style.hpp | 3 - .../src/cpp/util/tile_server_options.cpp | 126 +- .../src/cpp/util/tile_server_options.hpp | 24 +- platform/android/src/async_task.cpp | 11 +- platform/android/src/attach_env.cpp | 16 +- platform/android/src/attach_env.hpp | 13 +- platform/android/src/bitmap.cpp | 46 +- platform/android/src/bitmap.hpp | 14 +- platform/android/src/bitmap_factory.cpp | 7 +- platform/android/src/bitmap_factory.hpp | 6 +- platform/android/src/example_custom_layer.cpp | 57 +- platform/android/src/gl_functions.cpp | 515 ++--- platform/android/src/image.cpp | 5 +- platform/android/src/jni.cpp | 6 +- platform/android/src/run_loop.cpp | 39 +- platform/android/src/run_loop_impl.hpp | 3 +- platform/android/src/string_util.cpp | 4 +- .../android/src/test/collator_test_stub.cpp | 3 +- .../src/test/http_file_source_test_stub.cpp | 9 +- .../src/test/number_format_test_stub.cpp | 3 +- platform/android/src/test/runtime.cpp | 15 +- platform/android/src/test/test_runner.cpp | 2 +- .../android/src/test/test_runner_common.cpp | 22 +- platform/android/src/timer.cpp | 18 +- .../include/mbgl/gfx/headless_backend.hpp | 5 +- .../include/mbgl/map/map_snapshotter.hpp | 6 +- .../include/mbgl/storage/merge_sideloaded.hpp | 95 +- .../include/mbgl/storage/offline_database.hpp | 18 +- .../include/mbgl/storage/offline_download.hpp | 2 +- .../include/mbgl/storage/offline_schema.hpp | 105 +- .../default/include/mbgl/storage/sqlite3.hpp | 35 +- .../default/src/mbgl/gfx/headless_backend.cpp | 3 +- .../src/mbgl/gfx/headless_frontend.cpp | 24 +- .../default/src/mbgl/gl/headless_backend.cpp | 12 +- platform/default/src/mbgl/i18n/collator.cpp | 13 +- .../src/mbgl/layermanager/layer_manager.cpp | 9 +- .../default/src/mbgl/map/map_snapshotter.cpp | 26 +- .../src/mbgl/storage/asset_file_source.cpp | 24 +- .../src/mbgl/storage/database_file_source.cpp | 39 +- .../src/mbgl/storage/file_source_manager.cpp | 52 +- .../src/mbgl/storage/file_source_request.cpp | 5 +- .../src/mbgl/storage/http_file_source.cpp | 181 +- .../src/mbgl/storage/local_file_request.cpp | 7 +- .../src/mbgl/storage/local_file_source.cpp | 17 +- .../src/mbgl/storage/main_resource_loader.cpp | 36 +- .../src/mbgl/storage/mbtiles_file_source.cpp | 60 +- platform/default/src/mbgl/storage/offline.cpp | 109 +- .../src/mbgl/storage/offline_database.cpp | 203 +- .../src/mbgl/storage/offline_download.cpp | 195 +- .../src/mbgl/storage/online_file_source.cpp | 99 +- platform/default/src/mbgl/storage/sqlite3.cpp | 197 +- platform/default/src/mbgl/text/bidi.cpp | 139 +- .../src/mbgl/text/local_glyph_rasterizer.cpp | 3 +- platform/default/src/mbgl/util/async_task.cpp | 19 +- .../default/src/mbgl/util/compression.cpp | 4 +- .../default/src/mbgl/util/jpeg_reader.cpp | 29 +- platform/default/src/mbgl/util/png_reader.cpp | 66 +- platform/default/src/mbgl/util/png_writer.cpp | 9 +- platform/default/src/mbgl/util/run_loop.cpp | 75 +- .../default/src/mbgl/util/string_stdlib.cpp | 50 +- .../default/src/mbgl/util/thread_local.cpp | 4 +- platform/default/src/mbgl/util/timer.cpp | 20 +- platform/glfw/glfw_gl_backend.cpp | 12 +- platform/glfw/glfw_gl_backend.hpp | 12 +- platform/glfw/glfw_renderer_frontend.cpp | 20 +- platform/glfw/glfw_renderer_frontend.hpp | 4 +- platform/glfw/glfw_view.cpp | 638 +++--- platform/glfw/glfw_view.hpp | 28 +- platform/glfw/main.cpp | 46 +- platform/glfw/settings_json.cpp | 4 +- platform/glfw/test_writer.cpp | 10 +- platform/linux/src/gl_functions.cpp | 515 ++--- platform/linux/src/headless_backend_egl.cpp | 59 +- platform/linux/src/headless_backend_glx.cpp | 22 +- platform/node/src/node_conversion.hpp | 29 +- platform/node/src/node_expression.cpp | 41 +- platform/node/src/node_feature.cpp | 59 +- platform/node/src/node_feature.hpp | 2 +- platform/node/src/node_logging.cpp | 29 +- platform/node/src/node_logging.hpp | 5 +- platform/node/src/node_map.cpp | 398 ++-- platform/node/src/node_map.hpp | 5 +- platform/node/src/node_mapbox_gl_native.cpp | 59 +- platform/node/src/node_request.cpp | 45 +- platform/node/src/node_request.hpp | 2 - platform/node/src/util/async_queue.hpp | 5 +- platform/qt/app/main.cpp | 3 +- platform/qt/app/mapwindow.cpp | 142 +- platform/qt/app/mapwindow.hpp | 3 +- platform/qt/include/QMapLibreGL/export.hpp | 12 +- platform/qt/include/QMapLibreGL/map.hpp | 25 +- platform/qt/include/QMapLibreGL/settings.hpp | 9 +- platform/qt/include/QMapLibreGL/types.hpp | 39 +- platform/qt/src/map.cpp | 772 ++++--- platform/qt/src/map_p.hpp | 10 +- platform/qt/src/mbgl/async_task.cpp | 10 +- platform/qt/src/mbgl/async_task_impl.hpp | 3 +- platform/qt/src/mbgl/bidi.cpp | 5 +- platform/qt/src/mbgl/gl_functions.cpp | 554 ++--- platform/qt/src/mbgl/headless_backend_qt.cpp | 8 +- platform/qt/src/mbgl/http_file_source.cpp | 42 +- platform/qt/src/mbgl/http_file_source.hpp | 5 +- platform/qt/src/mbgl/http_request.cpp | 107 +- platform/qt/src/mbgl/http_request.hpp | 7 +- platform/qt/src/mbgl/image.cpp | 15 +- .../qt/src/mbgl/local_glyph_rasterizer.cpp | 11 +- platform/qt/src/mbgl/number_format.cpp | 8 +- platform/qt/src/mbgl/run_loop.cpp | 19 +- platform/qt/src/mbgl/sqlite3.cpp | 137 +- platform/qt/src/mbgl/thread.cpp | 12 +- platform/qt/src/mbgl/thread_local.cpp | 11 +- platform/qt/src/mbgl/timer.cpp | 9 +- platform/qt/src/mbgl/timer_impl.hpp | 2 +- platform/qt/src/settings.cpp | 194 +- platform/qt/src/types.cpp | 34 +- platform/qt/src/utils.cpp | 28 +- platform/qt/src/utils/conversion.hpp | 63 +- platform/qt/src/utils/geojson.cpp | 84 +- platform/qt/src/utils/map_observer.cpp | 46 +- platform/qt/src/utils/map_observer.hpp | 7 +- platform/qt/src/utils/map_renderer.cpp | 25 +- platform/qt/src/utils/map_renderer.hpp | 3 +- platform/qt/src/utils/renderer_backend.cpp | 11 +- platform/qt/src/utils/renderer_backend.hpp | 7 +- platform/qt/src/utils/renderer_observer.hpp | 25 +- platform/qt/src/utils/scheduler.cpp | 10 +- platform/qt/src/utils/scheduler.hpp | 5 +- platform/qt/test/qmaplibregl.test.cpp | 6 +- platform/windows/include/gl_functions_wgl.h | 1780 +++++++++++++---- platform/windows/include/thread.h | 29 +- platform/windows/src/gl_functions.cpp | 515 ++--- platform/windows/src/headless_backend_egl.cpp | 58 +- .../windows/src/headless_backend_osmesa.cpp | 33 +- platform/windows/src/headless_backend_wgl.cpp | 188 +- platform/windows/src/thread.cpp | 15 +- platform/windows/src/thread_local.cpp | 4 +- render-test/allocation_index.cpp | 6 +- render-test/allocation_index.hpp | 21 +- render-test/file_source.cpp | 24 +- render-test/file_source.hpp | 2 +- render-test/manifest_parser.cpp | 55 +- render-test/manifest_parser.hpp | 3 +- render-test/metadata.hpp | 23 +- render-test/parser.cpp | 34 +- render-test/render_test.cpp | 59 +- render-test/runner.cpp | 62 +- render-test/runner.hpp | 8 +- src/mbgl/actor/mailbox.cpp | 22 +- src/mbgl/actor/scheduler.cpp | 2 +- src/mbgl/algorithm/update_renderables.hpp | 27 +- src/mbgl/algorithm/update_tile_masks.hpp | 73 +- src/mbgl/annotation/annotation_manager.cpp | 67 +- src/mbgl/annotation/annotation_manager.hpp | 10 +- src/mbgl/annotation/annotation_source.cpp | 6 +- src/mbgl/annotation/annotation_source.hpp | 6 +- src/mbgl/annotation/annotation_tile.cpp | 21 +- src/mbgl/annotation/fill_annotation_impl.cpp | 6 +- src/mbgl/annotation/line_annotation_impl.cpp | 6 +- .../annotation/render_annotation_source.cpp | 13 +- .../annotation/render_annotation_source.hpp | 17 +- src/mbgl/annotation/shape_annotation_impl.cpp | 10 +- src/mbgl/annotation/shape_annotation_impl.hpp | 14 +- .../annotation/symbol_annotation_impl.cpp | 9 +- .../annotation/symbol_annotation_impl.hpp | 46 +- src/mbgl/geometry/anchor.hpp | 4 +- src/mbgl/geometry/debug_font_data.hpp | 520 +++-- src/mbgl/geometry/dem_data.cpp | 71 +- src/mbgl/geometry/dem_data.hpp | 6 +- src/mbgl/geometry/feature_index.cpp | 131 +- src/mbgl/geometry/feature_index.hpp | 44 +- src/mbgl/geometry/line_atlas.cpp | 29 +- src/mbgl/geometry/line_atlas.hpp | 5 +- src/mbgl/gfx/attribute.cpp | 3 +- src/mbgl/gfx/attribute.hpp | 187 +- src/mbgl/gfx/color_mode.hpp | 24 +- src/mbgl/gfx/command_encoder.hpp | 4 +- src/mbgl/gfx/context.hpp | 20 +- src/mbgl/gfx/cull_face_mode.hpp | 8 +- src/mbgl/gfx/debug_group.hpp | 8 +- src/mbgl/gfx/depth_mode.hpp | 4 +- src/mbgl/gfx/draw_mode.hpp | 57 +- src/mbgl/gfx/draw_scope.hpp | 5 +- src/mbgl/gfx/index_buffer.hpp | 5 +- src/mbgl/gfx/index_vector.hpp | 26 +- src/mbgl/gfx/offscreen_texture.hpp | 3 +- src/mbgl/gfx/program.hpp | 9 +- src/mbgl/gfx/render_pass.hpp | 4 +- src/mbgl/gfx/renderbuffer.hpp | 16 +- src/mbgl/gfx/renderer_backend.cpp | 8 +- src/mbgl/gfx/shader_registry.cpp | 26 +- src/mbgl/gfx/stencil_mode.hpp | 26 +- src/mbgl/gfx/texture.hpp | 26 +- src/mbgl/gfx/uniform.hpp | 37 +- src/mbgl/gfx/upload_pass.hpp | 44 +- src/mbgl/gfx/vertex_buffer.hpp | 10 +- src/mbgl/gfx/vertex_vector.hpp | 30 +- src/mbgl/gl/attribute.hpp | 39 +- src/mbgl/gl/command_encoder.cpp | 11 +- src/mbgl/gl/command_encoder.hpp | 4 +- src/mbgl/gl/context.cpp | 250 +-- src/mbgl/gl/context.hpp | 47 +- src/mbgl/gl/custom_layer.cpp | 10 +- src/mbgl/gl/custom_layer_factory.cpp | 3 +- src/mbgl/gl/custom_layer_impl.cpp | 6 +- src/mbgl/gl/custom_layer_impl.hpp | 3 +- src/mbgl/gl/debugging_extension.cpp | 104 +- src/mbgl/gl/debugging_extension.hpp | 127 +- src/mbgl/gl/defines.hpp | 1232 ++++++------ src/mbgl/gl/draw_scope_resource.hpp | 4 +- src/mbgl/gl/enum.cpp | 390 ++-- src/mbgl/gl/enum.hpp | 8 +- src/mbgl/gl/extension.hpp | 12 +- src/mbgl/gl/index_buffer_resource.hpp | 4 +- src/mbgl/gl/offscreen_texture.cpp | 17 +- src/mbgl/gl/program.hpp | 43 +- src/mbgl/gl/render_custom_layer.cpp | 9 +- src/mbgl/gl/render_pass.cpp | 6 +- src/mbgl/gl/renderbuffer_resource.hpp | 3 +- src/mbgl/gl/renderer_backend.cpp | 10 +- src/mbgl/gl/state.hpp | 28 +- src/mbgl/gl/texture.cpp | 39 +- src/mbgl/gl/texture.hpp | 18 +- src/mbgl/gl/texture_resource.hpp | 4 +- src/mbgl/gl/types.hpp | 12 +- src/mbgl/gl/uniform.cpp | 28 +- src/mbgl/gl/uniform.hpp | 23 +- src/mbgl/gl/upload_pass.cpp | 80 +- src/mbgl/gl/upload_pass.hpp | 8 +- src/mbgl/gl/value.cpp | 42 +- src/mbgl/gl/value.hpp | 17 +- src/mbgl/gl/vertex_array.cpp | 4 +- src/mbgl/gl/vertex_array.hpp | 6 +- src/mbgl/gl/vertex_buffer_resource.hpp | 4 +- .../layermanager/background_layer_factory.cpp | 3 +- .../layermanager/circle_layer_factory.cpp | 3 +- .../fill_extrusion_layer_factory.cpp | 10 +- src/mbgl/layermanager/fill_layer_factory.cpp | 11 +- .../layermanager/heatmap_layer_factory.cpp | 6 +- .../layermanager/hillshade_layer_factory.cpp | 3 +- src/mbgl/layermanager/layer_factory.cpp | 3 +- src/mbgl/layermanager/layer_manager.cpp | 18 +- src/mbgl/layermanager/line_layer_factory.cpp | 10 +- .../layermanager/raster_layer_factory.cpp | 3 +- .../layermanager/symbol_layer_factory.cpp | 10 +- src/mbgl/layout/circle_layout.hpp | 4 +- src/mbgl/layout/clip_lines.cpp | 9 +- src/mbgl/layout/layout.hpp | 6 +- src/mbgl/layout/merge_lines.cpp | 17 +- src/mbgl/layout/pattern_layout.hpp | 20 +- src/mbgl/layout/symbol_feature.hpp | 4 +- src/mbgl/layout/symbol_instance.cpp | 72 +- src/mbgl/layout/symbol_instance.hpp | 9 +- src/mbgl/layout/symbol_layout.cpp | 369 ++-- src/mbgl/layout/symbol_layout.hpp | 13 +- src/mbgl/layout/symbol_projection.cpp | 830 ++++---- src/mbgl/layout/symbol_projection.hpp | 119 +- src/mbgl/map/map.cpp | 63 +- src/mbgl/map/map_impl.hpp | 5 +- src/mbgl/map/map_options.cpp | 7 +- src/mbgl/map/map_projection.cpp | 7 +- src/mbgl/map/transform.cpp | 80 +- src/mbgl/map/transform.hpp | 6 +- src/mbgl/map/transform_state.cpp | 45 +- src/mbgl/map/transform_state.hpp | 4 +- src/mbgl/math/log2.cpp | 9 +- src/mbgl/platform/gl_functions.cpp | 7 +- src/mbgl/platform/settings.cpp | 3 +- src/mbgl/programs/attributes.hpp | 6 +- src/mbgl/programs/background_program.cpp | 56 +- src/mbgl/programs/background_program.hpp | 80 +- src/mbgl/programs/circle_program.hpp | 40 +- src/mbgl/programs/clipping_mask_program.cpp | 4 +- src/mbgl/programs/clipping_mask_program.hpp | 21 +- src/mbgl/programs/collision_box_program.hpp | 121 +- src/mbgl/programs/debug_program.cpp | 4 +- src/mbgl/programs/debug_program.hpp | 20 +- src/mbgl/programs/fill_extrusion_program.cpp | 79 +- src/mbgl/programs/fill_extrusion_program.hpp | 122 +- src/mbgl/programs/fill_program.cpp | 39 +- src/mbgl/programs/fill_program.hpp | 117 +- src/mbgl/programs/heatmap_program.hpp | 33 +- src/mbgl/programs/heatmap_texture_program.hpp | 33 +- .../programs/hillshade_prepare_program.hpp | 40 +- src/mbgl/programs/hillshade_program.hpp | 44 +- src/mbgl/programs/line_program.cpp | 101 +- src/mbgl/programs/line_program.hpp | 203 +- src/mbgl/programs/program.hpp | 51 +- src/mbgl/programs/program_parameters.cpp | 44 +- src/mbgl/programs/program_parameters.hpp | 90 +- src/mbgl/programs/programs.cpp | 76 +- src/mbgl/programs/raster_program.hpp | 56 +- src/mbgl/programs/segment.hpp | 4 +- src/mbgl/programs/symbol_program.cpp | 159 +- src/mbgl/programs/symbol_program.hpp | 239 +-- src/mbgl/renderer/backend_scope.cpp | 8 +- src/mbgl/renderer/bucket.hpp | 17 +- src/mbgl/renderer/bucket_parameters.cpp | 4 +- src/mbgl/renderer/bucket_parameters.hpp | 2 +- src/mbgl/renderer/buckets/circle_bucket.cpp | 8 +- src/mbgl/renderer/buckets/debug_bucket.cpp | 15 +- src/mbgl/renderer/buckets/debug_bucket.hpp | 1 - src/mbgl/renderer/buckets/fill_bucket.cpp | 40 +- .../buckets/fill_extrusion_bucket.cpp | 65 +- .../buckets/fill_extrusion_bucket.hpp | 2 +- src/mbgl/renderer/buckets/heatmap_bucket.cpp | 18 +- .../renderer/buckets/hillshade_bucket.cpp | 42 +- .../renderer/buckets/hillshade_bucket.hpp | 13 +- src/mbgl/renderer/buckets/line_bucket.cpp | 219 +- src/mbgl/renderer/buckets/line_bucket.hpp | 16 +- src/mbgl/renderer/buckets/raster_bucket.cpp | 39 +- src/mbgl/renderer/buckets/raster_bucket.hpp | 2 +- src/mbgl/renderer/buckets/symbol_bucket.cpp | 61 +- src/mbgl/renderer/buckets/symbol_bucket.hpp | 11 +- .../cross_faded_property_evaluator.cpp | 4 +- .../cross_faded_property_evaluator.hpp | 3 +- .../data_driven_property_evaluator.hpp | 25 +- src/mbgl/renderer/image_atlas.cpp | 59 +- src/mbgl/renderer/image_atlas.hpp | 9 +- src/mbgl/renderer/image_manager.cpp | 9 +- src/mbgl/renderer/image_manager.hpp | 8 +- .../layers/render_background_layer.cpp | 72 +- .../renderer/layers/render_circle_layer.cpp | 91 +- .../layers/render_fill_extrusion_layer.cpp | 229 ++- .../renderer/layers/render_fill_layer.cpp | 127 +- .../renderer/layers/render_heatmap_layer.cpp | 38 +- .../layers/render_hillshade_layer.cpp | 101 +- .../layers/render_hillshade_layer.hpp | 2 +- .../renderer/layers/render_line_layer.cpp | 143 +- .../render_location_indicator_layer.cpp | 103 +- .../renderer/layers/render_raster_layer.cpp | 67 +- .../renderer/layers/render_symbol_layer.cpp | 400 ++-- .../renderer/layers/render_symbol_layer.hpp | 48 +- src/mbgl/renderer/paint_parameters.cpp | 169 +- src/mbgl/renderer/paint_parameters.hpp | 1 - src/mbgl/renderer/paint_property_binder.hpp | 311 +-- .../renderer/paint_property_statistics.hpp | 8 +- src/mbgl/renderer/pattern_atlas.cpp | 31 +- src/mbgl/renderer/pattern_atlas.hpp | 6 +- .../possibly_evaluated_property_value.hpp | 81 +- .../property_evaluation_parameters.hpp | 14 +- src/mbgl/renderer/render_layer.cpp | 42 +- src/mbgl/renderer/render_layer.hpp | 23 +- src/mbgl/renderer/render_light.cpp | 3 +- src/mbgl/renderer/render_light.hpp | 2 +- src/mbgl/renderer/render_orchestrator.cpp | 147 +- src/mbgl/renderer/render_orchestrator.hpp | 40 +- src/mbgl/renderer/render_source.cpp | 45 +- src/mbgl/renderer/render_source.hpp | 41 +- src/mbgl/renderer/render_static_data.cpp | 27 +- src/mbgl/renderer/render_tile.cpp | 160 +- src/mbgl/renderer/render_tree.hpp | 8 +- src/mbgl/renderer/renderer.cpp | 58 +- src/mbgl/renderer/renderer_impl.cpp | 61 +- src/mbgl/renderer/renderer_impl.hpp | 2 +- src/mbgl/renderer/source_state.cpp | 13 +- src/mbgl/renderer/source_state.hpp | 10 +- .../sources/render_custom_geometry_source.cpp | 8 +- .../sources/render_custom_geometry_source.hpp | 2 +- .../sources/render_geojson_source.cpp | 28 +- .../sources/render_geojson_source.hpp | 10 +- .../renderer/sources/render_image_source.cpp | 82 +- .../renderer/sources/render_image_source.hpp | 23 +- .../sources/render_raster_dem_source.cpp | 66 +- .../sources/render_raster_dem_source.hpp | 17 +- .../renderer/sources/render_raster_source.cpp | 16 +- .../renderer/sources/render_raster_source.hpp | 17 +- .../renderer/sources/render_tile_source.cpp | 45 +- .../renderer/sources/render_tile_source.hpp | 18 +- .../renderer/sources/render_vector_source.cpp | 3 +- .../renderer/sources/render_vector_source.hpp | 1 + src/mbgl/renderer/style_diff.cpp | 23 +- src/mbgl/renderer/tile_mask.hpp | 9 +- src/mbgl/renderer/tile_pyramid.cpp | 68 +- src/mbgl/renderer/tile_pyramid.hpp | 9 +- src/mbgl/renderer/tile_render_data.cpp | 3 +- src/mbgl/renderer/tile_render_data.hpp | 6 +- src/mbgl/renderer/update_parameters.hpp | 2 +- src/mbgl/renderer/upload_parameters.hpp | 6 +- src/mbgl/sprite/sprite_loader.cpp | 4 +- src/mbgl/sprite/sprite_parser.cpp | 29 +- src/mbgl/storage/asset_file_source.hpp | 3 +- src/mbgl/storage/file_source_manager.cpp | 15 +- src/mbgl/storage/local_file_source.hpp | 3 +- src/mbgl/storage/mbtiles_file_source.hpp | 5 +- src/mbgl/storage/network_status.cpp | 6 +- src/mbgl/storage/resource.cpp | 118 +- src/mbgl/storage/resource_options.cpp | 21 +- src/mbgl/storage/resource_transform.cpp | 3 +- src/mbgl/storage/response.cpp | 5 +- src/mbgl/style/collection.hpp | 27 +- .../conversion/color_ramp_property_value.cpp | 5 +- src/mbgl/style/conversion/constant.cpp | 51 +- src/mbgl/style/conversion/coordinate.cpp | 16 +- .../custom_geometry_source_options.cpp | 3 +- src/mbgl/style/conversion/filter.cpp | 50 +- src/mbgl/style/conversion/function.cpp | 399 ++-- src/mbgl/style/conversion/geojson_options.cpp | 100 +- src/mbgl/style/conversion/json.hpp | 6 +- src/mbgl/style/conversion/layer.cpp | 9 +- src/mbgl/style/conversion/light.cpp | 2 +- src/mbgl/style/conversion/property_value.cpp | 106 +- src/mbgl/style/conversion/source.cpp | 44 +- src/mbgl/style/conversion/stringify.hpp | 39 +- src/mbgl/style/conversion/tileset.cpp | 26 +- .../style/conversion/transition_options.cpp | 7 +- src/mbgl/style/custom_tile_loader.cpp | 14 +- src/mbgl/style/expression/assertion.cpp | 33 +- src/mbgl/style/expression/at.cpp | 24 +- .../style/expression/boolean_operator.cpp | 16 +- src/mbgl/style/expression/case.cpp | 8 +- src/mbgl/style/expression/check_subtype.cpp | 21 +- src/mbgl/style/expression/coalesce.cpp | 9 +- src/mbgl/style/expression/coercion.cpp | 109 +- .../style/expression/collator_expression.cpp | 47 +- src/mbgl/style/expression/comparison.cpp | 178 +- .../style/expression/compound_expression.cpp | 564 +++--- src/mbgl/style/expression/distance.cpp | 74 +- src/mbgl/style/expression/dsl.cpp | 62 +- src/mbgl/style/expression/expression.cpp | 6 +- src/mbgl/style/expression/find_zoom_curve.cpp | 86 +- .../style/expression/format_expression.cpp | 21 +- src/mbgl/style/expression/formatted.cpp | 15 +- .../style/expression/get_covering_stops.cpp | 9 +- src/mbgl/style/expression/image.cpp | 10 +- .../style/expression/image_expression.cpp | 3 +- src/mbgl/style/expression/in.cpp | 28 +- src/mbgl/style/expression/interpolate.cpp | 109 +- src/mbgl/style/expression/is_constant.cpp | 1 - src/mbgl/style/expression/is_expression.cpp | 3 +- src/mbgl/style/expression/length.cpp | 21 +- src/mbgl/style/expression/let.cpp | 27 +- src/mbgl/style/expression/literal.cpp | 70 +- src/mbgl/style/expression/match.cpp | 99 +- src/mbgl/style/expression/number_format.cpp | 33 +- src/mbgl/style/expression/parsing_context.cpp | 57 +- src/mbgl/style/expression/step.cpp | 50 +- src/mbgl/style/expression/util.cpp | 27 +- src/mbgl/style/expression/value.cpp | 136 +- src/mbgl/style/expression/within.cpp | 44 +- src/mbgl/style/filter.cpp | 3 +- src/mbgl/style/layer.cpp | 12 +- src/mbgl/style/layer_impl.cpp | 3 +- src/mbgl/style/layer_impl.hpp | 28 +- .../layers/fill_extrusion_layer_impl.cpp | 4 +- src/mbgl/style/layers/heatmap_layer_impl.cpp | 4 +- src/mbgl/style/layers/line_layer_impl.cpp | 4 +- src/mbgl/style/layers/symbol_layer_impl.cpp | 14 +- src/mbgl/style/layers/symbol_layer_impl.hpp | 79 +- src/mbgl/style/light.cpp | 47 +- src/mbgl/style/light_impl.cpp | 4 +- src/mbgl/style/light_impl.hpp | 16 +- src/mbgl/style/parser.cpp | 33 +- src/mbgl/style/parser.hpp | 2 +- src/mbgl/style/properties.hpp | 127 +- src/mbgl/style/property_expression.cpp | 10 +- src/mbgl/style/rapidjson_conversion.hpp | 47 +- src/mbgl/style/source.cpp | 3 +- src/mbgl/style/source_impl.cpp | 9 +- .../style/sources/custom_geometry_source.cpp | 3 +- .../sources/custom_geometry_source_impl.cpp | 5 +- src/mbgl/style/sources/geojson_source.cpp | 12 +- .../style/sources/geojson_source_impl.cpp | 14 +- src/mbgl/style/sources/image_source.cpp | 7 +- src/mbgl/style/sources/image_source_impl.cpp | 12 +- src/mbgl/style/sources/image_source_impl.hpp | 1 + src/mbgl/style/sources/raster_source.cpp | 10 +- src/mbgl/style/sources/raster_source_impl.cpp | 6 +- src/mbgl/style/sources/vector_source.cpp | 6 +- src/mbgl/style/sources/vector_source_impl.cpp | 6 +- src/mbgl/style/style_impl.cpp | 12 +- src/mbgl/style/style_impl.hpp | 8 +- src/mbgl/style/types.cpp | 231 +-- src/mbgl/text/bidi.hpp | 2 +- src/mbgl/text/check_max_angle.cpp | 14 +- src/mbgl/text/collision_feature.cpp | 48 +- src/mbgl/text/collision_feature.hpp | 34 +- src/mbgl/text/collision_index.cpp | 216 +- src/mbgl/text/collision_index.hpp | 27 +- src/mbgl/text/cross_tile_symbol_index.cpp | 47 +- src/mbgl/text/cross_tile_symbol_index.hpp | 10 +- src/mbgl/text/get_anchors.cpp | 57 +- src/mbgl/text/get_anchors.hpp | 14 +- src/mbgl/text/glyph.cpp | 4 +- src/mbgl/text/glyph.hpp | 19 +- src/mbgl/text/glyph_atlas.cpp | 39 +- src/mbgl/text/glyph_manager.cpp | 31 +- src/mbgl/text/glyph_manager.hpp | 21 +- src/mbgl/text/glyph_pbf.cpp | 88 +- src/mbgl/text/glyph_range.hpp | 4 +- src/mbgl/text/language_tag.cpp | 99 +- src/mbgl/text/language_tag.hpp | 19 +- src/mbgl/text/local_glyph_rasterizer.hpp | 7 +- src/mbgl/text/placement.cpp | 474 +++-- src/mbgl/text/placement.hpp | 41 +- src/mbgl/text/quads.cpp | 64 +- src/mbgl/text/shaping.cpp | 164 +- src/mbgl/text/shaping.hpp | 4 +- src/mbgl/text/tagged_string.cpp | 5 +- src/mbgl/text/tagged_string.hpp | 77 +- src/mbgl/tile/custom_geometry_tile.cpp | 17 +- src/mbgl/tile/custom_geometry_tile.hpp | 6 +- src/mbgl/tile/geojson_tile.cpp | 8 +- src/mbgl/tile/geojson_tile.hpp | 4 +- src/mbgl/tile/geojson_tile_data.hpp | 43 +- src/mbgl/tile/geometry_tile.cpp | 95 +- src/mbgl/tile/geometry_tile.hpp | 26 +- src/mbgl/tile/geometry_tile_data.cpp | 27 +- src/mbgl/tile/geometry_tile_data.hpp | 38 +- src/mbgl/tile/geometry_tile_worker.cpp | 242 +-- src/mbgl/tile/geometry_tile_worker.hpp | 6 +- src/mbgl/tile/raster_dem_tile.cpp | 20 +- src/mbgl/tile/raster_dem_tile.hpp | 67 +- src/mbgl/tile/raster_dem_tile_worker.cpp | 3 +- src/mbgl/tile/raster_tile.cpp | 8 +- src/mbgl/tile/raster_tile.hpp | 4 +- src/mbgl/tile/raster_tile_worker.cpp | 3 +- src/mbgl/tile/tile.cpp | 38 +- src/mbgl/tile/tile.hpp | 77 +- src/mbgl/tile/tile_cache.cpp | 1 - src/mbgl/tile/tile_cache.hpp | 4 +- src/mbgl/tile/tile_loader.hpp | 10 +- src/mbgl/tile/tile_loader_impl.hpp | 60 +- src/mbgl/tile/vector_tile.cpp | 3 +- src/mbgl/tile/vector_tile.hpp | 5 +- src/mbgl/tile/vector_tile_data.cpp | 41 +- src/mbgl/util/bounding_volumes.cpp | 23 +- src/mbgl/util/camera.cpp | 3 +- src/mbgl/util/camera.hpp | 5 +- src/mbgl/util/chrono.cpp | 25 +- src/mbgl/util/client_options.cpp | 18 +- src/mbgl/util/color.cpp | 21 +- src/mbgl/util/default_style.cpp | 7 +- src/mbgl/util/event.cpp | 56 +- src/mbgl/util/geo.cpp | 29 +- src/mbgl/util/geometry_util.cpp | 12 +- src/mbgl/util/grid_index.cpp | 41 +- src/mbgl/util/grid_index.hpp | 31 +- src/mbgl/util/hash.hpp | 2 +- src/mbgl/util/http_header.cpp | 14 +- src/mbgl/util/http_timeout.cpp | 5 +- src/mbgl/util/http_timeout.hpp | 4 +- src/mbgl/util/i18n.cpp | 186 +- src/mbgl/util/i18n.hpp | 2 +- src/mbgl/util/interpolate.cpp | 6 +- src/mbgl/util/intersection_tests.cpp | 19 +- src/mbgl/util/io.cpp | 10 +- src/mbgl/util/io.hpp | 6 +- src/mbgl/util/literal.hpp | 18 +- src/mbgl/util/logging.cpp | 13 +- src/mbgl/util/longest_common_subsequence.hpp | 39 +- src/mbgl/util/mapbox.cpp | 199 +- src/mbgl/util/mapbox.hpp | 32 +- src/mbgl/util/mat2.cpp | 4 +- src/mbgl/util/mat4.cpp | 67 +- src/mbgl/util/math.hpp | 7 +- src/mbgl/util/premultiply.cpp | 4 +- src/mbgl/util/quaternion.hpp | 12 +- src/mbgl/util/rapidjson.cpp | 4 +- src/mbgl/util/rect.hpp | 8 +- src/mbgl/util/stopwatch.cpp | 20 +- src/mbgl/util/stopwatch.hpp | 15 +- src/mbgl/util/thread_local.hpp | 12 +- src/mbgl/util/tile_coordinate.hpp | 25 +- src/mbgl/util/tile_cover.cpp | 91 +- src/mbgl/util/tile_cover_impl.cpp | 121 +- src/mbgl/util/tile_cover_impl.hpp | 29 +- src/mbgl/util/tile_range.hpp | 22 +- src/mbgl/util/tile_server_options.cpp | 563 +++--- src/mbgl/util/tiny_sdf.cpp | 17 +- src/mbgl/util/tiny_sdf.hpp | 11 +- src/mbgl/util/token.hpp | 5 +- src/mbgl/util/url.cpp | 29 +- src/mbgl/util/url.hpp | 11 +- src/mbgl/util/work_request.cpp | 3 +- test/actor/actor.test.cpp | 87 +- test/actor/actor_ref.test.cpp | 29 +- test/algorithm/update_renderables.test.cpp | 1220 ++++++----- test/algorithm/update_tile_masks.test.cpp | 107 +- test/api/annotations.test.cpp | 222 +- test/api/api_misuse.test.cpp | 8 +- test/api/custom_geometry_source.test.cpp | 24 +- test/api/custom_layer.test.cpp | 41 +- test/api/query.test.cpp | 103 +- test/api/recycle_map.cpp | 18 +- test/geometry/dem_data.test.cpp | 20 +- test/geometry/line_atlas.test.cpp | 4 +- test/gl/bucket.test.cpp | 318 +-- test/gl/context.test.cpp | 15 +- test/gl/gl_functions.test.cpp | 1 - test/gl/object.test.cpp | 11 +- test/include/mbgl/test/util.hpp | 12 +- test/map/map.test.cpp | 214 +- test/map/prefetch.test.cpp | 22 +- test/map/transform.test.cpp | 162 +- test/programs/symbol_program.test.cpp | 62 +- test/renderer/backend_scope.test.cpp | 54 +- test/renderer/image_manager.test.cpp | 58 +- test/renderer/pattern_atlas.test.cpp | 6 +- test/renderer/shader_registry.test.cpp | 165 +- test/sprite/sprite_loader.test.cpp | 25 +- test/sprite/sprite_parser.test.cpp | 258 +-- test/src/mbgl/test/fake_file_source.hpp | 56 +- test/src/mbgl/test/fixture_log_observer.cpp | 23 +- test/src/mbgl/test/fixture_log_observer.hpp | 18 +- test/src/mbgl/test/getrss.cpp | 101 +- test/src/mbgl/test/getrss.hpp | 6 +- test/src/mbgl/test/http_server.cpp | 4 +- test/src/mbgl/test/mock.hpp | 18 +- test/src/mbgl/test/sqlite3_test_fs.cpp | 4 +- test/src/mbgl/test/sqlite3_test_fs.hpp | 23 +- test/src/mbgl/test/stub_file_source.cpp | 79 +- test/src/mbgl/test/stub_file_source.hpp | 4 +- .../mbgl/test/stub_geometry_tile_feature.hpp | 26 +- test/src/mbgl/test/stub_layer_observer.hpp | 5 +- test/src/mbgl/test/stub_map_observer.hpp | 1 - .../mbgl/test/stub_render_source_observer.hpp | 10 +- test/src/mbgl/test/stub_style_observer.hpp | 13 +- test/src/mbgl/test/stub_tile_observer.hpp | 7 +- test/src/mbgl/test/test.cpp | 2 +- test/src/mbgl/test/util.cpp | 4 +- test/storage/asset_file_source.test.cpp | 26 +- test/storage/database_file_source.test.cpp | 8 +- test/storage/http_file_source.test.cpp | 98 +- test/storage/local_file_source.test.cpp | 38 +- test/storage/main_resource_loader.test.cpp | 211 +- test/storage/mbtiles_file_source.test.cpp | 38 +- test/storage/offline.test.cpp | 8 +- test/storage/offline_database.test.cpp | 438 ++-- test/storage/offline_download.test.cpp | 415 ++-- test/storage/online_file_source.test.cpp | 69 +- test/storage/resource.test.cpp | 6 +- test/storage/sqlite.test.cpp | 22 +- test/storage/sync_file_source.test.cpp | 14 +- .../style/conversion/conversion_impl.test.cpp | 58 +- test/style/conversion/function.test.cpp | 27 +- .../style/conversion/geojson_options.test.cpp | 16 +- test/style/conversion/layer.test.cpp | 6 +- test/style/conversion/light.test.cpp | 32 +- test/style/conversion/property_value.test.cpp | 3 +- test/style/conversion/stringify.test.cpp | 65 +- test/style/conversion/tileset.test.cpp | 64 +- test/style/expression/expression.test.cpp | 16 +- test/style/filter.test.cpp | 160 +- test/style/properties.test.cpp | 102 +- test/style/property_expression.test.cpp | 236 ++- test/style/source.test.cpp | 358 ++-- test/style/style.test.cpp | 22 +- test/style/style_image.test.cpp | 18 +- test/style/style_layer.test.cpp | 35 +- test/style/style_parser.test.cpp | 17 +- test/text/bidi.test.cpp | 55 +- test/text/cross_tile_symbol_index.test.cpp | 45 +- test/text/get_anchors.test.cpp | 72 +- test/text/glyph_manager.test.cpp | 264 ++- test/text/glyph_pbf.test.cpp | 2 +- test/text/language_tag.test.cpp | 15 +- test/text/local_glyph_rasterizer.test.cpp | 64 +- test/text/quads.test.cpp | 17 +- test/text/shaping.test.cpp | 4 +- test/text/tagged_string.test.cpp | 6 +- test/tile/custom_geometry_tile.test.cpp | 52 +- test/tile/geojson_tile.test.cpp | 41 +- test/tile/geometry_tile_data.test.cpp | 41 +- test/tile/raster_dem_tile.test.cpp | 14 +- test/tile/raster_tile.test.cpp | 13 +- test/tile/tile_coordinate.test.cpp | 41 +- test/tile/tile_id.test.cpp | 286 +-- test/tile/vector_tile.test.cpp | 9 +- test/util/async_task.test.cpp | 13 +- test/util/geo.test.cpp | 57 +- test/util/grid_index.test.cpp | 10 +- test/util/http_timeout.test.cpp | 4 +- test/util/image.test.cpp | 8 +- test/util/mapbox.test.cpp | 660 +++--- test/util/memory.test.cpp | 42 +- test/util/merge_lines.test.cpp | 71 +- test/util/offscreen_texture.test.cpp | 55 +- test/util/position.test.cpp | 14 +- test/util/projection.test.cpp | 22 +- test/util/run_loop.test.cpp | 10 +- test/util/string.test.cpp | 1 - test/util/text_conversions.test.cpp | 22 +- test/util/thread.test.cpp | 65 +- test/util/thread_local.test.cpp | 20 +- test/util/tile_cover.test.cpp | 337 ++-- test/util/tile_range.test.cpp | 10 +- test/util/tile_server_options.test.cpp | 5 +- test/util/timer.test.cpp | 17 +- test/util/token.test.cpp | 67 +- test/util/url.test.cpp | 413 ++-- 1018 files changed, 28391 insertions(+), 26377 deletions(-) create mode 100644 .clang-format create mode 100644 .pre-commit-config.yaml mode change 100755 => 100644 platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp mode change 100755 => 100644 platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp mode change 100755 => 100644 platform/android/src/jni.cpp diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000..e6e6177a85c --- /dev/null +++ b/.clang-format @@ -0,0 +1,18 @@ +--- +BasedOnStyle: Google +AccessModifierOffset: -4 +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortLambdasOnASingleLine: Inline +BinPackArguments: false +BinPackParameters: false +ColumnLimit: 120 +IncludeBlocks: Preserve +IndentWidth: 4 +Language: Cpp +PackConstructorInitializers: Never +PenaltyBreakAssignment: 80 +SortIncludes: false +SpacesBeforeTrailingComments: 1 +Standard: c++17 +... diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..5887c742e71 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,7 @@ +repos: +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: v14.0.6 + hooks: + - id: clang-format + files: '.*\.(hpp|cpp|h)' + exclude: '(vendor/.*|platform/(ios|darwin)/.*|test/ios/.*|render-test/ios/.*|benchmark/ios/.*)' diff --git a/DEVELOPING.md b/DEVELOPING.md index a92594ba23a..b1cdb2816c5 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -1,5 +1,16 @@ # Developing + +## Pre-commit hooks + +Install [pre-commit](https://pre-commit.com/) and run + +``` +pre-commit install +``` + +to install the pre-commit hooks configured in `.pre-commit-config.yml`. + ## Render Tests To check that the output of the rendering is correct, we compare actual rendered PNGs for simple styles with expected PNGs. The content of the tests is stored in the MapLibre GL JS submodule which means that GL JS and Native are in fact quasi pixel-identical in their rendering. @@ -76,6 +87,7 @@ or any of the platform make files: * iOS developers can use [Xcode](https://developer.apple.com/support/debugging/). See also [Advanced Debugging with Xcode and LLDB](https://developer.apple.com/videos/play/wwdc2018/412/). ## Static Analysis + We use [`clang-tidy`](https://clang.llvm.org/extra/clang-tidy/) for static analysis and run it on CI for each pull request. If you want to run it locally use `-DMLN_WITH_CLANG_TIDY=ON` CMake option and just run regular build. For the list of enabled checks please see: [`.clang-tidy`](.clang-tidy) and [`test/.clang-tidy`](test/.clang-tidy)(for tests we are less strict and use different set of checks). @@ -166,3 +178,6 @@ autoload -Uz compinit && compinit ### Kotlin and Java compatibility We are moving the Android SDK to Kotlin, which is backward compatible with Java, but if you need a Java version of the Android SDK there is a `before-kotlin-port` tag available. + + + diff --git a/benchmark/api/query.benchmark.cpp b/benchmark/api/query.benchmark.cpp index 1502ca49995..e660be753bb 100644 --- a/benchmark/api/query.benchmark.cpp +++ b/benchmark/api/query.benchmark.cpp @@ -21,19 +21,20 @@ class QueryBenchmark { NetworkStatus::Set(NetworkStatus::Status::Offline); map.getStyle().loadJSON(util::read_file("benchmark/fixtures/api/style.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 40.726989, -73.992857 }).withZoom(15.0)); // Manhattan - map.getStyle().addImage(std::make_unique("test-icon", - decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png")), 1.0f)); + map.jumpTo(CameraOptions().withCenter(LatLng{40.726989, -73.992857}).withZoom(15.0)); // Manhattan + map.getStyle().addImage(std::make_unique( + "test-icon", decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png")), 1.0f)); frontend.render(map); } util::RunLoop loop; - HeadlessFrontend frontend { { 1000, 1000 }, 1 }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), - ResourceOptions().withCachePath("benchmark/fixtures/api/cache.db").withAssetPath(".").withApiKey("foobar") }; - ScreenBox box{{ 0, 0 }, { 1000, 1000 }}; + HeadlessFrontend frontend{{1000, 1000}, 1}; + Map map{frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), + ResourceOptions().withCachePath("benchmark/fixtures/api/cache.db").withAssetPath(".").withApiKey("foobar")}; + ScreenBox box{{0, 0}, {1000, 1000}}; }; } // end namespace @@ -74,7 +75,7 @@ static void API_queryRenderedFeaturesLayerFromLowDensity(::benchmark::State& sta QueryBenchmark bench; while (state.KeepRunning()) { - bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{ "testlayer" }}, {}}); + bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{"testlayer"}}, {}}); } } @@ -82,7 +83,7 @@ static void API_queryRenderedFeaturesLayerFromHighDensity(::benchmark::State& st QueryBenchmark bench; while (state.KeepRunning()) { - bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{"road-street" }}, {}}); + bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{"road-street"}}, {}}); } } BENCHMARK(API_queryPixelsForLatLngs); diff --git a/benchmark/api/render.benchmark.cpp b/benchmark/api/render.benchmark.cpp index e91376e13ee..79bdef734a8 100644 --- a/benchmark/api/render.benchmark.cpp +++ b/benchmark/api/render.benchmark.cpp @@ -22,22 +22,20 @@ using namespace mbgl; namespace { -static std::string cachePath { "benchmark/fixtures/api/cache.db" }; -constexpr double pixelRatio { 1.0 }; -constexpr Size size { 1000, 1000 }; +static std::string cachePath{"benchmark/fixtures/api/cache.db"}; +constexpr double pixelRatio{1.0}; +constexpr Size size{1000, 1000}; class RenderBenchmark { public: - RenderBenchmark() { - NetworkStatus::Set(NetworkStatus::Status::Offline); - } + RenderBenchmark() { NetworkStatus::Set(NetworkStatus::Status::Offline); } util::RunLoop loop; }; void prepare(Map& map, std::optional json = std::nullopt) { map.getStyle().loadJSON(json ? *json : util::read_file("benchmark/fixtures/api/style.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 40.726989, -73.992857 }).withZoom(15.0)); // Manhattan + map.jumpTo(CameraOptions().withCenter(LatLng{40.726989, -73.992857}).withZoom(15.0)); // Manhattan auto image = decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png")); map.getStyle().addImage(std::make_unique("test-icon", std::move(image), 1.0f)); @@ -55,10 +53,11 @@ void prepare_map2(Map& map, std::optional json = std::nullopt) { static void API_renderStill_reuse_map(::benchmark::State& state) { RenderBenchmark bench; - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare(map); for (auto _ : state) { @@ -68,10 +67,11 @@ static void API_renderStill_reuse_map(::benchmark::State& state) { static void API_renderStill_reuse_map_formatted_labels(::benchmark::State& state) { RenderBenchmark bench; - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare(map, util::read_file("benchmark/fixtures/api/style_formatted_labels.json")); for (auto _ : state) { @@ -81,13 +81,14 @@ static void API_renderStill_reuse_map_formatted_labels(::benchmark::State& state static void API_renderStill_reuse_map_switch_styles(::benchmark::State& state) { RenderBenchmark bench; - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; for (auto _ : state) { - prepare(map, { "{}" }); + prepare(map, {"{}"}); frontend.render(map); prepare(map); frontend.render(map); @@ -98,10 +99,11 @@ static void API_renderStill_recreate_map(::benchmark::State& state) { RenderBenchmark bench; for (auto _ : state) { - HeadlessFrontend frontend { size, pixelRatio }; - Map map { frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), - ResourceOptions().withCachePath(cachePath).withApiKey("foobar") }; + HeadlessFrontend frontend{size, pixelRatio}; + Map map{frontend, + MapObserver::nullObserver(), + MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio), + ResourceOptions().withCachePath(cachePath).withApiKey("foobar")}; prepare(map); frontend.render(map); } diff --git a/benchmark/function/camera_function.benchmark.cpp b/benchmark/function/camera_function.benchmark.cpp index d152c516adf..74f70b34da7 100644 --- a/benchmark/function/camera_function.benchmark.cpp +++ b/benchmark/function/camera_function.benchmark.cpp @@ -21,13 +21,14 @@ static std::string createFunctionJSON(size_t stopCount) { static void Parse_CameraFunction(benchmark::State& state) { size_t stopCount = state.range(0); - + while (state.KeepRunning()) { conversion::Error error; state.PauseTiming(); auto doc = createFunctionJSON(stopCount); state.ResumeTiming(); - std::optional> result = conversion::convertJSON>(doc, error, false, false); + std::optional> result = conversion::convertJSON>( + doc, error, false, false); if (!result) { state.SkipWithError(error.message.c_str()); } @@ -39,23 +40,20 @@ static void Evaluate_CameraFunction(benchmark::State& state) { size_t stopCount = state.range(0); auto doc = createFunctionJSON(stopCount); conversion::Error error; - std::optional> function = conversion::convertJSON>(doc, error, false, false); + std::optional> function = conversion::convertJSON>( + doc, error, false, false); if (!function) { state.SkipWithError(error.message.c_str()); } - - while(state.KeepRunning()) { + + while (state.KeepRunning()) { float z = 24.0f * static_cast(rand() % 100) / 100; function->asExpression().evaluate(z); } - + state.SetLabel(std::to_string(stopCount).c_str()); } -BENCHMARK(Parse_CameraFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - -BENCHMARK(Evaluate_CameraFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - +BENCHMARK(Parse_CameraFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); +BENCHMARK(Evaluate_CameraFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); diff --git a/benchmark/function/composite_function.benchmark.cpp b/benchmark/function/composite_function.benchmark.cpp index 4957ae5b4d4..466defe767a 100644 --- a/benchmark/function/composite_function.benchmark.cpp +++ b/benchmark/function/composite_function.benchmark.cpp @@ -18,7 +18,7 @@ static std::string createFunctionJSON(size_t stopCount) { std::string value = std::to_string(100.0f / stopCount * innerStop); if (stops.size() > 1) stops += ","; - stops += R"([{"zoom":)" + zoom + R"(,"value":)" + value + "}, " + value + "]"; + stops += R"([{"zoom":)" + zoom + R"(,"value":)" + value + "}, " + value + "]"; } } stops += "]"; @@ -33,7 +33,8 @@ static void Parse_CompositeFunction(benchmark::State& state) { state.PauseTiming(); auto doc = createFunctionJSON(stopCount); state.ResumeTiming(); - std::optional> result = conversion::convertJSON>(doc, error, true, false); + std::optional> result = conversion::convertJSON>( + doc, error, true, false); if (!result) { state.SkipWithError(error.message.c_str()); } @@ -45,23 +46,21 @@ static void Evaluate_CompositeFunction(benchmark::State& state) { size_t stopCount = state.range(0); auto doc = createFunctionJSON(stopCount); conversion::Error error; - std::optional> function = conversion::convertJSON>(doc, error, true, false); + std::optional> function = conversion::convertJSON>( + doc, error, true, false); if (!function) { state.SkipWithError(error.message.c_str()); } - while(state.KeepRunning()) { + while (state.KeepRunning()) { float z = 24.0f * static_cast(rand() % 100) / 100; - function->asExpression().evaluate(z, StubGeometryTileFeature(PropertyMap { { "x", static_cast(rand() % 100) } }), -1.0f); + function->asExpression().evaluate( + z, StubGeometryTileFeature(PropertyMap{{"x", static_cast(rand() % 100)}}), -1.0f); } state.SetLabel(std::to_string(stopCount).c_str()); } -BENCHMARK(Parse_CompositeFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - -BENCHMARK(Evaluate_CompositeFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - +BENCHMARK(Parse_CompositeFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); +BENCHMARK(Evaluate_CompositeFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); diff --git a/benchmark/function/source_function.benchmark.cpp b/benchmark/function/source_function.benchmark.cpp index 2056fe706e2..a54d75e1938 100644 --- a/benchmark/function/source_function.benchmark.cpp +++ b/benchmark/function/source_function.benchmark.cpp @@ -28,7 +28,8 @@ static void Parse_SourceFunction(benchmark::State& state) { state.PauseTiming(); auto doc = createFunctionJSON(stopCount); state.ResumeTiming(); - std::optional> result = conversion::convertJSON>(doc, error, true, false); + std::optional> result = conversion::convertJSON>( + doc, error, true, false); if (!result) { state.SkipWithError(error.message.c_str()); } @@ -40,22 +41,20 @@ static void Evaluate_SourceFunction(benchmark::State& state) { size_t stopCount = state.range(0); auto doc = createFunctionJSON(stopCount); conversion::Error error; - std::optional> function = conversion::convertJSON>(doc, error, true, false); + std::optional> function = conversion::convertJSON>( + doc, error, true, false); if (!function) { state.SkipWithError(error.message.c_str()); } - while(state.KeepRunning()) { - function->asExpression().evaluate(StubGeometryTileFeature(PropertyMap { { "x", static_cast(rand() % 100) } }), -1.0f); + while (state.KeepRunning()) { + function->asExpression().evaluate( + StubGeometryTileFeature(PropertyMap{{"x", static_cast(rand() % 100)}}), -1.0f); } state.SetLabel(std::to_string(stopCount).c_str()); } -BENCHMARK(Parse_SourceFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - -BENCHMARK(Evaluate_SourceFunction) - ->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); - +BENCHMARK(Parse_SourceFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); +BENCHMARK(Evaluate_SourceFunction)->Arg(1)->Arg(2)->Arg(4)->Arg(6)->Arg(8)->Arg(10)->Arg(12); diff --git a/benchmark/parse/filter.benchmark.cpp b/benchmark/parse/filter.benchmark.cpp index 7f94d9d7446..fd19d708ea4 100644 --- a/benchmark/parse/filter.benchmark.cpp +++ b/benchmark/parse/filter.benchmark.cpp @@ -22,7 +22,7 @@ static void Parse_Filter(benchmark::State& state) { static void Parse_EvaluateFilter(benchmark::State& state) { const style::Filter filter = parse(R"FILTER(["==", "foo", "bar"])FILTER"); - const StubGeometryTileFeature feature = { {}, FeatureType::Unknown , {}, {{ "foo", std::string("bar") }} }; + const StubGeometryTileFeature feature = {{}, FeatureType::Unknown, {}, {{"foo", std::string("bar")}}}; const style::expression::EvaluationContext context(&feature); while (state.KeepRunning()) { diff --git a/benchmark/parse/tile_mask.benchmark.cpp b/benchmark/parse/tile_mask.benchmark.cpp index a31e0b5eab6..226b1e0e57c 100644 --- a/benchmark/parse/tile_mask.benchmark.cpp +++ b/benchmark/parse/tile_mask.benchmark.cpp @@ -7,11 +7,8 @@ using namespace mbgl; class FakeTile { public: FakeTile(TileMask mask_) - : mask(std::move(mask_)) { - } - void setMask(TileMask mask_) { - mask = std::move(mask_); - } + : mask(std::move(mask_)) {} + void setMask(TileMask mask_) { mask = std::move(mask_); } const bool usedByRenderedLayers = true; TileMask mask; @@ -19,13 +16,13 @@ class FakeTile { static void TileMaskGeneration(benchmark::State& state) { std::map renderables = { - { UnwrappedTileID{ 12, 1028, 1456 }, TileMask{} }, - { UnwrappedTileID{ 13, 2056, 2912 }, TileMask{} }, - { UnwrappedTileID{ 13, 2056, 2913 }, TileMask{} }, - { UnwrappedTileID{ 14, 4112, 5824 }, TileMask{} }, - { UnwrappedTileID{ 14, 4112, 5827 }, TileMask{} }, - { UnwrappedTileID{ 14, 4114, 5824 }, TileMask{} }, - { UnwrappedTileID{ 14, 4114, 5825 }, TileMask{} }, + {UnwrappedTileID{12, 1028, 1456}, TileMask{}}, + {UnwrappedTileID{13, 2056, 2912}, TileMask{}}, + {UnwrappedTileID{13, 2056, 2913}, TileMask{}}, + {UnwrappedTileID{14, 4112, 5824}, TileMask{}}, + {UnwrappedTileID{14, 4112, 5827}, TileMask{}}, + {UnwrappedTileID{14, 4114, 5824}, TileMask{}}, + {UnwrappedTileID{14, 4114, 5825}, TileMask{}}, }; while (state.KeepRunning()) { diff --git a/benchmark/parse/vector_tile.benchmark.cpp b/benchmark/parse/vector_tile.benchmark.cpp index b87241a2c5a..35f11e9c7df 100644 --- a/benchmark/parse/vector_tile.benchmark.cpp +++ b/benchmark/parse/vector_tile.benchmark.cpp @@ -6,7 +6,8 @@ using namespace mbgl; static void Parse_VectorTile(benchmark::State& state) { - auto data = std::make_shared(util::read_file("test/fixtures/api/assets/streets/10-163-395.vector.pbf")); + auto data = std::make_shared( + util::read_file("test/fixtures/api/assets/streets/10-163-395.vector.pbf")); while (state.KeepRunning()) { std::size_t length = 0; diff --git a/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp b/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp index fe19cbb313f..27edd1f9df7 100644 --- a/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp +++ b/benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp @@ -8,34 +8,29 @@ using namespace mbgl; class StubGeometryTileFeature : public GeometryTileFeature { public: StubGeometryTileFeature(PropertyMap properties_) - : properties(std::move(properties_)) { - } + : properties(std::move(properties_)) {} - StubGeometryTileFeature(FeatureIdentifier id_, FeatureType type_, GeometryCollection geometry_, PropertyMap properties_) + StubGeometryTileFeature(FeatureIdentifier id_, + FeatureType type_, + GeometryCollection geometry_, + PropertyMap properties_) : properties(std::move(properties_)), id(std::move(id_)), type(type_), - geometry(std::move(geometry_)) { - } + geometry(std::move(geometry_)) {} PropertyMap properties; FeatureIdentifier id; FeatureType type = FeatureType::Point; GeometryCollection geometry; - FeatureType getType() const override { - return type; - } + FeatureType getType() const override { return type; } - FeatureIdentifier getID() const override { - return id; - } + FeatureIdentifier getID() const override { return id; } std::optional getValue(const std::string& key) const override { return properties.count(key) ? properties.at(key) : std::optional(); } - const GeometryCollection& getGeometries() const override { - return geometry; - } + const GeometryCollection& getGeometries() const override { return geometry; } }; diff --git a/benchmark/storage/offline_database.benchmark.cpp b/benchmark/storage/offline_database.benchmark.cpp index 09da8bcb067..abede0d0dcb 100644 --- a/benchmark/storage/offline_database.benchmark.cpp +++ b/benchmark/storage/offline_database.benchmark.cpp @@ -30,7 +30,8 @@ class OfflineDatabase : public benchmark::Fixture { db.clearAmbientCache(); for (unsigned i = 0; i < tileCount; ++i) { - const Resource ambient = Resource::tile("mapbox://tile_ambient" + util::toString(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://tile_ambient" + util::toString(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambient, response); } } @@ -43,14 +44,16 @@ class OfflineDatabase : public benchmark::Fixture { db.deleteRegion(std::move(regions[0])); } - OfflineTilePyramidRegionDefinition definition{ "mapbox://style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "mapbox://style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); regionID = region->getID(); for (unsigned i = 0; i < tileCount; ++i) { - const Resource offline = Resource::tile("mapbox://tile_offline_region" + util::toString(i), 1.0, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource offline = Resource::tile( + "mapbox://tile_offline_region" + util::toString(i), 1.0, 0, 0, 0, Tileset::Scheme::XYZ); db.putRegionResource(regionID, offline, response); } } @@ -78,8 +81,8 @@ BENCHMARK_F(OfflineDatabase, InsertTileRegion)(benchmark::State& state) { using namespace mbgl; while (state.KeepRunning()) { - const Resource offline = Resource::tile("mapbox://InsertTileRegion" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource offline = Resource::tile( + "mapbox://InsertTileRegion" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.putRegionResource(regionID, offline, response); } } @@ -99,8 +102,8 @@ BENCHMARK_F(OfflineDatabase, InsertTileCache)(benchmark::State& state) { using namespace mbgl; while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://InsertTileCache" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://InsertTileCache" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambient, response); } } @@ -112,8 +115,8 @@ BENCHMARK_F(OfflineDatabase, InsertBigTileCache)(benchmark::State& state) { big.data = std::make_shared(util::DEFAULT_MAX_CACHE_SIZE / 100, 0); while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://InsertTileCache" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://InsertTileCache" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambient, big); } } @@ -126,7 +129,8 @@ BENCHMARK_F(OfflineDatabase, GetTile)(benchmark::State& state) { std::uniform_int_distribution<> dis(0, tileCount - 1); while (state.KeepRunning()) { - auto res = db.get(Resource::tile("mapbox://tile_ambient" + util::toString(dis(gen)), 1, 0, 0, 0, Tileset::Scheme::XYZ)); + auto res = db.get( + Resource::tile("mapbox://tile_ambient" + util::toString(dis(gen)), 1, 0, 0, 0, Tileset::Scheme::XYZ)); assert(res != std::nullopt); } } @@ -138,15 +142,16 @@ BENCHMARK_F(OfflineDatabase, AddTilesToFullDatabase)(benchmark::State& state) { db.setMaximumAmbientCacheSize(50 * 1024 * 5); while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://AddTilesToFullDatabase" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://AddTilesToFullDatabase" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambient, response); } Log::removeObserver(); } -BENCHMARK_F(OfflineDatabase, AddTilesToDisabledDatabase)(benchmark::State& state) { +BENCHMARK_F(OfflineDatabase, AddTilesToDisabledDatabase) +(benchmark::State& state) { using namespace mbgl; auto regions = db.listRegions().value(); @@ -158,13 +163,14 @@ BENCHMARK_F(OfflineDatabase, AddTilesToDisabledDatabase)(benchmark::State& state db.setMaximumAmbientCacheSize(0); while (state.KeepRunning()) { - const Resource ambient = Resource::tile("mapbox://AddTilesToFullDatabase" + - util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambient = Resource::tile( + "mapbox://AddTilesToFullDatabase" + util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambient, response); } } -BENCHMARK_F(OfflineDatabase, GetTileFromDisabledDatabase)(benchmark::State& state) { +BENCHMARK_F(OfflineDatabase, GetTileFromDisabledDatabase) +(benchmark::State& state) { using namespace mbgl; auto regions = db.listRegions().value(); diff --git a/benchmark/util/tilecover.benchmark.cpp b/benchmark/util/tilecover.benchmark.cpp index dbac201bfd0..b3c63c61e81 100644 --- a/benchmark/util/tilecover.benchmark.cpp +++ b/benchmark/util/tilecover.benchmark.cpp @@ -7,8 +7,7 @@ using namespace mbgl; -static const LatLngBounds sanFrancisco = - LatLngBounds::hull({ 37.6609, -122.5744 }, { 37.8271, -122.3204 }); +static const LatLngBounds sanFrancisco = LatLngBounds::hull({37.6609, -122.5744}, {37.8271, -122.3204}); static void TileCountBounds(benchmark::State& state) { std::size_t length = 0; @@ -21,9 +20,9 @@ static void TileCountBounds(benchmark::State& state) { static void TileCoverPitchedViewport(benchmark::State& state) { Transform transform; - transform.resize({ 512, 512 }); + transform.resize({512, 512}); // slightly offset center so that tile order is better defined - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.1, -0.1 }).withZoom(8.0).withBearing(5.0).withPitch(40.0)); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.1, -0.1}).withZoom(8.0).withBearing(5.0).withPitch(40.0)); std::size_t length = 0; while (state.KeepRunning()) { @@ -43,32 +42,18 @@ static void TileCoverBounds(benchmark::State& state) { } static const auto geomPolygon = Polygon{ - { - {-122.5143814086914,37.779127216982424}, - {-122.50811576843262,37.72721239056709}, - {-122.50313758850099,37.70820178063929}, - {-122.3938751220703,37.707454835665274}, - {-122.37567901611328,37.70663997801684}, - {-122.36297607421874,37.71343018466285}, - {-122.354736328125,37.727280276860036}, - {-122.36469268798828,37.73868429065797}, - {-122.38014221191408,37.75442980295571}, - {-122.38391876220702,37.78753873820529}, - {-122.35919952392578,37.8065289741725}, - {-122.35679626464844,37.820632846207864}, - {-122.3712158203125,37.835276322922695}, - {-122.3818588256836,37.82958198283902}, - {-122.37190246582031,37.80788523279169}, - {-122.38735198974608,37.791337175930686}, - {-122.40966796874999,37.812767557570204}, - {-122.46425628662108,37.807071480609274}, - {-122.46803283691405,37.810326435534755}, - {-122.47901916503906,37.81168262440736}, - {-122.48966217041016,37.78916666399649}, - {-122.50579833984375,37.78781006166096}, - {-122.5143814086914,37.779127216982424} - } -}; + {{-122.5143814086914, 37.779127216982424}, {-122.50811576843262, 37.72721239056709}, + {-122.50313758850099, 37.70820178063929}, {-122.3938751220703, 37.707454835665274}, + {-122.37567901611328, 37.70663997801684}, {-122.36297607421874, 37.71343018466285}, + {-122.354736328125, 37.727280276860036}, {-122.36469268798828, 37.73868429065797}, + {-122.38014221191408, 37.75442980295571}, {-122.38391876220702, 37.78753873820529}, + {-122.35919952392578, 37.8065289741725}, {-122.35679626464844, 37.820632846207864}, + {-122.3712158203125, 37.835276322922695}, {-122.3818588256836, 37.82958198283902}, + {-122.37190246582031, 37.80788523279169}, {-122.38735198974608, 37.791337175930686}, + {-122.40966796874999, 37.812767557570204}, {-122.46425628662108, 37.807071480609274}, + {-122.46803283691405, 37.810326435534755}, {-122.47901916503906, 37.81168262440736}, + {-122.48966217041016, 37.78916666399649}, {-122.50579833984375, 37.78781006166096}, + {-122.5143814086914, 37.779127216982424}}}; static void TileCoverPolygon(benchmark::State& state) { std::size_t length = 0; @@ -95,4 +80,3 @@ BENCHMARK(TileCountPolygon); BENCHMARK(TileCoverPitchedViewport); BENCHMARK(TileCoverBounds); BENCHMARK(TileCoverPolygon); - diff --git a/bin/offline.cpp b/bin/offline.cpp index 1025608009b..eb1930d39d1 100644 --- a/bin/offline.cpp +++ b/bin/offline.cpp @@ -24,52 +24,47 @@ std::string readFile(const std::string& fileName) { if (!stream.good()) { throw std::runtime_error("Cannot read file: " + fileName); } - + std::stringstream buffer; buffer << stream.rdbuf(); stream.close(); - + return buffer.str(); } mapbox::geometry::geometry parseGeometry(const std::string& json) { using namespace mapbox::geojson; auto geojson = parse(json); - return geojson.match( - [](const geometry& geom) { - return geom; - }, - [](const feature& feature) { - return feature.geometry; - }, - [](const feature_collection& featureCollection) { - if (featureCollection.size() < 1) { - throw std::runtime_error("No features in feature collection"); - } - geometry_collection geometries; - - for (auto feature : featureCollection) { - geometries.push_back(feature.geometry); - } - - return geometries; - }); + return geojson.match([](const geometry& geom) { return geom; }, + [](const feature& feature) { return feature.geometry; }, + [](const feature_collection& featureCollection) { + if (featureCollection.size() < 1) { + throw std::runtime_error("No features in feature collection"); + } + geometry_collection geometries; + + for (auto feature : featureCollection) { + geometries.push_back(feature.geometry); + } + + return geometries; + }); } std::ostream& operator<<(std::ostream& os, mbgl::Response::Error::Reason r) { switch (r) { - case mbgl::Response::Error::Reason::Success: - return os << "Response::Error::Reason::Success"; - case mbgl::Response::Error::Reason::NotFound: - return os << "Response::Error::Reason::NotFound"; - case mbgl::Response::Error::Reason::Server: - return os << "Response::Error::Reason::Server"; - case mbgl::Response::Error::Reason::Connection: - return os << "Response::Error::Reason::Connection"; - case mbgl::Response::Error::Reason::RateLimit: - return os << "Response::Error::Reason::RateLimit"; - case mbgl::Response::Error::Reason::Other: - return os << "Response::Error::Reason::Other"; + case mbgl::Response::Error::Reason::Success: + return os << "Response::Error::Reason::Success"; + case mbgl::Response::Error::Reason::NotFound: + return os << "Response::Error::Reason::NotFound"; + case mbgl::Response::Error::Reason::Server: + return os << "Response::Error::Reason::Server"; + case mbgl::Response::Error::Reason::Connection: + return os << "Response::Error::Reason::Connection"; + case mbgl::Response::Error::Reason::RateLimit: + return os << "Response::Error::Reason::RateLimit"; + case mbgl::Response::Error::Reason::Other: + return os << "Response::Error::Reason::Other"; } // The above switch is exhaustive, but placate GCC nonetheless: @@ -77,7 +72,7 @@ std::ostream& operator<<(std::ostream& os, mbgl::Response::Error::Reason r) { return os; } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { args::ArgumentParser argumentParser("Mapbox GL offline tool"); args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {'h', "help"}); @@ -85,10 +80,11 @@ int main(int argc, char *argv[]) { args::ValueFlag styleValue(argumentParser, "URL", "Map stylesheet", {'s', "style"}); args::ValueFlag outputValue(argumentParser, "file", "Output database file name", {'o', "output"}); args::ValueFlag apiBaseValue(argumentParser, "URL", "API Base URL", {'a', "apiBaseURL"}); - + args::Group mergeGroup(argumentParser, "Merge databases:", args::Group::Validators::AllOrNone); args::ValueFlag mergePathValue(mergeGroup, "merge", "Database to merge from", {'m', "merge"}); - args::ValueFlag inputValue(mergeGroup, "input", "Database to merge into. Use with --merge option.", {'i', "input"}); + args::ValueFlag inputValue( + mergeGroup, "input", "Database to merge into. Use with --merge option.", {'i', "input"}); // LatLngBounds args::Group latLngBoundsGroup(argumentParser, "LatLng bounds:", args::Group::Validators::AllOrNone); @@ -99,12 +95,17 @@ int main(int argc, char *argv[]) { // Geometry args::Group geoJSONGroup(argumentParser, "GeoJson geometry:", args::Group::Validators::AllOrNone); - args::ValueFlag geometryValue(geoJSONGroup, "file", "GeoJSON Feature file containing the region geometry (can't be a FeatureCollection)", {"geojson"}); + args::ValueFlag geometryValue(geoJSONGroup, + "file", + "GeoJSON Feature file containing the region geometry (can't be a " + "FeatureCollection)", + {"geojson"}); args::ValueFlag minZoomValue(argumentParser, "number", "Min zoom level", {"minZoom"}); args::ValueFlag maxZoomValue(argumentParser, "number", "Max zoom level", {"maxZoom"}); args::ValueFlag pixelRatioValue(argumentParser, "number", "Pixel ratio", {"pixelRatio"}); - args::ValueFlag includeIdeographsValue(argumentParser, "boolean", "Include CJK glyphs", {"includeIdeographs"}); + args::ValueFlag includeIdeographsValue( + argumentParser, "boolean", "Include CJK glyphs", {"includeIdeographs"}); try { argumentParser.ParseCLI(argc, argv); @@ -122,10 +123,10 @@ int main(int argc, char *argv[]) { } auto mapTilerConfiguration = mbgl::TileServerOptions::MapTilerConfiguration(); - + std::string style = styleValue ? args::get(styleValue) : mapTilerConfiguration.defaultStyles().at(0).getUrl(); std::cout << " Style: " << style << std::endl; - + std::optional mergePath = std::nullopt; if (mergePathValue) mergePath = args::get(mergePathValue); std::optional inputDb = std::nullopt; @@ -136,16 +137,17 @@ int main(int argc, char *argv[]) { const double pixelRatio = pixelRatioValue ? args::get(pixelRatioValue) : 1.0; const bool includeIdeographs = includeIdeographsValue ? args::get(includeIdeographsValue) : false; const std::string output = outputValue ? args::get(outputValue) : "offline.db"; - + using namespace mbgl; - + OfflineRegionDefinition definition = [&]() { if (geometryValue) { try { std::string json = readFile(geometryValue.Get()); auto geometry = parseGeometry(json); - return OfflineRegionDefinition{ OfflineGeometryRegionDefinition(style, geometry, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs) }; - } catch(const std::runtime_error& e) { + return OfflineRegionDefinition{OfflineGeometryRegionDefinition( + style, geometry, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs)}; + } catch (const std::runtime_error& e) { std::cerr << "Could not parse geojson file " << geometryValue.Get() << ": " << e.what() << std::endl; exit(1); } @@ -156,13 +158,14 @@ int main(int argc, char *argv[]) { const double south = southValue ? args::get(southValue) : 38.1; const double east = eastValue ? args::get(eastValue) : -121.7; LatLngBounds boundingBox = LatLngBounds::hull(LatLng(north, west), LatLng(south, east)); - return OfflineRegionDefinition{ OfflineTilePyramidRegionDefinition(style, boundingBox, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs) }; + return OfflineRegionDefinition{OfflineTilePyramidRegionDefinition( + style, boundingBox, minZoom, maxZoom, static_cast(pixelRatio), includeIdeographs)}; } }(); const char* apiEnv = getenv("MLN_API_KEY"); const std::string apiKey = tokenValue ? args::get(tokenValue) : (apiEnv ? apiEnv : std::string()); - + if (apiBaseValue) { mapTilerConfiguration.withBaseURL(args::get(apiBaseValue)); } @@ -171,9 +174,7 @@ int main(int argc, char *argv[]) { std::shared_ptr fileSource = std::static_pointer_cast( std::shared_ptr(FileSourceManager::get()->getFileSource( FileSourceType::Database, - ResourceOptions().withApiKey(apiKey) - .withTileServerOptions(mapTilerConfiguration) - .withCachePath(output), + ResourceOptions().withApiKey(apiKey).withTileServerOptions(mapTilerConfiguration).withCachePath(output), ClientOptions()))); std::unique_ptr region; @@ -183,17 +184,17 @@ int main(int argc, char *argv[]) { int retCode = 0; std::cout << "Start Merge" << std::endl; - inputSource.mergeOfflineRegions(*mergePath, [&] (mbgl::expected, std::exception_ptr> result) { - - if (!result) { - std::cerr << "Error merging database: " << util::toString(result.error()) << std::endl; - retCode = 1; - } else { - std::cout << " Added " << result->size() << " Regions" << std::endl; - std::cout << "Finished Merge" << std::endl; - } - loop.stop(); - }); + inputSource.mergeOfflineRegions( + *mergePath, [&](mbgl::expected, std::exception_ptr> result) { + if (!result) { + std::cerr << "Error merging database: " << util::toString(result.error()) << std::endl; + retCode = 1; + } else { + std::cout << " Added " << result->size() << " Regions" << std::endl; + std::cout << "Finished Merge" << std::endl; + } + loop.stop(); + }); loop.run(); return retCode; } @@ -260,7 +261,7 @@ int main(int argc, char *argv[]) { } }; - std::signal(SIGINT, [] (int) { stop(); }); + std::signal(SIGINT, [](int) { stop(); }); fileSource->createOfflineRegion( definition, metadata, [&](mbgl::expected region_) { diff --git a/bin/render.cpp b/bin/render.cpp index 3f704fe026f..b6bb55cf6cb 100644 --- a/bin/render.cpp +++ b/bin/render.cpp @@ -13,7 +13,7 @@ #include #include -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { args::ArgumentParser argumentParser("Mapbox GL render tool"); args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {"help"}); @@ -22,7 +22,8 @@ int main(int argc, char *argv[]) { args::ValueFlag styleValue(argumentParser, "URL", "Map stylesheet", {'s', "style"}); args::ValueFlag outputValue(argumentParser, "file", "Output file name", {'o', "output"}); args::ValueFlag cacheValue(argumentParser, "file", "Cache database file name", {'c', "cache"}); - args::ValueFlag assetsValue(argumentParser, "file", "Directory to which asset:// URLs will resolve", {'a', "assets"}); + args::ValueFlag assetsValue( + argumentParser, "file", "Directory to which asset:// URLs will resolve", {'a', "assets"}); args::Flag debugFlag(argumentParser, "debug", "Debug mode", {"debug"}); @@ -78,31 +79,36 @@ int main(int argc, char *argv[]) { util::RunLoop loop; - HeadlessFrontend frontend({ width, height }, static_cast(pixelRatio)); - Map map(frontend, MapObserver::nullObserver(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()).withPixelRatio(static_cast(pixelRatio)), - ResourceOptions().withCachePath(cache_file).withAssetPath(asset_root).withApiKey(apikey).withTileServerOptions(mapTilerConfiguration)); + HeadlessFrontend frontend({width, height}, static_cast(pixelRatio)); + Map map(frontend, + MapObserver::nullObserver(), + MapOptions() + .withMapMode(MapMode::Static) + .withSize(frontend.getSize()) + .withPixelRatio(static_cast(pixelRatio)), + ResourceOptions() + .withCachePath(cache_file) + .withAssetPath(asset_root) + .withApiKey(apikey) + .withTileServerOptions(mapTilerConfiguration)); if (style.find("://") == std::string::npos) { style = std::string("file://") + style; } map.getStyle().loadURL(style); - map.jumpTo(CameraOptions() - .withCenter(LatLng { lat, lon }) - .withZoom(zoom) - .withBearing(bearing) - .withPitch(pitch)); + map.jumpTo(CameraOptions().withCenter(LatLng{lat, lon}).withZoom(zoom).withBearing(bearing).withPitch(pitch)); if (debug) { - map.setDebug(debug ? mbgl::MapDebugOptions::TileBorders | mbgl::MapDebugOptions::ParseStatus : mbgl::MapDebugOptions::NoDebug); + map.setDebug(debug ? mbgl::MapDebugOptions::TileBorders | mbgl::MapDebugOptions::ParseStatus + : mbgl::MapDebugOptions::NoDebug); } try { std::ofstream out(output, std::ios::binary); out << encodePNG(frontend.render(map).image); out.close(); - } catch(std::exception& e) { + } catch (std::exception& e) { std::cout << "Error: " << e.what() << std::endl; exit(1); } diff --git a/expression-test/expression_test_logger.cpp b/expression-test/expression_test_logger.cpp index 9127a6d7aed..a6d51346653 100644 --- a/expression-test/expression_test_logger.cpp +++ b/expression-test/expression_test_logger.cpp @@ -60,7 +60,7 @@ document.getElementById('toggle-sequence').addEventListener('click', function (e std::string createResultItem(const TestRunOutput& result, const std::string& status, bool shouldHide) { std::ostringstream html; html << "
\n"; - html << R"(

)" << status << " " << result.id << "

\n"; + html << R"(

)" << status << " " << result.id << "

\n"; html << "

"s << result.expression << "

\n"s; if (result.passed) { @@ -98,11 +98,11 @@ std::string createResultPage(const TestStats& stats, bool shuffle, uint32_t seed // Failed tests if (unsuccessful) { - resultsPage << "

Failed tests:"; + resultsPage << "

Failed tests:"; for (const auto& failed : stats.failed) { resultsPage << failed.id << " "; } - resultsPage << "

Errored tests:"; + resultsPage << "

Errored tests:"; for (const auto& errored : stats.errored) { resultsPage << errored.id << " "; } @@ -127,9 +127,9 @@ std::string createResultPage(const TestStats& stats, bool shuffle, uint32_t seed // Script resultsPage << resultsScript; - // Tests + // Tests resultsPage << "

\n"; - const auto appendResult = [&] (const auto& results, const std::string& status, bool hide = false) { + const auto appendResult = [&](const auto& results, const std::string& status, bool hide = false) { for (const auto& result : results) { resultsPage << createResultItem(result, status, hide); } @@ -153,16 +153,21 @@ void printStats(const TestStats& stats) { printf(ANSI_COLOR_GREEN "%zu passed (%.1lf%%)" ANSI_COLOR_RESET "\n", passedTests, 100.0 * passedTests / count); } if (std::size_t ignorePassedTests = stats.ignorePassed.size()) { - printf(ANSI_COLOR_YELLOW "%zu passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", ignorePassedTests, 100.0 * ignorePassedTests / count); + printf(ANSI_COLOR_YELLOW "%zu passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + ignorePassedTests, + 100.0 * ignorePassedTests / count); } if (std::size_t ignoreFailedTests = stats.ignoreFailed.size()) { - printf(ANSI_COLOR_LIGHT_GRAY "%zu ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", ignoreFailedTests, 100.0 * ignoreFailedTests / count); + printf(ANSI_COLOR_LIGHT_GRAY "%zu ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + ignoreFailedTests, + 100.0 * ignoreFailedTests / count); } if (std::size_t failedTests = stats.failed.size()) { printf(ANSI_COLOR_RED "%zu failed (%.1lf%%)" ANSI_COLOR_RESET "\n", failedTests, 100.0 * failedTests / count); } if (std::size_t erroredTests = stats.errored.size()) { - printf(ANSI_COLOR_RED "%zu errored (%.1lf%%)" ANSI_COLOR_RESET "\n", erroredTests, 100.0 * erroredTests / count); + printf( + ANSI_COLOR_RED "%zu errored (%.1lf%%)" ANSI_COLOR_RESET "\n", erroredTests, 100.0 * erroredTests / count); } } diff --git a/expression-test/expression_test_logger.hpp b/expression-test/expression_test_logger.hpp index ae03476fa3e..e8dabcedf86 100644 --- a/expression-test/expression_test_logger.hpp +++ b/expression-test/expression_test_logger.hpp @@ -3,11 +3,11 @@ #include #include -#define ANSI_COLOR_RED "\x1b[31m" -#define ANSI_COLOR_GREEN "\x1b[32m" -#define ANSI_COLOR_YELLOW "\x1b[33m" +#define ANSI_COLOR_RED "\x1b[31m" +#define ANSI_COLOR_GREEN "\x1b[32m" +#define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_LIGHT_GRAY "\x1b[90m" -#define ANSI_COLOR_RESET "\x1b[0m" +#define ANSI_COLOR_RESET "\x1b[0m" class TestStats; diff --git a/expression-test/expression_test_parser.cpp b/expression-test/expression_test_parser.cpp index ca504a01424..352330e8f9d 100644 --- a/expression-test/expression_test_parser.cpp +++ b/expression-test/expression_test_parser.cpp @@ -28,29 +28,27 @@ using namespace std::literals; namespace { void writeJSON(rapidjson::PrettyWriter& writer, const Value& value) { - value.match( - [&] (const NullValue&) { writer.Null(); }, - [&] (bool b) { writer.Bool(b); }, - [&] (uint64_t u) { writer.Uint64(u); }, - [&] (int64_t i) { writer.Int64(i); }, - [&] (double d) { d == std::floor(d) ? writer.Int64(static_cast(d)) : writer.Double(d); }, - [&] (const std::string& s) { writer.String(s); }, - [&] (const std::vector& arr) { - writer.StartArray(); - for(const auto& item : arr) { - writeJSON(writer, item); - } - writer.EndArray(); - }, - [&] (const std::unordered_map& obj) { - writer.StartObject(); - for(const auto& entry : obj) { - writer.Key(entry.first.c_str()); - writeJSON(writer, entry.second); - } - writer.EndObject(); - } - ); + value.match([&](const NullValue&) { writer.Null(); }, + [&](bool b) { writer.Bool(b); }, + [&](uint64_t u) { writer.Uint64(u); }, + [&](int64_t i) { writer.Int64(i); }, + [&](double d) { d == std::floor(d) ? writer.Int64(static_cast(d)) : writer.Double(d); }, + [&](const std::string& s) { writer.String(s); }, + [&](const std::vector& arr) { + writer.StartArray(); + for (const auto& item : arr) { + writeJSON(writer, item); + } + writer.EndArray(); + }, + [&](const std::unordered_map& obj) { + writer.StartObject(); + for (const auto& entry : obj) { + writer.Key(entry.first.c_str()); + writeJSON(writer, entry.second); + } + writer.EndObject(); + }); } using ErrorMessage = std::string; @@ -58,21 +56,21 @@ using JSONReply = variant; JSONReply readJson(const filesystem::path& jsonPath) { auto maybeJSON = util::readFile(jsonPath); if (!maybeJSON) { - return { "Unable to open file "s + jsonPath.string() }; + return {"Unable to open file "s + jsonPath.string()}; } JSDocument document; document.Parse(*maybeJSON); if (document.HasParseError()) { - return { formatJSONParseError(document) }; + return {formatJSONParseError(document)}; } - return { std::move(document) }; + return {std::move(document)}; } std::string toString(const JSValue& value) { assert(value.IsString()); - return { value.GetString(), value.GetStringLength() }; + return {value.GetString(), value.GetStringLength()}; } std::optional toValue(const JSValue& jsvalue) { @@ -314,10 +312,9 @@ bool parseInputs(const JSValue& inputsValue, TestData& data) { std::tuple, bool, uint32_t> parseArguments(int argc, char** argv) { args::ArgumentParser argumentParser("Mapbox GL Expression Test Runner"); - args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", { 'h', "help" }); + args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {'h', "help"}); args::Flag shuffleFlag(argumentParser, "shuffle", "Toggle shuffling the tests order", {'s', "shuffle"}); - args::ValueFlag seedValue(argumentParser, "seed", "Shuffle seed (default: random)", - { "seed" }); + args::ValueFlag seedValue(argumentParser, "seed", "Shuffle seed (default: random)", {"seed"}); args::PositionalList testNameValues(argumentParser, "URL", "Test name(s)"); args::ValueFlag testFilterValue(argumentParser, "filter", "Test filter regex", {'f', "filter"}); @@ -342,7 +339,7 @@ std::tuple, bool, uint32_t> pars exit(2); } - filesystem::path rootPath {std::string(TEST_RUNNER_ROOT_PATH).append("/metrics/integration/expression-tests")}; + filesystem::path rootPath{std::string(TEST_RUNNER_ROOT_PATH).append("/metrics/integration/expression-tests")}; if (!filesystem::exists(rootPath)) { Log::Error(Event::General, "Test path '" + rootPath.string() + "' does not exist."); exit(3); @@ -377,10 +374,10 @@ std::tuple, bool, uint32_t> pars } } - return Arguments{ std::move(rootPath), - std::move(testPaths), - shuffleFlag ? args::get(shuffleFlag) : false, - seedValue ? args::get(seedValue) : 1u }; + return Arguments{std::move(rootPath), + std::move(testPaths), + shuffleFlag ? args::get(shuffleFlag) : false, + seedValue ? args::get(seedValue) : 1u}; } Ignores parseExpressionIgnores() { @@ -392,12 +389,12 @@ Ignores parseExpressionIgnores() { } for (const auto& property : maybeIgnores.get().GetObject()) { - std::string id{ toString(property.name) }; + std::string id{toString(property.name)}; // Keep only expression-test ignores if (id.rfind("expression-tests", 0) != 0) { continue; } - std::string reason{ toString(property.value) }; + std::string reason{toString(property.value)}; ignores.emplace_back(std::move(id), std::move(reason)); } @@ -474,7 +471,8 @@ Value toValue(const Compiled& compiled) { std::optional toValue(const expression::Value& exprValue) { return exprValue.match( [](const Color& c) -> std::optional { - std::vector color { static_cast(c.r), static_cast(c.g), static_cast(c.b), static_cast(c.a) }; + std::vector color{ + static_cast(c.r), static_cast(c.g), static_cast(c.b), static_cast(c.a)}; return {Value{std::move(color)}}; }, [](const expression::Formatted& formatted) -> std::optional { return {formatted.toObject()}; }, @@ -503,11 +501,10 @@ std::unique_ptr parseExpression(const JSValue& va std::optional& spec, TestResult& result) { std::optional expected = spec ? toExpressionType(*spec) : std::nullopt; - expression::ParsingContext ctx = expected ? expression::ParsingContext(*expected) : - expression::ParsingContext(); + expression::ParsingContext ctx = expected ? expression::ParsingContext(*expected) : expression::ParsingContext(); Convertible convertible(&value); expression::ParseResult parsed; - if (value.IsObject() && !value.IsArray() && expected){ + if (value.IsObject() && !value.IsArray() && expected) { Error error; parsed = convertFunctionToExpression(*expected, convertible, error, false /*convert tokens*/); if (!parsed) { diff --git a/expression-test/expression_test_parser.hpp b/expression-test/expression_test_parser.hpp index 2c4eaa55a70..b1d7b4772e0 100644 --- a/expression-test/expression_test_parser.hpp +++ b/expression-test/expression_test_parser.hpp @@ -32,10 +32,8 @@ struct Input { struct Compiled { bool operator==(const Compiled& other) const { - bool typeEqual = success == other.success && - isFeatureConstant == other.isFeatureConstant && - isZoomConstant == other.isZoomConstant && - serializedType == other.serializedType && + bool typeEqual = success == other.success && isFeatureConstant == other.isFeatureConstant && + isZoomConstant == other.isZoomConstant && serializedType == other.serializedType && errors == other.errors; return typeEqual; } @@ -99,4 +97,3 @@ std::unique_ptr parseExpression(const JSValue&, std::unique_ptr parseExpression(const std::optional&, std::optional&, TestResult&); - diff --git a/expression-test/expression_test_runner.cpp b/expression-test/expression_test_runner.cpp index c0d45116367..3a322a5b29d 100644 --- a/expression-test/expression_test_runner.cpp +++ b/expression-test/expression_test_runner.cpp @@ -18,15 +18,16 @@ using namespace std::literals; namespace { std::string simpleDiff(const Value& result, const Value& expected) { - std::vector resultTokens {tokenize(toJSON(result, 2, true))}; - std::vector expectedTokens {tokenize(toJSON(expected, 2, true))}; + std::vector resultTokens{tokenize(toJSON(result, 2, true))}; + std::vector expectedTokens{tokenize(toJSON(expected, 2, true))}; std::size_t maxLength = std::max(resultTokens.size(), expectedTokens.size()); std::ostringstream diff; - const auto flush = [] (const std::vector& vec, std::size_t pos, std::ostringstream& out, std::string separator) { - for (std::size_t j = pos; j < vec.size(); ++j) { - out << separator << vec[j] << std::endl; - } - }; + const auto flush = + [](const std::vector& vec, std::size_t pos, std::ostringstream& out, std::string separator) { + for (std::size_t j = pos; j < vec.size(); ++j) { + out << separator << vec[j] << std::endl; + } + }; for (std::size_t i = 0; i < maxLength; ++i) { if (resultTokens.size() <= i) { @@ -109,8 +110,8 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con evaluationResult = expression->evaluate( input.zoom, input.feature, input.heatmapDensity, input.availableImages, *input.canonical); } else { - evaluationResult = - expression->evaluate(input.zoom, input.feature, input.heatmapDensity, input.availableImages); + evaluationResult = expression->evaluate( + input.zoom, input.feature, input.heatmapDensity, input.availableImages); } if (!evaluationResult) { std::unordered_map error{{"error", Value{evaluationResult.error().message}}}; @@ -138,8 +139,7 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con auto recompiledExpression = parseExpression(data.result.serialized, data.spec, data.recompiled); if (recompiledExpression) { evaluateExpression(recompiledExpression, data.recompiled); - rewriteRoundtrippedType(data.expected.compiled.serializedType, - data.recompiled.compiled.serializedType); + rewriteRoundtrippedType(data.expected.compiled.serializedType, data.recompiled.compiled.serializedType); } } @@ -159,7 +159,7 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con if (data.expected.compiled.success) { serializationOk = compileOk && deepEqual(data.result.serialized, data.expected.serialized); - recompileOk = compileOk && data.recompiled.compiled == data.expected.compiled; + recompileOk = compileOk && data.recompiled.compiled == data.expected.compiled; roundTripOk = recompileOk && deepEqual(data.recompiled.outputs, data.expected.outputs); } @@ -168,36 +168,28 @@ TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, con if (!compileOk) { auto resultValue = toValue(data.result.compiled); auto expectedValue = toValue(data.expected.compiled); - output.text += "Compiled expression difference:\n"s + - simpleDiff(resultValue, expectedValue) + - "\n"s; + output.text += "Compiled expression difference:\n"s + simpleDiff(resultValue, expectedValue) + "\n"s; } if (compileOk && !serializationOk) { - auto diff = simpleDiff(data.expected.serialized.value_or(Value{}), - data.result.serialized.value_or(Value{})); + auto diff = simpleDiff(data.expected.serialized.value_or(Value{}), data.result.serialized.value_or(Value{})); output.text += "Serialized expression difference:\n"s + diff + "\n"s; } if (compileOk && !recompileOk) { auto recompiledValue = toValue(data.recompiled.compiled); auto expectedValue = toValue(data.expected.compiled); - output.text += "Recompiled expression difference:\n"s + - simpleDiff(recompiledValue, expectedValue) + - "\n"s; + output.text += "Recompiled expression difference:\n"s + simpleDiff(recompiledValue, expectedValue) + "\n"s; } if (compileOk && !evalOk) { - auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), - data.result.outputs.value_or(Value{})); + auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), data.result.outputs.value_or(Value{})); output.text += "Expression outputs difference:\n"s + diff + "\n"s; } if (recompileOk && !roundTripOk) { - auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), - data.recompiled.outputs.value_or(Value{})); - output.text += "Roundtripped through serialize expression outputs difference:\n"s + - diff + "\n"s; + auto diff = simpleDiff(data.expected.outputs.value_or(Value{}), data.recompiled.outputs.value_or(Value{})); + output.text += "Roundtripped through serialize expression outputs difference:\n"s + diff + "\n"s; } return output; diff --git a/expression-test/expression_test_runner.hpp b/expression-test/expression_test_runner.hpp index 596d5c11b67..4a868d3ae49 100644 --- a/expression-test/expression_test_runner.hpp +++ b/expression-test/expression_test_runner.hpp @@ -6,7 +6,8 @@ class TestData; struct TestRunOutput { - TestRunOutput(std::string id_) : id(std::move(id_)) {} + TestRunOutput(std::string id_) + : id(std::move(id_)) {} std::string id; bool passed = false; std::string text; @@ -17,8 +18,7 @@ struct TestRunOutput { class TestStats { public: std::size_t testCount() const { - return passed.size() + failed.size() + errored.size() + - ignorePassed.size() + ignoreFailed.size(); + return passed.size() + failed.size() + errored.size() + ignorePassed.size() + ignoreFailed.size(); } std::vector passed; diff --git a/expression-test/main.cpp b/expression-test/main.cpp index e1b2d0d77ec..21be570f3bf 100644 --- a/expression-test/main.cpp +++ b/expression-test/main.cpp @@ -5,8 +5,7 @@ #include #include -int main(int argc, char** argv) -try { +int main(int argc, char** argv) try { // Parse args std::vector testPaths; mbgl::filesystem::path rootPath; @@ -19,7 +18,7 @@ try { if (shuffle) { printf(ANSI_COLOR_YELLOW "Shuffle seed: %d" ANSI_COLOR_RESET "\n", seed); - std::seed_seq sequence { seed }; + std::seed_seq sequence{seed}; std::mt19937 shuffler(sequence); std::shuffle(testPaths.begin(), testPaths.end(), shuffler); } @@ -28,13 +27,15 @@ try { TestStats stats; for (const auto& path : testPaths) { const auto& expectation = path.parent_path().string(); - std::string id = expectation.substr(rootPath.string().length() + 1, expectation.length() - rootPath.string().length()); + std::string id = expectation.substr(rootPath.string().length() + 1, + expectation.length() - rootPath.string().length()); stats.ids.emplace_back(id); bool shouldIgnore = false; std::string ignoreReason; const std::string ignoreName = "expression-tests/" + id; - const auto it = std::find_if(ignores.cbegin(), ignores.cend(), [&ignoreName] (const auto& ignore) { return ignore.id == ignoreName; }); + const auto it = std::find_if( + ignores.cbegin(), ignores.cend(), [&ignoreName](const auto& ignore) { return ignore.id == ignoreName; }); if (it != ignores.end()) { shouldIgnore = true; ignoreReason = (*it).reason; @@ -54,10 +55,14 @@ try { if (shouldIgnore) { if (testRun->passed) { stats.ignorePassed.emplace_back(std::move(*testRun)); - printf(ANSI_COLOR_YELLOW "* PASSED ignored test %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str()); + printf(ANSI_COLOR_YELLOW "* PASSED ignored test %s (%s)" ANSI_COLOR_RESET "\n", + id.c_str(), + ignoreReason.c_str()); } else { stats.ignoreFailed.emplace_back(std::move(*testRun)); - printf(ANSI_COLOR_LIGHT_GRAY "* FAILED ignored test %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str()); + printf(ANSI_COLOR_LIGHT_GRAY "* FAILED ignored test %s (%s)" ANSI_COLOR_RESET "\n", + id.c_str(), + ignoreReason.c_str()); } } else { if (testRun->passed) { @@ -72,10 +77,9 @@ try { printStats(stats); writeHTMLResults(stats, rootPath.string(), shuffle, seed); - + return stats.errored.size() + stats.failed.size() == 0 ? 0 : 1; -} -catch (std::exception const& ex) { +} catch (std::exception const& ex) { std::cerr << "Caught an exception while running tests:\n" << ex.what() << '\n'; return 1; } diff --git a/expression-test/test_runner_common.cpp b/expression-test/test_runner_common.cpp index dc84ff1e55b..5bc96f6a1be 100644 --- a/expression-test/test_runner_common.cpp +++ b/expression-test/test_runner_common.cpp @@ -5,8 +5,8 @@ using namespace mbgl; -// Strip precision for numbers, so that we can compare evaluated results with fixtures. -// Copied from JS expression harness. +// Strip precision for numbers, so that we can compare evaluated results with +// fixtures. Copied from JS expression harness. Value stripPrecision(const Value& value) { const double decimalSigFigs = 6; if (auto num = numericValue(value)) { diff --git a/include/mbgl/actor/actor.hpp b/include/mbgl/actor/actor.hpp index f56e8ccab78..7ecc559d57e 100644 --- a/include/mbgl/actor/actor.hpp +++ b/include/mbgl/actor/actor.hpp @@ -15,38 +15,44 @@ namespace mbgl { /** - An `Actor` is an owning reference to an asynchronous object of type `O`: an "actor". - Communication with an actor happens via message passing: you send a message to the object - (using `invoke`), passing a pointer to the member function to call and arguments which - are then forwarded to the actor. + An `Actor` is an owning reference to an asynchronous object of type `O`: + an "actor". Communication with an actor happens via message passing: you send + a message to the object (using `invoke`), passing a pointer to the member + function to call and arguments which are then forwarded to the actor. - The actor receives messages sent to it asynchronously, in a manner defined its `Scheduler`. - To store incoming messages before their receipt, each actor has a `Mailbox`, which acts as - a FIFO queue. Messages sent from actor S to actor R are guaranteed to be processed in the - order sent. However, relative order of messages sent by two *different* actors S1 and S2 - to R is *not* guaranteed (and can't be: S1 and S2 may be acting asynchronously with respect + The actor receives messages sent to it asynchronously, in a manner defined + its `Scheduler`. To store incoming messages before their receipt, each actor + has a `Mailbox`, which acts as a FIFO queue. Messages sent from actor S to + actor R are guaranteed to be processed in the order sent. However, relative + order of messages sent by two *different* actors S1 and S2 to R is *not* + guaranteed (and can't be: S1 and S2 may be acting asynchronously with respect to each other). - An `Actor` can be converted to an `ActorRef`, a non-owning value object representing - a (weak) reference to the actor. Messages can be sent via the `Ref` as well. + An `Actor` can be converted to an `ActorRef`, a non-owning value + object representing a (weak) reference to the actor. Messages can be sent via + the `Ref` as well. - It's safe -- and encouraged -- to pass `Ref`s between actors via messages. This is how two-way - communication and other forms of collaboration between multiple actors is accomplished. + It's safe -- and encouraged -- to pass `Ref`s between actors via messages. + This is how two-way communication and other forms of collaboration between + multiple actors is accomplished. - It's safe for a `Ref` to outlive its `Actor` -- the reference is "weak", and does not extend - the lifetime of the owning Actor, and sending a message to a `Ref` whose `Actor` has died is - a no-op. (In the future, a dead-letters queue or log may be implemented.) + It's safe for a `Ref` to outlive its `Actor` -- the reference is "weak", and + does not extend the lifetime of the owning Actor, and sending a message to a + `Ref` whose `Actor` has died is a no-op. (In the future, a dead-letters queue + or log may be implemented.) - Construction and destruction of an Actor is synchronous: the corresponding `O` - object is constructed synchronously by the `Actor` constructor, and destructed synchronously - by the `~Actor` destructor, after ensuring that the `O` is not currently receiving an - asynchronous message. The constructor of `O` is passed an `ActorRef` referring to itself - (which it can use to self-send messages), followed by the forwarded arguments passed to - `Actor`. Asynchronous object construction can be accomplished by directly using the - lower-level types, `AspiringActor` and `EstablishedActor`. + Construction and destruction of an Actor is synchronous: the corresponding + `O` object is constructed synchronously by the `Actor` constructor, and + destructed synchronously by the `~Actor` destructor, after ensuring that the + `O` is not currently receiving an asynchronous message. The constructor of + `O` is passed an `ActorRef` referring to itself (which it can use to + self-send messages), followed by the forwarded arguments passed to + `Actor`. Asynchronous object construction can be accomplished by directly + using the lower-level types, `AspiringActor` and `EstablishedActor`. - Please don't send messages that contain shared pointers or references. That subverts the - purpose of the actor model: prohibiting direct concurrent access to shared state. + Please don't send messages that contain shared pointers or references. That + subverts the purpose of the actor model: prohibiting direct concurrent access + to shared state. */ template class Actor { @@ -57,13 +63,12 @@ class Actor { template Actor(std::shared_ptr scheduler, Args&&... args) - : retainer(std::move(scheduler)), target(*retainer, parent, std::forward(args)...) {} + : retainer(std::move(scheduler)), + target(*retainer, parent, std::forward(args)...) {} Actor(const Actor&) = delete; - ActorRef> self() { - return parent.self(); - } + ActorRef> self() { return parent.self(); } private: std::shared_ptr retainer; diff --git a/include/mbgl/actor/actor_ref.hpp b/include/mbgl/actor/actor_ref.hpp index d9fefc731d2..3e0689505e9 100644 --- a/include/mbgl/actor/actor_ref.hpp +++ b/include/mbgl/actor/actor_ref.hpp @@ -8,24 +8,25 @@ namespace mbgl { /** - An `ActorRef` is a *non*-owning, weak reference to an actor of type `O`. You can send it - messages just like an `Actor`. It's a value object: safe to copy and pass between actors - via messages. - - An `ActorRef` does not extend the lifetime of the corresponding `Actor`. That's determined - entirely by whichever object owns the `Actor` -- the actor's "supervisor". - - It's safe for a `Ref` to outlive its `Actor` -- the reference is "weak", and does not extend - the lifetime of the owning Actor, and sending a message to a `Ref` whose `Actor` has died is - a no-op. (In the future, a dead-letters queue or log may be implemented.) + An `ActorRef` is a *non*-owning, weak reference to an actor of type `O`. + You can send it messages just like an `Actor`. It's a value object: safe + to copy and pass between actors via messages. + + An `ActorRef` does not extend the lifetime of the corresponding + `Actor`. That's determined entirely by whichever object owns the + `Actor` -- the actor's "supervisor". + + It's safe for a `Ref` to outlive its `Actor` -- the reference is "weak", and + does not extend the lifetime of the owning Actor, and sending a message to a + `Ref` whose `Actor` has died is a no-op. (In the future, a dead-letters queue + or log may be implemented.) */ template class ActorRef { public: ActorRef(Object& object_, std::weak_ptr weakMailbox_) : object(&object_), - weakMailbox(std::move(weakMailbox_)) { - } + weakMailbox(std::move(weakMailbox_)) {} template void invoke(Fn fn, Args&&... args) const { @@ -43,11 +44,7 @@ class ActorRef { auto future = promise.get_future(); if (auto mailbox = weakMailbox.lock()) { - mailbox->push( - actor::makeMessage( - std::move(promise), *object, fn, std::forward(args)... - ) - ); + mailbox->push(actor::makeMessage(std::move(promise), *object, fn, std::forward(args)...)); } else { promise.set_exception(std::make_exception_ptr(std::runtime_error("Actor has gone away"))); } diff --git a/include/mbgl/actor/aspiring_actor.hpp b/include/mbgl/actor/aspiring_actor.hpp index 7d4910a2a43..777c83b9c51 100644 --- a/include/mbgl/actor/aspiring_actor.hpp +++ b/include/mbgl/actor/aspiring_actor.hpp @@ -18,41 +18,40 @@ template class Actor; /** - An `AspiringActor` is one half of the pair of types that comprise an actor (see `Actor`), - the other half being `EstablishedActor`. It is responsible for: + An `AspiringActor` is one half of the pair of types that comprise an + actor (see `Actor`), the other half being `EstablishedActor`. It is + responsible for: - ownership of the actor's `Mailbox` - allocating the memory for (but *not* constructing) the target object `O` - - Using these two pieces--the mailbox and a stable address for `O`--an `AspiringActor` can - accept messages for the target object, or provide `ActorRef`s that do so, before the object - has actually been constructed by the corresponding `EstablishedActor`. (Such messages are - queued in the mailbox until after the object is constructed.) - - This allows for an `AspiringActor` to be created and safely used by a thread other than the - one on which the target object will (eventually) live. + + Using these two pieces--the mailbox and a stable address for `O`--an + `AspiringActor` can accept messages for the target object, or provide + `ActorRef`s that do so, before the object has actually been constructed by + the corresponding `EstablishedActor`. (Such messages are queued in the + mailbox until after the object is constructed.) + + This allows for an `AspiringActor` to be created and safely used by a + thread other than the one on which the target object will (eventually) live. */ template class AspiringActor { public: - AspiringActor() : mailbox(std::make_shared()) { + AspiringActor() + : mailbox(std::make_shared()) { // mailbox starts closed because the `Object` hasn't yet been constructed assert(!mailbox->isOpen()); } - + AspiringActor(const AspiringActor&) = delete; - - ActorRef> self() { - return ActorRef>(object(), mailbox); - } - + + ActorRef> self() { return ActorRef>(object(), mailbox); } + private: std::shared_ptr mailbox; std::aligned_storage_t objectStorage; - - Object& object() { - return *reinterpret_cast(&objectStorage); - } - + + Object& object() { return *reinterpret_cast(&objectStorage); } + friend class EstablishedActor; friend class Actor; }; diff --git a/include/mbgl/actor/established_actor.hpp b/include/mbgl/actor/established_actor.hpp index 3e52f21e2f7..3a60033672f 100644 --- a/include/mbgl/actor/established_actor.hpp +++ b/include/mbgl/actor/established_actor.hpp @@ -13,64 +13,70 @@ namespace mbgl { /** - An `EstablishedActor` is one half of the pair of types that comprise an actor (see `Actor`), - the other half being `AspiringActor`. It is responsible for managing the lifetime of the - target object `O` and the open/closed state of the parent's `mailbox`. - - The `O` object's lifetime is contained by that of its owning `EstablishedActor`: the - `EstablishedActor` constructor executes the `O` constructor via "placement new", constructing - it at the address provided by the parent `AspiringActor`, and the `~EstablishedActor` destructor - similarly executes the `~O` destructor (after closing the mailbox). `EstablishedActor` should - therefore live entirely on the thread intended to own `O`. + An `EstablishedActor` is one half of the pair of types that comprise an + actor (see `Actor`), the other half being `AspiringActor`. It is + responsible for managing the lifetime of the target object `O` and the + open/closed state of the parent's `mailbox`. + + The `O` object's lifetime is contained by that of its owning + `EstablishedActor`: the `EstablishedActor` constructor executes the `O` + constructor via "placement new", constructing it at the address provided by + the parent `AspiringActor`, and the `~EstablishedActor` destructor similarly + executes the `~O` destructor (after closing the mailbox). `EstablishedActor` + should therefore live entirely on the thread intended to own `O`. */ template class EstablishedActor { public: // Construct the Object from a parameter pack `args` (i.e. `Object(args...)`) - template || - std::is_constructible_v, Args...> - > * = nullptr> - EstablishedActor(Scheduler& scheduler, AspiringActor& parent_, Args&& ... args) - : parent(parent_) { + template || + std::is_constructible_v, Args...>>* = nullptr> + EstablishedActor(Scheduler& scheduler, AspiringActor& parent_, Args&&... args) + : parent(parent_) { emplaceObject(std::forward(args)...); parent.mailbox->open(scheduler); } - - // Construct the `Object` from a tuple containing the constructor arguments (i.e. - // `Object(std::get<0>(args), std::get<1>(args), ...)`) + + // Construct the `Object` from a tuple containing the constructor arguments + // (i.e. `Object(std::get<0>(args), std::get<1>(args), ...)`) template >::value> EstablishedActor(Scheduler& scheduler, AspiringActor& parent_, ArgsTuple&& args) - : parent(parent_) { + : parent(parent_) { emplaceObject(std::forward(args), std::make_index_sequence{}); parent.mailbox->open(scheduler); } - + EstablishedActor(const EstablishedActor&) = delete; ~EstablishedActor() { parent.mailbox->close(); parent.object().~Object(); } - + private: // Enabled for Objects with a constructor taking ActorRef as the first parameter - template , Args...>> * = nullptr> + template , Args...>>* = nullptr> void emplaceObject(Args&&... args_) { new (&parent.objectStorage) Object(parent.self(), std::forward(args_)...); } // Enabled for plain Objects - template > * = nullptr> + template >* = nullptr> void emplaceObject(Args&&... args_) { new (&parent.objectStorage) Object(std::forward(args_)...); } - + // Used to expand a tuple holding the constructor arguments template void emplaceObject(ArgsTuple&& args, std::index_sequence) { emplaceObject(std::move(std::get(std::forward(args)))...); - (void) args; // mark args as used: if it's empty tuple, it's not actually used above. + (void)args; // mark args as used: if it's empty tuple, it's not actually used above. } AspiringActor& parent; diff --git a/include/mbgl/actor/mailbox.hpp b/include/mbgl/actor/mailbox.hpp index 37bdf2dca2c..782af736608 100644 --- a/include/mbgl/actor/mailbox.hpp +++ b/include/mbgl/actor/mailbox.hpp @@ -14,13 +14,12 @@ class Message; class Mailbox : public std::enable_shared_from_this { public: - /// Create a "holding" mailbox, messages to which will remain queued, /// unconsumed, until the mailbox is associated with a Scheduler using /// start(). This allows a Mailbox object to be created on one thread and /// later transferred to a different target thread that may not yet exist. Mailbox(); - + Mailbox(Scheduler&); /// Attach the given scheduler to this mailbox and begin processing messages @@ -43,7 +42,7 @@ class Mailbox : public std::enable_shared_from_this { std::recursive_mutex receivingMutex; std::mutex pushingMutex; - bool closed { false }; + bool closed{false}; std::mutex queueMutex; std::queue> queue; diff --git a/include/mbgl/actor/message.hpp b/include/mbgl/actor/message.hpp index 3167a9f252a..1ec011284d0 100644 --- a/include/mbgl/actor/message.hpp +++ b/include/mbgl/actor/message.hpp @@ -5,9 +5,9 @@ namespace mbgl { -// A movable type-erasing function wrapper. This allows to store arbitrary invokable -// things (like std::function<>, or the result of a movable-only std::bind()) in the queue. -// Source: http://stackoverflow.com/a/29642072/331379 +// A movable type-erasing function wrapper. This allows to store arbitrary +// invokable things (like std::function<>, or the result of a movable-only +// std::bind()) in the queue. Source: http://stackoverflow.com/a/29642072/331379 class Message { public: virtual ~Message() = default; @@ -18,14 +18,11 @@ template class MessageImpl : public Message { public: MessageImpl(Object& object_, MemberFn memberFn_, ArgsTuple argsTuple_) - : object(object_), - memberFn(memberFn_), - argsTuple(std::move(argsTuple_)) { - } + : object(object_), + memberFn(memberFn_), + argsTuple(std::move(argsTuple_)) {} - void operator()() override { - invoke(std::make_index_sequence>()); - } + void operator()() override { invoke(std::make_index_sequence>()); } template void invoke(std::index_sequence) { @@ -44,12 +41,9 @@ class AskMessageImpl : public Message { : object(object_), memberFn(memberFn_), argsTuple(std::move(argsTuple_)), - promise(std::move(promise_)) { - } + promise(std::move(promise_)) {} - void operator()() override { - promise.set_value(ask(std::make_index_sequence>())); - } + void operator()() override { promise.set_value(ask(std::make_index_sequence>())); } template ResultType ask(std::index_sequence) { @@ -66,11 +60,10 @@ template class AskMessageImpl : public Message { public: AskMessageImpl(std::promise promise_, Object& object_, MemberFn memberFn_, ArgsTuple argsTuple_) - : object(object_), - memberFn(memberFn_), - argsTuple(std::move(argsTuple_)), - promise(std::move(promise_)) { - } + : object(object_), + memberFn(memberFn_), + argsTuple(std::move(argsTuple_)), + promise(std::move(promise_)) {} void operator()() override { ask(std::make_index_sequence>()); @@ -97,9 +90,13 @@ std::unique_ptr makeMessage(Object& object, MemberFn memberFn, Args&&.. } template -std::unique_ptr makeMessage(std::promise&& promise, Object& object, MemberFn memberFn, Args&&... args) { +std::unique_ptr makeMessage(std::promise&& promise, + Object& object, + MemberFn memberFn, + Args&&... args) { auto tuple = std::make_tuple(std::forward(args)...); - return std::make_unique>(std::move(promise), object, memberFn, std::move(tuple)); + return std::make_unique>( + std::move(promise), object, memberFn, std::move(tuple)); } } // namespace actor diff --git a/include/mbgl/actor/scheduler.hpp b/include/mbgl/actor/scheduler.hpp index 4525613afea..8d4fa187d75 100644 --- a/include/mbgl/actor/scheduler.hpp +++ b/include/mbgl/actor/scheduler.hpp @@ -1,6 +1,5 @@ #pragma once - #include #include @@ -47,16 +46,16 @@ class Scheduler { /// the given closure to this scheduler, the consequent calls of the /// returned closure are ignored. /// - /// If this scheduler is already deleted by the time the returnded closure is - /// first invoked, the call is ignored. + /// If this scheduler is already deleted by the time the returnded closure + /// is first invoked, the call is ignored. std::function bindOnce(std::function); - /// Enqueues the given |task| for execution into this scheduler's task queue and - /// then enqueues the |reply| with the captured task result to the current - /// task queue. + /// Enqueues the given |task| for execution into this scheduler's task queue + /// and then enqueues the |reply| with the captured task result to the + /// current task queue. /// - /// The |TaskFn| return type must be compatible with the |ReplyFn| argument type. - /// Note: the task result is copied and passed by value. + /// The |TaskFn| return type must be compatible with the |ReplyFn| argument + /// type. Note: the task result is copied and passed by value. template void scheduleAndReplyValue(const TaskFn& task, const ReplyFn& reply) { assert(GetCurrent()); @@ -93,7 +92,9 @@ class Scheduler { auto scheduled = [replyScheduler = std::move(replyScheduler), task, reply] { auto lock = replyScheduler.lock(); if (!replyScheduler) return; - auto scheduledReply = [reply, result = task()] { reply(result); }; + auto scheduledReply = [reply, result = task()] { + reply(result); + }; replyScheduler->schedule(std::move(scheduledReply)); }; @@ -101,4 +102,4 @@ class Scheduler { } }; -} /// namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/annotation/annotation.hpp b/include/mbgl/annotation/annotation.hpp index 0d67e90d78e..9f8c25113c7 100644 --- a/include/mbgl/annotation/annotation.hpp +++ b/include/mbgl/annotation/annotation.hpp @@ -16,17 +16,16 @@ using AnnotationIDs = std::vector; class SymbolAnnotation { public: - SymbolAnnotation(Point geometry_, std::string icon_ = {}) : geometry(geometry_), icon(std::move(icon_)) {} + SymbolAnnotation(Point geometry_, std::string icon_ = {}) + : geometry(geometry_), + icon(std::move(icon_)) {} Point geometry; std::string icon; }; -using ShapeAnnotationGeometry = variant< - LineString, - Polygon, - MultiLineString, - MultiPolygon>; +using ShapeAnnotationGeometry = + variant, Polygon, MultiLineString, MultiPolygon>; class LineAnnotation { public: @@ -62,9 +61,6 @@ class FillAnnotation { style::PropertyValue outlineColor; }; -using Annotation = variant< - SymbolAnnotation, - LineAnnotation, - FillAnnotation>; +using Annotation = variant; } // namespace mbgl diff --git a/include/mbgl/gfx/backend.hpp b/include/mbgl/gfx/backend.hpp index ef6df989bb1..46d85d51919 100644 --- a/include/mbgl/gfx/backend.hpp +++ b/include/mbgl/gfx/backend.hpp @@ -11,9 +11,9 @@ class Backend { public: /// @brief The active graphics API/backend type. enum class Type : uint8_t { - OpenGL, ///< The OpenGL API backend - TYPE_MAX, ///< Not a valid backend type, used to determine the number - ///< of available backends (ie for array allocation). + OpenGL, ///< The OpenGL API backend + TYPE_MAX, ///< Not a valid backend type, used to determine the number + ///< of available backends (ie for array allocation). }; static constexpr Type DefaultType = Type::OpenGL; @@ -24,9 +24,7 @@ class Backend { } } - static Type GetType() { - return Value(DefaultType); - } + static Type GetType() { return Value(DefaultType); } template static std::unique_ptr Create(Args... args) { diff --git a/include/mbgl/gfx/backend_scope.hpp b/include/mbgl/gfx/backend_scope.hpp index cf8defe14eb..c3f25715aff 100644 --- a/include/mbgl/gfx/backend_scope.hpp +++ b/include/mbgl/gfx/backend_scope.hpp @@ -7,10 +7,11 @@ class RendererBackend; class BackendScope { public: - /// There are two types of scopes: Creating an "Implicit" scope tells Mapbox GL that the - /// supporting windowing system has already activated the GL Backend and that no further actions - /// are required. Creating an "Explicit" scope actually enables the GL Backend, and disables it - /// when the BackendScope is destroyed. + /// There are two types of scopes: Creating an "Implicit" scope tells Mapbox + /// GL that the supporting windowing system has already activated the GL + /// Backend and that no further actions are required. Creating an "Explicit" + /// scope actually enables the GL Backend, and disables it when the + /// BackendScope is destroyed. enum class ScopeType : bool { Implicit, Explicit, diff --git a/include/mbgl/gfx/renderable.hpp b/include/mbgl/gfx/renderable.hpp index 1aca5a789d2..0145614fdd5 100644 --- a/include/mbgl/gfx/renderable.hpp +++ b/include/mbgl/gfx/renderable.hpp @@ -21,14 +21,12 @@ class RenderableResource { class Renderable { protected: Renderable(const Size size_, std::unique_ptr resource_) - : size(size_), resource(std::move(resource_)) { - } + : size(size_), + resource(std::move(resource_)) {} virtual ~Renderable() = default; public: - Size getSize() const { - return size; - } + Size getSize() const { return size; } template T& getResource() const { diff --git a/include/mbgl/gfx/renderer_backend.hpp b/include/mbgl/gfx/renderer_backend.hpp index 5dc70338655..b6348360015 100644 --- a/include/mbgl/gfx/renderer_backend.hpp +++ b/include/mbgl/gfx/renderer_backend.hpp @@ -35,9 +35,7 @@ class RendererBackend { return static_cast(getContext()); } - bool contextIsShared() const { - return contextMode == ContextMode::Shared; - } + bool contextIsShared() const { return contextMode == ContextMode::Shared; } /// Returns a reference to the default surface that should be rendered on. virtual Renderable& getDefaultRenderable() = 0; @@ -45,13 +43,16 @@ class RendererBackend { protected: virtual std::unique_ptr createContext() = 0; - /// Called when the backend's GL context needs to be made active or inactive. These are called, - /// as a matched pair, exclusively through BackendScope, in two situations: + /// Called when the backend's GL context needs to be made active or + /// inactive. These are called, as a matched pair, exclusively through + /// BackendScope, in two situations: /// /// 1. When releasing GL resources during Renderer destruction - /// (Including calling CustomLayerHost::deinitialize during RenderCustomLayer destruction) + /// (Including calling CustomLayerHost::deinitialize during + /// RenderCustomLayer destruction) /// 2. When renderering through Renderer::render() - /// (Including calling CustomLayerHost::initialize for newly added custom layers and + /// (Including calling CustomLayerHost::initialize for newly added + /// custom layers and /// CustomLayerHost::deinitialize on layer removal) virtual void activate() = 0; virtual void deactivate() = 0; diff --git a/include/mbgl/gfx/shader.hpp b/include/mbgl/gfx/shader.hpp index 2cee56b7803..5241ab0341d 100644 --- a/include/mbgl/gfx/shader.hpp +++ b/include/mbgl/gfx/shader.hpp @@ -13,36 +13,30 @@ class Shader; // * Inherit gfx::Shader // * Declare a public, unique type name (string_view T::Name) // * Be a final class -template -inline constexpr bool is_shader_v = - std::is_base_of_v && - std::is_same_v< - std::remove_cv_t, - std::string_view> && - std::is_final_v; - +template +inline constexpr bool is_shader_v = std::is_base_of_v&& + std::is_same_v, std::string_view>&& std::is_final_v; /// @brief A shader is used as the base class for all programs across any supported /// backend API. Shaders are registered with a `gfx::ShaderRegistry` instance. class Shader { - public: - virtual ~Shader() = default; - - /// @brief Get the type name of this shader - /// @return Shader type name - virtual const std::string_view typeName() const noexcept = 0; - - /// @brief Downcast to a type - /// @tparam T Derived type - /// @return Type or nullptr if type info was not a match - template, bool>* = nullptr> - T* to() noexcept { - if (typeName() != T::Name) { - return nullptr; - } - return static_cast(this); +public: + virtual ~Shader() = default; + + /// @brief Get the type name of this shader + /// @return Shader type name + virtual const std::string_view typeName() const noexcept = 0; + + /// @brief Downcast to a type + /// @tparam T Derived type + /// @return Type or nullptr if type info was not a match + template , bool>* = nullptr> + T* to() noexcept { + if (typeName() != T::Name) { + return nullptr; } + return static_cast(this); + } }; } // namespace gfx diff --git a/include/mbgl/gfx/shader_registry.hpp b/include/mbgl/gfx/shader_registry.hpp index d57ece1db02..ec3716ceb6d 100644 --- a/include/mbgl/gfx/shader_registry.hpp +++ b/include/mbgl/gfx/shader_registry.hpp @@ -14,141 +14,128 @@ namespace gfx { /// Using the registry, shaders may be dynamically registered or replaced /// at runtime. class ShaderRegistry { - public: - explicit ShaderRegistry(); - ShaderRegistry(const ShaderRegistry&) = delete; - ShaderRegistry(ShaderRegistry&&) noexcept = delete; - ShaderRegistry& operator=(const ShaderRegistry&) = delete; - ShaderRegistry& operator=(ShaderRegistry&&) noexcept = delete; - virtual ~ShaderRegistry() = default; - - /// @brief Checks if a shader exists in the registry for the given name. - /// @param shaderName Name of shader - /// @return If a shader is found, true - [[nodiscard]] virtual bool isShader(const std::string& shaderName) - const noexcept; - - /// @brief Get a shader from the registry by name. - /// @param shaderName Name of shader - /// @return A `gfx::Shader` or `nullptr` if no shader is found with the - /// given name - [[nodiscard]] virtual const std::shared_ptr getShader( - const std::string& shaderName) const noexcept; - - /// @brief Replace a matching shader in the registry with the provided - /// instance. Shader type-names must match. - /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. - /// @return True if a match was found and the shader was replaced, false - /// otherwise. - [[nodiscard]] virtual bool replaceShader( - std::shared_ptr&& shader) noexcept; - - /// @brief Replace a matching shader in the registry with the provided - /// instance. Shader type-names must match. - /// This variant replaces by explicit name. - /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. - /// @param shaderName Unique name to register the shader under. - /// @return True if a match was found and the shader was replaced, false - /// otherwise. - [[nodiscard]] virtual bool replaceShader( - std::shared_ptr&& shader, const std::string& shaderName) noexcept; - - /// @brief Register a new shader with the registry. If a shader is present - /// in the registry with a conflicting name, registration will fail. - /// @param shader A `gfx::Shader` to register. The ShaderRegistry will - /// take ownership. - /// @return True if the shader was registered, false if another shader is - /// already present with a conflicting name. - [[nodiscard]] virtual bool registerShader( - std::shared_ptr&& shader) noexcept; - - /// @brief Register a new shader with the registry. If a shader is present - /// in the registry with a conflicting name, registration will fail. - /// This variant registers using an explicit name. - /// @param shader A `gfx::Shader` to register. The ShaderRegistry will - /// take ownership. - /// @param shaderName Unique name to register the shader under. - /// @return True if the shader was registered, false if another shader is - /// already present with a conflicting name. - [[nodiscard]] virtual bool registerShader( - std::shared_ptr&& shader, const std::string& shaderName) noexcept; - - /// @brief Shorthand helper to quickly get a derived type from the registry. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @param shaderName The registry name to look up - /// @return T or nullptr if not found in the registry - template, bool>* = nullptr> - std::shared_ptr get(const std::string& shaderName) noexcept { - auto shader = getShader(shaderName); - if (!shader || shader->typeName() != T::Name) { - return nullptr; - } - return std::static_pointer_cast(shader); +public: + explicit ShaderRegistry(); + ShaderRegistry(const ShaderRegistry&) = delete; + ShaderRegistry(ShaderRegistry&&) noexcept = delete; + ShaderRegistry& operator=(const ShaderRegistry&) = delete; + ShaderRegistry& operator=(ShaderRegistry&&) noexcept = delete; + virtual ~ShaderRegistry() = default; + + /// @brief Checks if a shader exists in the registry for the given name. + /// @param shaderName Name of shader + /// @return If a shader is found, true + [[nodiscard]] virtual bool isShader(const std::string& shaderName) const noexcept; + + /// @brief Get a shader from the registry by name. + /// @param shaderName Name of shader + /// @return A `gfx::Shader` or `nullptr` if no shader is found with the + /// given name + [[nodiscard]] virtual const std::shared_ptr getShader(const std::string& shaderName) const noexcept; + + /// @brief Replace a matching shader in the registry with the provided + /// instance. Shader type-names must match. + /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. + /// @return True if a match was found and the shader was replaced, false + /// otherwise. + [[nodiscard]] virtual bool replaceShader(std::shared_ptr&& shader) noexcept; + + /// @brief Replace a matching shader in the registry with the provided + /// instance. Shader type-names must match. + /// This variant replaces by explicit name. + /// @param shader A `gfx::Shader`. The ShaderRegistry will take ownership. + /// @param shaderName Unique name to register the shader under. + /// @return True if a match was found and the shader was replaced, false + /// otherwise. + [[nodiscard]] virtual bool replaceShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept; + + /// @brief Register a new shader with the registry. If a shader is present + /// in the registry with a conflicting name, registration will fail. + /// @param shader A `gfx::Shader` to register. The ShaderRegistry will + /// take ownership. + /// @return True if the shader was registered, false if another shader is + /// already present with a conflicting name. + [[nodiscard]] virtual bool registerShader(std::shared_ptr&& shader) noexcept; + + /// @brief Register a new shader with the registry. If a shader is present + /// in the registry with a conflicting name, registration will fail. + /// This variant registers using an explicit name. + /// @param shader A `gfx::Shader` to register. The ShaderRegistry will + /// take ownership. + /// @param shaderName Unique name to register the shader under. + /// @return True if the shader was registered, false if another shader is + /// already present with a conflicting name. + [[nodiscard]] virtual bool registerShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept; + + /// @brief Shorthand helper to quickly get a derived type from the registry. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @param shaderName The registry name to look up + /// @return T or nullptr if not found in the registry + template , bool>* = nullptr> + std::shared_ptr get(const std::string& shaderName) noexcept { + auto shader = getShader(shaderName); + if (!shader || shader->typeName() != T::Name) { + return nullptr; } + return std::static_pointer_cast(shader); + } - /// @brief Shorthand helper to quickly get a derived type from the registry. - /// This variant looks up shaders only by type name. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @return T or nullptr if not found in the registry - template, bool>* = nullptr> - std::shared_ptr get() noexcept { - auto shader = getShader(std::string(T::Name)); - if (!shader || shader->typeName() != T::Name) { - return nullptr; - } - return std::static_pointer_cast(shader); + /// @brief Shorthand helper to quickly get a derived type from the registry. + /// This variant looks up shaders only by type name. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @return T or nullptr if not found in the registry + template , bool>* = nullptr> + std::shared_ptr get() noexcept { + auto shader = getShader(std::string(T::Name)); + if (!shader || shader->typeName() != T::Name) { + return nullptr; } + return std::static_pointer_cast(shader); + } - /// @brief Ensure the destination 'to' is populated with the requested - /// shader. If already non-null, does nothing. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @param to Location to store the shader - /// @param shaderName The registry name to look up - /// @return True if 'to' has a valid program object, false otherwise. - template, bool>* = nullptr> - bool populate(std::shared_ptr& to, const std::string& shaderName) noexcept { - if (to) { - return true; - } - - auto shader = getShader(shaderName); - if (!shader || shader->typeName() != T::Name) { - return false; - } - to = std::static_pointer_cast(shader); + /// @brief Ensure the destination 'to' is populated with the requested + /// shader. If already non-null, does nothing. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @param to Location to store the shader + /// @param shaderName The registry name to look up + /// @return True if 'to' has a valid program object, false otherwise. + template , bool>* = nullptr> + bool populate(std::shared_ptr& to, const std::string& shaderName) noexcept { + if (to) { return true; } - /// @brief Ensure the destination 'to' is populated with the requested - /// shader. If already non-null, does nothing. This variant looks up - /// shaders only by type name. - /// @tparam T Derived type, inheriting `gfx::Shader` - /// @param to Location to store the shader - /// @return True if 'to' has a valid program object, false otherwise. - template, bool>* = nullptr> - bool populate(std::shared_ptr& to) noexcept { - if (to) { - return true; - } - - auto shader = getShader(std::string(T::Name)); - if (!shader || shader->typeName() != T::Name) { - return false; - } - to = std::static_pointer_cast(shader); + auto shader = getShader(shaderName); + if (!shader || shader->typeName() != T::Name) { + return false; + } + to = std::static_pointer_cast(shader); + return true; + } + + /// @brief Ensure the destination 'to' is populated with the requested + /// shader. If already non-null, does nothing. This variant looks up + /// shaders only by type name. + /// @tparam T Derived type, inheriting `gfx::Shader` + /// @param to Location to store the shader + /// @return True if 'to' has a valid program object, false otherwise. + template , bool>* = nullptr> + bool populate(std::shared_ptr& to) noexcept { + if (to) { return true; } - private: - std::unordered_map< - std::string, - std::shared_ptr - > programs; - mutable std::shared_mutex programLock; + auto shader = getShader(std::string(T::Name)); + if (!shader || shader->typeName() != T::Name) { + return false; + } + to = std::static_pointer_cast(shader); + return true; + } + +private: + std::unordered_map> programs; + mutable std::shared_mutex programLock; }; } // namespace gfx diff --git a/include/mbgl/gl/custom_layer.hpp b/include/mbgl/gl/custom_layer.hpp index ce12aa6181c..c957b6dc5d5 100644 --- a/include/mbgl/gl/custom_layer.hpp +++ b/include/mbgl/gl/custom_layer.hpp @@ -8,7 +8,8 @@ namespace mbgl { namespace style { /** - * Parameters that define the current camera position for a `CustomLayerHost::render()` function. + * Parameters that define the current camera position for a + * `CustomLayerHost::render()` function. */ struct CustomLayerRenderParameters { double width; @@ -26,21 +27,24 @@ class CustomLayerHost { public: virtual ~CustomLayerHost() = default; /** - * Initialize any GL state needed by the custom layer. This method is called once, from the - * main thread, at a point when the GL context is active but before rendering for the first - * time. + * Initialize any GL state needed by the custom layer. This method is called + * once, from the main thread, at a point when the GL context is active but + * before rendering for the first time. * - * Resources that are acquired in this method must be released in the `deinitialize` function. + * Resources that are acquired in this method must be released in the + * `deinitialize` function. */ virtual void initialize() = 0; /** - * Render the layer. This method is called once per frame. The implementation should not make - * any assumptions about the GL state (other than that the correct context is active). It may - * make changes to the state, and is not required to reset values such as the depth mask, stencil - * mask, and corresponding test flags to their original values. - * Make sure that you are drawing your fragments with a z value of 1 to take advantage of the - * opaque fragment culling in case there are opaque layers above your custom layer. + * Render the layer. This method is called once per frame. The + * implementation should not make any assumptions about the GL state (other + * than that the correct context is active). It may make changes to the + * state, and is not required to reset values such as the depth mask, + * stencil mask, and corresponding test flags to their original values. Make + * sure that you are drawing your fragments with a z value of 1 to take + * advantage of the opaque fragment culling in case there are opaque layers + * above your custom layer. */ virtual void render(const CustomLayerRenderParameters&) = 0; @@ -53,18 +57,19 @@ class CustomLayerHost { virtual void contextLost() = 0; /** - * Destroy any GL state needed by the custom layer, and deallocate context, if necessary. This - * method is called once, from the main thread, at a point when the GL context is active. + * Destroy any GL state needed by the custom layer, and deallocate context, + * if necessary. This method is called once, from the main thread, at a + * point when the GL context is active. * - * Note that it may be called even when the `initialize` function has not been called. + * Note that it may be called even when the `initialize` function has not + * been called. */ virtual void deinitialize() = 0; }; class CustomLayer final : public Layer { public: - CustomLayer(const std::string& id, - std::unique_ptr host); + CustomLayer(const std::string& id, std::unique_ptr host); CustomLayer(const CustomLayer&) = delete; ~CustomLayer() final; diff --git a/include/mbgl/gl/custom_layer_factory.hpp b/include/mbgl/gl/custom_layer_factory.hpp index 963a3dc2fd9..a4e44d0b100 100644 --- a/include/mbgl/gl/custom_layer_factory.hpp +++ b/include/mbgl/gl/custom_layer_factory.hpp @@ -10,7 +10,8 @@ namespace mbgl { class CustomLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/gl/renderable_resource.hpp b/include/mbgl/gl/renderable_resource.hpp index 9585269270c..d07e062e987 100644 --- a/include/mbgl/gl/renderable_resource.hpp +++ b/include/mbgl/gl/renderable_resource.hpp @@ -15,8 +15,8 @@ class RenderableResource : public gfx::RenderableResource { virtual void bind() = 0; virtual void swap() { - // Renderable resources that require a swap function to be called explicitly - // can override this method. + // Renderable resources that require a swap function to be called + // explicitly can override this method. } }; diff --git a/include/mbgl/gl/renderer_backend.hpp b/include/mbgl/gl/renderer_backend.hpp index 99191c9596e..3d781c0c560 100644 --- a/include/mbgl/gl/renderer_backend.hpp +++ b/include/mbgl/gl/renderer_backend.hpp @@ -22,17 +22,17 @@ class RendererBackend : public gfx::RendererBackend { protected: std::unique_ptr createContext() override; - /// Called with the name of an OpenGL extension that should be loaded. RendererBackend implementations - /// must call the API-specific version that obtains the function pointer for this function, - /// or a null pointer if unsupported/unavailable. + /// Called with the name of an OpenGL extension that should be loaded. + /// RendererBackend implementations must call the API-specific version that + /// obtains the function pointer for this function, or a null pointer if + /// unsupported/unavailable. virtual ProcAddress getExtensionFunctionPointer(const char*) = 0; /// Reads the color pixel data from the currently bound framebuffer. PremultipliedImage readFramebuffer(const Size&); /// A constant to signal that a framebuffer is bound, but with an unknown ID. - static constexpr const FramebufferID ImplicitFramebufferBinding = - std::numeric_limits::max(); + static constexpr const FramebufferID ImplicitFramebufferBinding = std::numeric_limits::max(); /// Tells the renderer that OpenGL state has already been set by the windowing toolkit. /// It sets the internal assumed state to the supplied values. @@ -44,8 +44,8 @@ class RendererBackend : public gfx::RendererBackend { bool implicitFramebufferBound(); public: - /// Triggers an OpenGL state update if the internal assumed state doesn't match the - /// supplied values. + /// Triggers an OpenGL state update if the internal assumed state doesn't + /// match the supplied values. void setFramebufferBinding(FramebufferID fbo); void setViewport(int32_t x, int32_t y, const Size&); void setScissorTest(bool); diff --git a/include/mbgl/i18n/collator.hpp b/include/mbgl/i18n/collator.hpp index b170347d6a9..e520d099afe 100644 --- a/include/mbgl/i18n/collator.hpp +++ b/include/mbgl/i18n/collator.hpp @@ -9,7 +9,9 @@ namespace platform { class Collator { public: - explicit Collator(bool caseSensitive, bool diacriticSensitive, const std::optional& locale = std::nullopt); + explicit Collator(bool caseSensitive, + bool diacriticSensitive, + const std::optional& locale = std::nullopt); int compare(const std::string& lhs, const std::string& rhs) const; std::string resolvedLocale() const; bool operator==(const Collator& other) const; diff --git a/include/mbgl/layermanager/background_layer_factory.hpp b/include/mbgl/layermanager/background_layer_factory.hpp index f2fa2f7a560..17528fcde86 100644 --- a/include/mbgl/layermanager/background_layer_factory.hpp +++ b/include/mbgl/layermanager/background_layer_factory.hpp @@ -7,7 +7,8 @@ namespace mbgl { class BackgroundLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/circle_layer_factory.hpp b/include/mbgl/layermanager/circle_layer_factory.hpp index aaf5fddfb6a..11b4a6086a8 100644 --- a/include/mbgl/layermanager/circle_layer_factory.hpp +++ b/include/mbgl/layermanager/circle_layer_factory.hpp @@ -7,7 +7,8 @@ namespace mbgl { class CircleLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; std::unique_ptr createLayout(const LayoutParameters& parameters, std::unique_ptr tileLayer, const std::vector>& group) noexcept final; diff --git a/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp b/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp index fbaa5c12544..4d65140c3a9 100644 --- a/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp +++ b/include/mbgl/layermanager/fill_extrusion_layer_factory.hpp @@ -7,8 +7,11 @@ namespace mbgl { class FillExtrusionLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayout(const LayoutParameters&, + std::unique_ptr, + const std::vector>&) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/fill_layer_factory.hpp b/include/mbgl/layermanager/fill_layer_factory.hpp index 09afb0dc3a1..594ccf1940b 100644 --- a/include/mbgl/layermanager/fill_layer_factory.hpp +++ b/include/mbgl/layermanager/fill_layer_factory.hpp @@ -7,8 +7,11 @@ namespace mbgl { class FillLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayout(const LayoutParameters&, + std::unique_ptr, + const std::vector>&) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/heatmap_layer_factory.hpp b/include/mbgl/layermanager/heatmap_layer_factory.hpp index 2d0e1a5a027..f20c061ab9a 100644 --- a/include/mbgl/layermanager/heatmap_layer_factory.hpp +++ b/include/mbgl/layermanager/heatmap_layer_factory.hpp @@ -7,8 +7,10 @@ namespace mbgl { class HeatmapLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; - std::unique_ptr createBucket(const BucketParameters&, const std::vector>&) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createBucket(const BucketParameters&, + const std::vector>&) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/hillshade_layer_factory.hpp b/include/mbgl/layermanager/hillshade_layer_factory.hpp index 25b4f6c2c40..48a8d871628 100644 --- a/include/mbgl/layermanager/hillshade_layer_factory.hpp +++ b/include/mbgl/layermanager/hillshade_layer_factory.hpp @@ -7,7 +7,8 @@ namespace mbgl { class HillshadeLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/layer_factory.hpp b/include/mbgl/layermanager/layer_factory.hpp index 23de124bd69..b581362730c 100644 --- a/include/mbgl/layermanager/layer_factory.hpp +++ b/include/mbgl/layermanager/layer_factory.hpp @@ -8,7 +8,7 @@ namespace mbgl { namespace style { class LayerProperties; -} // namespace style +} // namespace style class Bucket; class BucketParameters; class GeometryTileLayer; @@ -18,22 +18,27 @@ class RenderLayer; /** * @brief The LayerFactory abstract class - * - * This class is responsible for creation of the layer objects that belong to a concrete layer type. + * + * This class is responsible for creation of the layer objects that belong to a + * concrete layer type. */ class LayerFactory { public: virtual ~LayerFactory() = default; /// Returns the layer type data. virtual const style::LayerTypeInfo* getTypeInfo() const noexcept = 0; - /// Returns a new Layer instance on success call; returns `nullptr` otherwise. - virtual std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept = 0; + /// Returns a new Layer instance on success call; returns `nullptr` otherwise. + virtual std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept = 0; /// Returns a new RenderLayer instance. virtual std::unique_ptr createRenderLayer(Immutable) noexcept = 0; - /// Returns a new Bucket instance on success call; returns `nullptr` otherwise. - virtual std::unique_ptr createBucket(const BucketParameters&, const std::vector>&) noexcept; - /// Returns a new Layout instance on success call; returns `nullptr` otherwise. - virtual std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, const std::vector>&) noexcept; + /// Returns a new Bucket instance on success call; returns `nullptr` otherwise. + virtual std::unique_ptr createBucket(const BucketParameters&, + const std::vector>&) noexcept; + /// Returns a new Layout instance on success call; returns `nullptr` otherwise. + virtual std::unique_ptr createLayout(const LayoutParameters&, + std::unique_ptr, + const std::vector>&) noexcept; protected: std::optional getSource(const style::conversion::Convertible& value) const noexcept; diff --git a/include/mbgl/layermanager/layer_manager.hpp b/include/mbgl/layermanager/layer_manager.hpp index c6802dbb495..fb7b980312e 100644 --- a/include/mbgl/layermanager/layer_manager.hpp +++ b/include/mbgl/layermanager/layer_manager.hpp @@ -7,7 +7,7 @@ namespace mbgl { namespace style { class LayerProperties; -} // namespace style +} // namespace style class GeometryTileLayer; class LayerFactory; class RenderLayer; @@ -18,10 +18,10 @@ class LayoutParameters; /** * @brief A singleton class responsible for creating layer instances. - * + * * The LayerManager has implementation per platform. The LayerManager implementation * defines what layer types are available and it can also disable annotations. - * + * * Linker excludes the unreachable code for the disabled annotations and layers * from the binaries, significantly reducing their size. */ @@ -29,34 +29,40 @@ class LayerManager { public: /** * @brief A singleton getter. - * - * @return LayerManager* + * + * @return LayerManager* */ static LayerManager* get() noexcept; /// Returns a new Layer instance on success call; returns `nullptr` otherwise. - std::unique_ptr createLayer(const std::string& type, const std::string& id, - const style::conversion::Convertible& value, style::conversion::Error& error) noexcept; + std::unique_ptr createLayer(const std::string& type, + const std::string& id, + const style::conversion::Convertible& value, + style::conversion::Error& error) noexcept; /// Returns a new RenderLayer instance on success call; returns `nullptr` otherwise. std::unique_ptr createRenderLayer(Immutable) noexcept; /// Returns a new Bucket instance on success call; returns `nullptr` otherwise. - std::unique_ptr createBucket(const BucketParameters&, const std::vector>&) noexcept; - /// Returns a new Layout instance on success call; returns `nullptr` otherwise. - std::unique_ptr createLayout(const LayoutParameters&, std::unique_ptr, + std::unique_ptr createBucket(const BucketParameters&, + const std::vector>&) noexcept; + /// Returns a new Layout instance on success call; returns `nullptr` otherwise. + std::unique_ptr createLayout(const LayoutParameters&, + std::unique_ptr, const std::vector>&) noexcept; /** - * @brief a build-time flag to enable/disable annotations in mapbox-gl-native core. - * - * At the moment, the annotations implementation in core is creating concrete - * layer instances apart from LayerManager/LayerFactory code path. - * + * @brief a build-time flag to enable/disable annotations in + * mapbox-gl-native core. + * + * At the moment, the annotations implementation in core is creating + * concrete layer instances apart from LayerManager/LayerFactory code path. + * * So, annotations must be disabled if the LayerManager implementation does - * not provide line, fill or symbol layers (those, used by the annotations + * not provide line, fill or symbol layers (those, used by the annotations * implementation). - * - * Note: in future, annotations implemantation will be moved from the core to platform - * SDK (see https://github.com/mapbox/mapbox-plugins-android/tree/master/plugin-annotation) + * + * Note: in future, annotations implemantation will be moved from the core + * to platform SDK (see + * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugin-annotation) * and this flag won't be needed any more. */ static const bool annotationsEnabled; diff --git a/include/mbgl/layermanager/line_layer_factory.hpp b/include/mbgl/layermanager/line_layer_factory.hpp index 803f550e57b..3daae41bcfc 100644 --- a/include/mbgl/layermanager/line_layer_factory.hpp +++ b/include/mbgl/layermanager/line_layer_factory.hpp @@ -7,7 +7,8 @@ namespace mbgl { class LineLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; std::unique_ptr createLayout(const LayoutParameters& parameters, std::unique_ptr tileLayer, const std::vector>& group) noexcept final; diff --git a/include/mbgl/layermanager/raster_layer_factory.hpp b/include/mbgl/layermanager/raster_layer_factory.hpp index d82137ee81f..d935c1373d7 100644 --- a/include/mbgl/layermanager/raster_layer_factory.hpp +++ b/include/mbgl/layermanager/raster_layer_factory.hpp @@ -7,7 +7,8 @@ namespace mbgl { class RasterLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; std::unique_ptr createRenderLayer(Immutable) noexcept final; }; diff --git a/include/mbgl/layermanager/symbol_layer_factory.hpp b/include/mbgl/layermanager/symbol_layer_factory.hpp index 38f382e96c5..8aacca77105 100644 --- a/include/mbgl/layermanager/symbol_layer_factory.hpp +++ b/include/mbgl/layermanager/symbol_layer_factory.hpp @@ -7,7 +7,8 @@ namespace mbgl { class SymbolLayerFactory : public LayerFactory { protected: const style::LayerTypeInfo* getTypeInfo() const noexcept final; - std::unique_ptr createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final; + std::unique_ptr createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept final; std::unique_ptr createLayout(const LayoutParameters& parameters, std::unique_ptr tileLayer, const std::vector>& group) noexcept final; diff --git a/include/mbgl/map/bound_options.hpp b/include/mbgl/map/bound_options.hpp index 27cba371ac7..5901a252cfa 100644 --- a/include/mbgl/map/bound_options.hpp +++ b/include/mbgl/map/bound_options.hpp @@ -12,11 +12,20 @@ namespace mbgl { */ struct BoundOptions { /// Sets the latitude and longitude bounds to which the camera center are constrained - BoundOptions& withLatLngBounds(LatLngBounds b) { bounds = b; return *this; } + BoundOptions& withLatLngBounds(LatLngBounds b) { + bounds = b; + return *this; + } /// Sets the minimum zoom level - BoundOptions& withMinZoom(double z) { minZoom = z; return *this; } + BoundOptions& withMinZoom(double z) { + minZoom = z; + return *this; + } /// Sets the maximum zoom level - BoundOptions& withMaxZoom(double z) { maxZoom = z; return *this; } + BoundOptions& withMaxZoom(double z) { + maxZoom = z; + return *this; + } /// Sets the minimum pitch BoundOptions& withMinPitch(double p) { minPitch = p; @@ -44,4 +53,4 @@ struct BoundOptions { std::optional minPitch; }; -} // namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/map/camera.hpp b/include/mbgl/map/camera.hpp index 52f08bb2b12..efdd23309c2 100644 --- a/include/mbgl/map/camera.hpp +++ b/include/mbgl/map/camera.hpp @@ -17,12 +17,30 @@ namespace mbgl { center point when both are set. */ struct CameraOptions { - CameraOptions& withCenter(const std::optional& o) { center = o; return *this; } - CameraOptions& withPadding(const std::optional& p) { padding = p; return *this; } - CameraOptions& withAnchor(const std::optional& o) { anchor = o; return *this; } - CameraOptions& withZoom(const std::optional& o) { zoom = o; return *this; } - CameraOptions& withBearing(const std::optional& o) { bearing = o; return *this; } - CameraOptions& withPitch(const std::optional& o) { pitch = o; return *this; } + CameraOptions& withCenter(const std::optional& o) { + center = o; + return *this; + } + CameraOptions& withPadding(const std::optional& p) { + padding = p; + return *this; + } + CameraOptions& withAnchor(const std::optional& o) { + anchor = o; + return *this; + } + CameraOptions& withZoom(const std::optional& o) { + zoom = o; + return *this; + } + CameraOptions& withBearing(const std::optional& o) { + bearing = o; + return *this; + } + CameraOptions& withPitch(const std::optional& o) { + pitch = o; + return *this; + } /** Coordinate at the center of the map. */ std::optional center; @@ -48,12 +66,8 @@ struct CameraOptions { }; constexpr bool operator==(const CameraOptions& a, const CameraOptions& b) { - return a.center == b.center - && a.padding == b.padding - && a.anchor == b.anchor - && a.zoom == b.zoom - && a.bearing == b.bearing - && a.pitch == b.pitch; + return a.center == b.center && a.padding == b.padding && a.anchor == b.anchor && a.zoom == b.zoom && + a.bearing == b.bearing && a.pitch == b.pitch; } constexpr bool operator!=(const CameraOptions& a, const CameraOptions& b) { @@ -98,24 +112,26 @@ struct AnimationOptions { : duration(d) {} }; -/** Various options for accessing physical properties of the underlying camera entity. - A direct access to these properties allows more flexible and precise controlling of the camera - while also being fully compatible and interchangeable with CameraOptions. All fields are optional. */ +/** Various options for accessing physical properties of the underlying camera + entity. A direct access to these properties allows more flexible and precise + controlling of the camera while also being fully compatible and + interchangeable with CameraOptions. All fields are optional. */ struct FreeCameraOptions { /** Position of the camera in slightly modified web mercator coordinates - - The size of 1 unit is the width of the projected world instead of the "mercator meter". - Coordinate [0, 0, 0] is the north-west corner and [1, 1, 0] is the south-east corner. - - Z coordinate is conformal and must respect minimum and maximum zoom values. + - The size of 1 unit is the width of the projected world instead of the + "mercator meter". Coordinate [0, 0, 0] is the north-west corner and [1, + 1, 0] is the south-east corner. + - Z coordinate is conformal and must respect minimum and maximum zoom + values. - Zoom is automatically computed from the altitude (z) */ std::optional position = std::nullopt; /** Orientation of the camera represented as a unit quaternion [x, y, z, w]. - The default pose of the camera is such that the forward vector is looking up the -Z axis and - the up vector is aligned with north orientation of the map: - forward: [0, 0, -1] - up: [0, -1, 0] - right [1, 0, 0] + The default pose of the camera is such that the forward vector is + looking up the -Z axis and the up vector is aligned with north + orientation of the map: forward: [0, 0, -1] up: [0, -1, 0] right [1, + 0, 0] Orientation can be set freely but certain constraints still apply - Orientation must be representable with only pitch and bearing. @@ -125,17 +141,18 @@ struct FreeCameraOptions { /** Helper function for setting the mercator position as Lat&Lng and altitude in meters */ void setLocation(const LatLngAltitude& location); - /** Helper function for converting mercator position into Lat&Lng and altitude in meters. - This function fails to return a value if `position` is invalid or is not set */ + /** Helper function for converting mercator position into Lat&Lng and + altitude in meters. This function fails to return a value if `position` + is invalid or is not set */ std::optional getLocation() const; - /** Helper function for setting orientation of the camera by defining a focus point - on the map. Up vector is required in certain scenarios where bearing can't be deduced - from the viewing direction */ + /** Helper function for setting orientation of the camera by defining a + focus point on the map. Up vector is required in certain scenarios where + bearing can't be deduced from the viewing direction */ void lookAtPoint(const LatLng& location, const std::optional& upVector = std::nullopt); - /** Helper function for setting the orientation of the camera as a pitch and a bearing. - Both values are in degrees */ + /** Helper function for setting the orientation of the camera as a pitch and + a bearing. Both values are in degrees */ void setPitchBearing(double pitch, double bearing); }; diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp index 2363156378f..914560c9203 100644 --- a/include/mbgl/map/map.hpp +++ b/include/mbgl/map/map.hpp @@ -40,16 +40,16 @@ class Map : private util::noncopyable { const ClientOptions& = ClientOptions()); ~Map(); - /// Register a callback that will get called (on the render thread) when all resources have - /// been loaded and a complete render occurs. - using StillImageCallback = std::function; + /// Register a callback that will get called (on the render thread) when all + /// resources have been loaded and a complete render occurs. + using StillImageCallback = std::function; void renderStill(StillImageCallback); void renderStill(const CameraOptions&, MapDebugOptions, StillImageCallback); /// Triggers a repaint. void triggerRepaint(); - style::Style& getStyle(); + style::Style& getStyle(); const style::Style& getStyle() const; void setStyle(std::unique_ptr); @@ -103,7 +103,7 @@ class Map : private util::noncopyable { void setSize(Size); MapOptions getMapOptions() const; - //Projection Mode + // Projection Mode void setProjectionMode(const ProjectionMode&); ProjectionMode getProjectionMode() const; @@ -127,10 +127,11 @@ class Map : private util::noncopyable { // Tile prefetching // - /// When loading a map, if `PrefetchZoomDelta` is set to any number greater than 0, the map will - /// first request a tile for `zoom - delta` in a attempt to display a full map at lower - /// resolution as quick as possible. It will get clamped at the tile source minimum zoom. The - /// default `delta` is 4. + /// When loading a map, if `PrefetchZoomDelta` is set to any number greater + /// than 0, the map will first request a tile for `zoom - delta` in a + /// attempt to display a full map at lower resolution as quick as possible. + /// It will get clamped at the tile source minimum zoom. The default `delta` + /// is 4. void setPrefetchZoomDelta(uint8_t delta); uint8_t getPrefetchZoomDelta() const; @@ -141,11 +142,13 @@ class Map : private util::noncopyable { bool isFullyLoaded() const; void dumpDebugLogs() const; - /// FreeCameraOptions provides more direct access to the underlying camera entity. - /// For backwards compatibility the state set using this API must be representable with - /// `CameraOptions` as well. Parameters are clamped to a valid range or discarded as invalid - /// if the conversion to the pitch and bearing presentation is ambiguous. For example orientation - /// can be invalid if it leads to the camera being upside down or the quaternion has zero length. + /// FreeCameraOptions provides more direct access to the underlying camera + /// entity. For backwards compatibility the state set using this API must be + /// representable with `CameraOptions` as well. Parameters are clamped to a + /// valid range or discarded as invalid if the conversion to the pitch and + /// bearing presentation is ambiguous. For example orientation can be + /// invalid if it leads to the camera being upside down or the quaternion + /// has zero length. void setFreeCameraOptions(const FreeCameraOptions& camera); FreeCameraOptions getFreeCameraOptions() const; diff --git a/include/mbgl/map/map_observer.hpp b/include/mbgl/map/map_observer.hpp index 7a400bc749b..675b86c0562 100644 --- a/include/mbgl/map/map_observer.hpp +++ b/include/mbgl/map/map_observer.hpp @@ -63,7 +63,7 @@ class MapObserver { virtual bool onCanRemoveUnusedStyleImage(const std::string&) { return true; } // Observe this event to easily mutate or observe shaders as soon // as the registry becomes available. - virtual void onRegisterShaders(gfx::ShaderRegistry&) {}; + virtual void onRegisterShaders(gfx::ShaderRegistry&){}; }; } // namespace mbgl diff --git a/include/mbgl/map/map_options.hpp b/include/mbgl/map/map_options.hpp index eb5e43a7f3c..12a6b874f9e 100644 --- a/include/mbgl/map/map_options.hpp +++ b/include/mbgl/map/map_options.hpp @@ -138,4 +138,4 @@ class MapOptions final { std::unique_ptr impl_; }; -} // namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/map/mode.hpp b/include/mbgl/map/mode.hpp index a04ad589b80..b16026bd119 100644 --- a/include/mbgl/map/mode.hpp +++ b/include/mbgl/map/mode.hpp @@ -15,8 +15,8 @@ using EnumType = uint32_t; enum class MapMode : EnumType { Continuous, ///< continually updating map - Static, ///< a once-off still image of an arbitrary viewport - Tile ///< a once-off still image of a single tile + Static, ///< a once-off still image of an arbitrary viewport + Tile ///< a once-off still image of a single tile }; /// We can choose to constrain the map both horizontally or vertically, or only @@ -35,12 +35,12 @@ enum class ViewportMode : EnumType { }; enum class MapDebugOptions : EnumType { - NoDebug = 0, + NoDebug = 0, TileBorders = 1 << 1, ParseStatus = 1 << 2, - Timestamps = 1 << 3, - Collision = 1 << 4, - Overdraw = 1 << 5, + Timestamps = 1 << 3, + Collision = 1 << 4, + Overdraw = 1 << 5, StencilClip = 1 << 6, DepthBuffer = 1 << 7, }; diff --git a/include/mbgl/map/projection_mode.hpp b/include/mbgl/map/projection_mode.hpp index ed04fd82d0d..7809605a3ce 100644 --- a/include/mbgl/map/projection_mode.hpp +++ b/include/mbgl/map/projection_mode.hpp @@ -10,9 +10,18 @@ namespace mbgl { * optional. */ struct ProjectionMode { - ProjectionMode& withAxonometric(bool o) { axonometric = o; return *this; } - ProjectionMode& withXSkew(double o) { xSkew = o; return *this; } - ProjectionMode& withYSkew(double o) { ySkew = o; return *this; } + ProjectionMode& withAxonometric(bool o) { + axonometric = o; + return *this; + } + ProjectionMode& withXSkew(double o) { + xSkew = o; + return *this; + } + ProjectionMode& withYSkew(double o) { + ySkew = o; + return *this; + } /** * @brief Set to True to enable axonometric rendering, false otherwise. @@ -30,4 +39,4 @@ struct ProjectionMode { std::optional ySkew; }; -} // namespace mbgl +} // namespace mbgl diff --git a/include/mbgl/math/log2.hpp b/include/mbgl/math/log2.hpp index 694cbdf337d..9bedfc8961d 100644 --- a/include/mbgl/math/log2.hpp +++ b/include/mbgl/math/log2.hpp @@ -30,8 +30,7 @@ T log2(T x) { } // namespace mbgl // log2 is not available on Android before API 18. -#if defined(__ANDROID__) && defined(__GNUC__) && \ - defined(__ANDROID_API__) && __ANDROID_API__ < 18 +#if defined(__ANDROID__) && defined(__GNUC__) && defined(__ANDROID_API__) && __ANDROID_API__ < 18 template typename std::enable_if_t, T> log2(T x) { diff --git a/include/mbgl/platform/gl_functions.hpp b/include/mbgl/platform/gl_functions.hpp index 00a84818d94..ab1766b04a2 100644 --- a/include/mbgl/platform/gl_functions.hpp +++ b/include/mbgl/platform/gl_functions.hpp @@ -7,7 +7,13 @@ // initialized by the platform at linking time. #ifndef NDEBUG -#define MBGL_CHECK_ERROR(cmd) ([&]() { struct __MBGL_CHECK_ERROR { ~__MBGL_CHECK_ERROR() noexcept(false) { mbgl::platform::glCheckError(#cmd, __FILE__, __LINE__); } } __MBGL_CHECK_ERROR; return cmd; }()) +#define MBGL_CHECK_ERROR(cmd) \ + ([&]() { \ + struct __MBGL_CHECK_ERROR { \ + ~__MBGL_CHECK_ERROR() noexcept(false) { mbgl::platform::glCheckError(#cmd, __FILE__, __LINE__); } \ + } __MBGL_CHECK_ERROR; \ + return cmd; \ + }()) #else #define MBGL_CHECK_ERROR(cmd) (cmd) #endif @@ -30,7 +36,7 @@ using GLuint = unsigned int; using GLvoid = void; using GLint64 = int64_t; using GLuint64 = uint64_t; -using GLsync = ::__GLsync *; +using GLsync = ::__GLsync*; #if defined(_WIN32) using GLintptr = long long; @@ -43,505 +49,510 @@ using GLsizeiptr = long; /* OpenGL ES 2.0 */ /// Pointer to glActiveTexture OpenGL function. -extern void (* const glActiveTexture)(GLenum); +extern void (*const glActiveTexture)(GLenum); /// Pointer to glAttachShader OpenGL function. -extern void (* const glAttachShader)(GLuint, GLuint); +extern void (*const glAttachShader)(GLuint, GLuint); /// Pointer to glBindAttribLocation OpenGL function. -extern void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *); +extern void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*); /// Pointer to glBindBuffer OpenGL function. -extern void (* const glBindBuffer)(GLenum, GLuint); +extern void (*const glBindBuffer)(GLenum, GLuint); /// Pointer to glBindFramebuffer OpenGL function. -extern void (* const glBindFramebuffer)(GLenum, GLuint); +extern void (*const glBindFramebuffer)(GLenum, GLuint); /// Pointer to glBindRenderbuffer OpenGL function. -extern void (* const glBindRenderbuffer)(GLenum, GLuint); +extern void (*const glBindRenderbuffer)(GLenum, GLuint); /// Pointer to glBindTexture OpenGL function. -extern void (* const glBindTexture)(GLenum, GLuint); +extern void (*const glBindTexture)(GLenum, GLuint); /// Pointer to glBlendColor OpenGL function. -extern void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glBlendEquation OpenGL function. -extern void (* const glBlendEquation)(GLenum); +extern void (*const glBlendEquation)(GLenum); /// Pointer to glBlendEquationSeparate OpenGL function. -extern void (* const glBlendEquationSeparate)(GLenum, GLenum); +extern void (*const glBlendEquationSeparate)(GLenum, GLenum); /// Pointer to glBlendFunc OpenGL function. -extern void (* const glBlendFunc)(GLenum, GLenum); +extern void (*const glBlendFunc)(GLenum, GLenum); /// Pointer to glBlendFuncSeparate OpenGL function. -extern void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum); +extern void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum); /// Pointer to glBufferData OpenGL function. -extern void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum); +extern void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum); /// Pointer to glBufferSubData OpenGL function. -extern void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *); +extern void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*); /// Pointer to glCheckFramebufferStatus OpenGL function. -extern GLenum (* const glCheckFramebufferStatus)(GLenum); +extern GLenum (*const glCheckFramebufferStatus)(GLenum); /// Pointer to glClear OpenGL function. -extern void (* const glClear)(GLbitfield); +extern void (*const glClear)(GLbitfield); /// Pointer to glClearColor OpenGL function. -extern void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glClearDepthf OpenGL function. -extern void (* const glClearDepthf)(GLfloat); +extern void (*const glClearDepthf)(GLfloat); /// Pointer to glClearStencil OpenGL function. -extern void (* const glClearStencil)(GLint); +extern void (*const glClearStencil)(GLint); /// Pointer to glColorMask OpenGL function. -extern void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean); +extern void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean); /// Pointer to glCompileShader OpenGL function. -extern void (* const glCompileShader)(GLuint); +extern void (*const glCompileShader)(GLuint); /// Pointer to glCompressedTexImage2D OpenGL function. -extern void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *); +extern void (*const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*); /// Pointer to glCompressedTexSubImage2D OpenGL function. -extern void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *); +extern void (*const glCompressedTexSubImage2D)( + GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*); /// Pointer to glCopyTexImage2D OpenGL function. -extern void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint); +extern void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint); /// Pointer to glCopyTexSubImage2D OpenGL function. -extern void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +extern void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); /// Pointer to glCreateProgram OpenGL function. -extern GLuint (* const glCreateProgram)(); +extern GLuint (*const glCreateProgram)(); /// Pointer to glCreateShader OpenGL function. -extern GLuint (* const glCreateShader)(GLenum); +extern GLuint (*const glCreateShader)(GLenum); /// Pointer to glCullFace OpenGL function. -extern void (* const glCullFace)(GLenum); +extern void (*const glCullFace)(GLenum); /// Pointer to glDeleteBuffers OpenGL function. -extern void (* const glDeleteBuffers)(GLsizei, const GLuint *); +extern void (*const glDeleteBuffers)(GLsizei, const GLuint*); /// Pointer to glDeleteFramebuffers OpenGL function. -extern void (* const glDeleteFramebuffers)(GLsizei, const GLuint *); +extern void (*const glDeleteFramebuffers)(GLsizei, const GLuint*); /// Pointer to glDeleteProgram OpenGL function. -extern void (* const glDeleteProgram)(GLuint); +extern void (*const glDeleteProgram)(GLuint); /// Pointer to glDeleteRenderbuffers OpenGL function. -extern void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *); +extern void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*); /// Pointer to glDeleteShader OpenGL function. -extern void (* const glDeleteShader)(GLuint); +extern void (*const glDeleteShader)(GLuint); /// Pointer to glDeleteTextures OpenGL function. -extern void (* const glDeleteTextures)(GLsizei, const GLuint *); +extern void (*const glDeleteTextures)(GLsizei, const GLuint*); /// Pointer to glDepthFunc OpenGL function. -extern void (* const glDepthFunc)(GLenum); +extern void (*const glDepthFunc)(GLenum); /// Pointer to glDepthMask OpenGL function. -extern void (* const glDepthMask)(GLboolean); +extern void (*const glDepthMask)(GLboolean); /// Pointer to glDepthRangef OpenGL function. -extern void (* const glDepthRangef)(GLfloat, GLfloat); +extern void (*const glDepthRangef)(GLfloat, GLfloat); /// Pointer to glDetachShader OpenGL function. -extern void (* const glDetachShader)(GLuint, GLuint); +extern void (*const glDetachShader)(GLuint, GLuint); /// Pointer to glDisable OpenGL function. -extern void (* const glDisable)(GLenum); +extern void (*const glDisable)(GLenum); /// Pointer to glDisableVertexAttribArray OpenGL function. -extern void (* const glDisableVertexAttribArray)(GLuint); +extern void (*const glDisableVertexAttribArray)(GLuint); /// Pointer to glDrawArrays OpenGL function. -extern void (* const glDrawArrays)(GLenum, GLint, GLsizei); +extern void (*const glDrawArrays)(GLenum, GLint, GLsizei); /// Pointer to glDrawElements OpenGL function. -extern void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *); +extern void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*); /// Pointer to glEnable OpenGL function. -extern void (* const glEnable)(GLenum); +extern void (*const glEnable)(GLenum); /// Pointer to glEnableVertexAttribArray OpenGL function. -extern void (* const glEnableVertexAttribArray)(GLuint); +extern void (*const glEnableVertexAttribArray)(GLuint); /// Pointer to glFinish OpenGL function. -extern void (* const glFinish)(); +extern void (*const glFinish)(); /// Pointer to glFlush OpenGL function. -extern void (* const glFlush)(); +extern void (*const glFlush)(); /// Pointer to glFramebufferRenderbuffer OpenGL function. -extern void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint); +extern void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint); /// Pointer to glFramebufferTexture2D OpenGL function. -extern void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint); +extern void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint); /// Pointer to glFrontFace OpenGL function. -extern void (* const glFrontFace)(GLenum); +extern void (*const glFrontFace)(GLenum); /// Pointer to glGenBuffers OpenGL function. -extern void (* const glGenBuffers)(GLsizei, GLuint *); +extern void (*const glGenBuffers)(GLsizei, GLuint*); /// Pointer to glGenerateMipmap OpenGL function. -extern void (* const glGenerateMipmap)(GLenum); +extern void (*const glGenerateMipmap)(GLenum); /// Pointer to glGenFramebuffers OpenGL function. -extern void (* const glGenFramebuffers)(GLsizei, GLuint *); +extern void (*const glGenFramebuffers)(GLsizei, GLuint*); /// Pointer to glGenRenderbuffers OpenGL function. -extern void (* const glGenRenderbuffers)(GLsizei, GLuint *); +extern void (*const glGenRenderbuffers)(GLsizei, GLuint*); /// Pointer to glGenTextures OpenGL function. -extern void (* const glGenTextures)(GLsizei, GLuint *); +extern void (*const glGenTextures)(GLsizei, GLuint*); /// Pointer to glGetActiveAttrib OpenGL function. -extern void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); +extern void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*); /// Pointer to glGetActiveUniform OpenGL function. -extern void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); +extern void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*); /// Pointer to glGetAttachedShaders OpenGL function. -extern void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *); +extern void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*); /// Pointer to glGetAttribLocation OpenGL function. -extern GLint (* const glGetAttribLocation)(GLuint, const GLchar *); +extern GLint (*const glGetAttribLocation)(GLuint, const GLchar*); /// Pointer to glGetBooleanv OpenGL function. -extern void (* const glGetBooleanv)(GLenum, GLboolean *); +extern void (*const glGetBooleanv)(GLenum, GLboolean*); /// Pointer to glGetBufferParameteriv OpenGL function. -extern void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *); +extern void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*); /// Pointer to glGetError OpenGL function. -extern GLenum (* const glGetError)(); +extern GLenum (*const glGetError)(); /// Pointer to glGetFloatv OpenGL function. -extern void (* const glGetFloatv)(GLenum, GLfloat *); +extern void (*const glGetFloatv)(GLenum, GLfloat*); /// Pointer to glGetFramebufferAttachmentParameteriv OpenGL function. -extern void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *); +extern void (*const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint*); /// Pointer to glGetIntegerv OpenGL function. -extern void (* const glGetIntegerv)(GLenum, GLint *); +extern void (*const glGetIntegerv)(GLenum, GLint*); /// Pointer to glGetProgramInfoLog OpenGL function. -extern void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glGetProgramiv OpenGL function. -extern void (* const glGetProgramiv)(GLuint, GLenum, GLint *); +extern void (*const glGetProgramiv)(GLuint, GLenum, GLint*); /// Pointer to glGetRenderbufferParameteriv OpenGL function. -extern void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *); +extern void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*); /// Pointer to glGetShaderInfoLog OpenGL function. -extern void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glGetShaderiv OpenGL function. -extern void (* const glGetShaderiv)(GLuint, GLenum, GLint *); +extern void (*const glGetShaderiv)(GLuint, GLenum, GLint*); /// Pointer to glGetShaderPrecisionFormat OpenGL function. -extern void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *); +extern void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*); /// Pointer to glGetShaderSource OpenGL function. -extern void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glGetString OpenGL function. -extern const GLubyte *(* const glGetString)(GLenum); +extern const GLubyte* (*const glGetString)(GLenum); /// Pointer to glGetTexParameterfv OpenGL function. -extern void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *); +extern void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*); /// Pointer to glGetTexParameteriv OpenGL function. -extern void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *); +extern void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*); /// Pointer to glGetUniformfv OpenGL function. -extern void (* const glGetUniformfv)(GLuint, GLint, GLfloat *); +extern void (*const glGetUniformfv)(GLuint, GLint, GLfloat*); /// Pointer to glGetUniformiv OpenGL function. -extern void (* const glGetUniformiv)(GLuint, GLint, GLint *); +extern void (*const glGetUniformiv)(GLuint, GLint, GLint*); /// Pointer to glGetUniformLocation OpenGL function. -extern GLint (* const glGetUniformLocation)(GLuint, const GLchar *); +extern GLint (*const glGetUniformLocation)(GLuint, const GLchar*); /// Pointer to glGetVertexAttribfv OpenGL function. -extern void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *); +extern void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*); /// Pointer to glGetVertexAttribiv OpenGL function. -extern void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *); +extern void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*); /// Pointer to glGetVertexAttribPointerv OpenGL function. -extern void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **); +extern void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**); /// Pointer to glHint OpenGL function. -extern void (* const glHint)(GLenum, GLenum); +extern void (*const glHint)(GLenum, GLenum); /// Pointer to glIsBuffer OpenGL function. -extern GLboolean (* const glIsBuffer)(GLuint); +extern GLboolean (*const glIsBuffer)(GLuint); /// Pointer to glIsEnabled OpenGL function. -extern GLboolean (* const glIsEnabled)(GLenum); +extern GLboolean (*const glIsEnabled)(GLenum); /// Pointer to glIsFramebuffer OpenGL function. -extern GLboolean (* const glIsFramebuffer)(GLuint); +extern GLboolean (*const glIsFramebuffer)(GLuint); /// Pointer to glIsProgram OpenGL function. -extern GLboolean (* const glIsProgram)(GLuint); +extern GLboolean (*const glIsProgram)(GLuint); /// Pointer to glIsRenderbuffer OpenGL function. -extern GLboolean (* const glIsRenderbuffer)(GLuint); +extern GLboolean (*const glIsRenderbuffer)(GLuint); /// Pointer to glIsShader OpenGL function. -extern GLboolean (* const glIsShader)(GLuint); +extern GLboolean (*const glIsShader)(GLuint); /// Pointer to glIsTexture OpenGL function. -extern GLboolean (* const glIsTexture)(GLuint); +extern GLboolean (*const glIsTexture)(GLuint); /// Pointer to glLineWidth OpenGL function. -extern void (* const glLineWidth)(GLfloat); +extern void (*const glLineWidth)(GLfloat); /// Pointer to glLinkProgram OpenGL function. -extern void (* const glLinkProgram)(GLuint); +extern void (*const glLinkProgram)(GLuint); /// Pointer to glPixelStorei OpenGL function. -extern void (* const glPixelStorei)(GLenum, GLint); +extern void (*const glPixelStorei)(GLenum, GLint); /// Pointer to glPolygonOffset OpenGL function. -extern void (* const glPolygonOffset)(GLfloat, GLfloat); +extern void (*const glPolygonOffset)(GLfloat, GLfloat); /// Pointer to glReadPixels OpenGL function. -extern void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *); +extern void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*); /// Pointer to glReleaseShaderCompiler OpenGL function. -extern void (* const glReleaseShaderCompiler)(); +extern void (*const glReleaseShaderCompiler)(); /// Pointer to glRenderbufferStorage OpenGL function. -extern void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei); +extern void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei); /// Pointer to glSampleCoverage OpenGL function. -extern void (* const glSampleCoverage)(GLfloat, GLboolean); +extern void (*const glSampleCoverage)(GLfloat, GLboolean); /// Pointer to glScissor OpenGL function. -extern void (* const glScissor)(GLint, GLint, GLsizei, GLsizei); +extern void (*const glScissor)(GLint, GLint, GLsizei, GLsizei); /// Pointer to glShaderBinary OpenGL function. -extern void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei); +extern void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei); /// Pointer to glShaderSource OpenGL function. -extern void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *); +extern void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*); /// Pointer to glStencilFunc OpenGL function. -extern void (* const glStencilFunc)(GLenum, GLint, GLuint); +extern void (*const glStencilFunc)(GLenum, GLint, GLuint); /// Pointer to glStencilFuncSeparate OpenGL function. -extern void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint); +extern void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint); /// Pointer to glStencilMask OpenGL function. -extern void (* const glStencilMask)(GLuint); +extern void (*const glStencilMask)(GLuint); /// Pointer to glStencilMaskSeparate OpenGL function. -extern void (* const glStencilMaskSeparate)(GLenum, GLuint); +extern void (*const glStencilMaskSeparate)(GLenum, GLuint); /// Pointer to glStencilOp OpenGL function. -extern void (* const glStencilOp)(GLenum, GLenum, GLenum); +extern void (*const glStencilOp)(GLenum, GLenum, GLenum); /// Pointer to glStencilOpSeparate OpenGL function. -extern void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum); +extern void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum); /// Pointer to glTexImage2D OpenGL function. -extern void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *); +extern void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*); /// Pointer to glTexParameterf OpenGL function. -extern void (* const glTexParameterf)(GLenum, GLenum, GLfloat); +extern void (*const glTexParameterf)(GLenum, GLenum, GLfloat); /// Pointer to glTexParameterfv OpenGL function. -extern void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *); +extern void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*); /// Pointer to glTexParameteri OpenGL function. -extern void (* const glTexParameteri)(GLenum, GLenum, GLint); +extern void (*const glTexParameteri)(GLenum, GLenum, GLint); /// Pointer to glTexParameteriv OpenGL function. -extern void (* const glTexParameteriv)(GLenum, GLenum, const GLint *); +extern void (*const glTexParameteriv)(GLenum, GLenum, const GLint*); /// Pointer to glTexSubImage2D OpenGL function. -extern void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *); +extern void (*const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*); /// Pointer to glUniform1f OpenGL function. -extern void (* const glUniform1f)(GLint, GLfloat); +extern void (*const glUniform1f)(GLint, GLfloat); /// Pointer to glUniform1fv OpenGL function. -extern void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform1i OpenGL function. -extern void (* const glUniform1i)(GLint, GLint); +extern void (*const glUniform1i)(GLint, GLint); /// Pointer to glUniform1iv OpenGL function. -extern void (* const glUniform1iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform1iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniform2f OpenGL function. -extern void (* const glUniform2f)(GLint, GLfloat, GLfloat); +extern void (*const glUniform2f)(GLint, GLfloat, GLfloat); /// Pointer to glUniform2fv OpenGL function. -extern void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform2i OpenGL function. -extern void (* const glUniform2i)(GLint, GLint, GLint); +extern void (*const glUniform2i)(GLint, GLint, GLint); /// Pointer to glUniform2iv OpenGL function. -extern void (* const glUniform2iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform2iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniform3f OpenGL function. -extern void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat); +extern void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat); /// Pointer to glUniform3fv OpenGL function. -extern void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform3i OpenGL function. -extern void (* const glUniform3i)(GLint, GLint, GLint, GLint); +extern void (*const glUniform3i)(GLint, GLint, GLint, GLint); /// Pointer to glUniform3iv OpenGL function. -extern void (* const glUniform3iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform3iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniform4f OpenGL function. -extern void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glUniform4fv OpenGL function. -extern void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *); +extern void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*); /// Pointer to glUniform4i OpenGL function. -extern void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint); +extern void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint); /// Pointer to glUniform4iv OpenGL function. -extern void (* const glUniform4iv)(GLint, GLsizei, const GLint *); +extern void (*const glUniform4iv)(GLint, GLsizei, const GLint*); /// Pointer to glUniformMatrix2fv OpenGL function. -extern void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix3fv OpenGL function. -extern void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix4fv OpenGL function. -extern void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUseProgram OpenGL function. -extern void (* const glUseProgram)(GLuint); +extern void (*const glUseProgram)(GLuint); /// Pointer to glValidateProgram OpenGL function. -extern void (* const glValidateProgram)(GLuint); +extern void (*const glValidateProgram)(GLuint); /// Pointer to glVertexAttrib1f OpenGL function. -extern void (* const glVertexAttrib1f)(GLuint, GLfloat); +extern void (*const glVertexAttrib1f)(GLuint, GLfloat); /// Pointer to glVertexAttrib1fv OpenGL function. -extern void (* const glVertexAttrib1fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib1fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttrib2f OpenGL function. -extern void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat); +extern void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat); /// Pointer to glVertexAttrib2fv OpenGL function. -extern void (* const glVertexAttrib2fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib2fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttrib3f OpenGL function. -extern void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat); +extern void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat); /// Pointer to glVertexAttrib3fv OpenGL function. -extern void (* const glVertexAttrib3fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib3fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttrib4f OpenGL function. -extern void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +extern void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat); /// Pointer to glVertexAttrib4fv OpenGL function. -extern void (* const glVertexAttrib4fv)(GLuint, const GLfloat *); +extern void (*const glVertexAttrib4fv)(GLuint, const GLfloat*); /// Pointer to glVertexAttribPointer OpenGL function. -extern void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *); +extern void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*); /// Pointer to glViewport OpenGL function. -extern void (* const glViewport)(GLint, GLint, GLsizei, GLsizei); +extern void (*const glViewport)(GLint, GLint, GLsizei, GLsizei); /* OpenGL ES 3.0 */ /// Pointer to glReadBuffer OpenGL function. -extern void (* const glReadBuffer)(GLenum); +extern void (*const glReadBuffer)(GLenum); /// Pointer to glDrawRangeElements OpenGL function. -extern void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); +extern void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*); /// Pointer to glTexImage3D OpenGL function. -extern void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); +extern void (*const glTexImage3D)( + GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*); /// Pointer to glTexSubImage3D OpenGL function. -extern void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +extern void (*const glTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*); /// Pointer to glCopyTexSubImage3D OpenGL function. -extern void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +extern void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); /// Pointer to glCompressedTexImage3D OpenGL function. -extern void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); +extern void (*const glCompressedTexImage3D)( + GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*); /// Pointer to glCompressedTexSubImage3D OpenGL function. -extern void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); +extern void (*const glCompressedTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*); /// Pointer to glGenQueries OpenGL function. -extern void (* const glGenQueries)(GLsizei, GLuint *); +extern void (*const glGenQueries)(GLsizei, GLuint*); /// Pointer to glDeleteQueries OpenGL function. -extern void (* const glDeleteQueries)(GLsizei, const GLuint *); +extern void (*const glDeleteQueries)(GLsizei, const GLuint*); /// Pointer to glIsQuery OpenGL function. -extern GLboolean (* const glIsQuery)(GLuint); +extern GLboolean (*const glIsQuery)(GLuint); /// Pointer to glBeginQuery OpenGL function. -extern void (* const glBeginQuery)(GLenum, GLuint); +extern void (*const glBeginQuery)(GLenum, GLuint); /// Pointer to glEndQuery OpenGL function. -extern void (* const glEndQuery)(GLenum); +extern void (*const glEndQuery)(GLenum); /// Pointer to glGetQueryiv OpenGL function. -extern void (* const glGetQueryiv)(GLenum, GLenum, GLint *); +extern void (*const glGetQueryiv)(GLenum, GLenum, GLint*); /// Pointer to glGetQueryObjectuiv OpenGL function. -extern void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *); +extern void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*); /// Pointer to glUnmapBuffer OpenGL function. -extern GLboolean (* const glUnmapBuffer)(GLenum); +extern GLboolean (*const glUnmapBuffer)(GLenum); /// Pointer to glGetBufferPointerv OpenGL function. -extern void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **); +extern void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**); /// Pointer to glDrawBuffers OpenGL function. -extern void (* const glDrawBuffers)(GLsizei, const GLenum *); +extern void (*const glDrawBuffers)(GLsizei, const GLenum*); /// Pointer to glUniformMatrix2x3fv OpenGL function. -extern void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix3x2fv OpenGL function. -extern void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix2x4fv OpenGL function. -extern void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix4x2fv OpenGL function. -extern void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix3x4fv OpenGL function. -extern void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glUniformMatrix4x3fv OpenGL function. -extern void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *); +extern void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*); /// Pointer to glBlitFramebuffer OpenGL function. -extern void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum); +extern void (*const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum); /// Pointer to glRenderbufferStorageMultisample OpenGL function. -extern void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); +extern void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); /// Pointer to glFramebufferTextureLayer OpenGL function. -extern void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint); +extern void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint); /// Pointer to glMapBufferRange OpenGL function. -extern GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield); +extern GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield); /// Pointer to glMapBufferRange OpenGL function. -extern void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr); +extern void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr); /// Pointer to glBindVertexArray OpenGL function. -extern void (* const glBindVertexArray)(GLuint); +extern void (*const glBindVertexArray)(GLuint); /// Pointer to glDeleteVertexArrays OpenGL function. -extern void (* const glDeleteVertexArrays)(GLsizei, const GLuint *); +extern void (*const glDeleteVertexArrays)(GLsizei, const GLuint*); /// Pointer to glGenVertexArrays OpenGL function. -extern void (* const glGenVertexArrays)(GLsizei, GLuint *); +extern void (*const glGenVertexArrays)(GLsizei, GLuint*); /// Pointer to glIsVertexArray OpenGL function. -extern GLboolean (* const glIsVertexArray)(GLuint); +extern GLboolean (*const glIsVertexArray)(GLuint); /// Pointer to glGetIntegeri_v OpenGL function. -extern void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *); +extern void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*); /// Pointer to glBeginTransformFeedback OpenGL function. -extern void (* const glBeginTransformFeedback)(GLenum); +extern void (*const glBeginTransformFeedback)(GLenum); /// Pointer to glEndTransformFeedback OpenGL function. -extern void (* const glEndTransformFeedback)(); +extern void (*const glEndTransformFeedback)(); /// Pointer to glBindBufferRange OpenGL function. -extern void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr); +extern void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr); /// Pointer to glBindBufferBase OpenGL function. -extern void (* const glBindBufferBase)(GLenum, GLuint, GLuint); +extern void (*const glBindBufferBase)(GLenum, GLuint, GLuint); /// Pointer to glTransformFeedbackVaryings OpenGL function. -extern void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum); +extern void (*const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum); /// Pointer to glGetTransformFeedbackVarying OpenGL function. -extern void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *); +extern void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*); /// Pointer to glVertexAttribIPointer OpenGL function. -extern void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *); +extern void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*); /// Pointer to glGetVertexAttribIiv OpenGL function. -extern void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *); +extern void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*); /// Pointer to glGetVertexAttribIiv OpenGL function. -extern void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *); +extern void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*); /// Pointer to glVertexAttribI4i OpenGL function. -extern void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint); +extern void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint); /// Pointer to glVertexAttribI4ui OpenGL function. -extern void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint); +extern void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint); /// Pointer to glVertexAttribI4iv OpenGL function. -extern void (* const glVertexAttribI4iv)(GLuint, const GLint *); +extern void (*const glVertexAttribI4iv)(GLuint, const GLint*); /// Pointer to glVertexAttribI4uiv OpenGL function. -extern void (* const glVertexAttribI4uiv)(GLuint, const GLuint *); +extern void (*const glVertexAttribI4uiv)(GLuint, const GLuint*); /// Pointer to glGetUniformuiv OpenGL function. -extern void (* const glGetUniformuiv)(GLuint, GLint, GLuint *); +extern void (*const glGetUniformuiv)(GLuint, GLint, GLuint*); /// Pointer to glGetFragDataLocation OpenGL function. -extern GLint (* const glGetFragDataLocation)(GLuint, const GLchar *); +extern GLint (*const glGetFragDataLocation)(GLuint, const GLchar*); /// Pointer to glUniform1ui OpenGL function. -extern void (* const glUniform1ui)(GLint, GLuint); +extern void (*const glUniform1ui)(GLint, GLuint); /// Pointer to glUniform2ui OpenGL function. -extern void (* const glUniform2ui)(GLint, GLuint, GLuint); +extern void (*const glUniform2ui)(GLint, GLuint, GLuint); /// Pointer to glUniform3ui OpenGL function. -extern void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint); +extern void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint); /// Pointer to glUniform4ui OpenGL function. -extern void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint); +extern void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint); /// Pointer to glUniform1uiv OpenGL function. -extern void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glUniform2uiv OpenGL function. -extern void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glUniform3uiv OpenGL function. -extern void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glUniform4uiv OpenGL function. -extern void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *); +extern void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*); /// Pointer to glClearBufferiv OpenGL function. -extern void (* const glClearBufferiv)(GLenum, GLint, const GLint *); +extern void (*const glClearBufferiv)(GLenum, GLint, const GLint*); /// Pointer to glClearBufferuiv OpenGL function. -extern void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *); +extern void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*); /// Pointer to glClearBufferfv OpenGL function. -extern void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *); +extern void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*); /// Pointer to glClearBufferfi OpenGL function. -extern void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint); +extern void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint); /// Pointer to glGetStringi OpenGL function. -extern const GLubyte* (* const glGetStringi)(GLenum, GLuint); +extern const GLubyte* (*const glGetStringi)(GLenum, GLuint); /// Pointer to glCopyBufferSubData OpenGL function. -extern void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr); +extern void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr); /// Pointer to glGetUniformIndices OpenGL function. -extern void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *); +extern void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*); /// Pointer to glGetActiveUniformsiv OpenGL function. -extern void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *); +extern void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*); /// Pointer to glGetUniformBlockIndex OpenGL function. -extern GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *); +extern GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*); /// Pointer to glGetActiveUniformBlockiv OpenGL function. -extern void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *); +extern void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*); /// Pointer to glGetActiveUniformBlockName OpenGL function. -extern void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *); +extern void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*); /// Pointer to glUniformBlockBinding OpenGL function. -extern void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint); +extern void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint); /// Pointer to glDrawArraysInstanced OpenGL function. -extern void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei); +extern void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei); /// Pointer to glDrawElementsInstanced OpenGL function. -extern void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei); +extern void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei); /// Pointer to glFenceSync OpenGL function. -extern GLsync (* const glFenceSync)(GLenum, GLbitfield); +extern GLsync (*const glFenceSync)(GLenum, GLbitfield); /// Pointer to glIsSync OpenGL function. -extern GLboolean (* const glIsSync)(GLsync); +extern GLboolean (*const glIsSync)(GLsync); /// Pointer to glDeleteSync OpenGL function. -extern void (* const glDeleteSync)(GLsync); +extern void (*const glDeleteSync)(GLsync); /// Pointer to glClientWaitSync OpenGL function. -extern GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64); +extern GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64); /// Pointer to glWaitSync OpenGL function. -extern void (* const glWaitSync)(GLsync, GLbitfield, GLuint64); +extern void (*const glWaitSync)(GLsync, GLbitfield, GLuint64); /// Pointer to glGetInteger64v OpenGL function. -extern void (* const glGetInteger64v)(GLenum, GLint64 *); +extern void (*const glGetInteger64v)(GLenum, GLint64*); /// Pointer to glGetSynciv OpenGL function. -extern void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *); +extern void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*); /// Pointer to glGetInteger64i_v OpenGL function. -extern void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *); +extern void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*); /// Pointer to glGetBufferParameteri64v OpenGL function. -extern void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *); +extern void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*); /// Pointer to glGenSamplers OpenGL function. -extern void (* const glGenSamplers)(GLsizei, GLuint *); +extern void (*const glGenSamplers)(GLsizei, GLuint*); /// Pointer to glDeleteSamplers OpenGL function. -extern void (* const glDeleteSamplers)(GLsizei, const GLuint *); +extern void (*const glDeleteSamplers)(GLsizei, const GLuint*); /// Pointer to glIsSampler OpenGL function. -extern GLboolean (* const glIsSampler)(GLuint); +extern GLboolean (*const glIsSampler)(GLuint); /// Pointer to glBindSampler OpenGL function. -extern void (* const glBindSampler)(GLuint, GLuint); +extern void (*const glBindSampler)(GLuint, GLuint); /// Pointer to glSamplerParameteri OpenGL function. -extern void (* const glSamplerParameteri)(GLuint, GLenum, GLint); +extern void (*const glSamplerParameteri)(GLuint, GLenum, GLint); /// Pointer to glSamplerParameteriv OpenGL function. -extern void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *); +extern void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*); /// Pointer to glSamplerParameterf OpenGL function. -extern void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat); +extern void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat); /// Pointer to glSamplerParameterfv OpenGL function. -extern void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *); +extern void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*); /// Pointer to glGetSamplerParameteriv OpenGL function. -extern void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *); +extern void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*); /// Pointer to glGetSamplerParameterfv OpenGL function. -extern void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *); +extern void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*); /// Pointer to glVertexAttribDivisor OpenGL function. -extern void (* const glVertexAttribDivisor)(GLuint, GLuint); +extern void (*const glVertexAttribDivisor)(GLuint, GLuint); /// Pointer to glBindTransformFeedback OpenGL function. -extern void (* const glBindTransformFeedback)(GLenum, GLuint); +extern void (*const glBindTransformFeedback)(GLenum, GLuint); /// Pointer to glDeleteTransformFeedbacks OpenGL function. -extern void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *); +extern void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*); /// Pointer to glGenTransformFeedbacks OpenGL function. -extern void (* const glGenTransformFeedbacks)(GLsizei, GLuint *); +extern void (*const glGenTransformFeedbacks)(GLsizei, GLuint*); /// Pointer to glIsTransformFeedback OpenGL function. -extern GLboolean (* const glIsTransformFeedback)(GLuint); +extern GLboolean (*const glIsTransformFeedback)(GLuint); /// Pointer to glPauseTransformFeedback OpenGL function. -extern void (* const glPauseTransformFeedback)(); +extern void (*const glPauseTransformFeedback)(); /// Pointer to glResumeTransformFeedback OpenGL function. -extern void (* const glResumeTransformFeedback)(); +extern void (*const glResumeTransformFeedback)(); /// Pointer to glGetProgramBinary OpenGL function. -extern void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *); +extern void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*); /// Pointer to glProgramBinary OpenGL function. -extern void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei); +extern void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei); /// Pointer to glProgramParameteri OpenGL function. -extern void (* const glProgramParameteri)(GLuint, GLenum, GLint); +extern void (*const glProgramParameteri)(GLuint, GLenum, GLint); /// Pointer to glInvalidateFramebuffer OpenGL function. -extern void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *); +extern void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*); /// Pointer to glInvalidateSubFramebuffer OpenGL function. -extern void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei); +extern void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei); /// Pointer to glTexStorage2D OpenGL function. -extern void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); +extern void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei); /// Pointer to glTexStorage3D OpenGL function. -extern void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei); +extern void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei); /// Pointer to glGetInternalformativ OpenGL function. -extern void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *); +extern void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*); #ifndef NDEBUG /// Check for GL errors and print on the console. -void glCheckError(const char *cmd, const char *file, int line); +void glCheckError(const char* cmd, const char* file, int line); #endif -} // namespace platform +} // namespace platform } // namespace mbgl diff --git a/include/mbgl/platform/settings.hpp b/include/mbgl/platform/settings.hpp index a8271768915..3b5a57d0a9d 100644 --- a/include/mbgl/platform/settings.hpp +++ b/include/mbgl/platform/settings.hpp @@ -32,8 +32,9 @@ class Settings final { /// for specified key is missing. mapbox::base::Value get(const std::string& key) const noexcept; - /// Returns values for settings whose keys are equal to the ones provided in `keys` argument. - /// Null values would be provided for keys whose elements are missing in Settings. + /// Returns values for settings whose keys are equal to the ones provided in + /// `keys` argument. Null values would be provided for keys whose elements + /// are missing in Settings. mapbox::base::ValueObject get(const std::vector& keys) const noexcept; private: diff --git a/include/mbgl/renderer/renderer.hpp b/include/mbgl/renderer/renderer.hpp index 6bfdee626c0..69c01a56f7a 100644 --- a/include/mbgl/renderer/renderer.hpp +++ b/include/mbgl/renderer/renderer.hpp @@ -42,7 +42,9 @@ struct PlacedSymbolData { class Renderer { public: - Renderer(gfx::RendererBackend&, float pixelRatio_, const std::optional& localFontFamily = std::nullopt); + Renderer(gfx::RendererBackend&, + float pixelRatio_, + const std::optional& localFontFamily = std::nullopt); ~Renderer(); void markContextLost(); @@ -53,7 +55,8 @@ class Renderer { /// Feature queries std::vector queryRenderedFeatures(const ScreenLineString&, const RenderedQueryOptions& options = {}) const; - std::vector queryRenderedFeatures(const ScreenCoordinate& point, const RenderedQueryOptions& options = {}) const; + std::vector queryRenderedFeatures(const ScreenCoordinate& point, + const RenderedQueryOptions& options = {}) const; std::vector queryRenderedFeatures(const ScreenBox& box, const RenderedQueryOptions& options = {}) const; std::vector querySourceFeatures(const std::string& sourceID, const SourceQueryOptions& options = {}) const; AnnotationIDs queryPointAnnotations(const ScreenBox& box) const; @@ -61,14 +64,17 @@ class Renderer { AnnotationIDs getAnnotationIDs(const std::vector&) const; /// Feature extension query - FeatureExtensionValue queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args = std::nullopt) const; - - void setFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::string& featureID, const FeatureState& state); + FeatureExtensionValue queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args = std::nullopt) const; + + void setFeatureState(const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID, + const FeatureState& state); void getFeatureState(FeatureState& state, const std::string& sourceID, @@ -84,16 +90,16 @@ class Renderer { void dumpDebugLogs(); /** - * @brief In Tile map mode, enables or disables collecting of the placed symbols data, - * which can be obtained with `getPlacedSymbolsData()`. + * @brief In Tile map mode, enables or disables collecting of the placed + * symbols data, which can be obtained with `getPlacedSymbolsData()`. * * The placed symbols data collecting is disabled by default. */ void collectPlacedSymbolData(bool enable); /** - * @brief If collecting of the placed symbols data is enabled, returns the reference - * to the `PlacedSymbolData` vector holding the collected data. + * @brief If collecting of the placed symbols data is enabled, returns the + * reference to the `PlacedSymbolData` vector holding the collected data. * * Note: the returned vector gets re-populated at every `render()` call. * diff --git a/include/mbgl/renderer/renderer_frontend.hpp b/include/mbgl/renderer/renderer_frontend.hpp index 038a905f2ef..3c9fb82181b 100644 --- a/include/mbgl/renderer/renderer_frontend.hpp +++ b/include/mbgl/renderer/renderer_frontend.hpp @@ -14,7 +14,6 @@ class UpdateParameters; /// the original thread. class RendererFrontend { public: - virtual ~RendererFrontend() = default; /// Must synchronously clean up the Renderer if set diff --git a/include/mbgl/renderer/renderer_observer.hpp b/include/mbgl/renderer/renderer_observer.hpp index d0bb7475413..fdaa40477fd 100644 --- a/include/mbgl/renderer/renderer_observer.hpp +++ b/include/mbgl/renderer/renderer_observer.hpp @@ -42,7 +42,7 @@ class RendererObserver { virtual void onRemoveUnusedStyleImages(const std::vector&) {} // Entry point for custom shader registration - virtual void onRegisterShaders(gfx::ShaderRegistry&) {}; + virtual void onRegisterShaders(gfx::ShaderRegistry&){}; }; } // namespace mbgl diff --git a/include/mbgl/renderer/renderer_state.hpp b/include/mbgl/renderer/renderer_state.hpp index bd8c811aa7a..844bcfacac2 100644 --- a/include/mbgl/renderer/renderer_state.hpp +++ b/include/mbgl/renderer/renderer_state.hpp @@ -8,12 +8,11 @@ namespace mbgl { class UpdateParameters; /** - * RendererState acts as a Memento object that is able to extract data out of UpdateParameters (an opaque object - * from the public API perspective). + * RendererState acts as a Memento object that is able to extract data out of + * UpdateParameters (an opaque object from the public API perspective). */ class RendererState { public: - /// Obtains a CameraOptions out of a given UpdateParameters object. static CameraOptions getCameraOptions(const UpdateParameters&, const EdgeInsets& = {}); diff --git a/include/mbgl/shaders/gl/background.hpp b/include/mbgl/shaders/gl/background.hpp index 4a728f31c1e..ba3d012d7d6 100644 --- a/include/mbgl/shaders/gl/background.hpp +++ b/include/mbgl/shaders/gl/background.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/background_pattern.hpp b/include/mbgl/shaders/gl/background_pattern.hpp index 2626c78f495..b3241b2567b 100644 --- a/include/mbgl/shaders/gl/background_pattern.hpp +++ b/include/mbgl/shaders/gl/background_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_pattern_size_a; uniform vec2 u_pattern_size_b; diff --git a/include/mbgl/shaders/gl/circle.hpp b/include/mbgl/shaders/gl/circle.hpp index 9a32675e954..2999d5b5622 100644 --- a/include/mbgl/shaders/gl/circle.hpp +++ b/include/mbgl/shaders/gl/circle.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform bool u_scale_with_map; uniform bool u_pitch_with_map; diff --git a/include/mbgl/shaders/gl/clipping_mask.hpp b/include/mbgl/shaders/gl/clipping_mask.hpp index abb4799f884..45c4903bd33 100644 --- a/include/mbgl/shaders/gl/clipping_mask.hpp +++ b/include/mbgl/shaders/gl/clipping_mask.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/collision_box.hpp b/include/mbgl/shaders/gl/collision_box.hpp index b68f4dddb05..6a6c25aff22 100644 --- a/include/mbgl/shaders/gl/collision_box.hpp +++ b/include/mbgl/shaders/gl/collision_box.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; layout (location = 1) in vec2 a_anchor_pos; layout (location = 2) in vec2 a_extrude; diff --git a/include/mbgl/shaders/gl/collision_circle.hpp b/include/mbgl/shaders/gl/collision_circle.hpp index 2c87ba93102..db07f556310 100644 --- a/include/mbgl/shaders/gl/collision_circle.hpp +++ b/include/mbgl/shaders/gl/collision_circle.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; layout (location = 1) in vec2 a_anchor_pos; layout (location = 2) in vec2 a_extrude; diff --git a/include/mbgl/shaders/gl/debug.hpp b/include/mbgl/shaders/gl/debug.hpp index daae1d7c745..ae0661b6fe5 100644 --- a/include/mbgl/shaders/gl/debug.hpp +++ b/include/mbgl/shaders/gl/debug.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; out vec2 v_uv; diff --git a/include/mbgl/shaders/gl/fill.hpp b/include/mbgl/shaders/gl/fill.hpp index 5fd3872ebce..f9d373f811d 100644 --- a/include/mbgl/shaders/gl/fill.hpp +++ b/include/mbgl/shaders/gl/fill.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/fill_extrusion.hpp b/include/mbgl/shaders/gl/fill_extrusion.hpp index 41cf60e4f8f..cfb5f4339ad 100644 --- a/include/mbgl/shaders/gl/fill_extrusion.hpp +++ b/include/mbgl/shaders/gl/fill_extrusion.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec3 u_lightcolor; uniform lowp vec3 u_lightpos; diff --git a/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp b/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp index 35d9c00cf3a..30c3fb804ed 100644 --- a/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp +++ b/include/mbgl/shaders/gl/fill_extrusion_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_pixel_coord_upper; uniform vec2 u_pixel_coord_lower; diff --git a/include/mbgl/shaders/gl/fill_outline.hpp b/include/mbgl/shaders/gl/fill_outline.hpp index 33be116975b..b7f452e3946 100644 --- a/include/mbgl/shaders/gl/fill_outline.hpp +++ b/include/mbgl/shaders/gl/fill_outline.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(layout (location = 0) in vec2 a_pos; uniform mat4 u_matrix; diff --git a/include/mbgl/shaders/gl/fill_outline_pattern.hpp b/include/mbgl/shaders/gl/fill_outline_pattern.hpp index 2d7a5c40b17..dcfb603f76a 100644 --- a/include/mbgl/shaders/gl/fill_outline_pattern.hpp +++ b/include/mbgl/shaders/gl/fill_outline_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_world; uniform vec2 u_pixel_coord_upper; diff --git a/include/mbgl/shaders/gl/fill_pattern.hpp b/include/mbgl/shaders/gl/fill_pattern.hpp index 38139ca6f09..cea58657720 100644 --- a/include/mbgl/shaders/gl/fill_pattern.hpp +++ b/include/mbgl/shaders/gl/fill_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_pixel_coord_upper; uniform vec2 u_pixel_coord_lower; diff --git a/include/mbgl/shaders/gl/heatmap.hpp b/include/mbgl/shaders/gl/heatmap.hpp index edf51615dd6..c7a13c9287a 100644 --- a/include/mbgl/shaders/gl/heatmap.hpp +++ b/include/mbgl/shaders/gl/heatmap.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform float u_extrude_scale; uniform float u_opacity; diff --git a/include/mbgl/shaders/gl/heatmap_texture.hpp b/include/mbgl/shaders/gl/heatmap_texture.hpp index e052cbdfee1..dc89ad0ad34 100644 --- a/include/mbgl/shaders/gl/heatmap_texture.hpp +++ b/include/mbgl/shaders/gl/heatmap_texture.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_world; layout (location = 0) in vec2 a_pos; diff --git a/include/mbgl/shaders/gl/hillshade.hpp b/include/mbgl/shaders/gl/hillshade.hpp index ed569b814ae..3ade4f435a3 100644 --- a/include/mbgl/shaders/gl/hillshade.hpp +++ b/include/mbgl/shaders/gl/hillshade.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; layout (location = 0) in vec2 a_pos; diff --git a/include/mbgl/shaders/gl/hillshade_prepare.hpp b/include/mbgl/shaders/gl/hillshade_prepare.hpp index 6e26c12a69c..4836ccf17e5 100644 --- a/include/mbgl/shaders/gl/hillshade_prepare.hpp +++ b/include/mbgl/shaders/gl/hillshade_prepare.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_dimension; diff --git a/include/mbgl/shaders/gl/line.hpp b/include/mbgl/shaders/gl/line.hpp index 1c772b165c8..c140c70fa53 100644 --- a/include/mbgl/shaders/gl/line.hpp +++ b/include/mbgl/shaders/gl/line.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(// floor(127 / 2) == 63.0 // the maximum allowed miter limit is 2.0 at the moment. the extrude normal is // stored in a byte (-128..127). we scale regular normals up to length 63, but diff --git a/include/mbgl/shaders/gl/line_gradient.hpp b/include/mbgl/shaders/gl/line_gradient.hpp index 7f2901d8ad1..c98f1746a51 100644 --- a/include/mbgl/shaders/gl/line_gradient.hpp +++ b/include/mbgl/shaders/gl/line_gradient.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"( // the attribute conveying progress along a line is scaled to [0, 2^15) #define MAX_LINE_DISTANCE 32767.0 diff --git a/include/mbgl/shaders/gl/line_pattern.hpp b/include/mbgl/shaders/gl/line_pattern.hpp index 617ed764858..c18c98250f1 100644 --- a/include/mbgl/shaders/gl/line_pattern.hpp +++ b/include/mbgl/shaders/gl/line_pattern.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(// floor(127 / 2) == 63.0 // the maximum allowed miter limit is 2.0 at the moment. the extrude normal is // stored in a byte (-128..127). we scale regular normals up to length 63, but diff --git a/include/mbgl/shaders/gl/line_sdf.hpp b/include/mbgl/shaders/gl/line_sdf.hpp index 66206befc48..62a34d7cff0 100644 --- a/include/mbgl/shaders/gl/line_sdf.hpp +++ b/include/mbgl/shaders/gl/line_sdf.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(// floor(127 / 2) == 63.0 // the maximum allowed miter limit is 2.0 at the moment. the extrude normal is // stored in a byte (-128..127). we scale regular normals up to length 63, but diff --git a/include/mbgl/shaders/gl/prelude.hpp b/include/mbgl/shaders/gl/prelude.hpp index f4d4c93e631..822fd2b3941 100644 --- a/include/mbgl/shaders/gl/prelude.hpp +++ b/include/mbgl/shaders/gl/prelude.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(#ifdef GL_ES precision highp float; #else diff --git a/include/mbgl/shaders/gl/raster.hpp b/include/mbgl/shaders/gl/raster.hpp index c275c443de1..7087a548013 100644 --- a/include/mbgl/shaders/gl/raster.hpp +++ b/include/mbgl/shaders/gl/raster.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(uniform mat4 u_matrix; uniform vec2 u_tl_parent; uniform float u_scale_parent; diff --git a/include/mbgl/shaders/gl/symbol_icon.hpp b/include/mbgl/shaders/gl/symbol_icon.hpp index 273a1ac393a..abfc29e5180 100644 --- a/include/mbgl/shaders/gl/symbol_icon.hpp +++ b/include/mbgl/shaders/gl/symbol_icon.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/gl/symbol_sdf_icon.hpp b/include/mbgl/shaders/gl/symbol_sdf_icon.hpp index cbf4b9f1d92..babe133eb32 100644 --- a/include/mbgl/shaders/gl/symbol_sdf_icon.hpp +++ b/include/mbgl/shaders/gl/symbol_sdf_icon.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/gl/symbol_sdf_text.hpp b/include/mbgl/shaders/gl/symbol_sdf_text.hpp index d453fead3b2..fc170dd5889 100644 --- a/include/mbgl/shaders/gl/symbol_sdf_text.hpp +++ b/include/mbgl/shaders/gl/symbol_sdf_text.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/gl/symbol_text_and_icon.hpp b/include/mbgl/shaders/gl/symbol_text_and_icon.hpp index 716f75798d1..a448b437bd5 100644 --- a/include/mbgl/shaders/gl/symbol_text_and_icon.hpp +++ b/include/mbgl/shaders/gl/symbol_text_and_icon.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace shaders { -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = R"(const float PI = 3.141592653589793; layout (location = 0) in vec4 a_pos_offset; diff --git a/include/mbgl/shaders/shader_source.hpp b/include/mbgl/shaders/shader_source.hpp index 9eb79b6218f..22cf642e882 100644 --- a/include/mbgl/shaders/shader_source.hpp +++ b/include/mbgl/shaders/shader_source.hpp @@ -45,10 +45,12 @@ enum class BuiltIn { /// @tparam T One of the built-in shader types available in the BuiltIn enum /// @tparam The desired graphics API to request shader code for. One of /// gfx::Backend::Type enums. -template struct ShaderSource; +template +struct ShaderSource; /// @brief A specialization of the ShaderSource template for no shader code. -template <> struct ShaderSource { +template <> +struct ShaderSource { static constexpr const char* vertex = ""; static constexpr const char* fragment = ""; }; diff --git a/include/mbgl/storage/database_file_source.hpp b/include/mbgl/storage/database_file_source.hpp index 195e04087c1..f591e275196 100644 --- a/include/mbgl/storage/database_file_source.hpp +++ b/include/mbgl/storage/database_file_source.hpp @@ -26,17 +26,17 @@ class DatabaseFileSource : public FileSource { // Methods common to Ambient cache and Offline functionality /** - * Sets path of a database to be used by DatabaseFileSource and invokes provided - * callback when a database path is set. + * Sets path of a database to be used by DatabaseFileSource and invokes + * provided callback when a database path is set. */ virtual void setDatabasePath(const std::string&, std::function callback); /** * Delete existing database and re-initialize. * - * When the operation is complete or encounters an error, the given callback will be - * executed on the database thread; it is the responsibility of the SDK bindings - * to re-execute a user-provided callback on the main thread. + * When the operation is complete or encounters an error, the given callback + * will be executed on the database thread; it is the responsibility of the + * SDK bindings to re-execute a user-provided callback on the main thread. */ virtual void resetDatabase(std::function); @@ -46,16 +46,16 @@ class DatabaseFileSource : public FileSource { * This operation has a performance impact as it will vacuum the database, * forcing it to move pages on the filesystem. * - * When the operation is complete or encounters an error, the given callback will be - * executed on the database thread; it is the responsibility of the SDK bindings - * to re-execute a user-provided callback on the main thread. + * When the operation is complete or encounters an error, the given callback + * will be executed on the database thread; it is the responsibility of the + * SDK bindings to re-execute a user-provided callback on the main thread. */ virtual void packDatabase(std::function callback); /** - * Sets whether packing the database file occurs automatically after an offline - * region is deleted (deleteOfflineRegion()) or the ambient cache is cleared - * (clearAmbientCache()). + * Sets whether packing the database file occurs automatically after an + * offline region is deleted (deleteOfflineRegion()) or the ambient cache is + * cleared (clearAmbientCache()). * * By default, packing is enabled. If disabled, disk space will not be freed * after resources are removed unless packDatabase() is explicitly called. @@ -129,21 +129,23 @@ class DatabaseFileSource : public FileSource { /** * Retrieve all regions in the offline database. * - * The query will be executed asynchronously and the results passed to the given - * callback, which will be executed on the database thread; it is the responsibility - * of the SDK bindings to re-execute a user-provided callback on the main thread. + * The query will be executed asynchronously and the results passed to the + * given callback, which will be executed on the database thread; it is the + * responsibility of the SDK bindings to re-execute a user-provided callback + * on the main thread. */ virtual void listOfflineRegions(std::function)>); /** * Create an offline region in the database. * - * When the initial database queries have completed, the provided callback will be - * executed on the database thread; it is the responsibility of the SDK bindings - * to re-execute a user-provided callback on the main thread. + * When the initial database queries have completed, the provided callback + * will be executed on the database thread; it is the responsibility of the + * SDK bindings to re-execute a user-provided callback on the main thread. * - * Note that the resulting region will be in an inactive download state; to begin - * downloading resources, call `setOfflineRegionDownloadState(OfflineRegionDownloadState::Active)`, + * Note that the resulting region will be in an inactive download state; to + * begin downloading resources, call + * `setOfflineRegionDownloadState(OfflineRegionDownloadState::Active)`, * optionally registering an `OfflineRegionObserver` beforehand. */ virtual void createOfflineRegion(const OfflineRegionDefinition& definition, @@ -168,9 +170,9 @@ class DatabaseFileSource : public FileSource { /** * Retrieve the current status of the region. The query will be executed - * asynchronously and the results passed to the given callback, which will be - * executed on the database thread; it is the responsibility of the SDK bindings - * to re-execute a user-provided callback on the main thread. + * asynchronously and the results passed to the given callback, which will + * be executed on the database thread; it is the responsibility of the SDK + * bindings to re-execute a user-provided callback on the main thread. */ virtual void getOfflineRegionStatus(const OfflineRegion&, std::function)>) const; @@ -199,36 +201,38 @@ class DatabaseFileSource : public FileSource { std::function)>); /** - * Remove an offline region from the database and perform any resources evictions - * necessary as a result. + * Remove an offline region from the database and perform any resources + * evictions necessary as a result. * - * Eviction works by removing the least-recently requested resources not also required - * by other regions, until the database shrinks below a certain size. + * Eviction works by removing the least-recently requested resources not + * also required by other regions, until the database shrinks below a + * certain size. * - * Note that this method takes ownership of the input, reflecting the fact that once - * region deletion is initiated, it is not legal to perform further actions with the - * region. + * Note that this method takes ownership of the input, reflecting the fact + * that once region deletion is initiated, it is not legal to perform + * further actions with the region. * - * Note that this operation can be potentially slow if packing the database occurs - * automatically (see runPackDatabaseAutomatically() and packDatabase()). + * Note that this operation can be potentially slow if packing the database + * occurs automatically (see runPackDatabaseAutomatically() and + * packDatabase()). * - * When the operation is complete or encounters an error, the given callback will be - * executed on the database thread; it is the responsibility of the SDK bindings - * to re-execute a user-provided callback on the main thread. + * When the operation is complete or encounters an error, the given callback + * will be executed on the database thread; it is the responsibility of the + * SDK bindings to re-execute a user-provided callback on the main thread. */ virtual void deleteOfflineRegion(const OfflineRegion&, std::function); /** - * Invalidate all the tiles from an offline region forcing Mapbox GL to revalidate - * the tiles with the server before using. This is more efficient than deleting the - * offline region and downloading it again because if the data on the cache matches - * the server, no new data gets transmitted. + * Invalidate all the tiles from an offline region forcing Mapbox GL to + * revalidate the tiles with the server before using. This is more efficient + * than deleting the offline region and downloading it again because if the + * data on the cache matches the server, no new data gets transmitted. */ virtual void invalidateOfflineRegion(const OfflineRegion&, std::function); /** - * Changing or bypassing this limit without permission from Mapbox is prohibited - * by the Mapbox Terms of Service. + * Changing or bypassing this limit without permission from Mapbox is + * prohibited by the Mapbox Terms of Service. */ virtual void setOfflineMapboxTileCountLimit(uint64_t) const; diff --git a/include/mbgl/storage/file_source.hpp b/include/mbgl/storage/file_source.hpp index a5e95ce8d45..ccfdc2b2ce2 100644 --- a/include/mbgl/storage/file_source.hpp +++ b/include/mbgl/storage/file_source.hpp @@ -37,13 +37,13 @@ class FileSource { FileSource& operator=(const FileSource&) = delete; virtual ~FileSource() = default; - using Callback = std::function; + using Callback = std::function; - /// Request a resource. The callback will be called asynchronously, in the same - /// thread as the request was made. This thread must have an active RunLoop. The - /// request may be cancelled before completion by releasing the returned AsyncRequest. - /// If the request is cancelled before the callback is executed, the callback will - /// not be executed. + /// Request a resource. The callback will be called asynchronously, in the + /// same thread as the request was made. This thread must have an active + /// RunLoop. The request may be cancelled before completion by releasing the + /// returned AsyncRequest. If the request is cancelled before the callback + /// is executed, the callback will not be executed. virtual std::unique_ptr request(const Resource&, Callback) = 0; /// Allows to forward response from one source to another. @@ -53,10 +53,11 @@ class FileSource { // NOLINTNEXTLINE(performance-unnecessary-value-param) virtual void forward(const Resource&, const Response&, std::function) {} - /// When a file source supports consulting a local cache only, it must return true. - /// Cache-only requests are requests that aren't as urgent, but could be useful, e.g. - /// to cover part of the map while loading. The FileSource should only do cheap actions to - /// retrieve the data, e.g. load it from a cache, but not from the internet. + /// When a file source supports consulting a local cache only, it must + /// return true. Cache-only requests are requests that aren't as urgent, but + /// could be useful, e.g. to cover part of the map while loading. The + /// FileSource should only do cheap actions to retrieve the data, e.g. load + /// it from a cache, but not from the internet. virtual bool supportsCacheOnlyRequests() const { return false; } /// Checks whether a resource could be requested from this file source. @@ -112,8 +113,8 @@ constexpr const char* MAX_CONCURRENT_REQUESTS_KEY = "max-concurrent-requests"; // Properties that may be supported by database file sources: -/// Property to set database mode. When set, database opens in read-only mode; database opens in read-write-create mode -/// otherwise. type: bool +/// Property to set database mode. When set, database opens in read-only mode; +/// database opens in read-write-create mode otherwise. type: bool constexpr const char* READ_ONLY_MODE_KEY = "read-only-mode"; } // namespace mbgl diff --git a/include/mbgl/storage/file_source_manager.hpp b/include/mbgl/storage/file_source_manager.hpp index dd78eb319d9..b6ef59c09b3 100644 --- a/include/mbgl/storage/file_source_manager.hpp +++ b/include/mbgl/storage/file_source_manager.hpp @@ -28,17 +28,19 @@ class FileSourceManager { static FileSourceManager* get() noexcept; // Returns shared instance of a file source for (type, options) tuple. - // Creates new instance via registered factory if needed. If new instance cannot be - // created, nullptr would be returned. - [[nodiscard]] std::shared_ptr getFileSource(FileSourceType, const ResourceOptions&, const ClientOptions& = ClientOptions()) noexcept; - - // Registers file source factory for a provided FileSourceType type. If factory for the - // same type was already registered, will unregister previously registered factory. - // Provided factory must not be null. + // Creates new instance via registered factory if needed. If new instance + // cannot be created, nullptr would be returned. + [[nodiscard]] std::shared_ptr getFileSource(FileSourceType, + const ResourceOptions&, + const ClientOptions& = ClientOptions()) noexcept; + + // Registers file source factory for a provided FileSourceType type. If + // factory for the same type was already registered, will unregister + // previously registered factory. Provided factory must not be null. virtual void registerFileSourceFactory(FileSourceType, FileSourceFactory&&) noexcept; - // Unregisters file source factory. If there are no registered factories for a FileSourceType - // invocation has no effect. + // Unregisters file source factory. If there are no registered factories for + // a FileSourceType invocation has no effect. virtual FileSourceFactory unRegisterFileSourceFactory(FileSourceType) noexcept; protected: diff --git a/include/mbgl/storage/offline.hpp b/include/mbgl/storage/offline.hpp index 77ad3e31d5a..5f0d9fccd53 100644 --- a/include/mbgl/storage/offline.hpp +++ b/include/mbgl/storage/offline.hpp @@ -16,8 +16,8 @@ namespace mbgl { class TileID; /* - * An offline region defined by a style URL, geographic bounding box, zoom range, and - * device pixel ratio. + * An offline region defined by a style URL, geographic bounding box, zoom + * range, and device pixel ratio. * * Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom. * @@ -52,7 +52,12 @@ class OfflineTilePyramidRegionDefinition { */ class OfflineGeometryRegionDefinition { public: - OfflineGeometryRegionDefinition(std::string styleURL, Geometry, double minZoom, double maxZoom, float pixelRatio, bool includeIdeographs); + OfflineGeometryRegionDefinition(std::string styleURL, + Geometry, + double minZoom, + double maxZoom, + float pixelRatio, + bool includeIdeographs); /* Private */ std::string styleURL; @@ -75,11 +80,12 @@ std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition&); OfflineRegionDefinition decodeOfflineRegionDefinition(const std::string&); /* - * Arbitrary binary region metadata. The contents are opaque to the mbgl implementation; - * it just stores and retrieves a BLOB. SDK bindings should leave the interpretation of - * this data up to the application; they _should not_ enforce a higher-level data format. - * In the future we want offline database to be portable across target platforms, and a - * platform-specific metadata format would prevent that. + * Arbitrary binary region metadata. The contents are opaque to the mbgl + * implementation; it just stores and retrieves a BLOB. SDK bindings should + * leave the interpretation of this data up to the application; they _should + * not_ enforce a higher-level data format. In the future we want offline + * database to be portable across target platforms, and a platform-specific + * metadata format would prevent that. */ using OfflineRegionMetadata = std::vector; @@ -116,14 +122,14 @@ class OfflineRegionStatus { uint64_t completedResourceCount = 0; /** - * The cumulative size, in bytes, of all resources (inclusive of tiles) that have - * been fully downloaded. + * The cumulative size, in bytes, of all resources (inclusive of tiles) that + * have been fully downloaded. */ uint64_t completedResourceSize = 0; /** - * The number of tiles that are known to be required for this region. This is a - * subset of `completedResourceCount`. + * The number of tiles that are known to be required for this region. This + * is a subset of `completedResourceCount`. */ uint64_t completedTileCount = 0; @@ -133,15 +139,15 @@ class OfflineRegionStatus { uint64_t requiredTileCount = 0; /** - * The cumulative size, in bytes, of all tiles that have been fully downloaded. - * This is a subset of `completedResourceSize`. + * The cumulative size, in bytes, of all tiles that have been fully + * downloaded. This is a subset of `completedResourceSize`. */ uint64_t completedTileSize = 0; /** - * The number of resources that are known to be required for this region. See the - * documentation for `requiredResourceCountIsPrecise` for an important caveat - * about this number. + * The number of resources that are known to be required for this region. + * See the documentation for `requiredResourceCountIsPrecise` for an + * important caveat about this number. */ uint64_t requiredResourceCount = 0; @@ -156,9 +162,7 @@ class OfflineRegionStatus { */ bool requiredResourceCountIsPrecise = false; - bool complete() const { - return completedResourceCount >= requiredResourceCount; - } + bool complete() const { return completedResourceCount >= requiredResourceCount; } }; /* @@ -175,35 +179,36 @@ class OfflineRegionObserver { * of OfflineRegionStatus. * * Note that this method will be executed on the database thread; it is the - * responsibility of the SDK bindings to wrap this object in an interface that - * re-executes the user-provided implementation on the main thread. + * responsibility of the SDK bindings to wrap this object in an interface + * that re-executes the user-provided implementation on the main thread. */ virtual void statusChanged(OfflineRegionStatus) {} /* - * Implement this method to be notified of errors encountered while downloading - * regional resources. Such errors may be recoverable; for example the implementation - * will attempt to re-request failed resources based on an exponential backoff - * algorithm, or when it detects that network access has been restored. + * Implement this method to be notified of errors encountered while + * downloading regional resources. Such errors may be recoverable; for + * example the implementation will attempt to re-request failed resources + * based on an exponential backoff algorithm, or when it detects that + * network access has been restored. * * Note that this method will be executed on the database thread; it is the - * responsibility of the SDK bindings to wrap this object in an interface that - * re-executes the user-provided implementation on the main thread. + * responsibility of the SDK bindings to wrap this object in an interface + * that re-executes the user-provided implementation on the main thread. */ virtual void responseError(Response::Error) {} // NOLINT(performance-unnecessary-value-param) /* - * Implement this method to be notified when the limit on the number of Mapbox - * tiles stored for offline regions has been reached. + * Implement this method to be notified when the limit on the number of + * Mapbox tiles stored for offline regions has been reached. * - * Once the limit has been reached, the SDK will not download further offline - * tiles from Mapbox APIs until existing tiles have been removed. + * Once the limit has been reached, the SDK will not download further + * offline tiles from Mapbox APIs until existing tiles have been removed. * * This limit does not apply to non-Mapbox tile sources. * * Note that this method will be executed on the database thread; it is the - * responsibility of the SDK bindings to wrap this object in an interface that - * re-executes the user-provided implementation on the main thread. + * responsibility of the SDK bindings to wrap this object in an interface + * that re-executes the user-provided implementation on the main thread. */ virtual void mapboxTileCountLimitExceeded(uint64_t /* limit */) {} }; @@ -220,9 +225,7 @@ class OfflineRegion { private: friend class OfflineDatabase; - OfflineRegion(int64_t id, - OfflineRegionDefinition, - OfflineRegionMetadata); + OfflineRegion(int64_t id, OfflineRegionDefinition, OfflineRegionMetadata); int64_t id; OfflineRegionDefinition definition; diff --git a/include/mbgl/storage/resource.hpp b/include/mbgl/storage/resource.hpp index 580d2696278..114bd2f7640 100644 --- a/include/mbgl/storage/resource.hpp +++ b/include/mbgl/storage/resource.hpp @@ -33,7 +33,10 @@ class Resource { Offline }; - enum class StoragePolicy : bool { Permanent, Volatile }; + enum class StoragePolicy : bool { + Permanent, + Volatile + }; struct TileData { std::string urlTemplate; @@ -44,13 +47,13 @@ class Resource { }; enum class LoadingMethod : uint8_t { - None = 0b00, - Cache = 0b01, - Network = 0b10, + None = 0b00, + Cache = 0b01, + Network = 0b10, - CacheOnly = Cache, + CacheOnly = Cache, NetworkOnly = Network, - All = Cache | Network, + All = Cache | Network, }; Resource(Kind kind_, @@ -60,8 +63,7 @@ class Resource { : kind(kind_), loadingMethod(loadingMethod_), url(std::move(url_)), - tileData(std::move(tileData_)) { - } + tileData(std::move(tileData_)) {} void setPriority(Priority p) { priority = p; } void setUsage(Usage u) { usage = u; } @@ -86,8 +88,8 @@ class Resource { Kind kind; LoadingMethod loadingMethod; - Usage usage{ Usage::Online }; - Priority priority{ Priority::Regular }; + Usage usage{Usage::Online}; + Priority priority{Priority::Regular}; std::string url; // Includes auxiliary data if this is a tile request. diff --git a/include/mbgl/storage/resource_options.hpp b/include/mbgl/storage/resource_options.hpp index 2b14c2bd396..bb5619c7048 100644 --- a/include/mbgl/storage/resource_options.hpp +++ b/include/mbgl/storage/resource_options.hpp @@ -24,7 +24,8 @@ class ResourceOptions final { ResourceOptions clone() const; /** - * @brief Sets the Mapbox access token - see https://docs.mapbox.com/help/how-mapbox-works/access-tokens/ for details. + * @brief Sets the Mapbox access token - see + * https://docs.mapbox.com/help/how-mapbox-works/access-tokens/ for details. * * @param token Mapbox access token. * @return ResourceOptions for chaining options together. diff --git a/include/mbgl/storage/response.hpp b/include/mbgl/storage/response.hpp index 7516c7944f1..a8d9bb0283d 100644 --- a/include/mbgl/storage/response.hpp +++ b/include/mbgl/storage/response.hpp @@ -19,15 +19,15 @@ class Response { // When this object is empty, the response was successful. std::unique_ptr error; - // This is set to true for 204 Not Modified responses, and, for backward compatibility, - // for 404 Not Found responses for tiles. + // This is set to true for 204 Not Modified responses, and, for backward + // compatibility, for 404 Not Found responses for tiles. bool noContent = false; // This is set to true for 304 Not Modified responses. bool notModified = false; - // This is set to true when the server requested that no expired resources be used by - // specifying "Cache-Control: must-revalidate". + // This is set to true when the server requested that no expired resources + // be used by specifying "Cache-Control: must-revalidate". bool mustRevalidate = false; // The actual data of the response. Present only for non-error, non-notModified responses. @@ -37,15 +37,11 @@ class Response { std::optional expires; std::optional etag; - bool isFresh() const { - return expires ? *expires > util::now() : !error; - } + bool isFresh() const { return expires ? *expires > util::now() : !error; } - // Indicates whether we are allowed to use this response according to HTTP caching rules. - // It may or may not be stale. - bool isUsable() const { - return !mustRevalidate || (expires && *expires > util::now()); - } + // Indicates whether we are allowed to use this response according to HTTP + // caching rules. It may or may not be stale. + bool isUsable() const { return !mustRevalidate || (expires && *expires > util::now()); } }; class Response::Error { @@ -59,8 +55,8 @@ class Response::Error { Other = 6, } reason = Reason::Other; - // An error message from the request handler, e.g. a server message or a system message - // informing the user about the reason for the failure. + // An error message from the request handler, e.g. a server message or a + // system message informing the user about the reason for the failure. std::string message; std::optional retryAfter; diff --git a/include/mbgl/style/color_ramp_property_value.hpp b/include/mbgl/style/color_ramp_property_value.hpp index cae06e15796..192ff2bb2f2 100644 --- a/include/mbgl/style/color_ramp_property_value.hpp +++ b/include/mbgl/style/color_ramp_property_value.hpp @@ -24,14 +24,18 @@ class ColorRampPropertyValue { } public: - ColorRampPropertyValue() : value(nullptr) {} - ColorRampPropertyValue(std::shared_ptr value_) : value(std::move(value_)) {} + ColorRampPropertyValue() + : value(nullptr) {} + ColorRampPropertyValue(std::shared_ptr value_) + : value(std::move(value_)) {} bool isUndefined() const { return value == nullptr; } // noop, needed for batch evaluation of paint property values to compile template - Color evaluate(const Evaluator&, TimePoint = {}) const { return {}; } + Color evaluate(const Evaluator&, TimePoint = {}) const { + return {}; + } Color evaluate(double rampEvaluationParameter) const { const auto result = value->evaluate(expression::EvaluationContext({}, nullptr, {rampEvaluationParameter})); @@ -44,6 +48,5 @@ class ColorRampPropertyValue { const expression::Expression& getExpression() const { return *value; } }; - } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/conversion.hpp b/include/mbgl/style/conversion.hpp index 29af9fac911..e289d1f7884 100644 --- a/include/mbgl/style/conversion.hpp +++ b/include/mbgl/style/conversion.hpp @@ -6,11 +6,14 @@ namespace mbgl { namespace style { namespace conversion { -// This is a forward-declaration only header intended to minimize dependencies and to improve -// compilation speed. In order to specialize implementations and get access to the actual -// implementation, include . +// This is a forward-declaration only header intended to minimize dependencies +// and to improve compilation speed. In order to specialize implementations and +// get access to the actual implementation, include +// . -struct Error { std::string message; }; +struct Error { + std::string message; +}; template class ConversionTraits; @@ -26,4 +29,3 @@ struct ValueFactory; } // namespace conversion } // namespace style } // namespace mbgl - diff --git a/include/mbgl/style/conversion/color_ramp_property_value.hpp b/include/mbgl/style/conversion/color_ramp_property_value.hpp index 59ff13932ee..aa19f7ca2c9 100644 --- a/include/mbgl/style/conversion/color_ramp_property_value.hpp +++ b/include/mbgl/style/conversion/color_ramp_property_value.hpp @@ -9,7 +9,10 @@ namespace conversion { template <> struct Converter { - std::optional operator()(const Convertible& value, Error& error, bool /* allowDataExpressions */ = false, bool /* convertTokens */ = false) const; + std::optional operator()(const Convertible& value, + Error& error, + bool /* allowDataExpressions */ = false, + bool /* convertTokens */ = false) const; }; } // namespace conversion diff --git a/include/mbgl/style/conversion/coordinate.hpp b/include/mbgl/style/conversion/coordinate.hpp index 13a992d2e5f..c32e0b38ea2 100644 --- a/include/mbgl/style/conversion/coordinate.hpp +++ b/include/mbgl/style/conversion/coordinate.hpp @@ -8,11 +8,11 @@ namespace mbgl { namespace style { namespace conversion { - -template<> + +template <> struct Converter { public: - std::optional operator() (const Convertible& value, Error& error) const; + std::optional operator()(const Convertible& value, Error& error) const; }; } // namespace conversion diff --git a/include/mbgl/style/conversion/function.hpp b/include/mbgl/style/conversion/function.hpp index 6e9375ff15c..2b707122c5a 100644 --- a/include/mbgl/style/conversion/function.hpp +++ b/include/mbgl/style/conversion/function.hpp @@ -17,10 +17,15 @@ std::unique_ptr convertTokenStringToFormatExpression(con std::unique_ptr convertTokenStringToImageExpression(const std::string&); std::unique_ptr convertTokenStringToExpression(const std::string&); -std::optional> convertFunctionToExpression(expression::type::Type, const Convertible&, Error&, bool convertTokens); +std::optional> convertFunctionToExpression(expression::type::Type, + const Convertible&, + Error&, + bool convertTokens); template -std::optional> convertFunctionToExpression(const Convertible& value, Error& error, bool convertTokens); +std::optional> convertFunctionToExpression(const Convertible& value, + Error& error, + bool convertTokens); } // namespace conversion } // namespace style diff --git a/include/mbgl/style/conversion/property_value.hpp b/include/mbgl/style/conversion/property_value.hpp index 75829919bc2..bcc174a91b6 100644 --- a/include/mbgl/style/conversion/property_value.hpp +++ b/include/mbgl/style/conversion/property_value.hpp @@ -18,7 +18,10 @@ namespace conversion { template struct Converter> { - std::optional> operator()(const Convertible& value, Error& error, bool allowDataExpressions, bool convertTokens) const; + std::optional> operator()(const Convertible& value, + Error& error, + bool allowDataExpressions, + bool convertTokens) const; template PropertyValue maybeConvertTokens(const S& t) const { @@ -26,20 +29,19 @@ struct Converter> { }; PropertyValue maybeConvertTokens(const std::string& t) const { - return hasTokens(t) - ? PropertyValue(PropertyExpression(convertTokenStringToExpression(t))) - : PropertyValue(t); + return hasTokens(t) ? PropertyValue(PropertyExpression(convertTokenStringToExpression(t))) + : PropertyValue(t); } - + PropertyValue maybeConvertTokens(const expression::Formatted& t) const { // This only works with a single-section `Formatted` created automatically // by parsing a plain-text `text-field` property. // Token conversion happens later than the initial string->Formatted conversion // General purpose `format` expressions with embedded tokens are not supported const std::string& firstUnformattedSection = t.sections[0].text; - return hasTokens(firstUnformattedSection) - ? PropertyValue(PropertyExpression(convertTokenStringToFormatExpression(firstUnformattedSection))) - : PropertyValue(t); + return hasTokens(firstUnformattedSection) ? PropertyValue(PropertyExpression( + convertTokenStringToFormatExpression(firstUnformattedSection))) + : PropertyValue(t); } PropertyValue maybeConvertTokens(const expression::Image& image) const { @@ -51,7 +53,10 @@ struct Converter> { template <> struct Converter>, void> { - std::optional>> operator()(const Convertible& value, Error& error, bool, bool) const; + std::optional>> operator()(const Convertible& value, + Error& error, + bool, + bool) const; }; } // namespace conversion } // namespace style diff --git a/include/mbgl/style/conversion/source.hpp b/include/mbgl/style/conversion/source.hpp index 10d06ee665a..6e8c81db4ed 100644 --- a/include/mbgl/style/conversion/source.hpp +++ b/include/mbgl/style/conversion/source.hpp @@ -13,7 +13,9 @@ namespace conversion { template <> struct Converter> { public: - std::optional> operator()(const Convertible& value, Error& error, const std::string& id) const; + std::optional> operator()(const Convertible& value, + Error& error, + const std::string& id) const; }; } // namespace conversion diff --git a/include/mbgl/style/conversion_impl.hpp b/include/mbgl/style/conversion_impl.hpp index 94960d27dae..69215712dde 100644 --- a/include/mbgl/style/conversion_impl.hpp +++ b/include/mbgl/style/conversion_impl.hpp @@ -23,8 +23,9 @@ namespace mbgl { namespace style { /** - The `conversion` namespace defines conversions from JSON structures conforming to the schema defined by - the MapLibre %Style Specification, to the various C++ types that form the C++ model of that domain: + The `conversion` namespace defines conversions from JSON structures + conforming to the schema defined by the MapLibre %Style Specification, to the + various C++ types that form the C++ model of that domain: * `std::unique_ptr` * `std::unique_ptr` @@ -36,57 +37,74 @@ namespace style { template std::optional convert(const Convertible& input, Error& error); - Where `T` is one of the above types. If the conversion fails, the result is empty, and the - error parameter includes diagnostic text suitable for presentation to a library user. Otherwise, - a filled optional is returned. + Where `T` is one of the above types. If the conversion fails, the result is + empty, and the error parameter includes diagnostic text suitable for + presentation to a library user. Otherwise, a filled optional is returned. - `Convertible` is a type that encapsulates a special form of polymorphism over various underlying types that - can serve as input to the conversion algorithm. For instance, on macOS, we need to support - conversion from both RapidJSON types, and a JSON structure represented with `NSArray`/`NSDictionary`/etc. - On Qt, we need to support conversion from RapidJSON types and QVariant. + `Convertible` is a type that encapsulates a special form of polymorphism over + various underlying types that can serve as input to the conversion algorithm. + For instance, on macOS, we need to support conversion from both RapidJSON + types, and a JSON structure represented with `NSArray`/`NSDictionary`/etc. On + Qt, we need to support conversion from RapidJSON types and QVariant. We don't want to use traditional forms of polymorphism to accomplish this: - * Compile time polymorphism using a template parameter for the actual value type leads to - excessive code bloat and long compile times. - * Runtime polymorphism using virtual methods requires extra heap allocation and ubiquitous - use of std::unique_ptr, unsuitable for this performance-sensitive code. + * Compile time polymorphism using a template parameter for the actual value + type leads to excessive code bloat and long compile times. + * Runtime polymorphism using virtual methods requires extra heap allocation + and ubiquitous use of std::unique_ptr, unsuitable for this + performance-sensitive code. - Therefore, we're using a custom implementation of runtime polymorphism where we manually create and - dispatch through a table of function pointers (vtable), while keeping the storage for any of the possible - underlying types inline on the stack, using `std::aligned_storage`. + Therefore, we're using a custom implementation of runtime polymorphism where + we manually create and dispatch through a table of function pointers + (vtable), while keeping the storage for any of the possible underlying types + inline on the stack, using `std::aligned_storage`. - For a given underlying type T, an explicit specialization of `ConversionTraits` must be provided. This - specialization must provide the following static methods: + For a given underlying type T, an explicit specialization of + `ConversionTraits` must be provided. This specialization must provide the + following static methods: - * `isUndefined(v)` -- returns a boolean indication whether `v` is undefined or a JSON null + * `isUndefined(v)` -- returns a boolean indication whether `v` is + undefined or a JSON null - * `isArray(v)` -- returns a boolean indicating whether `v` represents a JSON array + * `isArray(v)` -- returns a boolean indicating whether `v` represents a + JSON array * `arrayLength(v)` -- called only if `isArray(v)`; returns a size_t length * `arrayMember(v)` -- called only if `isArray(v)`; returns `V` or `V&` - * `isObject(v)` -- returns a boolean indicating whether `v` represents a JSON object - * `objectMember(v, name)` -- called only if `isObject(v)`; `name` is `const char *`; return value: - * is true when evaluated in a boolean context iff the named member exists + * `isObject(v)` -- returns a boolean indicating whether `v` represents a + JSON object + * `objectMember(v, name)` -- called only if `isObject(v)`; `name` is + `const char *`; return value: + * is true when evaluated in a boolean context iff the named member + exists * is convertable to a `V` or `V&` when dereferenced - * `eachMember(v, [] (const std::string&, const V&) -> std::optional {...})` -- called - only if `isObject(v)`; calls the provided lambda once for each key and value of the object; - short-circuits if any call returns an `Error` - - * `toBool(v)` -- returns `optional`, absence indicating `v` is not a JSON boolean - * `toNumber(v)` -- returns `optional`, absence indicating `v` is not a JSON number - * `toDouble(v)` -- returns `optional`, absence indicating `v` is not a JSON number - * `toString(v)` -- returns `optional`, absence indicating `v` is not a JSON string - * `toValue(v)` -- returns `optional`, a variant type, for generic conversion, - absence indicating `v` is not a boolean, number, or string. Numbers should be converted to - unsigned integer, signed integer, or floating point, in descending preference. - - In addition, the type T must be move-constructable. And finally, `Convertible::Storage`, a typedef for - `std::aligned_storage_t`, must be large enough to satisfy the memory requirements for any of the - possible underlying types. (A static assert will fail if this is not the case.) - - `Convertible` itself is movable, but not copyable. A moved-from `Convertible` is in an invalid state; - you must not do anything with it except let it go out of scope. + * `eachMember(v, [] (const std::string&, const V&) -> std::optional + {...})` -- called only if `isObject(v)`; calls the provided lambda once for + each key and value of the object; short-circuits if any call returns an + `Error` + + * `toBool(v)` -- returns `optional`, absence indicating `v` is not a + JSON boolean + * `toNumber(v)` -- returns `optional`, absence indicating `v` is + not a JSON number + * `toDouble(v)` -- returns `optional`, absence indicating `v` is + not a JSON number + * `toString(v)` -- returns `optional`, absence indicating `v` + is not a JSON string + * `toValue(v)` -- returns `optional`, a variant type, for generic + conversion, absence indicating `v` is not a boolean, number, or string. + Numbers should be converted to unsigned integer, signed integer, or floating + point, in descending preference. + + In addition, the type T must be move-constructable. And finally, + `Convertible::Storage`, a typedef for `std::aligned_storage_t`, must be large + enough to satisfy the memory requirements for any of the possible underlying + types. (A static assert will fail if this is not the case.) + + `Convertible` itself is movable, but not copyable. A moved-from `Convertible` + is in an invalid state; you must not do anything with it except let it go out + of scope. */ namespace conversion { @@ -97,19 +115,19 @@ class Convertible { public: template // NOLINTNEXTLINE(bugprone-forwarding-reference-overload) - Convertible(T&& value) : vtable(vtableForType>()) { + Convertible(T&& value) + : vtable(vtableForType>()) { static_assert(sizeof(Storage) >= sizeof(std::decay_t), "Storage must be large enough to hold value type"); new (static_cast(&storage)) std::decay_t(std::forward(value)); } - Convertible(Convertible&& v) noexcept : vtable(v.vtable) { + Convertible(Convertible&& v) noexcept + : vtable(v.vtable) { // NOLINTNEXTLINE(performance-move-const-arg) vtable->move(std::move(v.storage), storage); } - ~Convertible() { - vtable->destroy(storage); - } + ~Convertible() { vtable->destroy(storage); } Convertible& operator=(Convertible&& v) noexcept { if (this != &v) { @@ -121,8 +139,8 @@ class Convertible { return *this; } - Convertible() = delete; - Convertible(const Convertible&) = delete; + Convertible() = delete; + Convertible(const Convertible&) = delete; Convertible& operator=(const Convertible&) = delete; friend inline bool isUndefined(const Convertible& v) { @@ -150,12 +168,13 @@ class Convertible { return v.vtable->isObject(v.storage); } - friend inline std::optional objectMember(const Convertible& v, const char * name) { + friend inline std::optional objectMember(const Convertible& v, const char* name) { assert(v.vtable); return v.vtable->objectMember(v.storage, name); } - friend inline std::optional eachMember(const Convertible& v, const std::function (const std::string&, const Convertible&)>& fn) { + friend inline std::optional eachMember( + const Convertible& v, const std::function(const std::string&, const Convertible&)>& fn) { assert(v.vtable); return v.vtable->eachMember(v.storage, fn); } @@ -204,33 +223,36 @@ class Convertible { #endif struct VTable { - void (*move) (Storage&& src, Storage& dest); - void (*destroy) (Storage&); + void (*move)(Storage&& src, Storage& dest); + void (*destroy)(Storage&); - bool (*isUndefined) (const Storage&); + bool (*isUndefined)(const Storage&); - bool (*isArray) (const Storage&); - std::size_t (*arrayLength) (const Storage&); - Convertible (*arrayMember) (const Storage&, std::size_t); + bool (*isArray)(const Storage&); + std::size_t (*arrayLength)(const Storage&); + Convertible (*arrayMember)(const Storage&, std::size_t); - bool (*isObject) (const Storage&); - std::optional (*objectMember) (const Storage&, const char *); - std::optional (*eachMember) (const Storage&, const std::function (const std::string&, const Convertible&)>&); + bool (*isObject)(const Storage&); + std::optional (*objectMember)(const Storage&, const char*); + std::optional (*eachMember)( + const Storage&, const std::function(const std::string&, const Convertible&)>&); - std::optional (*toBool) (const Storage&); - std::optional (*toNumber) (const Storage&); - std::optional (*toDouble) (const Storage&); - std::optional (*toString) (const Storage&); - std::optional (*toValue) (const Storage&); + std::optional (*toBool)(const Storage&); + std::optional (*toNumber)(const Storage&); + std::optional (*toDouble)(const Storage&); + std::optional (*toString)(const Storage&); + std::optional (*toValue)(const Storage&); // https://github.com/mapbox/mapbox-gl-native/issues/5623 - std::optional (*toGeoJSON) (const Storage&, Error&); + std::optional (*toGeoJSON)(const Storage&, Error&); }; - // Extracted this function from the table below to work around a GCC bug with differing - // visibility settings for capturing lambdas: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80947 + // Extracted this function from the table below to work around a GCC bug + // with differing visibility settings for capturing lambdas: + // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80947 template - static auto vtableEachMember(const Storage& s, const std::function(const std::string&, const Convertible&)>& fn) { + static auto vtableEachMember( + const Storage& s, const std::function(const std::string&, const Convertible&)>& fn) { return ConversionTraits::eachMember(reinterpret_cast(s), [&](const std::string& k, T&& v) { return fn(k, Convertible(std::move(v))); }); @@ -240,28 +262,16 @@ class Convertible { static VTable* vtableForType() { using Traits = ConversionTraits; static VTable vtable = { - [] (Storage&& src, Storage& dest) { - new (static_cast(&dest)) T(reinterpret_cast(src)); - }, - [] (Storage& s) { - reinterpret_cast(s).~T(); - }, - [] (const Storage& s) { - return Traits::isUndefined(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::isArray(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::arrayLength(reinterpret_cast(s)); - }, - [] (const Storage& s, std::size_t i) { + [](Storage&& src, Storage& dest) { new (static_cast(&dest)) T(reinterpret_cast(src)); }, + [](Storage& s) { reinterpret_cast(s).~T(); }, + [](const Storage& s) { return Traits::isUndefined(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::isArray(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::arrayLength(reinterpret_cast(s)); }, + [](const Storage& s, std::size_t i) { return Convertible(Traits::arrayMember(reinterpret_cast(s), i)); }, - [] (const Storage& s) { - return Traits::isObject(reinterpret_cast(s)); - }, - [] (const Storage& s, const char * key) { + [](const Storage& s) { return Traits::isObject(reinterpret_cast(s)); }, + [](const Storage& s, const char* key) { std::optional member = Traits::objectMember(reinterpret_cast(s), key); if (member) { return std::optional(Convertible(std::move(*member))); @@ -270,25 +280,14 @@ class Convertible { } }, vtableEachMember, - [] (const Storage& s) { - return Traits::toBool(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toNumber(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toDouble(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toString(reinterpret_cast(s)); - }, - [] (const Storage& s) { - return Traits::toValue(reinterpret_cast(s)); - }, - [] (const Storage& s, Error& err) { + [](const Storage& s) { return Traits::toBool(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toNumber(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toDouble(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toString(reinterpret_cast(s)); }, + [](const Storage& s) { return Traits::toValue(reinterpret_cast(s)); }, + [](const Storage& s, Error& err) { return Traits::toGeoJSON(reinterpret_cast(s), err); - } - }; + }}; return &vtable; } @@ -296,8 +295,8 @@ class Convertible { Storage storage; }; -template -std::optional convert(const Convertible& value, Error& error, Args&&...args) { +template +std::optional convert(const Convertible& value, Error& error, Args&&... args) { return Converter()(value, error, std::forward(args)...); } diff --git a/include/mbgl/style/expression/assertion.hpp b/include/mbgl/style/expression/assertion.hpp index 8921cf92138..aee30724cd8 100644 --- a/include/mbgl/style/expression/assertion.hpp +++ b/include/mbgl/style/expression/assertion.hpp @@ -11,7 +11,7 @@ namespace mbgl { namespace style { namespace expression { -class Assertion : public Expression { +class Assertion : public Expression { public: Assertion(type::Type type_, std::vector> inputs_); @@ -19,11 +19,11 @@ class Assertion : public Expression { EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - + bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; - + mbgl::Value serialize() const override; std::string getOperator() const override; diff --git a/include/mbgl/style/expression/at.hpp b/include/mbgl/style/expression/at.hpp index c208b4712b2..ab6a6247f33 100644 --- a/include/mbgl/style/expression/at.hpp +++ b/include/mbgl/style/expression/at.hpp @@ -10,14 +10,13 @@ namespace expression { class At : public Expression { public: - At(std::unique_ptr index_, std::unique_ptr input_) : - Expression(Kind::At, input_->getType().get().itemType), - index(std::move(index_)), - input(std::move(input_)) - {} - + At(std::unique_ptr index_, std::unique_ptr input_) + : Expression(Kind::At, input_->getType().get().itemType), + index(std::move(index_)), + input(std::move(input_)) {} + static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); - + EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; @@ -29,10 +28,8 @@ class At : public Expression { return false; } - std::vector> possibleOutputs() const override { - return { std::nullopt }; - } - + std::vector> possibleOutputs() const override { return {std::nullopt}; } + std::string getOperator() const override { return "at"; } private: diff --git a/include/mbgl/style/expression/boolean_operator.hpp b/include/mbgl/style/expression/boolean_operator.hpp index cb67fb4aba0..442de3d278f 100644 --- a/include/mbgl/style/expression/boolean_operator.hpp +++ b/include/mbgl/style/expression/boolean_operator.hpp @@ -9,12 +9,11 @@ namespace mbgl { namespace style { namespace expression { -class Any : public Expression { +class Any : public Expression { public: - Any(std::vector> inputs_) : - Expression(Kind::Any, type::Boolean), - inputs(std::move(inputs_)) - {} + Any(std::vector> inputs_) + : Expression(Kind::Any, type::Boolean), + inputs(std::move(inputs_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); @@ -24,16 +23,16 @@ class Any : public Expression { std::vector> possibleOutputs() const override; std::string getOperator() const override { return "any"; } + private: std::vector> inputs; }; -class All : public Expression { +class All : public Expression { public: - All(std::vector> inputs_) : - Expression(Kind::All, type::Boolean), - inputs(std::move(inputs_)) - {} + All(std::vector> inputs_) + : Expression(Kind::All, type::Boolean), + inputs(std::move(inputs_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); @@ -43,6 +42,7 @@ class All : public Expression { std::vector> possibleOutputs() const override; std::string getOperator() const override { return "all"; } + private: std::vector> inputs; }; diff --git a/include/mbgl/style/expression/case.hpp b/include/mbgl/style/expression/case.hpp index 8785049b1e3..93a4edc87c7 100644 --- a/include/mbgl/style/expression/case.hpp +++ b/include/mbgl/style/expression/case.hpp @@ -17,18 +17,21 @@ class Case : public Expression { using Branch = std::pair, std::unique_ptr>; Case(type::Type type_, std::vector branches_, std::unique_ptr otherwise_) - : Expression(Kind::Case, std::move(type_)), branches(std::move(branches_)), otherwise(std::move(otherwise_)) {} + : Expression(Kind::Case, std::move(type_)), + branches(std::move(branches_)), + otherwise(std::move(otherwise_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - + bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; std::string getOperator() const override { return "case"; } + private: std::vector branches; std::unique_ptr otherwise; diff --git a/include/mbgl/style/expression/coalesce.hpp b/include/mbgl/style/expression/coalesce.hpp index 3273fbfc652..044ba7b1629 100644 --- a/include/mbgl/style/expression/coalesce.hpp +++ b/include/mbgl/style/expression/coalesce.hpp @@ -14,31 +14,26 @@ namespace expression { class Coalesce : public Expression { public: using Args = std::vector>; - Coalesce(const type::Type& type_, Args args_) : - Expression(Kind::Coalesce, type_), - args(std::move(args_)) - {} + Coalesce(const type::Type& type_, Args args_) + : Expression(Kind::Coalesce, type_), + args(std::move(args_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); - EvaluationResult evaluate(const EvaluationContext& params) const override; - + void eachChild(const std::function& visit) const override; bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; - std::size_t getLength() const { - return args.size(); - } - - Expression* getChild(std::size_t i) const { - return args.at(i).get(); - } - + std::size_t getLength() const { return args.size(); } + + Expression* getChild(std::size_t i) const { return args.at(i).get(); } + std::string getOperator() const override { return "coalesce"; } + private: Args args; }; diff --git a/include/mbgl/style/expression/coercion.hpp b/include/mbgl/style/expression/coercion.hpp index df70182ab87..124a1176bf6 100644 --- a/include/mbgl/style/expression/coercion.hpp +++ b/include/mbgl/style/expression/coercion.hpp @@ -10,7 +10,7 @@ namespace mbgl { namespace style { namespace expression { -class Coercion : public Expression { +class Coercion : public Expression { public: Coercion(type::Type type_, std::vector> inputs_); @@ -18,7 +18,7 @@ class Coercion : public Expression { EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - + mbgl::Value serialize() const override; bool operator==(const Expression& e) const override; @@ -26,12 +26,12 @@ class Coercion : public Expression { std::vector> possibleOutputs() const override; std::string getOperator() const override; + private: - EvaluationResult (*coerceSingleValue) (const Value& v); + EvaluationResult (*coerceSingleValue)(const Value& v); std::vector> inputs; }; } // namespace expression } // namespace style } // namespace mbgl - diff --git a/include/mbgl/style/expression/collator.hpp b/include/mbgl/style/expression/collator.hpp index eb82f8f1739..9c94f8109eb 100644 --- a/include/mbgl/style/expression/collator.hpp +++ b/include/mbgl/style/expression/collator.hpp @@ -18,6 +18,7 @@ class Collator { int compare(const std::string& lhs, const std::string& rhs) const; std::string resolvedLocale() const; + private: platform::Collator collator; }; diff --git a/include/mbgl/style/expression/collator_expression.hpp b/include/mbgl/style/expression/collator_expression.hpp index 7889f8a7c8e..3b51f32eae9 100644 --- a/include/mbgl/style/expression/collator_expression.hpp +++ b/include/mbgl/style/expression/collator_expression.hpp @@ -13,8 +13,8 @@ namespace expression { class CollatorExpression : public Expression { public: CollatorExpression(std::unique_ptr caseSensitive, - std::unique_ptr diacriticSensitive, - std::optional> locale); + std::unique_ptr diacriticSensitive, + std::optional> locale); EvaluationResult evaluate(const EvaluationContext&) const override; static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); @@ -24,15 +24,17 @@ class CollatorExpression : public Expression { bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override { - // Technically the set of possible outputs is the combinatoric set of Collators produced - // by all possibleOutputs of locale/caseSensitive/diacriticSensitive - // But for the primary use of Collators in comparison operators, we ignore the Collator's - // possibleOutputs anyway, so we can get away with leaving this undefined for now. - return { std::nullopt }; + // Technically the set of possible outputs is the combinatoric set of + // Collators produced by all possibleOutputs of + // locale/caseSensitive/diacriticSensitive But for the primary use of + // Collators in comparison operators, we ignore the Collator's possibleOutputs + // anyway, so we can get away with leaving this undefined for now. + return {std::nullopt}; } mbgl::Value serialize() const override; std::string getOperator() const override { return "collator"; } + private: std::unique_ptr caseSensitive; std::unique_ptr diacriticSensitive; diff --git a/include/mbgl/style/expression/comparison.hpp b/include/mbgl/style/expression/comparison.hpp index 09f461537ba..ccd08c46e32 100644 --- a/include/mbgl/style/expression/comparison.hpp +++ b/include/mbgl/style/expression/comparison.hpp @@ -17,10 +17,7 @@ class BasicComparison : public Expression { public: using CompareFunctionType = bool (*)(const Value&, const Value&); - BasicComparison( - std::string op, - std::unique_ptr lhs, - std::unique_ptr rhs); + BasicComparison(std::string op, std::unique_ptr lhs, std::unique_ptr rhs); void eachChild(const std::function& visit) const override; bool operator==(const Expression&) const override; @@ -40,11 +37,10 @@ class CollatorComparison : public Expression { public: using CompareFunctionType = bool (*)(const std::string&, const std::string&, const Collator&); - CollatorComparison( - std::string op, - std::unique_ptr lhs, - std::unique_ptr rhs, - std::unique_ptr collator); + CollatorComparison(std::string op, + std::unique_ptr lhs, + std::unique_ptr rhs, + std::unique_ptr collator); void eachChild(const std::function& visit) const override; bool operator==(const Expression&) const override; @@ -61,8 +57,6 @@ class CollatorComparison : public Expression { bool needsRuntimeTypeCheck; }; - - } // namespace expression } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/expression/distance.hpp b/include/mbgl/style/expression/distance.hpp index 670ae11cd75..3fc44b9a2bf 100644 --- a/include/mbgl/style/expression/distance.hpp +++ b/include/mbgl/style/expression/distance.hpp @@ -2,8 +2,8 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4244) -#pragma warning(disable: 4267) +#pragma warning(disable : 4244) +#pragma warning(disable : 4267) #endif #include diff --git a/include/mbgl/style/expression/dsl.hpp b/include/mbgl/style/expression/dsl.hpp index c31dd2b4f61..a928ebdbf7e 100644 --- a/include/mbgl/style/expression/dsl.hpp +++ b/include/mbgl/style/expression/dsl.hpp @@ -12,14 +12,15 @@ namespace mbgl { namespace style { namespace expression { -/// This convenience API does little to no expression validation or type-checking, and is intended for -/// use only by test and other non-production code. +/// This convenience API does little to no expression validation or +/// type-checking, and is intended for use only by test and other non-production +/// code. namespace dsl { template std::vector> vec(Args... args) { std::vector> result; - util::ignore({ (result.push_back(std::move(args)), 0)... }); + util::ignore({(result.push_back(std::move(args)), 0)...}); return result; } @@ -35,19 +36,13 @@ std::unique_ptr literal(std::initializer_list value); std::unique_ptr assertion(const type::Type&, std::unique_ptr, std::unique_ptr def = nullptr); -std::unique_ptr number(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr string(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr boolean(std::unique_ptr, - std::unique_ptr def = nullptr); - -std::unique_ptr toColor(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr toString(std::unique_ptr, - std::unique_ptr def = nullptr); -std::unique_ptr toFormatted(std::unique_ptr, - std::unique_ptr def = nullptr); +std::unique_ptr number(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr string(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr boolean(std::unique_ptr, std::unique_ptr def = nullptr); + +std::unique_ptr toColor(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr toString(std::unique_ptr, std::unique_ptr def = nullptr); +std::unique_ptr toFormatted(std::unique_ptr, std::unique_ptr def = nullptr); std::unique_ptr toImage(std::unique_ptr, std::unique_ptr def = nullptr); std::unique_ptr get(const char* value); @@ -63,7 +58,8 @@ std::unique_ptr lt(std::unique_ptr, std::unique_ptr step(std::unique_ptr input, std::unique_ptr output0, - double input1, std::unique_ptr output1); + double input1, + std::unique_ptr output1); Interpolator linear(); Interpolator exponential(double base); @@ -71,18 +67,24 @@ Interpolator cubicBezier(double x1, double y1, double x2, double y2); std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr input, - double input1, std::unique_ptr output1); + double input1, + std::unique_ptr output1); std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2); + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2); std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2, - double input3, std::unique_ptr output3); + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2, + double input3, + std::unique_ptr output3); std::unique_ptr concat(std::vector> inputs); diff --git a/include/mbgl/style/expression/error.hpp b/include/mbgl/style/expression/error.hpp index 7cf76f285e8..bcb6e739749 100644 --- a/include/mbgl/style/expression/error.hpp +++ b/include/mbgl/style/expression/error.hpp @@ -10,23 +10,17 @@ namespace expression { class Error : public Expression { public: - Error(std::string message_) + Error(std::string message_) : Expression(Kind::Error, type::Error), message(std::move(message_)) {} void eachChild(const std::function&) const override {} - bool operator==(const Expression& e) const override { - return e.getKind() == Kind::Error; - } + bool operator==(const Expression& e) const override { return e.getKind() == Kind::Error; } - EvaluationResult evaluate(const EvaluationContext&) const override { - return EvaluationError{message}; - } + EvaluationResult evaluate(const EvaluationContext&) const override { return EvaluationError{message}; } - std::vector> possibleOutputs() const override { - return {}; - } + std::vector> possibleOutputs() const override { return {}; } std::string getOperator() const override { return "error"; } diff --git a/include/mbgl/style/expression/expression.hpp b/include/mbgl/style/expression/expression.hpp index e620a8f26af..be677fdcea0 100644 --- a/include/mbgl/style/expression/expression.hpp +++ b/include/mbgl/style/expression/expression.hpp @@ -27,17 +27,26 @@ class EvaluationError { class EvaluationContext { public: EvaluationContext() = default; - explicit EvaluationContext(float zoom_) : zoom(zoom_) {} - explicit EvaluationContext(GeometryTileFeature const * feature_) : feature(feature_) {} - EvaluationContext(float zoom_, GeometryTileFeature const* feature_) : zoom(zoom_), feature(feature_) {} - EvaluationContext(std::optional accumulated_, GeometryTileFeature const * feature_) : - accumulated(std::move(accumulated_)), feature(feature_) - {} + explicit EvaluationContext(float zoom_) + : zoom(zoom_) {} + explicit EvaluationContext(GeometryTileFeature const* feature_) + : feature(feature_) {} + EvaluationContext(float zoom_, GeometryTileFeature const* feature_) + : zoom(zoom_), + feature(feature_) {} + EvaluationContext(std::optional accumulated_, GeometryTileFeature const* feature_) + : accumulated(std::move(accumulated_)), + feature(feature_) {} EvaluationContext(float zoom_, GeometryTileFeature const* feature_, const FeatureState* state_) - : zoom(zoom_), feature(feature_), featureState(state_) {} - EvaluationContext(std::optional zoom_, GeometryTileFeature const * feature_, std::optional colorRampParameter_) : - zoom(std::move(zoom_)), feature(feature_), colorRampParameter(std::move(colorRampParameter_)) - {} + : zoom(zoom_), + feature(feature_), + featureState(state_) {} + EvaluationContext(std::optional zoom_, + GeometryTileFeature const* feature_, + std::optional colorRampParameter_) + : zoom(std::move(zoom_)), + feature(feature_), + colorRampParameter(std::move(colorRampParameter_)) {} EvaluationContext& withFormattedSection(const Value* formattedSection_) noexcept { formattedSection = formattedSection_; @@ -75,38 +84,37 @@ class Result : private variant { public: using variant::variant; using Value = T; - + Result() = default; template - VARIANT_INLINE Result(U&& val) : variant(val) {} - - explicit operator bool () const { - return this->template is(); - } - + VARIANT_INLINE Result(U&& val) + : variant(val) {} + + explicit operator bool() const { return this->template is(); } + // optional does some type trait magic for this one, so this might // be problematic as is. const T* operator->() const { assert(this->template is()); return std::addressof(this->template get()); } - + T* operator->() { assert(this->template is()); return std::addressof(this->template get()); } - + T& operator*() { assert(this->template is()); return this->template get(); } - + const T& operator*() const { assert(this->template is()); return this->template get(); } - + const EvaluationError& error() const { assert(this->template is()); return this->template get(); @@ -116,17 +124,14 @@ class Result : private variant { class EvaluationResult : public Result { public: using Result::Result; // NOLINT - + EvaluationResult() = default; - EvaluationResult(const std::array& arr) : - Result(toExpressionValue(arr)) - {} - + EvaluationResult(const std::array& arr) + : Result(toExpressionValue(arr)) {} + // used only for the special (private) "error" expression - EvaluationResult(const type::ErrorType&) { - assert(false); - } + EvaluationResult(const type::ErrorType&) { assert(false); } }; /** @@ -137,12 +142,12 @@ class EvaluationResult : public Result { inferring the argument and output from a simple function (const T0& arg0, const T1& arg1, ...) -> Result where T0, T1, ..., U are member types of mbgl::style::expression::Value. - + The other Expression subclasses (Let, Curve, Match, etc.) exist in order to implement expressions that need specialized parsing, type checking, or evaluation logic that can't be handled by CompoundExpression's inference mechanism. - + Each Expression subclass also provides a static ParseResult ExpressionClass::parse(const V&, ParsingContext), which handles parsing a style-spec JSON representation of the expression. @@ -178,20 +183,22 @@ enum class Kind : int32_t { class Expression { public: - Expression(Kind kind_, type::Type type_) : kind(kind_), type(std::move(type_)) {} + Expression(Kind kind_, type::Type type_) + : kind(kind_), + type(std::move(type_)) {} virtual ~Expression() = default; - + virtual EvaluationResult evaluate(const EvaluationContext& params) const = 0; virtual void eachChild(const std::function&) const = 0; virtual bool operator==(const Expression&) const = 0; - bool operator!=(const Expression& rhs) const { - return !operator==(rhs); - } + bool operator!=(const Expression& rhs) const { return !operator==(rhs); } Kind getKind() const { return kind; }; type::Type getType() const { return type; }; - EvaluationResult evaluate(std::optional zoom, const Feature& feature, std::optional colorRampParameter) const; + EvaluationResult evaluate(std::optional zoom, + const Feature& feature, + std::optional colorRampParameter) const; EvaluationResult evaluate(std::optional zoom, const Feature& feature, std::optional colorRampParameter, @@ -204,52 +211,49 @@ class Expression { EvaluationResult evaluate(std::optional accumulated, const Feature& feature) const; /** - * Statically analyze the expression, attempting to enumerate possible outputs. Returns - * an array of values plus the sentinel null optional value, used to indicate that the - * complete set of outputs is statically undecidable. + * Statically analyze the expression, attempting to enumerate possible + * outputs. Returns an array of values plus the sentinel null optional + * value, used to indicate that the complete set of outputs is statically + * undecidable. */ virtual std::vector> possibleOutputs() const = 0; - + virtual mbgl::Value serialize() const { std::vector serialized; serialized.emplace_back(getOperator()); - eachChild([&](const Expression &child) { - serialized.emplace_back(child.serialize()); - }); + eachChild([&](const Expression& child) { serialized.emplace_back(child.serialize()); }); return serialized; }; - + virtual std::string getOperator() const = 0; protected: template static bool childrenEqual(const T& lhs, const T& rhs) { if (lhs.size() != rhs.size()) return false; - for (auto leftChild = lhs.begin(), rightChild = rhs.begin(); - leftChild != lhs.end(); - leftChild++, rightChild++) - { - if (!Expression::childEqual(*leftChild, *rightChild)) return false; - } - return true; + for (auto leftChild = lhs.begin(), rightChild = rhs.begin(); leftChild != lhs.end(); + leftChild++, rightChild++) { + if (!Expression::childEqual(*leftChild, *rightChild)) return false; + } + return true; } - + static bool childEqual(const std::unique_ptr& lhs, const std::unique_ptr& rhs) { return *lhs == *rhs; } - + template static bool childEqual(const std::pair>& lhs, const std::pair>& rhs) { return lhs.first == rhs.first && *(lhs.second) == *(rhs.second); } - + template static bool childEqual(const std::pair>& lhs, const std::pair>& rhs) { return lhs.first == rhs.first && *(lhs.second) == *(rhs.second); } - + static bool childEqual(const std::pair, std::unique_ptr>& lhs, const std::pair, std::unique_ptr>& rhs) { return *(lhs.first) == *(rhs.first) && *(lhs.second) == *(rhs.second); diff --git a/include/mbgl/style/expression/format_expression.hpp b/include/mbgl/style/expression/format_expression.hpp index e6fec2e2bc6..edbd3ffe3a7 100644 --- a/include/mbgl/style/expression/format_expression.hpp +++ b/include/mbgl/style/expression/format_expression.hpp @@ -22,32 +22,33 @@ struct FormatExpressionSection { std::optional> textFont; std::optional> textColor; }; - + class FormatExpression final : public Expression { public: explicit FormatExpression(std::vector sections); - + EvaluationResult evaluate(const EvaluationContext&) const override; static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); - + void eachChild(const std::function&) const override; - + bool operator==(const Expression& e) const override; - + std::vector> possibleOutputs() const override { // Technically the combinatoric set of all children // Usually, this.text will be undefined anyway - return { std::nullopt }; + return {std::nullopt}; } - + const std::vector& getSections() const { return sections; } mbgl::Value serialize() const override; std::string getOperator() const override { return "format"; } + private: std::vector sections; }; - + } // namespace expression } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/expression/format_section_override.hpp b/include/mbgl/style/expression/format_section_override.hpp index 2fec025da36..c7698b0da7a 100644 --- a/include/mbgl/style/expression/format_section_override.hpp +++ b/include/mbgl/style/expression/format_section_override.hpp @@ -7,21 +7,19 @@ namespace mbgl { namespace style { namespace expression { -template +template class FormatSectionOverride final : public Expression { public: FormatSectionOverride(const type::Type& type_, - PossiblyEvaluatedPropertyValue defaultValue_, - std::string propertyName_) : - Expression(Kind::FormatSectionOverride, type_), - defaultValue(std::move(defaultValue_)), - propertyName(std::move(propertyName_)) - {} + PossiblyEvaluatedPropertyValue defaultValue_, + std::string propertyName_) + : Expression(Kind::FormatSectionOverride, type_), + defaultValue(std::move(defaultValue_)), + propertyName(std::move(propertyName_)) {} EvaluationResult evaluate(const EvaluationContext& context) const final { using Object = std::unordered_map; - if (context.formattedSection && - context.formattedSection->is()) { + if (context.formattedSection && context.formattedSection->is()) { const auto& section = context.formattedSection->get(); if (section.find(propertyName) != section.end()) { return section.at(propertyName); @@ -29,14 +27,12 @@ class FormatSectionOverride final : public Expression { } return defaultValue.match( - [&context] (const style::PropertyExpression& e) { return e.getExpression().evaluate(context); }, - [] (const T& t) -> EvaluationResult { return t; } - ); + [&context](const style::PropertyExpression& e) { return e.getExpression().evaluate(context); }, + [](const T& t) -> EvaluationResult { return t; }); } void eachChild(const std::function& fn) const final { - defaultValue.match([&fn] (const style::PropertyExpression& e) { fn(e.getExpression()); }, - [] (const T&) {}); + defaultValue.match([&fn](const style::PropertyExpression& e) { fn(e.getExpression()); }, [](const T&) {}); } bool operator==(const Expression& e) const final { @@ -49,30 +45,22 @@ class FormatSectionOverride final : public Expression { // Check that default values or property expressions are equal. return defaultValue.match( - [other] (const style::PropertyExpression& thisExpr) { - return other->defaultValue.match([&thisExpr] (const style::PropertyExpression& otherExpr) { - return thisExpr == otherExpr; - }, - [] (const T&) { - return false; - }); - }, - [other] (const T& thisValue) { - return other->defaultValue.match([&thisValue] (const T& otherValue) { - return thisValue == otherValue; - }, - [] (const style::PropertyExpression&) { - return false; - }); - }); + [other](const style::PropertyExpression& thisExpr) { + return other->defaultValue.match( + [&thisExpr](const style::PropertyExpression& otherExpr) { return thisExpr == otherExpr; }, + [](const T&) { return false; }); + }, + [other](const T& thisValue) { + return other->defaultValue.match( + [&thisValue](const T& otherValue) { return thisValue == otherValue; }, + [](const style::PropertyExpression&) { return false; }); + }); } return false; } - std::vector> possibleOutputs() const final { - return {std::nullopt}; - } + std::vector> possibleOutputs() const final { return {std::nullopt}; } std::string getOperator() const final { return "format-section-override"; } diff --git a/include/mbgl/style/expression/formatted.hpp b/include/mbgl/style/expression/formatted.hpp index 55c6ca65399..75184948c2d 100644 --- a/include/mbgl/style/expression/formatted.hpp +++ b/include/mbgl/style/expression/formatted.hpp @@ -27,7 +27,8 @@ struct FormattedSection { fontStack(std::move(fontStack_)), textColor(std::move(textColor_)) {} - explicit FormattedSection(Image image_) : image(std::move(image_)) {} + explicit FormattedSection(Image image_) + : image(std::move(image_)) {} std::string text; std::optional image; @@ -43,13 +44,12 @@ class Formatted { Formatted(const char* plainU8String) { sections.emplace_back(std::string(plainU8String), std::nullopt, std::nullopt, std::nullopt); } - + Formatted(std::vector sections_) - : sections(std::move(sections_)) - {} - - bool operator==(const Formatted& ) const; - + : sections(std::move(sections_)) {} + + bool operator==(const Formatted&) const; + std::string toString() const; mbgl::Value toObject() const; @@ -57,9 +57,9 @@ class Formatted { std::vector sections; }; - + } // namespace expression - + namespace conversion { template <> @@ -74,6 +74,6 @@ struct ValueFactory { }; } // namespace conversion - + } // namespace style } // namespace mbgl diff --git a/include/mbgl/style/expression/interpolate.hpp b/include/mbgl/style/expression/interpolate.hpp index 0035da713ae..d2715a0eb3c 100644 --- a/include/mbgl/style/expression/interpolate.hpp +++ b/include/mbgl/style/expression/interpolate.hpp @@ -39,25 +39,21 @@ class Interpolate : public Expression { visit(stop.first, *stop.second); } } - + // Return the smallest range of stops that covers the interval [lower, upper] Range getCoveringStops(const double lower, const double upper) const { return ::mbgl::style::expression::getCoveringStops(stops, lower, upper); } - + double interpolationFactor(const Range& inputLevels, const double inputValue) const { return interpolator.match( - [&](const auto& interp) { return interp.interpolationFactor(inputLevels, inputValue); } - ); + [&](const auto& interp) { return interp.interpolationFactor(inputLevels, inputValue); }); } bool operator==(const Expression& e) const override { if (e.getKind() == Kind::Interpolate) { auto rhs = static_cast(&e); - if (interpolator != rhs->interpolator || - *input != *(rhs->input) || - stops.size() != rhs->stops.size()) - { + if (interpolator != rhs->interpolator || *input != *(rhs->input) || stops.size() != rhs->stops.size()) { return false; } diff --git a/include/mbgl/style/expression/interpolator.hpp b/include/mbgl/style/expression/interpolator.hpp index bd68e5c2f06..18840b3778a 100644 --- a/include/mbgl/style/expression/interpolator.hpp +++ b/include/mbgl/style/expression/interpolator.hpp @@ -10,42 +10,36 @@ namespace expression { class ExponentialInterpolator { public: - ExponentialInterpolator(double base_) : base(base_) {} + ExponentialInterpolator(double base_) + : base(base_) {} double base; - + double interpolationFactor(const Range& inputLevels, const double input) const { - return util::interpolationFactor(static_cast(base), - Range { - static_cast(inputLevels.min), - static_cast(inputLevels.max) - }, - static_cast(input)); - } - - bool operator==(const ExponentialInterpolator& rhs) const { - return base == rhs.base; + return util::interpolationFactor( + static_cast(base), + Range{static_cast(inputLevels.min), static_cast(inputLevels.max)}, + static_cast(input)); } + + bool operator==(const ExponentialInterpolator& rhs) const { return base == rhs.base; } }; class CubicBezierInterpolator { public: - CubicBezierInterpolator(double x1_, double y1_, double x2_, double y2_) : ub(x1_, y1_, x2_, y2_) {} - + CubicBezierInterpolator(double x1_, double y1_, double x2_, double y2_) + : ub(x1_, y1_, x2_, y2_) {} + double interpolationFactor(const Range& inputLevels, const double input) const { - return ub.solve(util::interpolationFactor(1.0f, - Range { - static_cast(inputLevels.min), - static_cast(inputLevels.max) - }, - static_cast(input)), + return ub.solve(util::interpolationFactor( + 1.0f, + Range{static_cast(inputLevels.min), static_cast(inputLevels.max)}, + static_cast(input)), 1e-6); } - - bool operator==(const CubicBezierInterpolator& rhs) const { - return ub == rhs.ub; - } - + + bool operator==(const CubicBezierInterpolator& rhs) const { return ub == rhs.ub; } + util::UnitBezier ub; }; diff --git a/include/mbgl/style/expression/let.hpp b/include/mbgl/style/expression/let.hpp index 5e24c0a4ee9..5b37139df4f 100644 --- a/include/mbgl/style/expression/let.hpp +++ b/include/mbgl/style/expression/let.hpp @@ -15,15 +15,14 @@ namespace expression { class Let : public Expression { public: using Bindings = std::map>; - - Let(Bindings bindings_, std::unique_ptr result_) : - Expression(Kind::Let, result_->getType()), - bindings(std::move(bindings_)), - result(std::move(result_)) - {} - + + Let(Bindings bindings_, std::unique_ptr result_) + : Expression(Kind::Let, result_->getType()), + bindings(std::move(bindings_)), + result(std::move(result_)) {} + static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); - + EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; @@ -37,12 +36,11 @@ class Let : public Expression { std::vector> possibleOutputs() const override; - Expression* getResult() const { - return result.get(); - } + Expression* getResult() const { return result.get(); } mbgl::Value serialize() const override; std::string getOperator() const override { return "let"; } + private: Bindings bindings; std::unique_ptr result; @@ -51,7 +49,9 @@ class Let : public Expression { class Var : public Expression { public: Var(std::string name_, std::shared_ptr value_) - : Expression(Kind::Var, value_->getType()), name(std::move(name_)), value(std::move(value_)) {} + : Expression(Kind::Var, value_->getType()), + name(std::move(name_)), + value(std::move(value_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); @@ -70,9 +70,9 @@ class Var : public Expression { mbgl::Value serialize() const override; std::string getOperator() const override { return "var"; } - + const std::shared_ptr& getBoundExpression() const { return value; } - + private: std::string name; std::shared_ptr value; diff --git a/include/mbgl/style/expression/literal.hpp b/include/mbgl/style/expression/literal.hpp index c22e41b3798..857f07cefa9 100644 --- a/include/mbgl/style/expression/literal.hpp +++ b/include/mbgl/style/expression/literal.hpp @@ -12,19 +12,20 @@ namespace expression { class Literal : public Expression { public: - Literal(const Value& value_) : Expression(Kind::Literal, typeOf(value_)), value(value_) {} + Literal(const Value& value_) + : Expression(Kind::Literal, typeOf(value_)), + value(value_) {} Literal(const type::Array& type_, std::vector value_) - : Expression(Kind::Literal, type_), value(std::move(value_)) {} + : Expression(Kind::Literal, type_), + value(std::move(value_)) {} + + EvaluationResult evaluate(const EvaluationContext&) const override { return value; } - EvaluationResult evaluate(const EvaluationContext&) const override { - return value; - } - static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); void eachChild(const std::function&) const override {} - + bool operator==(const Expression& e) const override { if (e.getKind() == Kind::Literal) { auto rhs = static_cast(&e); @@ -33,13 +34,9 @@ class Literal : public Expression { return false; } - std::vector> possibleOutputs() const override { - return {{ value }}; - } - - Value getValue() const { - return value; - } + std::vector> possibleOutputs() const override { return {{value}}; } + + Value getValue() const { return value; } mbgl::Value serialize() const override; std::string getOperator() const override { return "literal"; } diff --git a/include/mbgl/style/expression/match.hpp b/include/mbgl/style/expression/match.hpp index c94b0bd447a..ed59705fcae 100644 --- a/include/mbgl/style/expression/match.hpp +++ b/include/mbgl/style/expression/match.hpp @@ -31,9 +31,10 @@ class Match : public Expression { bool operator==(const Expression& e) const override; std::vector> possibleOutputs() const override; - + mbgl::Value serialize() const override; std::string getOperator() const override { return "match"; } + private: std::unique_ptr input; Branches branches; diff --git a/include/mbgl/style/expression/parsing_context.hpp b/include/mbgl/style/expression/parsing_context.hpp index 16ce844acdb..01b47bcdfde 100644 --- a/include/mbgl/style/expression/parsing_context.hpp +++ b/include/mbgl/style/expression/parsing_context.hpp @@ -31,14 +31,13 @@ namespace detail { class Scope { public: - Scope(const std::map>& bindings_, std::shared_ptr parent_ = nullptr) : - bindings(bindings_), - parent(std::move(parent_)) - {} + Scope(const std::map>& bindings_, std::shared_ptr parent_ = nullptr) + : bindings(bindings_), + parent(std::move(parent_)) {} const std::map>& bindings; std::shared_ptr parent; - + std::optional> get(const std::string& name) { auto it = bindings.find(name); if (it != bindings.end()) { @@ -54,17 +53,20 @@ class Scope { } // namespace detail /** - Controls the annotation behavior of the parser when encountering an expression - whose type is not a subtype of the expected type. The default behavior, used - when optional is a nullopt, is as follows: + Controls the annotation behavior of the parser when encountering an + expression whose type is not a subtype of the expected type. The default + behavior, used when optional is a nullopt, is as + follows: - When we expect a number, string, boolean, or array but have a value, wrap it in an assertion. - When we expect a color or formatted string, but have a string or value, wrap it in a coercion. - Otherwise, we do static type-checking. + When we expect a number, string, boolean, or array but have a value, wrap it + in an assertion. When we expect a color or formatted string, but have a + string or value, wrap it in a coercion. Otherwise, we do static + type-checking. These behaviors are overridable for: * The "coalesce" operator, which needs to omit type annotations. - * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion. + * String-valued properties (e.g. `text-field`), where coercion is more + convenient than assertion. */ enum class TypeAnnotationOption { coerce, @@ -74,14 +76,16 @@ enum class TypeAnnotationOption { class ParsingContext { public: - ParsingContext() : errors(std::make_shared>()) {} - ParsingContext(std::string key_) : key(std::move(key_)), errors(std::make_shared>()) {} + ParsingContext() + : errors(std::make_shared>()) {} + ParsingContext(std::string key_) + : key(std::move(key_)), + errors(std::make_shared>()) {} explicit ParsingContext(type::Type expected_) : expected(std::move(expected_)), - errors(std::make_shared>()) - {} + errors(std::make_shared>()) {} ParsingContext(ParsingContext&&) = default; - + ParsingContext(const ParsingContext&) = delete; ParsingContext& operator=(const ParsingContext&) = delete; @@ -97,9 +101,9 @@ class ParsingContext { const std::optional& = std::nullopt); /** - Parse the given style-spec JSON value as an expression intended to be used - in a layout or paint property. This entails checking additional constraints - that exist in that context but not, e.g., for filters. + Parse the given style-spec JSON value as an expression intended to be + used in a layout or paint property. This entails checking additional + constraints that exist in that context but not, e.g., for filters. */ ParseResult parseLayerPropertyExpression(const mbgl::style::conversion::Convertible& value); @@ -134,22 +138,20 @@ class ParsingContext { void error(std::string message, std::size_t child) { errors->push_back({std::move(message), key + "[" + util::toString(child) + "]"}); } - + void error(std::string message, std::size_t child, std::size_t grandchild) { errors->push_back( {std::move(message), key + "[" + util::toString(child) + "][" + util::toString(grandchild) + "]"}); } - + void appendErrors(ParsingContext&& ctx) { errors->reserve(errors->size() + ctx.errors->size()); std::move(ctx.errors->begin(), ctx.errors->end(), std::inserter(*errors, errors->end())); ctx.errors->clear(); } - - void clearErrors() { - errors->clear(); - } - + + void clearErrors() { errors->clear(); } + private: ParsingContext(std::string key_, std::shared_ptr> errors_, @@ -158,17 +160,16 @@ class ParsingContext { : key(std::move(key_)), expected(std::move(expected_)), scope(std::move(scope_)), - errors(std::move(errors_)) - {} - - + errors(std::move(errors_)) {} + /** Parse the given style-spec JSON value into an Expression object. Specifically, this function is responsible for determining the expression type (either Literal, or the one named in value[0]) and dispatching to the appropriate ParseXxxx::parse(const V&, ParsingContext) method. */ - ParseResult parse(const mbgl::style::conversion::Convertible& value, const std::optional& = std::nullopt); + ParseResult parse(const mbgl::style::conversion::Convertible& value, + const std::optional& = std::nullopt); std::string key; std::optional expected; diff --git a/include/mbgl/style/expression/type.hpp b/include/mbgl/style/expression/type.hpp index ddd58dbe57b..14f18e225bc 100644 --- a/include/mbgl/style/expression/type.hpp +++ b/include/mbgl/style/expression/type.hpp @@ -61,13 +61,13 @@ struct ValueType { std::string getName() const { return "value"; } bool operator==(const ValueType&) const { return true; } }; - + struct CollatorType { constexpr CollatorType() = default; std::string getName() const { return "collator"; } bool operator==(const CollatorType&) const { return true; } }; - + struct FormattedType { constexpr FormattedType() = default; std::string getName() const { return "formatted"; } @@ -108,9 +108,14 @@ using Type = variant; struct Array { - explicit Array(Type itemType_) : itemType(std::move(itemType_)) {} - Array(Type itemType_, std::size_t N_) : itemType(std::move(itemType_)), N(N_) {} - Array(Type itemType_, std::optional N_) : itemType(std::move(itemType_)), N(std::move(N_)) {} + explicit Array(Type itemType_) + : itemType(std::move(itemType_)) {} + Array(Type itemType_, std::size_t N_) + : itemType(std::move(itemType_)), + N(N_) {} + Array(Type itemType_, std::optional N_) + : itemType(std::move(itemType_)), + N(std::move(N_)) {} std::string getName() const { if (N) { return "array<" + toString(itemType) + ", " + util::toString(*N) + ">"; @@ -122,13 +127,15 @@ struct Array { } bool operator==(const Array& rhs) const { return itemType == rhs.itemType && N == rhs.N; } - + Type itemType; std::optional N; }; - + template -std::string toString(const T& type) { return type.match([&] (const auto& t) { return t.getName(); }); } +std::string toString(const T& type) { + return type.match([&](const auto& t) { return t.getName(); }); +} } // namespace type } // namespace expression diff --git a/include/mbgl/style/expression/value.hpp b/include/mbgl/style/expression/value.hpp index 74af6eedcac..88349a4a526 100644 --- a/include/mbgl/style/expression/value.hpp +++ b/include/mbgl/style/expression/value.hpp @@ -35,22 +35,19 @@ using ValueBase = variant - VARIANT_INLINE Value(T&& val) : ValueBase(val) {} + VARIANT_INLINE Value(T&& val) + : ValueBase(val) {} // Javascript's Number.MAX_SAFE_INTEGER static uint64_t maxSafeInteger() { return 9007199254740991ULL; } - + static bool isSafeInteger(uint64_t x) { return x <= maxSafeInteger(); }; - static bool isSafeInteger(int64_t x) { - return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); - } - static bool isSafeInteger(double x) { - return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); - } - + static bool isSafeInteger(int64_t x) { return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); } + static bool isSafeInteger(double x) { return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); } }; constexpr NullValue Null = NullValue(); @@ -74,9 +71,7 @@ type::Type valueTypeToExpressionType(); template struct ValueConverter { - static Value toExpressionValue(const T& value) { - return Value(value); - } + static Value toExpressionValue(const T& value) { return Value(value); } static std::optional fromExpressionValue(const Value& value) { return value.template is() ? value.template get() : std::optional(); @@ -105,18 +100,14 @@ struct ValueConverter { template struct ValueConverter> { - static type::Type expressionType() { - return type::Array(valueTypeToExpressionType(), N); - } + static type::Type expressionType() { return type::Array(valueTypeToExpressionType(), N); } static Value toExpressionValue(const std::array& value); static std::optional> fromExpressionValue(const Value& value); }; template struct ValueConverter> { - static type::Type expressionType() { - return type::Array(valueTypeToExpressionType()); - } + static type::Type expressionType() { return type::Array(valueTypeToExpressionType()); } static Value toExpressionValue(const std::vector& value); static std::optional> fromExpressionValue(const Value& value); }; @@ -129,7 +120,7 @@ struct ValueConverter { }; template -struct ValueConverter >> { +struct ValueConverter>> { static type::Type expressionType() { return type::String; } static Value toExpressionValue(const T& value); static std::optional fromExpressionValue(const Value& value); diff --git a/include/mbgl/style/filter.hpp b/include/mbgl/style/filter.hpp index 2652c01c3f7..bc6e98ff541 100644 --- a/include/mbgl/style/filter.hpp +++ b/include/mbgl/style/filter.hpp @@ -16,17 +16,19 @@ namespace style { class Filter { public: std::optional> expression; + private: std::optional legacyFilter; + public: Filter() = default; Filter(expression::ParseResult _expression, std::optional _filter = std::nullopt) - : expression(std::move(*_expression)), - legacyFilter(std::move(_filter)){ + : expression(std::move(*_expression)), + legacyFilter(std::move(_filter)) { assert(!expression || *expression != nullptr); } - + bool operator()(const expression::EvaluationContext& context) const; operator bool() const { return expression || legacyFilter; } @@ -38,16 +40,13 @@ class Filter { return *(lhs.expression) == *(rhs.expression); } } - - friend bool operator!=(const Filter& lhs, const Filter& rhs) { - return !(lhs == rhs); - } - + + friend bool operator!=(const Filter& lhs, const Filter& rhs) { return !(lhs == rhs); } + mbgl::Value serialize() const { if (legacyFilter) { return *legacyFilter; - } - else if (expression) { + } else if (expression) { return (**expression).serialize(); } return NullValue(); diff --git a/include/mbgl/style/image.hpp b/include/mbgl/style/image.hpp index 2c40d4b7eaa..30206a740d9 100644 --- a/include/mbgl/style/image.hpp +++ b/include/mbgl/style/image.hpp @@ -65,7 +65,8 @@ class Image { class Impl; Immutable baseImpl; - explicit Image(Immutable baseImpl_) : baseImpl(std::move(baseImpl_)) {} + explicit Image(Immutable baseImpl_) + : baseImpl(std::move(baseImpl_)) {} }; } // namespace style diff --git a/include/mbgl/style/layer.hpp b/include/mbgl/style/layer.hpp index 233755481ae..3f842d59009 100644 --- a/include/mbgl/style/layer.hpp +++ b/include/mbgl/style/layer.hpp @@ -33,58 +33,79 @@ struct LayerTypeInfo { * @brief contains \c Source::Required if the corresponding layer type * requires source. Contains \c Source::NotRequired otherwise. */ - const enum class Source { Required, NotRequired } source; + const enum class Source { + Required, + NotRequired + } source; /** * @brief contains \c Pass3D::Required if the corresponding layer type * requires 3D rendering pass. Contains \c Pass3D::NotRequired otherwise. */ - const enum class Pass3D { Required, NotRequired } pass3d; + const enum class Pass3D { + Required, + NotRequired + } pass3d; /** * @brief contains \c Layout::Required if the corresponding layer type * requires layouting. * contains \c Layout::NotRequired otherwise. */ - const enum class Layout { Required, NotRequired } layout; + const enum class Layout { + Required, + NotRequired + } layout; /** * @brief contains \c FadingTiles::Required if the corresponding layer type * requires rendering on fading tiles. Contains \c FadingTiles::NotRequired otherwise. */ - const enum class FadingTiles { Required, NotRequired } fadingTiles; + const enum class FadingTiles { + Required, + NotRequired + } fadingTiles; /** - * @brief contains \c CrossTileIndex::Required if the corresponding layer type - * requires cross-tile indexing and placement. Contains \c CrossTileIndex::NotRequired otherwise. + * @brief contains \c CrossTileIndex::Required if the corresponding layer + * type requires cross-tile indexing and placement. Contains \c + * CrossTileIndex::NotRequired otherwise. */ - const enum class CrossTileIndex { Required, NotRequired } crossTileIndex; + const enum class CrossTileIndex { + Required, + NotRequired + } crossTileIndex; /** - * @brief contains the Id of the supported tile type. Used for internal checks. - * The contained values correspond to \c Tile::Kind enum. + * @brief contains the Id of the supported tile type. Used for internal + * checks. The contained values correspond to \c Tile::Kind enum. */ - const enum class TileKind : uint8_t { Geometry, Raster, RasterDEM, NotRequired } tileKind; + const enum class TileKind : uint8_t { + Geometry, + Raster, + RasterDEM, + NotRequired + } tileKind; }; /** - * The runtime representation of a [layer](https://www.mapbox.com/mapbox-gl-style-spec/#layers) from the Mapbox Style - * Specification. + * The runtime representation of a [layer](https://www.mapbox.com/mapbox-gl-style-spec/#layers) + * from the Mapbox Style Specification. * - * `Layer` is an abstract base class; concrete derived classes are provided for each layer type. `Layer` contains - * functionality that is common to all layer types: + * `Layer` is an abstract base class; concrete derived classes are provided for + * each layer type. `Layer` contains functionality that is common to all layer types: * * * Runtime type information: type predicates and casting * * Accessors for properties common to all layer types: ID, visibility, etc. * * Cloning and copying * - * All other functionality lives in the derived classes. To instantiate a layer, create an instance of the desired - * type, calling `LayerManager`: + * All other functionality lives in the derived classes. To instantiate a layer, + * create an instance of the desired type, calling `LayerManager`: * * auto circleLayer = LayerManager::get()->createLayer("circle", ...); */ class Layer { public: - Layer(const Layer& ) = delete; + Layer(const Layer&) = delete; Layer& operator=(const Layer&) = delete; virtual ~Layer(); @@ -126,28 +147,25 @@ class Layer { // Create a layer, copying all properties except id and paint properties from this layer. virtual std::unique_ptr cloneRef(const std::string& id) const = 0; - void setObserver(LayerObserver*); - // For use in SDK bindings, which store a reference to a platform-native peer - // object here, so that separately-obtained references to this object share - // identical platform-native peers. + // For use in SDK bindings, which store a reference to a platform-native + // peer object here, so that separately-obtained references to this object + // share identical platform-native peers. mapbox::base::TypeWrapper peer; Layer(Immutable); const LayerTypeInfo* getTypeInfo() const noexcept; - mapbox::base::WeakPtr makeWeakPtr() { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() { return weakFactory.makeWeakPtr(); } protected: virtual Mutable mutableBaseImpl() const = 0; void serializeProperty(Value&, const StyleProperty&, const char* propertyName, bool isPaint) const; virtual std::optional setPropertyInternal(const std::string& name, - const conversion::Convertible& value) = 0; + const conversion::Convertible& value) = 0; LayerObserver* observer; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; private: std::optional setVisibility(const conversion::Convertible& value); diff --git a/include/mbgl/style/layer_properties.hpp b/include/mbgl/style/layer_properties.hpp index de0a0a4e16a..c8e9688aee0 100644 --- a/include/mbgl/style/layer_properties.hpp +++ b/include/mbgl/style/layer_properties.hpp @@ -7,8 +7,9 @@ namespace style { /** * @brief An interface, wrapping evaluated layer properties. - * - * It is an abstract base class; concrete derived classes that hold the actual data are provided for each layer type. + * + * It is an abstract base class; concrete derived classes that hold the actual + * data are provided for each layer type. */ class LayerProperties { public: @@ -20,7 +21,8 @@ class LayerProperties { uint8_t renderPasses = 0u; protected: - LayerProperties(Immutable impl) : baseImpl(std::move(impl)) {} + LayerProperties(Immutable impl) + : baseImpl(std::move(impl)) {} }; template diff --git a/include/mbgl/style/position.hpp b/include/mbgl/style/position.hpp index 43b54cb69d5..88d8d2d7c6f 100644 --- a/include/mbgl/style/position.hpp +++ b/include/mbgl/style/position.hpp @@ -11,18 +11,19 @@ class Position { public: Position() = default; Position(std::array& position_) - : radial(position_[0]), azimuthal(position_[1]), polar(position_[2]) { + : radial(position_[0]), + azimuthal(position_[1]), + polar(position_[2]) { calculateCartesian(); }; friend bool operator==(const Position& lhs, const Position& rhs) { return lhs.radial == rhs.radial && lhs.azimuthal == rhs.azimuthal && lhs.polar == rhs.polar; - // TODO this doesn't address wrapping, which would be better addressed by comparing cartesian coordinates but being calculated floats are ont to be trusted. + // TODO this doesn't address wrapping, which would be better addressed + // by comparing cartesian coordinates but being calculated floats are ont to be trusted. } - friend bool operator!=(const Position& lhs, const Position& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const Position& lhs, const Position& rhs) { return !(lhs == rhs); } std::array getCartesian() const { return {{x, y, z}}; }; @@ -35,7 +36,8 @@ class Position { calculateCartesian(); }; - /// Utility function to be used only during interpolation; this leaves spherical coordinates undefined. + /// Utility function to be used only during interpolation; this leaves + /// spherical coordinates undefined. void setCartesian(std::array& position_) { x = position_[0]; y = position_[1]; @@ -51,8 +53,8 @@ class Position { float z; void calculateCartesian() { - // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2): we - // correct for that here + // We abstract "north"/"up" (compass-wise) to be 0° when really this is + // 90° (π/2): we correct for that here const float _a = util::deg2radf(azimuthal + 90); const float _p = util::deg2radf(polar); diff --git a/include/mbgl/style/property_expression.hpp b/include/mbgl/style/property_expression.hpp index 477e7122482..3e2e7afeb9e 100644 --- a/include/mbgl/style/property_expression.hpp +++ b/include/mbgl/style/property_expression.hpp @@ -42,10 +42,10 @@ template class PropertyExpression final : public PropertyExpressionBase { public: // Second parameter to be used only for conversions from legacy functions. - PropertyExpression(std::unique_ptr expression_, std::optional defaultValue_ = std::nullopt) + PropertyExpression(std::unique_ptr expression_, + std::optional defaultValue_ = std::nullopt) : PropertyExpressionBase(std::move(expression_)), - defaultValue(std::move(defaultValue_)) { - } + defaultValue(std::move(defaultValue_)) {} T evaluate(const expression::EvaluationContext& context, T finalDefaultValue = T()) const { const expression::EvaluationResult result = expression->evaluate(context); @@ -129,8 +129,7 @@ class PropertyExpression final : public PropertyExpressionBase { return expression::fromExpressionValues(expression->possibleOutputs()); } - friend bool operator==(const PropertyExpression& lhs, - const PropertyExpression& rhs) { + friend bool operator==(const PropertyExpression& lhs, const PropertyExpression& rhs) { return *lhs.expression == *rhs.expression; } diff --git a/include/mbgl/style/property_value.hpp b/include/mbgl/style/property_value.hpp index 86812e23013..3071e7d07cc 100644 --- a/include/mbgl/style/property_value.hpp +++ b/include/mbgl/style/property_value.hpp @@ -10,22 +10,13 @@ namespace style { template class PropertyValue { private: - using Value = variant< - Undefined, - T, - PropertyExpression>; + using Value = variant>; Value value; - friend bool operator==(const PropertyValue& lhs, - const PropertyValue& rhs) { - return lhs.value == rhs.value; - } + friend bool operator==(const PropertyValue& lhs, const PropertyValue& rhs) { return lhs.value == rhs.value; } - friend bool operator!=(const PropertyValue& lhs, - const PropertyValue& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const PropertyValue& lhs, const PropertyValue& rhs) { return !(lhs == rhs); } public: PropertyValue() = default; @@ -36,41 +27,27 @@ class PropertyValue { PropertyValue(PropertyExpression expression) : value(std::move(expression)) {} - bool isUndefined() const { - return value.template is(); - } + bool isUndefined() const { return value.template is(); } - bool isConstant() const { - return value.template is(); - } + bool isConstant() const { return value.template is(); } - bool isExpression() const { - return value.template is>(); - } + bool isExpression() const { return value.template is>(); } bool isDataDriven() const { - return value.match( - [] (const Undefined&) { return false; }, - [] (const T&) { return false; }, - [] (const PropertyExpression& fn) { return !fn.isFeatureConstant(); } - ); + return value.match([](const Undefined&) { return false; }, + [](const T&) { return false; }, + [](const PropertyExpression& fn) { return !fn.isFeatureConstant(); }); } bool isZoomConstant() const { - return value.match( - [] (const Undefined&) { return true; }, - [] (const T&) { return true; }, - [] (const PropertyExpression& fn) { return fn.isZoomConstant(); } - ); + return value.match([](const Undefined&) { return true; }, + [](const T&) { return true; }, + [](const PropertyExpression& fn) { return fn.isZoomConstant(); }); } - const T& asConstant() const { - return value.template get(); - } + const T& asConstant() const { return value.template get(); } - const PropertyExpression& asExpression() const { - return value.template get>(); - } + const PropertyExpression& asExpression() const { return value.template get>(); } template auto match(Ts&&... ts) const { diff --git a/include/mbgl/style/rotation.hpp b/include/mbgl/style/rotation.hpp index 96b047c68ce..d17d89243d8 100644 --- a/include/mbgl/style/rotation.hpp +++ b/include/mbgl/style/rotation.hpp @@ -9,7 +9,8 @@ namespace style { class Rotation { public: Rotation() = default; - Rotation(double angle_) : angle(mbgl::util::wrap(angle_, 0, period())) {} + Rotation(double angle_) + : angle(mbgl::util::wrap(angle_, 0, period())) {} constexpr double period() const noexcept { return 360.0; } double getAngle() const noexcept { return angle; } diff --git a/include/mbgl/style/source.hpp b/include/mbgl/style/source.hpp index 9625fbdac2b..93b8d2e33d2 100644 --- a/include/mbgl/style/source.hpp +++ b/include/mbgl/style/source.hpp @@ -25,18 +25,20 @@ class SourceObserver; struct LayerTypeInfo; /** - * The runtime representation of a [source](https://maplibre.org/maplibre-gl-js-docs/style-spec/sources/) - * from the MapLibre Style Specification. + * The runtime representation of a + * [source](https://maplibre.org/maplibre-gl-js-docs/style-spec/sources/) from + * the MapLibre Style Specification. * - * `Source` is an abstract base class; concrete derived classes are provided for each source type. `Source` contains - * functionality that is common to all layer types: + * `Source` is an abstract base class; concrete derived classes are provided for + * each source type. `Source` contains functionality that is common to all layer + * types: * * * Runtime type information: type predicates and casting * * Accessors for properties common to all source types: ID, etc. * * Cloning and copying * - * All other functionality lives in the derived classes. To instantiate a source, create an instance of the desired - * type, passing the ID: + * All other functionality lives in the derived classes. To instantiate a + * source, create an instance of the desired type, passing the ID: * * auto vectorSource = std::make_unique("my-vector-source"); */ @@ -94,15 +96,16 @@ class Source { // Sets a limit for how much a parent tile can be overscaled. // - // When a set of tiles for a current zoom level is being rendered and some of the - // ideal tiles that cover the screen are not yet loaded, parent tile could be - // used instead. This might introduce unwanted rendering side-effects, especially - // for raster tiles that are overscaled multiple times. + // When a set of tiles for a current zoom level is being rendered and some + // of the ideal tiles that cover the screen are not yet loaded, parent tile + // could be used instead. This might introduce unwanted rendering + // side-effects, especially for raster tiles that are overscaled multiple + // times. // - // For example, an overscale factor of 3 would mean that on zoom level 3, the - // minimum zoom level of a parent tile that could be used in place of an ideal - // tile during rendering would be zoom 0. By default, no limit is set, so any - // parent tile may be used. + // For example, an overscale factor of 3 would mean that on zoom level 3, + // the minimum zoom level of a parent tile that could be used in place of an + // ideal tile during rendering would be zoom 0. By default, no limit is set, + // so any parent tile may be used. void setMaxOverscaleFactorForParentTiles(std::optional overscaleFactor) noexcept; std::optional getMaxOverscaleFactorForParentTiles() const noexcept; void dumpDebugLogs() const; @@ -111,9 +114,9 @@ class Source { bool loaded = false; - // For use in SDK bindings, which store a reference to a platform-native peer - // object here, so that separately-obtained references to this object share - // identical platform-native peers. + // For use in SDK bindings, which store a reference to a platform-native + // peer object here, so that separately-obtained references to this object + // share identical platform-native peers. mapbox::base::TypeWrapper peer; virtual mapbox::base::WeakPtr makeWeakPtr() = 0; diff --git a/include/mbgl/style/sources/custom_geometry_source.hpp b/include/mbgl/style/sources/custom_geometry_source.hpp index 90c9d2dfe08..172bf300a7d 100644 --- a/include/mbgl/style/sources/custom_geometry_source.hpp +++ b/include/mbgl/style/sources/custom_geometry_source.hpp @@ -33,9 +33,10 @@ class CustomGeometrySource final : public Source { struct Options { TileFunction fetchTileFunction; TileFunction cancelTileFunction; - Range zoomRange = { 0, 18}; + Range zoomRange = {0, 18}; TileOptions tileOptions; }; + public: CustomGeometrySource(std::string id, const CustomGeometrySource::Options& options); ~CustomGeometrySource() final; @@ -47,9 +48,7 @@ class CustomGeometrySource final : public Source { class Impl; const Impl& impl() const; bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -57,7 +56,7 @@ class CustomGeometrySource final : public Source { private: std::shared_ptr threadPool; std::unique_ptr> loader; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/geojson_source.hpp b/include/mbgl/style/sources/geojson_source.hpp index accb5444935..1759c4fb242 100644 --- a/include/mbgl/style/sources/geojson_source.hpp +++ b/include/mbgl/style/sources/geojson_source.hpp @@ -74,9 +74,7 @@ class GeoJSONSource final : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -85,7 +83,7 @@ class GeoJSONSource final : public Source { std::optional url; std::unique_ptr req; std::shared_ptr threadPool; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/image_source.hpp b/include/mbgl/style/sources/image_source.hpp index aae904a4a38..61429c6ee89 100644 --- a/include/mbgl/style/sources/image_source.hpp +++ b/include/mbgl/style/sources/image_source.hpp @@ -31,9 +31,7 @@ class ImageSource final : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -41,7 +39,7 @@ class ImageSource final : public Source { private: std::optional url; std::unique_ptr req; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/raster_source.hpp b/include/mbgl/style/sources/raster_source.hpp index 486cf7e0bab..11de4eadde3 100644 --- a/include/mbgl/style/sources/raster_source.hpp +++ b/include/mbgl/style/sources/raster_source.hpp @@ -12,7 +12,10 @@ namespace style { class RasterSource : public Source { public: - RasterSource(std::string id, variant urlOrTileset, uint16_t tileSize, SourceType sourceType = SourceType::Raster); + RasterSource(std::string id, + variant urlOrTileset, + uint16_t tileSize, + SourceType sourceType = SourceType::Raster); ~RasterSource() override; const variant& getURLOrTileset() const; @@ -27,9 +30,7 @@ class RasterSource : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() final { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() final { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -37,7 +38,7 @@ class RasterSource : public Source { private: const variant urlOrTileset; std::unique_ptr req; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; }; template <> diff --git a/include/mbgl/style/sources/vector_source.hpp b/include/mbgl/style/sources/vector_source.hpp index 55cdd8de2d7..0adb529a73b 100644 --- a/include/mbgl/style/sources/vector_source.hpp +++ b/include/mbgl/style/sources/vector_source.hpp @@ -12,7 +12,9 @@ namespace style { class VectorSource final : public Source { public: - VectorSource(std::string id, variant urlOrTileset, std::optional maxZoom = std::nullopt, + VectorSource(std::string id, + variant urlOrTileset, + std::optional maxZoom = std::nullopt, std::optional minZoom = std::nullopt); ~VectorSource() final; @@ -26,9 +28,7 @@ class VectorSource final : public Source { bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } protected: Mutable createMutable() const noexcept final; @@ -36,7 +36,7 @@ class VectorSource final : public Source { private: const variant urlOrTileset; std::unique_ptr req; - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtrFactory weakFactory{this}; std::optional maxZoom; std::optional minZoom; }; diff --git a/include/mbgl/style/style.hpp b/include/mbgl/style/style.hpp index 3d987deb901..8d7faab5dc4 100644 --- a/include/mbgl/style/style.hpp +++ b/include/mbgl/style/style.hpp @@ -40,7 +40,7 @@ class Style { void setTransitionOptions(const TransitionOptions&); // Light - Light* getLight(); + Light* getLight(); const Light* getLight() const; void setLight(std::unique_ptr); @@ -51,20 +51,20 @@ class Style { void removeImage(const std::string&); // Sources - std::vector< Source*> getSources(); + std::vector getSources(); std::vector getSources() const; - Source* getSource(const std::string&); + Source* getSource(const std::string&); const Source* getSource(const std::string&) const; void addSource(std::unique_ptr); std::unique_ptr removeSource(const std::string& sourceID); // Layers - std::vector< Layer*> getLayers(); + std::vector getLayers(); std::vector getLayers() const; - Layer* getLayer(const std::string&); + Layer* getLayer(const std::string&); const Layer* getLayer(const std::string&) const; void addLayer(std::unique_ptr, const std::optional& beforeLayerID = std::nullopt); diff --git a/include/mbgl/style/style_property.hpp b/include/mbgl/style/style_property.hpp index fc34078decf..d17d99aca2f 100644 --- a/include/mbgl/style/style_property.hpp +++ b/include/mbgl/style/style_property.hpp @@ -10,8 +10,15 @@ namespace style { */ class StyleProperty { public: - enum class Kind : uint8_t { Undefined, Constant, Expression, Transition }; - StyleProperty(Value value_, Kind kind_) : value(std::move(value_)), kind(kind_) {} + enum class Kind : uint8_t { + Undefined, + Constant, + Expression, + Transition + }; + StyleProperty(Value value_, Kind kind_) + : value(std::move(value_)), + kind(kind_) {} StyleProperty() = default; const Value& getValue() const { return value; } Value& getValue() { return value; } diff --git a/include/mbgl/style/transition_options.hpp b/include/mbgl/style/transition_options.hpp index c5e51267cf7..cc08f467d99 100644 --- a/include/mbgl/style/transition_options.hpp +++ b/include/mbgl/style/transition_options.hpp @@ -23,16 +23,10 @@ class TransitionOptions { enablePlacementTransitions(enablePlacementTransitions_) {} TransitionOptions reverseMerge(const TransitionOptions& defaults) const { - return { - duration ? duration : defaults.duration, - delay ? delay : defaults.delay, - enablePlacementTransitions - }; + return {duration ? duration : defaults.duration, delay ? delay : defaults.delay, enablePlacementTransitions}; } - bool isDefined() const { - return duration || delay; - } + bool isDefined() const { return duration || delay; } mapbox::base::Value serialize() const { mapbox::base::ValueObject result; diff --git a/include/mbgl/style/types.hpp b/include/mbgl/style/types.hpp index 5d88dafb331..3d5780935a8 100644 --- a/include/mbgl/style/types.hpp +++ b/include/mbgl/style/types.hpp @@ -68,7 +68,7 @@ enum class SymbolPlacementType : uint8_t { Line, LineCenter }; - + enum class SymbolZOrderType : uint8_t { Auto, ViewportY, @@ -120,7 +120,7 @@ enum class TextWritingModeType : uint8_t { Vertical }; -enum class LightAnchorType: bool { +enum class LightAnchorType : bool { Map, Viewport }; diff --git a/include/mbgl/style/undefined.hpp b/include/mbgl/style/undefined.hpp index e43f132a80e..b88f42f99f1 100644 --- a/include/mbgl/style/undefined.hpp +++ b/include/mbgl/style/undefined.hpp @@ -5,8 +5,12 @@ namespace style { class Undefined {}; -inline bool operator==(const Undefined&, const Undefined&) { return true; } -inline bool operator!=(const Undefined&, const Undefined&) { return false; } +inline bool operator==(const Undefined&, const Undefined&) { + return true; +} +inline bool operator!=(const Undefined&, const Undefined&) { + return false; +} } // namespace style } // namespace mbgl diff --git a/include/mbgl/tile/tile_id.hpp b/include/mbgl/tile/tile_id.hpp index e7e0ad567bc..c9c9ca7e72d 100644 --- a/include/mbgl/tile/tile_id.hpp +++ b/include/mbgl/tile/tile_id.hpp @@ -18,9 +18,9 @@ class CanonicalTileID; class UnwrappedTileID; // Has integer z/x/y coordinates -// All tiles must be derived from 0/0/0 (=no tiles outside of the main tile pyramid) -// Used for requesting data; represents data tiles that exist out there. -// z is never larger than the source's maxzoom +// All tiles must be derived from 0/0/0 (=no tiles outside of the main tile +// pyramid) Used for requesting data; represents data tiles that exist out +// there. z is never larger than the source's maxzoom class CanonicalTileID { public: CanonicalTileID(uint8_t z, uint32_t x, uint32_t y); @@ -42,9 +42,9 @@ std::string toString(const CanonicalTileID&); } // namespace util // Has integer z/x/y coordinates -// overscaledZ describes the zoom level this tile is intented to represent, e.g. when parsing data -// z is never larger than the source's maxzoom -// z/x/y describe the +// overscaledZ describes the zoom level this tile is intented to represent, e.g. +// when parsing data z is never larger than the source's maxzoom z/x/y describe +// the class OverscaledTileID { public: OverscaledTileID(uint8_t overscaledZ, int16_t wrap, CanonicalTileID); @@ -72,9 +72,9 @@ std::string toString(const OverscaledTileID&); } // namespace util // Has integer z/x/y coordinates -// wrap describes tiles that are left/right of the main tile pyramid, e.g. when wrapping the world -// Used for describing what position tiles are getting rendered at (= calc the matrix) -// z is never larger than the source's maxzoom +// wrap describes tiles that are left/right of the main tile pyramid, e.g. when +// wrapping the world Used for describing what position tiles are getting +// rendered at (= calc the matrix) z is never larger than the source's maxzoom class UnwrappedTileID { public: UnwrappedTileID(uint8_t z, int64_t x, int64_t y); @@ -97,7 +97,10 @@ namespace util { std::string toString(const UnwrappedTileID&); } // namespace util -inline CanonicalTileID::CanonicalTileID(uint8_t z_, uint32_t x_, uint32_t y_) : z(z_), x(x_), y(y_) { +inline CanonicalTileID::CanonicalTileID(uint8_t z_, uint32_t x_, uint32_t y_) + : z(z_), + x(x_), + y(y_) { assert(z <= 32); assert(x < (1ull << z)); assert(y < (1ull << z)); @@ -117,15 +120,14 @@ inline bool CanonicalTileID::operator<(const CanonicalTileID& rhs) const { inline bool CanonicalTileID::isChildOf(const CanonicalTileID& parent) const { // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined. - return parent.z == 0 || - (parent.z < z && parent.x == (x >> (z - parent.z)) && parent.y == (y >> (z - parent.z))); + return parent.z == 0 || (parent.z < z && parent.x == (x >> (z - parent.z)) && parent.y == (y >> (z - parent.z))); } inline CanonicalTileID CanonicalTileID::scaledTo(uint8_t targetZ) const { if (targetZ <= z) { - return { targetZ, x >> (z - targetZ), y >> (z - targetZ) }; // parent or same + return {targetZ, x >> (z - targetZ), y >> (z - targetZ)}; // parent or same } else { - return { targetZ, x << (targetZ - z), y << (targetZ - z) }; // child + return {targetZ, x << (targetZ - z), y << (targetZ - z)}; // child } } @@ -133,40 +135,49 @@ inline std::array CanonicalTileID::children() const { const uint8_t childZ = z + 1; const uint32_t childX = x * 2; const uint32_t childY = y * 2; - return { { - { childZ, childX, childY }, - { childZ, childX, childY + 1 }, - { childZ, childX + 1, childY }, - { childZ, childX + 1, childY + 1 }, - } }; + return {{ + {childZ, childX, childY}, + {childZ, childX, childY + 1}, + {childZ, childX + 1, childY}, + {childZ, childX + 1, childY + 1}, + }}; } inline OverscaledTileID::OverscaledTileID(uint8_t overscaledZ_, int16_t wrap_, CanonicalTileID canonical_) - : overscaledZ(overscaledZ_), wrap(wrap_), canonical(canonical_) { + : overscaledZ(overscaledZ_), + wrap(wrap_), + canonical(canonical_) { assert(overscaledZ >= canonical.z); } inline OverscaledTileID::OverscaledTileID(uint8_t overscaledZ_, int16_t wrap_, uint8_t z, uint32_t x, uint32_t y) - : overscaledZ(overscaledZ_), wrap(wrap_), canonical(z, x, y) { + : overscaledZ(overscaledZ_), + wrap(wrap_), + canonical(z, x, y) { assert(overscaledZ >= canonical.z); } inline OverscaledTileID::OverscaledTileID(uint8_t z, uint32_t x, uint32_t y) - : overscaledZ(z), wrap(0), canonical(z, x, y) { -} + : overscaledZ(z), + wrap(0), + canonical(z, x, y) {} inline OverscaledTileID::OverscaledTileID(const CanonicalTileID& canonical_) - : overscaledZ(canonical_.z), wrap(0), canonical(canonical_) { + : overscaledZ(canonical_.z), + wrap(0), + canonical(canonical_) { assert(overscaledZ >= canonical.z); } inline OverscaledTileID::OverscaledTileID(CanonicalTileID&& canonical_) - : overscaledZ(canonical_.z), wrap(0), canonical(std::forward(canonical_)) { + : overscaledZ(canonical_.z), + wrap(0), + canonical(std::forward(canonical_)) { assert(overscaledZ >= canonical.z); } inline bool OverscaledTileID::operator==(const OverscaledTileID& rhs) const { - return overscaledZ == rhs.overscaledZ && wrap == rhs.wrap &&canonical == rhs.canonical; + return overscaledZ == rhs.overscaledZ && wrap == rhs.wrap && canonical == rhs.canonical; } inline bool OverscaledTileID::operator!=(const OverscaledTileID& rhs) const { @@ -182,33 +193,31 @@ inline uint32_t OverscaledTileID::overscaleFactor() const { } inline bool OverscaledTileID::isChildOf(const OverscaledTileID& rhs) const { - return wrap == rhs.wrap && - overscaledZ > rhs.overscaledZ && + return wrap == rhs.wrap && overscaledZ > rhs.overscaledZ && (canonical == rhs.canonical || canonical.isChildOf(rhs.canonical)); } inline OverscaledTileID OverscaledTileID::scaledTo(uint8_t z) const { - return { z, wrap, z >= canonical.z ? canonical : canonical.scaledTo(z) }; + return {z, wrap, z >= canonical.z ? canonical : canonical.scaledTo(z)}; } inline UnwrappedTileID OverscaledTileID::toUnwrapped() const { - return { wrap, canonical }; + return {wrap, canonical}; } inline OverscaledTileID OverscaledTileID::unwrapTo(int16_t newWrap) const { - return { overscaledZ, newWrap, canonical }; + return {overscaledZ, newWrap, canonical}; } inline UnwrappedTileID::UnwrappedTileID(uint8_t z_, int64_t x_, int64_t y_) : wrap(static_cast((x_ < 0 ? x_ - (1ll << z_) + 1 : x_) / (1ll << z_))), - canonical( - z_, - static_cast(x_ - wrap * (1ll << z_)), - y_ < 0 ? 0 : std::min(static_cast(y_), static_cast(1ull << z_) - 1)) { -} + canonical(z_, + static_cast(x_ - wrap * (1ll << z_)), + y_ < 0 ? 0 : std::min(static_cast(y_), static_cast(1ull << z_) - 1)) {} inline UnwrappedTileID::UnwrappedTileID(int16_t wrap_, CanonicalTileID canonical_) - : wrap(wrap_), canonical(canonical_) {} + : wrap(wrap_), + canonical(canonical_) {} inline bool UnwrappedTileID::operator==(const UnwrappedTileID& rhs) const { return wrap == rhs.wrap && canonical == rhs.canonical; @@ -223,7 +232,7 @@ inline bool UnwrappedTileID::operator<(const UnwrappedTileID& rhs) const { } inline UnwrappedTileID UnwrappedTileID::unwrapTo(int16_t newWrap) const { - return { newWrap, canonical }; + return {newWrap, canonical}; } inline bool UnwrappedTileID::isChildOf(const UnwrappedTileID& parent) const { @@ -234,21 +243,22 @@ inline std::array UnwrappedTileID::children() const { const uint8_t childZ = canonical.z + 1; const uint32_t childX = canonical.x * 2; const uint32_t childY = canonical.y * 2; - return { { - { wrap, { childZ, childX, childY } }, - { wrap, { childZ, childX, childY + 1 } }, - { wrap, { childZ, childX + 1, childY } }, - { wrap, { childZ, childX + 1, childY + 1 } }, - } }; + return {{ + {wrap, {childZ, childX, childY}}, + {wrap, {childZ, childX, childY + 1}}, + {wrap, {childZ, childX + 1, childY}}, + {wrap, {childZ, childX + 1, childY + 1}}, + }}; } inline OverscaledTileID UnwrappedTileID::overscaleTo(const uint8_t overscaledZ) const { assert(overscaledZ >= canonical.z); - return { overscaledZ, wrap, canonical }; + return {overscaledZ, wrap, canonical}; } inline float UnwrappedTileID::pixelsToTileUnits(const float pixelValue, const float zoom) const { - return pixelValue * (static_cast(util::EXTENT) / (static_cast(util::tileSize_D) * std::pow(2.f, zoom - canonical.z))); + return pixelValue * (static_cast(util::EXTENT) / + (static_cast(util::tileSize_D) * std::pow(2.f, zoom - canonical.z))); } } // namespace mbgl @@ -271,4 +281,3 @@ struct hash { }; } // namespace std - diff --git a/include/mbgl/util/bitmask_operations.hpp b/include/mbgl/util/bitmask_operations.hpp index 014fabdea25..b22eb58c2f0 100644 --- a/include/mbgl/util/bitmask_operations.hpp +++ b/include/mbgl/util/bitmask_operations.hpp @@ -5,29 +5,28 @@ namespace mbgl { -template +template MBGL_CONSTEXPR Enum operator|(Enum a, Enum b) { static_assert(std::is_enum::value, "Enum must be an enum type"); return Enum(mbgl::underlying_type(a) | mbgl::underlying_type(b)); } -template +template MBGL_CONSTEXPR Enum& operator|=(Enum& a, Enum b) { static_assert(std::is_enum::value, "Enum must be an enum type"); return (a = a | b); } -template +template MBGL_CONSTEXPR bool operator&(Enum a, Enum b) { static_assert(std::is_enum::value, "Enum must be an enum type"); return bool(mbgl::underlying_type(a) & mbgl::underlying_type(b)); } -template +template MBGL_CONSTEXPR Enum operator~(Enum value) { static_assert(std::is_enum::value, "Enum must be an enum type"); return Enum(~mbgl::underlying_type(value)); } - } // namespace mbgl \ No newline at end of file diff --git a/include/mbgl/util/char_array_buffer.hpp b/include/mbgl/util/char_array_buffer.hpp index 80eeb2db625..0e84062fe6c 100644 --- a/include/mbgl/util/char_array_buffer.hpp +++ b/include/mbgl/util/char_array_buffer.hpp @@ -7,11 +7,12 @@ namespace util { // ref https://artofcode.wordpress.com/2010/12/12/deriving-from-stdstreambuf/ -class CharArrayBuffer : public std::streambuf -{ +class CharArrayBuffer : public std::streambuf { public: CharArrayBuffer(char const* data, std::size_t size) - : begin_(data), end_(data + size), current_(data) {} + : begin_(data), + end_(data + size), + current_(data) {} private: int_type underflow() final { @@ -35,20 +36,21 @@ class CharArrayBuffer : public std::streambuf return traits_type::to_int_type(*--current_); } - std::streamsize showmanyc() final { - return end_ - current_; - } + std::streamsize showmanyc() final { return end_ - current_; } pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode) final { - if (dir == std::ios_base::beg) current_ = std::min(begin_ + off, end_); - else if (dir == std::ios_base::cur) current_ = std::min(current_ + off, end_); - else current_ = std::max(end_ - off, begin_); // dir == std::ios_base::end + if (dir == std::ios_base::beg) + current_ = std::min(begin_ + off, end_); + else if (dir == std::ios_base::cur) + current_ = std::min(current_ + off, end_); + else + current_ = std::max(end_ - off, begin_); // dir == std::ios_base::end return {off_type(current_ - begin_)}; } - char const * const begin_; - char const * const end_; - char const * current_; + char const* const begin_; + char const* const end_; + char const* current_; }; } // namespace util diff --git a/include/mbgl/util/chrono.hpp b/include/mbgl/util/chrono.hpp index 0f2b85b256e..77dd49bb112 100644 --- a/include/mbgl/util/chrono.hpp +++ b/include/mbgl/util/chrono.hpp @@ -15,7 +15,7 @@ using Seconds = std::chrono::seconds; using Milliseconds = std::chrono::milliseconds; using TimePoint = Clock::time_point; -using Duration = Clock::duration; +using Duration = Clock::duration; // Used to measure second-precision times, such as times gathered from HTTP responses. using Timestamp = std::chrono::time_point; @@ -42,13 +42,15 @@ template : _NODISCARD constexpr std::chrono::duration<_Rep, _Period> abs(const std::chrono::duration<_Rep, _Period> _Dur) noexcept( std::is_arithmetic_v<_Rep>) /* strengthened */ { // create a duration with count() the absolute value of _Dur.count() - return _Dur < std::chrono::duration<_Rep, _Period>::zero() ? std::chrono::duration<_Rep, _Period>::zero() - _Dur : _Dur; + return _Dur < std::chrono::duration<_Rep, _Period>::zero() ? std::chrono::duration<_Rep, _Period>::zero() - _Dur + : _Dur; } #else -template ::min() < std::chrono::duration::zero()>> -constexpr std::chrono::duration abs(std::chrono::duration d) -{ +template < + class Rep, + class Period, + class = std::enable_if_t::min() < std::chrono::duration::zero()>> +constexpr std::chrono::duration abs(std::chrono::duration d) { return d >= d.zero() ? d : -d; } #endif diff --git a/include/mbgl/util/color.hpp b/include/mbgl/util/color.hpp index c8c48bb16e3..f60c9f4cb72 100644 --- a/include/mbgl/util/color.hpp +++ b/include/mbgl/util/color.hpp @@ -14,7 +14,10 @@ class Color { public: Color() = default; Color(float r_, float g_, float b_, float a_) - : r(r_), g(g_), b(b_), a(a_) { + : r(r_), + g(g_), + b(b_), + a(a_) { assert(r_ >= 0.0f); assert(r_ <= 1.0f); assert(g_ >= 0.0f); @@ -30,12 +33,12 @@ class Color { float b = 0.0f; float a = 0.0f; - static Color black() { return { 0.0f, 0.0f, 0.0f, 1.0f }; }; - static Color white() { return { 1.0f, 1.0f, 1.0f, 1.0f }; }; + static Color black() { return {0.0f, 0.0f, 0.0f, 1.0f}; }; + static Color white() { return {1.0f, 1.0f, 1.0f, 1.0f}; }; - static Color red() { return { 1.0f, 0.0f, 0.0f, 1.0f }; }; - static Color green() { return { 0.0f, 1.0f, 0.0f, 1.0f }; }; - static Color blue() { return { 0.0f, 0.0f, 1.0f, 1.0f }; }; + static Color red() { return {1.0f, 0.0f, 0.0f, 1.0f}; }; + static Color green() { return {0.0f, 1.0f, 0.0f, 1.0f}; }; + static Color blue() { return {0.0f, 0.0f, 1.0f, 1.0f}; }; static std::optional parse(const std::string&); std::string stringify() const; @@ -55,12 +58,7 @@ inline bool operator!=(const Color& colorA, const Color& colorB) { inline Color operator*(const Color& color, float alpha) { assert(alpha >= 0.0f); assert(alpha <= 1.0f); - return { - color.r * alpha, - color.g * alpha, - color.b * alpha, - color.a * alpha - }; + return {color.r * alpha, color.g * alpha, color.b * alpha, color.a * alpha}; } } // namespace mbgl diff --git a/include/mbgl/util/compression.hpp b/include/mbgl/util/compression.hpp index efe87ff2eae..b07cadd6561 100644 --- a/include/mbgl/util/compression.hpp +++ b/include/mbgl/util/compression.hpp @@ -5,7 +5,12 @@ namespace mbgl { namespace util { -enum CompressionFormat { ZLIB = 15, GZIP = 15 + 16, DEFLATE = -15, DETECT = 15 + 32 }; +enum CompressionFormat { + ZLIB = 15, + GZIP = 15 + 16, + DEFLATE = -15, + DETECT = 15 + 32 +}; std::string compress(const std::string& raw, int windowBits = CompressionFormat::ZLIB); std::string decompress(const std::string& raw, int windowBits = CompressionFormat::DETECT); diff --git a/include/mbgl/util/constants.hpp b/include/mbgl/util/constants.hpp index 8b05fad81c7..51900f93ed1 100644 --- a/include/mbgl/util/constants.hpp +++ b/include/mbgl/util/constants.hpp @@ -18,11 +18,11 @@ constexpr uint16_t tileSize_I = 512; * In practice, all features are converted to this extent before being added. * * Positions are stored as signed 16bit integers. - * One bit is lost for signedness to support features extending past the left edge of the tile. - * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int. - * This is no longer the case but we're reserving this bit anyway. - * One bit is lost to support features extending past the extent on the right edge of the tile. - * This leaves us with 2^13 = 8192 + * One bit is lost for signedness to support features extending past the left + * edge of the tile. One bit is lost because the line vertex buffer used to pack + * 1 bit of other data into the int. This is no longer the case but we're + * reserving this bit anyway. One bit is lost to support features extending past + * the extent on the right edge of the tile. This leaves us with 2^13 = 8192 */ constexpr int32_t EXTENT = 8192; @@ -35,8 +35,8 @@ constexpr double PITCH_MIN = 0.0; constexpr double PITCH_MAX = M_PI / 3; constexpr double MIN_ZOOM = 0.0; constexpr double MAX_ZOOM = 25.5; -constexpr float MIN_ZOOM_F = MIN_ZOOM; -constexpr float MAX_ZOOM_F = MAX_ZOOM; +constexpr float MIN_ZOOM_F = MIN_ZOOM; +constexpr float MAX_ZOOM_F = MAX_ZOOM; constexpr uint8_t DEFAULT_MAX_ZOOM = 22; // ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout. @@ -51,9 +51,9 @@ constexpr uint64_t DEFAULT_MAX_CACHE_SIZE = 50 * 1024 * 1024; constexpr std::size_t DEFAULT_ON_DEMAND_IMAGES_CACHE_SIZE = 100 * 8192; constexpr Duration DEFAULT_TRANSITION_DURATION = Milliseconds(300); -constexpr Seconds CLOCK_SKEW_RETRY_TIMEOUT { 30 }; +constexpr Seconds CLOCK_SKEW_RETRY_TIMEOUT{30}; -constexpr UnitBezier DEFAULT_TRANSITION_EASE = { 0, 0, 0.25, 1 }; +constexpr UnitBezier DEFAULT_TRANSITION_EASE = {0, 0, 0.25, 1}; constexpr int DEFAULT_RATE_LIMIT_TIMEOUT = 5; diff --git a/include/mbgl/util/convert.hpp b/include/mbgl/util/convert.hpp index e5458f2ed03..67342ea0d4e 100644 --- a/include/mbgl/util/convert.hpp +++ b/include/mbgl/util/convert.hpp @@ -7,10 +7,9 @@ namespace mbgl { namespace util { -template>> -MBGL_CONSTEXPR std::array convert(const std::array&from) { - std::array to {{}}; +template >> +MBGL_CONSTEXPR std::array convert(const std::array& from) { + std::array to{{}}; std::copy(std::begin(from), std::end(from), std::begin(to)); return to; } diff --git a/include/mbgl/util/default_style.hpp b/include/mbgl/util/default_style.hpp index 1fb5f696d6f..39b6afd2b86 100644 --- a/include/mbgl/util/default_style.hpp +++ b/include/mbgl/util/default_style.hpp @@ -10,7 +10,7 @@ class DefaultStyle { DefaultStyle(std::string, std::string, int); const std::string& getUrl() const; - const std::string& getName() const; + const std::string& getName() const; int getCurrentVersion() const; private: diff --git a/include/mbgl/util/enum.hpp b/include/mbgl/util/enum.hpp index c1a376e5f5d..468ff25d300 100644 --- a/include/mbgl/util/enum.hpp +++ b/include/mbgl/util/enum.hpp @@ -11,26 +11,27 @@ template class Enum { public: using Type = T; - static const char * toString(T); + static const char* toString(T); static std::optional toEnum(const std::string&); }; -#define MBGL_DEFINE_ENUM(T, ...) \ - \ -static const constexpr std::pair T##_names[] = __VA_ARGS__; \ - \ -template <> \ -const char * Enum::toString(T t) { \ - auto it = std::find_if(std::begin(T##_names), std::end(T##_names), \ - [&] (const auto& v) { return t == v.first; }); \ - assert(it != std::end(T##_names)); return it->second; \ -} \ - \ -template <> \ -std::optional Enum::toEnum(const std::string& s) { \ - auto it = std::find_if(std::begin(T##_names), std::end(T##_names), \ - [&] (const auto& v) { return s == v.second; }); \ - return it == std::end(T##_names) ? std::optional() : it->first; \ -} +#define MBGL_DEFINE_ENUM(T, ...) \ + \ + static const constexpr std::pair T##_names[] = __VA_ARGS__; \ + \ + template <> \ + const char* Enum::toString(T t) { \ + auto it = std::find_if( \ + std::begin(T##_names), std::end(T##_names), [&](const auto& v) { return t == v.first; }); \ + assert(it != std::end(T##_names)); \ + return it->second; \ + } \ + \ + template <> \ + std::optional Enum::toEnum(const std::string& s) { \ + auto it = std::find_if( \ + std::begin(T##_names), std::end(T##_names), [&](const auto& v) { return s == v.second; }); \ + return it == std::end(T##_names) ? std::optional() : it->first; \ + } } // namespace mbgl diff --git a/include/mbgl/util/event.hpp b/include/mbgl/util/event.hpp index 15583e956d4..bd517031beb 100644 --- a/include/mbgl/util/event.hpp +++ b/include/mbgl/util/event.hpp @@ -52,8 +52,6 @@ constexpr Event disabledEvents[] = { Event(-1) // Avoid zero size array }; -constexpr EventPermutation disabledEventPermutations[] = { - { EventSeverity::Debug, Event::Shader } -}; +constexpr EventPermutation disabledEventPermutations[] = {{EventSeverity::Debug, Event::Shader}}; } // namespace mbgl diff --git a/include/mbgl/util/exception.hpp b/include/mbgl/util/exception.hpp index f0d7c64f42e..fb42dd6bc53 100644 --- a/include/mbgl/util/exception.hpp +++ b/include/mbgl/util/exception.hpp @@ -6,33 +6,45 @@ namespace mbgl { namespace util { struct Exception : std::runtime_error { - Exception(const char *msg) : std::runtime_error(msg) {} - Exception(const std::string &msg) : std::runtime_error(msg) {} + Exception(const char *msg) + : std::runtime_error(msg) {} + Exception(const std::string &msg) + : std::runtime_error(msg) {} }; struct StyleImageException : Exception { - StyleImageException(const char *msg) : Exception(msg) {} - StyleImageException(const std::string &msg) : Exception(msg) {} + StyleImageException(const char *msg) + : Exception(msg) {} + StyleImageException(const std::string &msg) + : Exception(msg) {} }; struct MisuseException : Exception { - MisuseException(const char *msg) : Exception(msg) {} - MisuseException(const std::string &msg) : Exception(msg) {} + MisuseException(const char *msg) + : Exception(msg) {} + MisuseException(const std::string &msg) + : Exception(msg) {} }; struct StyleParseException : Exception { - StyleParseException(const char *msg) : Exception(msg) {} - StyleParseException(const std::string &msg) : Exception(msg) {} + StyleParseException(const char *msg) + : Exception(msg) {} + StyleParseException(const std::string &msg) + : Exception(msg) {} }; struct StyleLoadException : Exception { - StyleLoadException(const char *msg) : Exception(msg) {} - StyleLoadException(const std::string &msg) : Exception(msg) {} + StyleLoadException(const char *msg) + : Exception(msg) {} + StyleLoadException(const std::string &msg) + : Exception(msg) {} }; struct NotFoundException : Exception { - NotFoundException(const char *msg) : Exception(msg) {} - NotFoundException(const std::string &msg) : Exception(msg) {} + NotFoundException(const char *msg) + : Exception(msg) {} + NotFoundException(const std::string &msg) + : Exception(msg) {} }; } // namespace util diff --git a/include/mbgl/util/feature.hpp b/include/mbgl/util/feature.hpp index c8bd4e0d3f6..4f295643851 100644 --- a/include/mbgl/util/feature.hpp +++ b/include/mbgl/util/feature.hpp @@ -26,9 +26,12 @@ class Feature : public GeoJSONFeature { using GeometryType = mapbox::geometry::geometry; Feature() = default; - Feature(const GeoJSONFeature& f) : GeoJSONFeature(f) {} - Feature(const GeometryType& geom_) : GeoJSONFeature(geom_) {} - Feature(GeometryType&& geom_) : GeoJSONFeature(std::move(geom_)) {} + Feature(const GeoJSONFeature& f) + : GeoJSONFeature(f) {} + Feature(const GeometryType& geom_) + : GeoJSONFeature(geom_) {} + Feature(GeometryType&& geom_) + : GeoJSONFeature(std::move(geom_)) {} }; template @@ -44,10 +47,11 @@ inline std::optional featureIDtoString(const FeatureIdentifier& id) return std::nullopt; } - return id.match( - [](const std::string& value_) { return value_; }, [](uint64_t value_) { return util::toString(value_); }, - [](int64_t value_) { return util::toString(value_); }, [](double value_) { return util::toString(value_); }, -[](const auto&) -> std::optional { return std::nullopt; }); + return id.match([](const std::string& value_) { return value_; }, + [](uint64_t value_) { return util::toString(value_); }, + [](int64_t value_) { return util::toString(value_); }, + [](double value_) { return util::toString(value_); }, + [](const auto&) -> std::optional { return std::nullopt; }); } } // namespace mbgl diff --git a/include/mbgl/util/geo.hpp b/include/mbgl/util/geo.hpp index ae6c1550fab..bc8460f13c7 100644 --- a/include/mbgl/util/geo.hpp +++ b/include/mbgl/util/geo.hpp @@ -19,7 +19,7 @@ class UnwrappedTileID; using ScreenCoordinate = mapbox::geometry::point; using ScreenLineString = mapbox::geometry::line_string; -using ScreenBox = mapbox::geometry::box; +using ScreenBox = mapbox::geometry::box; class LatLng { private: @@ -27,10 +27,14 @@ class LatLng { double lon; public: - enum WrapMode : bool { Unwrapped, Wrapped }; + enum WrapMode : bool { + Unwrapped, + Wrapped + }; LatLng(double lat_ = 0, double lon_ = 0, WrapMode mode = Unwrapped) - : lat(lat_), lon(lon_) { + : lat(lat_), + lon(lon_) { if (std::isnan(lat)) { throw std::domain_error("latitude must not be NaN"); } @@ -51,32 +55,28 @@ class LatLng { double latitude() const { return lat; } double longitude() const { return lon; } - LatLng wrapped() const { return { lat, lon, Wrapped }; } + LatLng wrapped() const { return {lat, lon, Wrapped}; } - void wrap() { - lon = util::wrap(lon, -util::LONGITUDE_MAX, util::LONGITUDE_MAX); - } + void wrap() { lon = util::wrap(lon, -util::LONGITUDE_MAX, util::LONGITUDE_MAX); } // If the distance from start to end longitudes is between half and full // world, unwrap the start longitude to ensure the shortest path is taken. void unwrapForShortestPath(const LatLng& end) { const double delta = std::abs(end.lon - lon); if (delta <= util::LONGITUDE_MAX || delta >= util::DEGREES_MAX) return; - if (lon > 0 && end.lon < 0) lon -= util::DEGREES_MAX; - else if (lon < 0 && end.lon > 0) lon += util::DEGREES_MAX; + if (lon > 0 && end.lon < 0) + lon -= util::DEGREES_MAX; + else if (lon < 0 && end.lon > 0) + lon += util::DEGREES_MAX; } // Constructs a LatLng object with the top left position of the specified tile. LatLng(const CanonicalTileID& id); LatLng(const UnwrappedTileID& id); - friend bool operator==(const LatLng& a, const LatLng& b) { - return a.lat == b.lat && a.lon == b.lon; - } + friend bool operator==(const LatLng& a, const LatLng& b) { return a.lat == b.lat && a.lon == b.lon; } - friend bool operator!=(const LatLng& a, const LatLng& b) { - return !(a == b); - } + friend bool operator!=(const LatLng& a, const LatLng& b) { return !(a == b); } }; class LatLngBounds { @@ -101,24 +101,25 @@ class LatLngBounds { return bounds; } - /// Construct an infinite bound, a bound for which the constrain method returns its - /// input unmodified. + /// Construct an infinite bound, a bound for which the constrain method + /// returns its input unmodified. /// - /// Note: this is different than LatLngBounds::world() since arbitrary unwrapped - /// coordinates are also inside the bounds. - LatLngBounds() : sw({-90, -180}), ne({90, 180}), bounded(false) {} + /// Note: this is different than LatLngBounds::world() since arbitrary + /// unwrapped coordinates are also inside the bounds. + LatLngBounds() + : sw({-90, -180}), + ne({90, 180}), + bounded(false) {} // Constructs a LatLngBounds object with the tile's exact boundaries. LatLngBounds(const CanonicalTileID&); - bool valid() const { - return (sw.latitude() <= ne.latitude()) && (sw.longitude() <= ne.longitude()); - } + bool valid() const { return (sw.latitude() <= ne.latitude()) && (sw.longitude() <= ne.longitude()); } double south() const { return sw.latitude(); } - double west() const { return sw.longitude(); } + double west() const { return sw.longitude(); } double north() const { return ne.latitude(); } - double east() const { return ne.longitude(); } + double east() const { return ne.longitude(); } LatLng southwest() const { return sw; } LatLng northeast() const { return ne; } @@ -130,10 +131,8 @@ class LatLngBounds { LatLng constrain(const LatLng& p) const; void extend(const LatLng& point) { - sw = LatLng(std::min(point.latitude(), sw.latitude()), - std::min(point.longitude(), sw.longitude())); - ne = LatLng(std::max(point.latitude(), ne.latitude()), - std::max(point.longitude(), ne.longitude())); + sw = LatLng(std::min(point.latitude(), sw.latitude()), std::min(point.longitude(), sw.longitude())); + ne = LatLng(std::max(point.latitude(), ne.latitude()), std::max(point.longitude(), ne.longitude())); } void extend(const LatLngBounds& bounds) { @@ -141,14 +140,9 @@ class LatLngBounds { extend(bounds.ne); } - bool isEmpty() const { - return sw.latitude() > ne.latitude() || - sw.longitude() > ne.longitude(); - } + bool isEmpty() const { return sw.latitude() > ne.latitude() || sw.longitude() > ne.longitude(); } - bool crossesAntimeridian() const { - return (sw.wrapped().longitude() > ne.wrapped().longitude()); - } + bool crossesAntimeridian() const { return (sw.wrapped().longitude() > ne.wrapped().longitude()); } bool contains(const CanonicalTileID& tileID) const; bool contains(const LatLng& point, LatLng::WrapMode wrap = LatLng::Unwrapped) const; @@ -161,7 +155,9 @@ class LatLngBounds { LatLng ne; bool bounded = true; - LatLngBounds(LatLng sw_, LatLng ne_) : sw(sw_), ne(ne_) {} + LatLngBounds(LatLng sw_, LatLng ne_) + : sw(sw_), + ne(ne_) {} bool containsLatitude(double latitude) const; bool containsLongitude(double longitude, LatLng::WrapMode wrap) const; @@ -170,9 +166,7 @@ class LatLngBounds { return (!a.bounded && !b.bounded) || (a.bounded && b.bounded && a.sw == b.sw && a.ne == b.ne); } - friend bool operator!=(const LatLngBounds& a, const LatLngBounds& b) { - return !(a == b); - } + friend bool operator!=(const LatLngBounds& a, const LatLngBounds& b) { return !(a == b); } }; // Determines the orientation of the map. @@ -193,7 +187,10 @@ class EdgeInsets { public: EdgeInsets(double t_ = 0, double l_ = 0, double b_ = 0, double r_ = 0) - : _top(t_), _left(l_), _bottom(b_), _right(r_) { + : _top(t_), + _left(l_), + _bottom(b_), + _right(r_) { if (std::isnan(_top)) { throw std::domain_error("top must not be NaN"); } @@ -213,9 +210,7 @@ class EdgeInsets { double bottom() const { return _bottom; } double right() const { return _right; } - bool isFlush() const { - return _top == 0 && _left == 0 && _bottom == 0 && _right == 0; - } + bool isFlush() const { return _top == 0 && _left == 0 && _bottom == 0 && _right == 0; } void operator+=(const EdgeInsets& o) { _top += o._top; @@ -226,7 +221,10 @@ class EdgeInsets { EdgeInsets operator+(const EdgeInsets& o) const { return { - _top + o._top, _left + o._left, _bottom + o._bottom, _right + o._right, + _top + o._top, + _left + o._left, + _bottom + o._bottom, + _right + o._right, }; } @@ -236,9 +234,7 @@ class EdgeInsets { return a._top == b._top && a._left == b._left && a._bottom == b._bottom && a._right == b._right; } - friend bool operator!=(const EdgeInsets& a, const EdgeInsets& b) { - return !(a == b); - } + friend bool operator!=(const EdgeInsets& a, const EdgeInsets& b) { return !(a == b); } }; struct LatLngAltitude { diff --git a/include/mbgl/util/geometry.hpp b/include/mbgl/util/geometry.hpp index 5fc9c59e7f1..3b56d87240c 100644 --- a/include/mbgl/util/geometry.hpp +++ b/include/mbgl/util/geometry.hpp @@ -42,30 +42,44 @@ template using Geometry = mapbox::geometry::geometry; template -Point convertPoint(const Point& p) { +Point convertPoint(const Point &p) { return Point(static_cast(p.x), static_cast(p.y)); } struct ToFeatureType { - FeatureType operator()(const EmptyGeometry&) const { return FeatureType::Unknown; } + FeatureType operator()(const EmptyGeometry &) const { return FeatureType::Unknown; } template - FeatureType operator()(const Point &) const { return FeatureType::Point; } + FeatureType operator()(const Point &) const { + return FeatureType::Point; + } template - FeatureType operator()(const MultiPoint &) const { return FeatureType::Point; } + FeatureType operator()(const MultiPoint &) const { + return FeatureType::Point; + } template - FeatureType operator()(const LineString &) const { return FeatureType::LineString; } + FeatureType operator()(const LineString &) const { + return FeatureType::LineString; + } template - FeatureType operator()(const MultiLineString &) const { return FeatureType::LineString; } + FeatureType operator()(const MultiLineString &) const { + return FeatureType::LineString; + } template - FeatureType operator()(const Polygon &) const { return FeatureType::Polygon; } + FeatureType operator()(const Polygon &) const { + return FeatureType::Polygon; + } template - FeatureType operator()(const MultiPolygon &) const { return FeatureType::Polygon; } + FeatureType operator()(const MultiPolygon &) const { + return FeatureType::Polygon; + } template - FeatureType operator()(const mapbox::geometry::geometry_collection &) const { return FeatureType::Unknown; } + FeatureType operator()(const mapbox::geometry::geometry_collection &) const { + return FeatureType::Unknown; + } }; template -auto forEachPoint(const Geometry& g, F f) { +auto forEachPoint(const Geometry &g, F f) { mapbox::geometry::for_each_point(g, f); } diff --git a/include/mbgl/util/ignore.hpp b/include/mbgl/util/ignore.hpp index 37160ef9ad6..e2fbe878c69 100644 --- a/include/mbgl/util/ignore.hpp +++ b/include/mbgl/util/ignore.hpp @@ -9,13 +9,16 @@ namespace util { /// Useful for providing a context for parameter pack expansion where a legal /// expansion context is not otherwise available. /// -/// See https://github.com/mapbox/cpp/blob/1bb519ef25edd6169f1d6d8a65414044616590a9/docs/structural-metaprogramming.md +/// See +/// https://github.com/mapbox/cpp/blob/1bb519ef25edd6169f1d6d8a65414044616590a9/docs/structural-metaprogramming.md /// for more details. -template void ignore(Ts&&...) {} +template +void ignore(Ts&&...) {} // std::initializer_list overload, for situations where you need sequenced // modifications. -template void ignore(const std::initializer_list&) {} +template +void ignore(const std::initializer_list&) {} // Handle the zero-argument case. inline void ignore(const std::initializer_list&) {} diff --git a/include/mbgl/util/image.hpp b/include/mbgl/util/image.hpp index a3bce11135e..28c24d498a6 100644 --- a/include/mbgl/util/image.hpp +++ b/include/mbgl/util/image.hpp @@ -22,9 +22,12 @@ class Image : private util::noncopyable { public: Image() = default; - Image(Size size_) : size(size_), data(std::make_unique(bytes())) {} + Image(Size size_) + : size(size_), + data(std::make_unique(bytes())) {} - Image(Size size_, const uint8_t* srcData, std::size_t srcLength) : size(size_) { + Image(Size size_, const uint8_t* srcData, std::size_t srcLength) + : size(size_) { if (srcLength != bytes()) { throw std::invalid_argument("mismatched image size"); } @@ -32,9 +35,15 @@ class Image : private util::noncopyable { std::copy(srcData, srcData + srcLength, data.get()); } - Image(Size size_, std::unique_ptr data_) : size(size_), data(std::move(data_)) {} + Image(Size size_, std::unique_ptr data_) + : size(size_), + data(std::move(data_)) {} - Image(Image&& o) noexcept : size(o.size), data(std::move(o.data)) { o.size.width = o.size.height = 0; } + Image(Image&& o) noexcept + : size(o.size), + data(std::move(o.data)) { + o.size.width = o.size.height = 0; + } Image& operator=(Image&& o) noexcept { size = o.size; @@ -44,13 +53,10 @@ class Image : private util::noncopyable { } friend bool operator==(const Image& lhs, const Image& rhs) { - return std::equal(lhs.data.get(), lhs.data.get() + lhs.bytes(), - rhs.data.get(), rhs.data.get() + rhs.bytes()); + return std::equal(lhs.data.get(), lhs.data.get() + lhs.bytes(), rhs.data.get(), rhs.data.get() + rhs.bytes()); } - friend bool operator!=(const Image& lhs, const Image& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const Image& lhs, const Image& rhs) { return !(lhs == rhs); } bool valid() const { return !size.isEmpty() && data != nullptr; } @@ -64,9 +70,7 @@ class Image : private util::noncopyable { size_t stride() const { return channels * size.width; } size_t bytes() const { return stride() * size.height; } - void fill(uint8_t value) { - std::fill(data.get(), data.get() + bytes(), value); - } + void fill(uint8_t value) { std::fill(data.get(), data.get() + bytes(), value); } void resize(Size size_) { if (size == size_) { @@ -74,10 +78,7 @@ class Image : private util::noncopyable { } Image newImage(size_); newImage.fill(0); - copy(*this, newImage, {0, 0}, {0, 0}, { - std::min(size.width, size_.width), - std::min(size.height, size_.height) - }); + copy(*this, newImage, {0, 0}, {0, 0}, {std::min(size.width, size_.width), std::min(size.height, size_.height)}); operator=(std::move(newImage)); } @@ -91,10 +92,8 @@ class Image : private util::noncopyable { throw std::invalid_argument("invalid destination for image clear"); } - if (size.width > dstImg.size.width || - size.height > dstImg.size.height || - pt.x > dstImg.size.width - size.width || - pt.y > dstImg.size.height - size.height) { + if (size.width > dstImg.size.width || size.height > dstImg.size.height || + pt.x > dstImg.size.width - size.width || pt.y > dstImg.size.height - size.height) { throw std::out_of_range("out of range destination coordinates for image clear"); } @@ -106,10 +105,15 @@ class Image : private util::noncopyable { } } - /// Copy image data within `rect` from `src` to the rectangle of the same size at `pt` - /// in `dst`. If the specified bounds exceed the bounds of the source or destination, - /// throw `std::out_of_range`. Must not be used to move data within a single Image. - static void copy(const Image& srcImg, Image& dstImg, const Point& srcPt, const Point& dstPt, const Size& size) { + /// Copy image data within `rect` from `src` to the rectangle of the same + /// size at `pt` in `dst`. If the specified bounds exceed the bounds of the + /// source or destination, throw `std::out_of_range`. Must not be used to + /// move data within a single Image. + static void copy(const Image& srcImg, + Image& dstImg, + const Point& srcPt, + const Point& dstPt, + const Size& size) { if (size.isEmpty()) { return; } @@ -122,31 +126,25 @@ class Image : private util::noncopyable { throw std::invalid_argument("invalid destination for image copy"); } - if (size.width > srcImg.size.width || - size.height > srcImg.size.height || - srcPt.x > srcImg.size.width - size.width || - srcPt.y > srcImg.size.height - size.height) { + if (size.width > srcImg.size.width || size.height > srcImg.size.height || + srcPt.x > srcImg.size.width - size.width || srcPt.y > srcImg.size.height - size.height) { throw std::out_of_range("out of range source coordinates for image copy"); } - if (size.width > dstImg.size.width || - size.height > dstImg.size.height || - dstPt.x > dstImg.size.width - size.width || - dstPt.y > dstImg.size.height - size.height) { + if (size.width > dstImg.size.width || size.height > dstImg.size.height || + dstPt.x > dstImg.size.width - size.width || dstPt.y > dstImg.size.height - size.height) { throw std::out_of_range("out of range destination coordinates for image copy"); } const uint8_t* srcData = srcImg.data.get(); - uint8_t* dstData = dstImg.data.get(); + uint8_t* dstData = dstImg.data.get(); assert(srcData != dstData); for (uint32_t y = 0; y < size.height; y++) { const std::size_t srcOffset = (srcPt.y + y) * srcImg.stride() + srcPt.x * channels; const std::size_t dstOffset = (dstPt.y + y) * dstImg.stride() + dstPt.x * channels; - std::copy(srcData + srcOffset, - srcData + srcOffset + size.width * channels, - dstData + dstOffset); + std::copy(srcData + srcOffset, srcData + srcOffset + size.width * channels, dstData + dstOffset); } } diff --git a/include/mbgl/util/immutable.hpp b/include/mbgl/util/immutable.hpp index fbd3ac9b342..687303bcc48 100644 --- a/include/mbgl/util/immutable.hpp +++ b/include/mbgl/util/immutable.hpp @@ -5,18 +5,19 @@ namespace mbgl { /** - * `Mutable` is a non-nullable uniquely owning reference to a `T`. It can be efficiently converted - * to `Immutable`. - * + * `Mutable` is a non-nullable uniquely owning reference to a `T`. It can be + * efficiently converted to `Immutable`. + * * The lifecycle of `Mutable` and `Immutable` is as follows: - * + * * 1. Create a `Mutable` using `makeMutable(...)` * 2. Mutate it freely - * 3. When you're ready to freeze its state and enable safe cross-thread sharing, move assign or - * move construct it to `Immutable` + * 3. When you're ready to freeze its state and enable safe cross-thread + * sharing, move assign or move construct it to `Immutable` * - * The reason that `Mutable` exists, rather than simply using a `std::unique_ptr`, is to take advantage - * of the underlying single-allocation optimization provided by `std::make_shared`. + * The reason that `Mutable` exists, rather than simply using a + * `std::unique_ptr`, is to take advantage of the underlying + * single-allocation optimization provided by `std::make_shared`. */ template class Mutable { @@ -37,11 +38,14 @@ class Mutable { std::shared_ptr ptr; - template friend class Immutable; + template + friend class Immutable; // NOLINTNEXTLINE(readability-redundant-declaration) - template friend Mutable makeMutable(Args&&...); + template + friend Mutable makeMutable(Args&&...); // NOLINTNEXTLINE(readability-redundant-declaration) - template friend Mutable staticMutableCast(const Mutable&); + template + friend Mutable staticMutableCast(const Mutable&); }; template @@ -55,13 +59,15 @@ Mutable staticMutableCast(const Mutable& u) { } /** - * `Immutable` is a non-nullable shared reference to a `const T`. Construction requires - * a transfer of unique ownership from a `Mutable`; once constructed it has the same behavior - * as `std::shared_ptr` but with better indication of intent. + * `Immutable` is a non-nullable shared reference to a `const T`. + * Construction requires a transfer of unique ownership from a `Mutable`; + * once constructed it has the same behavior as `std::shared_ptr` but + * with better indication of intent. * - * Normally one should not share state between threads because it's difficult to verify the - * absence of read/write data races. `Immutable` provides a guarantee that no writes are - * possible, and instances therefore can be freely transferred and shared between threads. + * Normally one should not share state between threads because it's difficult to + * verify the absence of read/write data races. `Immutable` provides a guarantee + * that no writes are possible, and instances therefore can be freely + * transferred and shared between threads. */ template class Immutable { @@ -90,13 +96,9 @@ class Immutable { const T* operator->() const { return ptr.get(); } const T& operator*() const { return *ptr; } - friend bool operator==(const Immutable& lhs, const Immutable& rhs) { - return lhs.ptr == rhs.ptr; - } + friend bool operator==(const Immutable& lhs, const Immutable& rhs) { return lhs.ptr == rhs.ptr; } - friend bool operator!=(const Immutable& lhs, const Immutable& rhs) { - return lhs.ptr != rhs.ptr; - } + friend bool operator!=(const Immutable& lhs, const Immutable& rhs) { return lhs.ptr != rhs.ptr; } private: Immutable(std::shared_ptr&& s) @@ -104,10 +106,12 @@ class Immutable { std::shared_ptr ptr; - template friend class Immutable; + template + friend class Immutable; // NOLINTNEXTLINE(readability-redundant-declaration) - template friend Immutable staticImmutableCast(const Immutable&); + template + friend Immutable staticImmutableCast(const Immutable&); }; template @@ -116,12 +120,13 @@ Immutable staticImmutableCast(const Immutable& u) { } /** - * Constrained mutation of an immutable reference. Makes a temporarily-mutable copy of the - * input Immutable using the inner type's copy constructor, runs the given callable on the - * mutable copy, and then freezes the copy and reassigns it to the input reference. + * Constrained mutation of an immutable reference. Makes a temporarily-mutable + * copy of the input Immutable using the inner type's copy constructor, runs the + * given callable on the mutable copy, and then freezes the copy and reassigns + * it to the input reference. * - * Note that other Immutables referring to the same inner instance are not affected; they - * continue to referencing the original immutable instance. + * Note that other Immutables referring to the same inner instance are not + * affected; they continue to referencing the original immutable instance. */ template void mutate(Immutable& immutable, Fn&& fn) { diff --git a/include/mbgl/util/indexed_tuple.hpp b/include/mbgl/util/indexed_tuple.hpp index 4ad9e210956..4fc1e99c1c9 100644 --- a/include/mbgl/util/indexed_tuple.hpp +++ b/include/mbgl/util/indexed_tuple.hpp @@ -16,11 +16,13 @@ struct TypeIndex : std::integral_constant {}; template struct TypeIndex : std::integral_constant::value> {}; -template class IndexedTuple; +template +class IndexedTuple; /// A tuple of Ts, where individual members can be accessed via `t.get()` for I ∈ Is. /// -/// See https://github.com/mapbox/cpp/blob/1bb519ef25edd6169f1d6d8a65414044616590a9/docs/structural-metaprogramming.md +/// See +/// https://github.com/mapbox/cpp/blob/1bb519ef25edd6169f1d6d8a65414044616590a9/docs/structural-metaprogramming.md /// for motivation. template class IndexedTuple, TypeList> : public std::tuple { @@ -38,15 +40,13 @@ class IndexedTuple, TypeList> : public std::tuple } template - IndexedTuple(Us&&... other) : std::tuple(std::forward(other)...) {}; + IndexedTuple(Us&&... other) + : std::tuple(std::forward(other)...){}; template - IndexedTuple, TypeList> - concat(const IndexedTuple, TypeList>& other) const { - return IndexedTuple, TypeList> { - get()..., - other.template get()... - }; + IndexedTuple, TypeList> concat( + const IndexedTuple, TypeList>& other) const { + return IndexedTuple, TypeList>{get()..., other.template get()...}; } // Help out MSVC++ @@ -54,9 +54,7 @@ class IndexedTuple, TypeList> : public std::tuple return static_cast&>(*this) == static_cast&>(other); } - bool operator!=(const IndexedTuple, TypeList>& other) const { - return !(*this == other); - } + bool operator!=(const IndexedTuple, TypeList>& other) const { return !(*this == other); } }; template diff --git a/include/mbgl/util/interpolate.hpp b/include/mbgl/util/interpolate.hpp index 6434fd322a2..d893f8a4b1b 100644 --- a/include/mbgl/util/interpolate.hpp +++ b/include/mbgl/util/interpolate.hpp @@ -32,16 +32,12 @@ T interpolate(const T& a, const T& b, const float t) { template struct Interpolator { - T operator()(const T& a, const T& b, const double t) const { - return a * (1.0 - t) + b * t; - } + T operator()(const T& a, const T& b, const double t) const { return a * (1.0 - t) + b * t; } }; template <> struct Interpolator { - float operator()(const float& a, const float& b, const float t) const { - return a * (1.0f - t) + b * t; - } + float operator()(const float& a, const float& b, const float t) const { return a * (1.0f - t) + b * t; } float operator()(const float& a, const float& b, const double t) const { return static_cast(a * (1.0 - t) + b * t); @@ -55,7 +51,7 @@ struct Interpolator> { template Array operator()(const Array& a, const Array& b, const double t, std::index_sequence) { - return {{ interpolate(a[I], b[I], t)... }}; + return {{interpolate(a[I], b[I], t)...}}; } public: @@ -71,7 +67,7 @@ struct Interpolator> { template Array operator()(const Array& a, const Array& b, const float t, std::index_sequence) { - return {{ interpolate(a[I], b[I], t)... }}; + return {{interpolate(a[I], b[I], t)...}}; } public: @@ -80,7 +76,6 @@ struct Interpolator> { } }; - /// In order to accept Array as an output value for Curve /// expressions, we need to have an interpolatable std::vector type. /// However, style properties like line-dasharray are represented using @@ -89,21 +84,18 @@ struct Interpolator> { /// asserting that (a) the vectors are the same size, and (b) they contain /// only numeric values. (These invariants should be relatively safe, /// being enforced by the expression type system.) -template<> +template <> struct Interpolator> { std::vector operator()(const std::vector& a, - const std::vector& b, - const double t) const { + const std::vector& b, + const double t) const { assert(a.size() == b.size()); if (a.empty()) return {}; std::vector result; for (std::size_t i = 0; i < a.size(); i++) { assert(a[i].template is()); assert(b[i].template is()); - style::expression::Value item = interpolate( - a[i].template get(), - b[i].template get(), - t); + style::expression::Value item = interpolate(a[i].template get(), b[i].template get(), t); result.push_back(item); } return result; @@ -117,7 +109,7 @@ struct Interpolator { auto pos = style::Position(); auto interpolated = interpolate(a.getCartesian(), b.getCartesian(), t); pos.setCartesian(interpolated); - return { pos }; + return {pos}; } }; @@ -125,21 +117,11 @@ template <> struct Interpolator { public: Color operator()(const Color& a, const Color& b, const float t) { - return { - interpolate(a.r, b.r, t), - interpolate(a.g, b.g, t), - interpolate(a.b, b.b, t), - interpolate(a.a, b.a, t) - }; + return {interpolate(a.r, b.r, t), interpolate(a.g, b.g, t), interpolate(a.b, b.b, t), interpolate(a.a, b.a, t)}; } Color operator()(const Color& a, const Color& b, const double t) { - return { - interpolate(a.r, b.r, t), - interpolate(a.g, b.g, t), - interpolate(a.b, b.b, t), - interpolate(a.a, b.a, t) - }; + return {interpolate(a.r, b.r, t), interpolate(a.g, b.g, t), interpolate(a.b, b.b, t), interpolate(a.a, b.a, t)}; } }; @@ -172,29 +154,20 @@ struct Uninterpolated { }; template <> -struct Interpolator - : Uninterpolated {}; +struct Interpolator : Uninterpolated {}; template -struct Interpolator>> - : Uninterpolated {}; +struct Interpolator>> : Uninterpolated {}; template <> -struct Interpolator - : Uninterpolated {}; +struct Interpolator : Uninterpolated {}; template -struct Interpolator> - : Uninterpolated {}; +struct Interpolator> : Uninterpolated {}; template struct Interpolatable - : std::conditional_t< - !std::is_base_of_v>, - std::true_type, - std::false_type> {}; - - + : std::conditional_t>, std::true_type, std::false_type> {}; } // namespace util } // namespace mbgl diff --git a/include/mbgl/util/logging.hpp b/include/mbgl/util/logging.hpp index a3d6f776f56..fc6776d4c67 100644 --- a/include/mbgl/util/logging.hpp +++ b/include/mbgl/util/logging.hpp @@ -18,13 +18,11 @@ class Log { /// When an observer is set, this function will be called for every log /// message. Returning true will consume the message. - virtual bool onRecord(EventSeverity severity, Event event, int64_t code, const std::string &msg) = 0; + virtual bool onRecord(EventSeverity severity, Event event, int64_t code, const std::string& msg) = 0; }; class NullObserver : public Observer { - bool onRecord(EventSeverity, Event, int64_t, const std::string&) override { - return true; - } + bool onRecord(EventSeverity, Event, int64_t, const std::string&) override { return true; } }; static void setObserver(std::unique_ptr Observer); @@ -42,40 +40,39 @@ class Log { static void useLogThread(bool enable); - template - static void Debug(Event event, Args&& ...args) { + template + static void Debug(Event event, Args&&... args) { Record(EventSeverity::Debug, event, ::std::forward(args)...); } - template - static void Info(Event event, Args&& ...args) { + template + static void Info(Event event, Args&&... args) { Record(EventSeverity::Info, event, ::std::forward(args)...); } - template - static void Warning(Event event, Args&& ...args) { + template + static void Warning(Event event, Args&&... args) { Record(EventSeverity::Warning, event, ::std::forward(args)...); } - template - static void Error(Event event, Args&& ...args) { + template + static void Error(Event event, Args&&... args) { Record(EventSeverity::Error, event, ::std::forward(args)...); } - template - static void Record(EventSeverity severity, Event event, Args&& ...args) { - if (!includes(severity, disabledEventSeverities) && - !includes(event, disabledEvents) && - !includes({ severity, event }, disabledEventPermutations)) { - record(severity, event, ::std::forward(args)...); + template + static void Record(EventSeverity severity, Event event, Args&&... args) { + if (!includes(severity, disabledEventSeverities) && !includes(event, disabledEvents) && + !includes({severity, event}, disabledEventPermutations)) { + record(severity, event, ::std::forward(args)...); } } private: static Log* get() noexcept; - static void record(EventSeverity severity, Event event, const std::string &msg); - static void record(EventSeverity severity, Event event, int64_t code, const std::string &msg); + static void record(EventSeverity severity, Event event, const std::string& msg); + static void record(EventSeverity severity, Event event, int64_t code, const std::string& msg); static void record(EventSeverity severity, Event event, int64_t code, @@ -85,7 +82,7 @@ class Log { // This method is the data sink that must be implemented by each platform we // support. It should ideally output the error message in a human readable // format to the developer. - static void platformRecord(EventSeverity severity, const std::string &msg); + static void platformRecord(EventSeverity severity, const std::string& msg); class Impl; const std::unique_ptr impl; }; diff --git a/include/mbgl/util/noncopyable.hpp b/include/mbgl/util/noncopyable.hpp index 8cb7e198d9a..99706056c80 100644 --- a/include/mbgl/util/noncopyable.hpp +++ b/include/mbgl/util/noncopyable.hpp @@ -1,15 +1,14 @@ #pragma once -namespace mbgl { namespace util { +namespace mbgl { +namespace util { -namespace non_copyable_ -{ +namespace non_copyable_ { -class noncopyable -{ +class noncopyable { public: - noncopyable( noncopyable const& ) = delete; - noncopyable& operator=(noncopyable const& ) = delete; + noncopyable(noncopyable const&) = delete; + noncopyable& operator=(noncopyable const&) = delete; protected: constexpr noncopyable() = default; diff --git a/include/mbgl/util/platform.hpp b/include/mbgl/util/platform.hpp index ed4710424af..96a175ef740 100644 --- a/include/mbgl/util/platform.hpp +++ b/include/mbgl/util/platform.hpp @@ -17,7 +17,7 @@ std::string lowercase(const std::string &string); std::string getCurrentThreadName(); /// Set the name of the current thread, truncated at 15. -void setCurrentThreadName(const std::string& name); +void setCurrentThreadName(const std::string &name); /// Makes the current thread low priority. void makeThreadLowPriority(); diff --git a/include/mbgl/util/projection.hpp b/include/mbgl/util/projection.hpp index 4c2db837c87..a017496695a 100644 --- a/include/mbgl/util/projection.hpp +++ b/include/mbgl/util/projection.hpp @@ -15,7 +15,8 @@ class ProjectedMeters { public: ProjectedMeters(double n_ = 0, double e_ = 0) - : _northing(n_), _easting(e_) { + : _northing(n_), + _easting(e_) { if (std::isnan(_northing)) { throw std::domain_error("northing must not be NaN"); } @@ -31,9 +32,7 @@ class ProjectedMeters { return a._northing == b._northing && a._easting == b._easting; } - friend bool operator!=(const ProjectedMeters& a, const ProjectedMeters& b) { - return !(a == b); - } + friend bool operator!=(const ProjectedMeters& a, const ProjectedMeters& b) { return !(a == b); } }; /// Spherical Mercator projection @@ -41,15 +40,14 @@ class ProjectedMeters { class Projection { public: // Map pixel width at given scale. - static double worldSize(double scale) { - return scale * util::tileSize_D; - } + static double worldSize(double scale) { return scale * util::tileSize_D; } static double getMetersPerPixelAtLatitude(double lat, double zoom) { const double constrainedZoom = util::clamp(zoom, util::MIN_ZOOM, util::MAX_ZOOM); const double constrainedScale = std::pow(2.0, constrainedZoom); const double constrainedLatitude = util::clamp(lat, -util::LATITUDE_MAX, util::LATITUDE_MAX); - return std::cos(util::deg2rad(constrainedLatitude)) * util::M2PI * util::EARTH_RADIUS_M / worldSize(constrainedScale); + return std::cos(util::deg2rad(constrainedLatitude)) * util::M2PI * util::EARTH_RADIUS_M / + worldSize(constrainedScale); } static ProjectedMeters projectedMetersForLatLng(const LatLng& latLng) { @@ -59,14 +57,15 @@ class Projection { const double m = 1 - 1e-15; const double f = util::clamp(std::sin(util::deg2rad(constrainedLatitude)), -m, m); - const double easting = util::deg2rad(util::EARTH_RADIUS_M * constrainedLongitude); + const double easting = util::deg2rad(util::EARTH_RADIUS_M * constrainedLongitude); const double northing = 0.5 * util::EARTH_RADIUS_M * std::log((1 + f) / (1 - f)); return {northing, easting}; } static LatLng latLngForProjectedMeters(const ProjectedMeters& projectedMeters) { - double latitude = util::rad2deg(2 * std::atan(std::exp(projectedMeters.northing() / util::EARTH_RADIUS_M)) - (M_PI / 2.0)); + double latitude = util::rad2deg(2 * std::atan(std::exp(projectedMeters.northing() / util::EARTH_RADIUS_M)) - + (M_PI / 2.0)); double longitude = util::rad2deg(projectedMeters.easting()) / util::EARTH_RADIUS_M; latitude = util::clamp(latitude, -util::LATITUDE_MAX, util::LATITUDE_MAX); @@ -75,31 +74,25 @@ class Projection { return {latitude, longitude}; } - static Point project(const LatLng& latLng, double scale) { - return project_(latLng, worldSize(scale)); - } + static Point project(const LatLng& latLng, double scale) { return project_(latLng, worldSize(scale)); } /// Returns point on tile - static Point project(const LatLng& latLng, int32_t zoom) { - return project_(latLng, 1 << zoom); - } + static Point project(const LatLng& latLng, int32_t zoom) { return project_(latLng, 1 << zoom); } static LatLng unproject(const Point& p, double scale, LatLng::WrapMode wrapMode = LatLng::Unwrapped) { auto p2 = p * util::DEGREES_MAX / worldSize(scale); - return LatLng { - std::atan(std::exp(util::deg2rad(util::LONGITUDE_MAX - p2.y))) * util::DEGREES_MAX / M_PI - 90.0, - p2.x - util::LONGITUDE_MAX, - wrapMode - }; + return LatLng{std::atan(std::exp(util::deg2rad(util::LONGITUDE_MAX - p2.y))) * util::DEGREES_MAX / M_PI - 90.0, + p2.x - util::LONGITUDE_MAX, + wrapMode}; } private: static Point project_(const LatLng& latLng, double worldSize) { const double latitude = util::clamp(latLng.latitude(), -util::LATITUDE_MAX, util::LATITUDE_MAX); - return Point { - util::LONGITUDE_MAX + latLng.longitude(), - util::LONGITUDE_MAX - util::rad2deg(std::log(std::tan(M_PI / 4 + latitude * M_PI / util::DEGREES_MAX))) - } * (worldSize / util::DEGREES_MAX); + return Point{util::LONGITUDE_MAX + latLng.longitude(), + util::LONGITUDE_MAX - + util::rad2deg(std::log(std::tan(M_PI / 4 + latitude * M_PI / util::DEGREES_MAX)))} * + (worldSize / util::DEGREES_MAX); } }; diff --git a/include/mbgl/util/range.hpp b/include/mbgl/util/range.hpp index 5591a22a1f3..f5e4ac5357a 100644 --- a/include/mbgl/util/range.hpp +++ b/include/mbgl/util/range.hpp @@ -8,7 +8,8 @@ template class Range { public: constexpr Range(T min_, T max_) - : min(std::move(min_)), max(std::move(max_)) {} + : min(std::move(min_)), + max(std::move(max_)) {} T min; T max; diff --git a/include/mbgl/util/run_loop.hpp b/include/mbgl/util/run_loop.hpp index 26d6cbcc165..7e1d94332a9 100644 --- a/include/mbgl/util/run_loop.hpp +++ b/include/mbgl/util/run_loop.hpp @@ -16,10 +16,9 @@ namespace mbgl { namespace util { -using LOOP_HANDLE = void *; +using LOOP_HANDLE = void*; -class RunLoop : public Scheduler, - private util::noncopyable { +class RunLoop : public Scheduler, private util::noncopyable { public: enum class Type : uint8_t { Default, @@ -32,9 +31,9 @@ class RunLoop : public Scheduler, }; enum class Event : uint8_t { - None = 0, - Read = 1, - Write = 2, + None = 0, + Read = 1, + Write = 2, ReadWrite = Read | Write, }; @@ -73,8 +72,7 @@ class RunLoop : public Scheduler, // Post the cancellable work fn(args...) to this RunLoop. template - std::unique_ptr - invokeCancellable(Fn&& fn, Args&&... args) { + std::unique_ptr invokeCancellable(Fn&& fn, Args&&... args) { std::shared_ptr task = WorkTask::make(std::forward(fn), std::forward(args)...); push(Priority::Default, task); return std::make_unique(task); diff --git a/include/mbgl/util/size.hpp b/include/mbgl/util/size.hpp index e20be06bb5c..815ba54cbf7 100644 --- a/include/mbgl/util/size.hpp +++ b/include/mbgl/util/size.hpp @@ -8,20 +8,15 @@ class Size { public: constexpr Size() = default; - constexpr Size(const uint32_t width_, const uint32_t height_) : width(width_), height(height_) { - } - - constexpr uint32_t area() const { - return width * height; - } - - constexpr float aspectRatio() const { - return static_cast(width) / static_cast(height); - } - - constexpr bool isEmpty() const { - return width == 0 || height == 0; - } + constexpr Size(const uint32_t width_, const uint32_t height_) + : width(width_), + height(height_) {} + + constexpr uint32_t area() const { return width * height; } + + constexpr float aspectRatio() const { return static_cast(width) / static_cast(height); } + + constexpr bool isEmpty() const { return width == 0 || height == 0; } uint32_t width = 0; uint32_t height = 0; diff --git a/include/mbgl/util/string.hpp b/include/mbgl/util/string.hpp index 370b08afaf7..70e1212f949 100644 --- a/include/mbgl/util/string.hpp +++ b/include/mbgl/util/string.hpp @@ -11,8 +11,7 @@ namespace std { -inline int stoi(const std::string &str) -{ +inline int stoi(const std::string &str) { return atoi(str.c_str()); } @@ -85,7 +84,7 @@ std::string toString(T) = delete; std::string toHex(uint32_t); std::string toHex(uint64_t); -inline float stof(const std::string& str) { +inline float stof(const std::string &str) { return std::stof(str); } diff --git a/include/mbgl/util/thread.hpp b/include/mbgl/util/thread.hpp index 42a18ba6844..a2a339bad4e 100644 --- a/include/mbgl/util/thread.hpp +++ b/include/mbgl/util/thread.hpp @@ -22,12 +22,13 @@ namespace util { /// @brief Manages a thread with `Object`. /// -/// Upon creation of this object, it launches a thread and creates an object of type `Object` -/// in that thread. When the `Thread<>` object is destructed, the destructor waits -/// for thread termination. The `Thread<>` constructor blocks until the thread and -/// the `Object` are fully created, so after the object creation, it's safe to obtain the -/// `Object` stored in this thread. The thread created will always have low priority on -/// the platforms that support setting thread priority. +/// Upon creation of this object, it launches a thread and creates an object of +/// type `Object` in that thread. When the `Thread<>` object is destructed, the +/// destructor waits for thread termination. The `Thread<>` constructor blocks +/// until the thread and the `Object` are fully created, so after the object +/// creation, it's safe to obtain the `Object` stored in this thread. The thread +/// created will always have low priority on the platforms that support setting +/// thread priority. /// /// The following properties make this class different from `ThreadPool`: /// @@ -35,7 +36,8 @@ namespace util { /// - `Object` will live in a single thread, providing thread affinity. /// - It is safe to use `ThreadLocal` in an `Object` managed by `Thread<>` /// - A `RunLoop` is created for the `Object` thread. -/// - `Object` can use `Timer` and do asynchronous I/O, like wait for sockets events. +/// - `Object` can use `Timer` and do asynchronous I/O, like wait for sockets +/// events. template class Thread { public: @@ -62,7 +64,7 @@ class Thread { loop->run(); - (void) establishedActor; + (void)establishedActor; loop = nullptr; } @@ -85,14 +87,12 @@ class Thread { } std::promise stoppable; - + running.wait(); // Invoke a noop task on the run loop to ensure that we're executing // run() before we call stop() - loop->invoke([&] { - stoppable.set_value(); - }); + loop->invoke([&] { stoppable.set_value(); }); stoppable.get_future().get(); @@ -104,9 +104,7 @@ class Thread { /// can be used to send messages to `Object`. It is safe /// to the non-owning reference to outlive this object /// and be used after the `Thread<>` gets destroyed. - ActorRef> actor() { - return object.self(); - } + ActorRef> actor() { return object.self(); } /// Pauses the `Object` thread. It will prevent the object to wake /// up from events such as timers and file descriptor I/O. Messages @@ -153,7 +151,7 @@ class Thread { std::thread thread; std::future running; - + std::unique_ptr> paused; std::unique_ptr> resumed; diff --git a/include/mbgl/util/tile_server_options.hpp b/include/mbgl/util/tile_server_options.hpp index 41c5ba7d1fa..8fc1b943f6a 100644 --- a/include/mbgl/util/tile_server_options.hpp +++ b/include/mbgl/util/tile_server_options.hpp @@ -12,279 +12,295 @@ namespace mbgl { /** * @brief Holds values for tile server options. */ - class TileServerOptions final { - public: - /** - * @brief Constructs a TileServerOptions object with default values. - */ - explicit TileServerOptions(); - ~TileServerOptions(); - - // movable - TileServerOptions(TileServerOptions&& options) noexcept; - TileServerOptions& operator=(TileServerOptions&& options) noexcept; - - // copyable - TileServerOptions(const TileServerOptions&); - - - TileServerOptions clone() const; - - /** - * @brief Sets the API base URL. - * - * @param baseURL API base URL. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withBaseURL(std::string baseURL); - - /** - * @brief Gets the previously set (or default) API base URL. - * - * @return const std::string& API base URL. - */ - const std::string& baseURL() const; - - /** - * @brief Sets the scheme alias for the tile server. For example maptiler:// for MapTiler. - * - * @param alias The URI alias. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withUriSchemeAlias(std::string alias); - - /** - * @brief Gets the previously set (or default) tile server URI alias. - * - * @return const std::string& scheme alias. - */ - const std::string& uriSchemeAlias() const; - - /** - * @brief Sets the template for sources. - * - * @param sourceTemplate The source template. - * @param domainName The domain name. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withSourceTemplate(std::string sourceTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) source template. - * - * @return const std::string& source template. - */ - const std::string& sourceTemplate() const; - - /** - * @brief Gets the previously set (or default) source domain name - * - * @return const std::string& source domain name. - */ - const std::string& sourceDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& sourceVersionPrefix() const; - - /** - * @brief Sets the template for styles. - * - * @param styleTemplate The style template. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical style URL . - * - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withStyleTemplate(std::string styleTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) style template. - * - * @return const std::string& style template. - */ - const std::string& styleTemplate() const; - - /** - * @brief Gets the previously set (or default) style domain name. - * - * @return const std::string& domain name. - */ - const std::string& styleDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& styleVersionPrefix() const; - - /** - * @brief Sets the template for sprites. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical sprite URL . - * - * @param spritesTemplate The sprites template. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withSpritesTemplate(std::string spritesTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) sprites template. - * - * @return const std::string& sprites template. - */ - const std::string& spritesTemplate() const; - - /** - * @brief Gets the previously set (or default) sprites domain name. - * - * @return const std::string& domain name. - */ - const std::string& spritesDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& spritesVersionPrefix() const; - - /** - * @brief Sets the template for glyphs. - * - * @param glyphsTemplate The glyphs template. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical glyphs URL . - * - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withGlyphsTemplate(std::string glyphsTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) glyphs template. - * - * @return const std::string& glyphs template. - */ - const std::string& glyphsTemplate() const; - - /** - * @brief Gets the previously set (or default) glyphs domain name. - * - * @return const std::string& domain name. - */ - const std::string& glyphsDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& glyphsVersionPrefix() const; - - /** - * @brief Sets the template for tiles. - * - * @param tileTemplate The tile template. - * @param domainName If set, the URL domain must contain the specified string to be matched as canonical tile URL . - * - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withTileTemplate(std::string tileTemplate, std::string domainName, std::optional versionPrefix); - - /** - * @brief Gets the previously set (or default) tile template. - * - * @return const std::string& tile template. - */ - const std::string& tileTemplate() const; - - /** - * @brief Gets the previously set (or default) tile domain name. - * - * @return const std::string& domain name. - */ - const std::string& tileDomainName() const; - - /** - * @brief Gets the previously set (or default) version prefix - * - * @return const optional& version prefix. - */ - const std::optional& tileVersionPrefix() const; - - /** - * @brief Sets the access token parameter name. - * - * @param apiKeyParameterName The parameter name. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withApiKeyParameterName(std::string apiKeyParameterName); - - /** - * @brief Gets the previously set (or default) apiKeyParameterName. - * - * @return const std::string& apiKeyParameterName. - */ - const std::string& apiKeyParameterName() const; - - TileServerOptions& setRequiresApiKey(bool apiKeyRequired); - - /** - * @brief Whether the tile server requires API key - * - * @return const bool true if API key is required - */ - bool requiresApiKey() const; - /** - * @brief Gets the default styles. - */ - const std::vector defaultStyles() const; - - /** - * @brief Sets the collection default styles. - * - * @param styles The style set. - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withDefaultStyles(std::vector styles); - - /** - * @brief Sets the default style by name. The style name must exists in defaultStyles collection - * - * @param defaultStyle The style name - * @return TileServerOptions for chaining options together. - */ - TileServerOptions& withDefaultStyle(std::string defaultStyle); - - /** - * @brief Get the default style name - */ - const std::string& defaultStyle() const; - - /** - * @brief Get the default configuration - */ - static TileServerOptions DefaultConfiguration(); - - /** - * @brief Get the tile server options configured for MapLibre. - */ - static TileServerOptions MapLibreConfiguration(); - - /** - * @brief Get the tile server options configured for Mapbox. - */ - static TileServerOptions MapboxConfiguration(); - - /** - * @brief Get the tile server options configured for MapTiler. - */ - static TileServerOptions MapTilerConfiguration(); - - private: - class Impl; - std::unique_ptr impl_; - }; +class TileServerOptions final { +public: + /** + * @brief Constructs a TileServerOptions object with default values. + */ + explicit TileServerOptions(); + ~TileServerOptions(); + + // movable + TileServerOptions(TileServerOptions&& options) noexcept; + TileServerOptions& operator=(TileServerOptions&& options) noexcept; + + // copyable + TileServerOptions(const TileServerOptions&); + + TileServerOptions clone() const; + + /** + * @brief Sets the API base URL. + * + * @param baseURL API base URL. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withBaseURL(std::string baseURL); + + /** + * @brief Gets the previously set (or default) API base URL. + * + * @return const std::string& API base URL. + */ + const std::string& baseURL() const; + + /** + * @brief Sets the scheme alias for the tile server. For example maptiler:// for MapTiler. + * + * @param alias The URI alias. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withUriSchemeAlias(std::string alias); + + /** + * @brief Gets the previously set (or default) tile server URI alias. + * + * @return const std::string& scheme alias. + */ + const std::string& uriSchemeAlias() const; + + /** + * @brief Sets the template for sources. + * + * @param sourceTemplate The source template. + * @param domainName The domain name. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withSourceTemplate(std::string sourceTemplate, + std::string domainName, + std::optional versionPrefix); + + /** + * @brief Gets the previously set (or default) source template. + * + * @return const std::string& source template. + */ + const std::string& sourceTemplate() const; + + /** + * @brief Gets the previously set (or default) source domain name + * + * @return const std::string& source domain name. + */ + const std::string& sourceDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& sourceVersionPrefix() const; + + /** + * @brief Sets the template for styles. + * + * @param styleTemplate The style template. + * @param domainName If set, the URL domain must contain the specified + * string to be matched as canonical style URL . + * + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withStyleTemplate(std::string styleTemplate, + std::string domainName, + std::optional versionPrefix); + + /** + * @brief Gets the previously set (or default) style template. + * + * @return const std::string& style template. + */ + const std::string& styleTemplate() const; + + /** + * @brief Gets the previously set (or default) style domain name. + * + * @return const std::string& domain name. + */ + const std::string& styleDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& styleVersionPrefix() const; + + /** + * @brief Sets the template for sprites. + * @param domainName If set, the URL domain must contain the specified + * string to be matched as canonical sprite URL + * . + * + * @param spritesTemplate The sprites template. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withSpritesTemplate(std::string spritesTemplate, + std::string domainName, + std::optional versionPrefix); + + /** + * @brief Gets the previously set (or default) sprites template. + * + * @return const std::string& sprites template. + */ + const std::string& spritesTemplate() const; + + /** + * @brief Gets the previously set (or default) sprites domain name. + * + * @return const std::string& domain name. + */ + const std::string& spritesDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& spritesVersionPrefix() const; + + /** + * @brief Sets the template for glyphs. + * + * @param glyphsTemplate The glyphs template. + * @param domainName If set, the URL domain must contain the specified + * string to be matched as canonical glyphs URL + * . + * + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withGlyphsTemplate(std::string glyphsTemplate, + std::string domainName, + std::optional versionPrefix); + + /** + * @brief Gets the previously set (or default) glyphs template. + * + * @return const std::string& glyphs template. + */ + const std::string& glyphsTemplate() const; + + /** + * @brief Gets the previously set (or default) glyphs domain name. + * + * @return const std::string& domain name. + */ + const std::string& glyphsDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& glyphsVersionPrefix() const; + + /** + * @brief Sets the template for tiles. + * + * @param tileTemplate The tile template. + * @param domainName If set, the URL domain must contain the specified + * string to be matched as canonical tile URL . + * + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withTileTemplate(std::string tileTemplate, + std::string domainName, + std::optional versionPrefix); + + /** + * @brief Gets the previously set (or default) tile template. + * + * @return const std::string& tile template. + */ + const std::string& tileTemplate() const; + + /** + * @brief Gets the previously set (or default) tile domain name. + * + * @return const std::string& domain name. + */ + const std::string& tileDomainName() const; + + /** + * @brief Gets the previously set (or default) version prefix + * + * @return const optional& version prefix. + */ + const std::optional& tileVersionPrefix() const; + + /** + * @brief Sets the access token parameter name. + * + * @param apiKeyParameterName The parameter name. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withApiKeyParameterName(std::string apiKeyParameterName); + + /** + * @brief Gets the previously set (or default) apiKeyParameterName. + * + * @return const std::string& apiKeyParameterName. + */ + const std::string& apiKeyParameterName() const; + + TileServerOptions& setRequiresApiKey(bool apiKeyRequired); + + /** + * @brief Whether the tile server requires API key + * + * @return const bool true if API key is required + */ + bool requiresApiKey() const; + /** + * @brief Gets the default styles. + */ + const std::vector defaultStyles() const; + + /** + * @brief Sets the collection default styles. + * + * @param styles The style set. + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withDefaultStyles(std::vector styles); + + /** + * @brief Sets the default style by name. The style name must exists in + * defaultStyles collection + * + * @param defaultStyle The style name + * @return TileServerOptions for chaining options together. + */ + TileServerOptions& withDefaultStyle(std::string defaultStyle); + + /** + * @brief Get the default style name + */ + const std::string& defaultStyle() const; + + /** + * @brief Get the default configuration + */ + static TileServerOptions DefaultConfiguration(); + + /** + * @brief Get the tile server options configured for MapLibre. + */ + static TileServerOptions MapLibreConfiguration(); + + /** + * @brief Get the tile server options configured for Mapbox. + */ + static TileServerOptions MapboxConfiguration(); + + /** + * @brief Get the tile server options configured for MapTiler. + */ + static TileServerOptions MapTilerConfiguration(); + +private: + class Impl; + std::unique_ptr impl_; +}; } // namespace mbgl diff --git a/include/mbgl/util/tileset.hpp b/include/mbgl/util/tileset.hpp index 4bac337ffe3..d4bb5348f73 100644 --- a/include/mbgl/util/tileset.hpp +++ b/include/mbgl/util/tileset.hpp @@ -14,8 +14,14 @@ namespace mbgl { class Tileset { public: - enum class Scheme : bool { XYZ, TMS }; - enum class DEMEncoding : bool { Mapbox, Terrarium }; + enum class Scheme : bool { + XYZ, + TMS + }; + enum class DEMEncoding : bool { + Mapbox, + Terrarium + }; std::vector tiles; Range zoomRange; @@ -39,13 +45,11 @@ class Tileset { // TileJSON also includes center and zoom but they are not used by mbgl. friend bool operator==(const Tileset& lhs, const Tileset& rhs) { - return std::tie(lhs.tiles, lhs.zoomRange, lhs.attribution, lhs.scheme, lhs.bounds) - == std::tie(rhs.tiles, rhs.zoomRange, rhs.attribution, rhs.scheme, rhs.bounds); + return std::tie(lhs.tiles, lhs.zoomRange, lhs.attribution, lhs.scheme, lhs.bounds) == + std::tie(rhs.tiles, rhs.zoomRange, rhs.attribution, rhs.scheme, rhs.bounds); } - friend bool operator!=(const Tileset& lhs, const Tileset& rhs) { - return !(lhs == rhs); - } + friend bool operator!=(const Tileset& lhs, const Tileset& rhs) { return !(lhs == rhs); } }; } // namespace mbgl diff --git a/include/mbgl/util/traits.hpp b/include/mbgl/util/traits.hpp index 75ae6f315e7..b0fda1566c5 100644 --- a/include/mbgl/util/traits.hpp +++ b/include/mbgl/util/traits.hpp @@ -7,23 +7,31 @@ namespace mbgl { -template +template constexpr auto underlying_type(T t) -> typename std::underlying_type_t { return typename std::underlying_type_t(t); } -template struct is_utf16char_like: std::false_type {}; -template struct is_utf16char_like: is_utf16char_like {}; -template <> struct is_utf16char_like: std::true_type {}; -template <> struct is_utf16char_like: std::true_type {}; -template <> struct is_utf16char_like: std::true_type {}; +template +struct is_utf16char_like : std::false_type {}; +template +struct is_utf16char_like : is_utf16char_like {}; +template <> +struct is_utf16char_like : std::true_type {}; +template <> +struct is_utf16char_like : std::true_type {}; +template <> +struct is_utf16char_like : std::true_type {}; -template using is_utf16char_like_pointer = std::integral_constant - && is_utf16char_like::type>::value>; +template +using is_utf16char_like_pointer = + std::integral_constant && is_utf16char_like::type>::value>; template -typename std::enable_if::value && is_utf16char_like_pointer::value, OutPointer>::type utf16char_cast(InChar *in) -{ +typename std::enable_if::value && is_utf16char_like_pointer::value, + OutPointer>::type +utf16char_cast(InChar *in) { return reinterpret_cast(in); } diff --git a/include/mbgl/util/unitbezier.hpp b/include/mbgl/util/unitbezier.hpp index e55fcc21e64..e6fcf3fbf39 100644 --- a/include/mbgl/util/unitbezier.hpp +++ b/include/mbgl/util/unitbezier.hpp @@ -34,17 +34,14 @@ namespace util { struct UnitBezier { /// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). constexpr UnitBezier(double p1x, double p1y, double p2x, double p2y) - : cx(3.0 * p1x) - , bx(3.0 * (p2x - p1x) - (3.0 * p1x)) - , ax(1.0 - (3.0 * p1x) - (3.0 * (p2x - p1x) - (3.0 * p1x))) - , cy(3.0 * p1y) - , by(3.0 * (p2y - p1y) - (3.0 * p1y)) - , ay(1.0 - (3.0 * p1y) - (3.0 * (p2y - p1y) - (3.0 * p1y))) { - } + : cx(3.0 * p1x), + bx(3.0 * (p2x - p1x) - (3.0 * p1x)), + ax(1.0 - (3.0 * p1x) - (3.0 * (p2x - p1x) - (3.0 * p1x))), + cy(3.0 * p1y), + by(3.0 * (p2y - p1y) - (3.0 * p1y)), + ay(1.0 - (3.0 * p1y) - (3.0 * (p2y - p1y) - (3.0 * p1y))) {} - std::pair getP1() const { - return { cx / 3.0, cy / 3.0 }; - } + std::pair getP1() const { return {cx / 3.0, cy / 3.0}; } std::pair getP2() const { return { @@ -58,13 +55,9 @@ struct UnitBezier { return ((ax * t + bx) * t + cx) * t; } - double sampleCurveY(double t) const { - return ((ay * t + by) * t + cy) * t; - } + double sampleCurveY(double t) const { return ((ay * t + by) * t + cy) * t; } - double sampleCurveDerivativeX(double t) const { - return (3.0 * ax * t + 2.0 * bx) * t + cx; - } + double sampleCurveDerivativeX(double t) const { return (3.0 * ax * t + 2.0 * bx) * t + cx; } /// Given an x value, find a parametric value it came from. double solveCurveX(double x, double epsilon) const { @@ -78,11 +71,9 @@ struct UnitBezier { // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; ++i) { x2 = sampleCurveX(t2) - x; - if (fabs (x2) < epsilon) - return t2; + if (fabs(x2) < epsilon) return t2; d2 = sampleCurveDerivativeX(t2); - if (fabs(d2) < 1e-6) - break; + if (fabs(d2) < 1e-6) break; t2 = t2 - x2 / d2; } @@ -91,15 +82,12 @@ struct UnitBezier { t1 = 1.0; t2 = x; - if (t2 < t0) - return t0; - if (t2 > t1) - return t1; + if (t2 < t0) return t0; + if (t2 > t1) return t1; while (t0 < t1) { x2 = sampleCurveX(t2); - if (fabs(x2 - x) < epsilon) - return t2; + if (fabs(x2 - x) < epsilon) return t2; if (x > x2) t0 = t2; else @@ -111,13 +99,10 @@ struct UnitBezier { return t2; } - double solve(double x, double epsilon) const { - return sampleCurveY(solveCurveX(x, epsilon)); - } - + double solve(double x, double epsilon) const { return sampleCurveY(solveCurveX(x, epsilon)); } + bool operator==(const UnitBezier& rhs) const { - return std::tie(cx, bx, ax, cy, by, ay) == - std::tie(rhs.cx, rhs.bx, rhs.ax, rhs.cy, rhs.by, rhs.ay); + return std::tie(cx, bx, ax, cy, by, ay) == std::tie(rhs.cx, rhs.bx, rhs.ax, rhs.cy, rhs.by, rhs.ay); } private: diff --git a/include/mbgl/util/work_task.hpp b/include/mbgl/util/work_task.hpp index 830198805b2..3f44f529bc9 100644 --- a/include/mbgl/util/work_task.hpp +++ b/include/mbgl/util/work_task.hpp @@ -6,9 +6,10 @@ namespace mbgl { -/// A movable type-erasing function wrapper. This allows to store arbitrary invokable -/// things (like std::function<>, or the result of a movable-only std::bind()) in the queue. -/// Source: http://stackoverflow.com/a/29642072/331379 +/// A movable type-erasing function wrapper. This allows to store arbitrary +/// invokable things (like std::function<>, or the result of a movable-only +/// std::bind()) in the queue. Source: +/// http://stackoverflow.com/a/29642072/331379 class WorkTask : private util::noncopyable { public: virtual ~WorkTask() = default; diff --git a/include/mbgl/util/work_task_impl.hpp b/include/mbgl/util/work_task_impl.hpp index c194a50189b..0710192c4cc 100644 --- a/include/mbgl/util/work_task_impl.hpp +++ b/include/mbgl/util/work_task_impl.hpp @@ -11,10 +11,9 @@ template class WorkTaskImpl : public WorkTask { public: WorkTaskImpl(F f, P p, std::shared_ptr> canceled_) - : canceled(std::move(canceled_)), - func(std::move(f)), - params(std::move(p)) { - } + : canceled(std::move(canceled_)), + func(std::move(f)), + params(std::move(p)) {} void operator()() override { // Lock the mutex while processing so that cancel() will block. @@ -57,9 +56,7 @@ std::shared_ptr WorkTask::make(Fn&& fn, Args&&... args) { auto tuple = std::make_tuple(std::forward(args)...); return std::make_shared, decltype(tuple)>>( - std::forward(fn), - std::move(tuple), - flag); + std::forward(fn), std::move(tuple), flag); } } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp old mode 100755 new mode 100644 index e2d06483854..2d8880a3e64 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.cpp @@ -13,8 +13,8 @@ namespace android { class AndroidGLRenderableResource final : public mbgl::gl::RenderableResource { public: - AndroidGLRenderableResource(AndroidRendererBackend& backend_) : backend(backend_) { - } + AndroidGLRenderableResource(AndroidRendererBackend& backend_) + : backend(backend_) {} void bind() override { assert(gfx::BackendScope::exists()); @@ -28,8 +28,7 @@ class AndroidGLRenderableResource final : public mbgl::gl::RenderableResource { AndroidRendererBackend::AndroidRendererBackend() : gl::RendererBackend(gfx::ContextMode::Unique), - mbgl::gfx::Renderable({ 64, 64 }, std::make_unique(*this)) { -} + mbgl::gfx::Renderable({64, 64}, std::make_unique(*this)) {} AndroidRendererBackend::~AndroidRendererBackend() = default; @@ -44,7 +43,7 @@ void AndroidRendererBackend::updateViewPort() { } void AndroidRendererBackend::resizeFramebuffer(int width, int height) { - size = { static_cast(width), static_cast(height) }; + size = {static_cast(width), static_cast(height)}; } PremultipliedImage AndroidRendererBackend::readFramebuffer() { @@ -64,4 +63,4 @@ void AndroidRendererBackend::markContextLost() { } } // namespace android -} // namspace mbgl +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp old mode 100755 new mode 100644 index f06f38e688f..cdd9df9511c --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_backend.hpp @@ -21,9 +21,7 @@ class AndroidRendererBackend : public gl::RendererBackend, public mbgl::gfx::Ren // mbgl::gfx::RendererBackend implementation public: - mbgl::gfx::Renderable& getDefaultRenderable() override { - return *this; - } + mbgl::gfx::Renderable& getDefaultRenderable() override { return *this; } protected: void activate() override { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp index da6d979c377..5a7256cf7b5 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.cpp @@ -18,37 +18,24 @@ namespace android { class ForwardingRendererObserver : public RendererObserver { public: ForwardingRendererObserver(util::RunLoop& mapRunLoop, RendererObserver& delegate_) - : mailbox(std::make_shared(mapRunLoop)) - , delegate(delegate_, mailbox) { - } + : mailbox(std::make_shared(mapRunLoop)), + delegate(delegate_, mailbox) {} - ~ForwardingRendererObserver() { - mailbox->close(); - } + ~ForwardingRendererObserver() { mailbox->close(); } - void onInvalidate() override { - delegate.invoke(&RendererObserver::onInvalidate); - } + void onInvalidate() override { delegate.invoke(&RendererObserver::onInvalidate); } - void onResourceError(std::exception_ptr err) override { - delegate.invoke(&RendererObserver::onResourceError, err); - } + void onResourceError(std::exception_ptr err) override { delegate.invoke(&RendererObserver::onResourceError, err); } - void onWillStartRenderingMap() override { - delegate.invoke(&RendererObserver::onWillStartRenderingMap); - } + void onWillStartRenderingMap() override { delegate.invoke(&RendererObserver::onWillStartRenderingMap); } - void onWillStartRenderingFrame() override { - delegate.invoke(&RendererObserver::onWillStartRenderingFrame); - } + void onWillStartRenderingFrame() override { delegate.invoke(&RendererObserver::onWillStartRenderingFrame); } void onDidFinishRenderingFrame(RenderMode mode, bool repaintNeeded, bool placementChanged) override { delegate.invoke(&RendererObserver::onDidFinishRenderingFrame, mode, repaintNeeded, placementChanged); } - void onDidFinishRenderingMap() override { - delegate.invoke(&RendererObserver::onDidFinishRenderingMap); - } + void onDidFinishRenderingMap() override { delegate.invoke(&RendererObserver::onDidFinishRenderingMap); } void onStyleImageMissing(const std::string& id, const StyleImageMissingCallback& done) override { delegate.invoke(&RendererObserver::onStyleImageMissing, id, done); @@ -64,13 +51,12 @@ class ForwardingRendererObserver : public RendererObserver { }; AndroidRendererFrontend::AndroidRendererFrontend(MapRenderer& mapRenderer_) - : mapRenderer(mapRenderer_) - , mapRunLoop(util::RunLoop::Get()) - , updateAsyncTask(std::make_unique([this]() { - mapRenderer.update(std::move(updateParams)); - mapRenderer.requestRender(); - })) { -} + : mapRenderer(mapRenderer_), + mapRunLoop(util::RunLoop::Get()), + updateAsyncTask(std::make_unique([this]() { + mapRenderer.update(std::move(updateParams)); + mapRenderer.requestRender(); + })) {} AndroidRendererFrontend::~AndroidRendererFrontend() = default; @@ -79,7 +65,7 @@ void AndroidRendererFrontend::reset() { } void AndroidRendererFrontend::setObserver(RendererObserver& observer) { - assert (util::RunLoop::Get()); + assert(util::RunLoop::Get()); // Don't call the Renderer directly, but use MapRenderer#setObserver to make sure // the Renderer may be re-initialised without losing the RendererObserver reference. mapRenderer.setObserver(std::make_unique(*mapRunLoop, observer)); @@ -102,9 +88,9 @@ std::vector AndroidRendererFrontend::querySourceFeatures(const std::str std::vector AndroidRendererFrontend::queryRenderedFeatures(const ScreenBox& box, const RenderedQueryOptions& options) const { - // Select the right overloaded method - std::vector (Renderer::*fn)(const ScreenBox&, const RenderedQueryOptions&) const = &Renderer::queryRenderedFeatures; + std::vector (Renderer::*fn)(const ScreenBox&, const RenderedQueryOptions&) + const = &Renderer::queryRenderedFeatures; // Waits for the result from the orchestration thread and returns return mapRenderer.actor().ask(fn, box, options).get(); @@ -112,9 +98,9 @@ std::vector AndroidRendererFrontend::queryRenderedFeatures(const Screen std::vector AndroidRendererFrontend::queryRenderedFeatures(const ScreenCoordinate& point, const RenderedQueryOptions& options) const { - // Select the right overloaded method - std::vector (Renderer::*fn)(const ScreenCoordinate&, const RenderedQueryOptions&) const = &Renderer::queryRenderedFeatures; + std::vector (Renderer::*fn)(const ScreenCoordinate&, const RenderedQueryOptions&) + const = &Renderer::queryRenderedFeatures; // Waits for the result from the orchestration thread and returns return mapRenderer.actor().ask(fn, point, options).get(); @@ -130,14 +116,16 @@ AnnotationIDs AndroidRendererFrontend::queryShapeAnnotations(const ScreenBox& bo return mapRenderer.actor().ask(&Renderer::queryShapeAnnotations, box).get(); } -FeatureExtensionValue AndroidRendererFrontend::queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const { - return mapRenderer.actor().ask(&Renderer::queryFeatureExtensions, sourceID, feature, extension, extensionField, args).get(); +FeatureExtensionValue AndroidRendererFrontend::queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args) const { + return mapRenderer.actor() + .ask(&Renderer::queryFeatureExtensions, sourceID, feature, extension, extensionField, args) + .get(); } } // namespace android } // namespace mbgl - diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp index 7302f6e42d8..4dca8ac3ba6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/android_renderer_frontend.hpp @@ -29,7 +29,6 @@ namespace android { class AndroidRendererFrontend : public RendererFrontend { public: - AndroidRendererFrontend(MapRenderer&); ~AndroidRendererFrontend() override; @@ -45,14 +44,12 @@ class AndroidRendererFrontend : public RendererFrontend { AnnotationIDs queryPointAnnotations(const ScreenBox& box) const; AnnotationIDs queryShapeAnnotations(const ScreenBox& box) const; - // Feature extension query - FeatureExtensionValue - queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const; + FeatureExtensionValue queryFeatureExtensions(const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args) const; // Memory void reduceMemoryUse(); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp index b38a25b4fbd..3a657e36973 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/marker.hpp @@ -12,7 +12,6 @@ namespace android { class Marker : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/annotations/Marker"; }; static mbgl::Point getPosition(jni::JNIEnv&, const jni::Object&); @@ -20,9 +19,7 @@ class Marker : private mbgl::util::noncopyable { static std::string getIconId(jni::JNIEnv&, const jni::Object&); static void registerNative(jni::JNIEnv&); - }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp index 20f1b3eaf23..5755bbe3e4e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/multi_point.hpp @@ -10,24 +10,22 @@ namespace mbgl { namespace android { class MultiPoint : protected mbgl::util::noncopyable { - protected: + template + static Geometry toGeometry(JNIEnv& env, const jni::Object& pointsList) { + auto jarray = java::util::List::toArray(env, pointsList); - template - static Geometry toGeometry(JNIEnv& env, const jni::Object& pointsList) { - auto jarray = java::util::List::toArray(env, pointsList); - - std::size_t size = jarray.Length(env); + std::size_t size = jarray.Length(env); - Geometry geometry; - geometry.reserve(size); + Geometry geometry; + geometry.reserve(size); - for (std::size_t i = 0; i < size; i++) { - geometry.push_back(LatLng::getGeometry(env, jarray.Get(env, i))); - } + for (std::size_t i = 0; i < size; i++) { + geometry.push_back(LatLng::getGeometry(env, jarray.Get(env, i))); + } - return geometry; - } + return geometry; + } }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp index f22cffb1007..95d9f9a0682 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.cpp @@ -13,9 +13,7 @@ mbgl::FillAnnotation Polygon::toAnnotation(jni::JNIEnv& env, const jni::Object

(env, "fillColor"); static auto strokeColor = javaClass.GetField(env, "strokeColor"); - mbgl::Polygon geometry { - MultiPoint::toGeometry>(env, polygon.Get(env, points)) - }; + mbgl::Polygon geometry{MultiPoint::toGeometry>(env, polygon.Get(env, points))}; auto jHoleListsArray = java::util::List::toArray(env, polygon.Get(env, holes)); @@ -24,7 +22,7 @@ mbgl::FillAnnotation Polygon::toAnnotation(jni::JNIEnv& env, const jni::Object

>(env, jHoleListsArray.Get(env, i))); } - mbgl::FillAnnotation annotation { geometry }; + mbgl::FillAnnotation annotation{geometry}; annotation.opacity = polygon.Get(env, alpha); annotation.color = *conversion::convert(env, polygon.Get(env, fillColor)); annotation.outlineColor = *conversion::convert(env, polygon.Get(env, strokeColor)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp index bc21878ef34..69c44163678 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polygon.hpp @@ -16,6 +16,5 @@ class Polygon : private MultiPoint { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp index d6161e856e0..d8ab30d050f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.cpp @@ -12,9 +12,7 @@ mbgl::LineAnnotation Polyline::toAnnotation(jni::JNIEnv& env, const jni::Object< static auto color = javaClass.GetField(env, "color"); static auto width = javaClass.GetField(env, "width"); - mbgl::LineAnnotation annotation { - MultiPoint::toGeometry>(env, polyline.Get(env, points)) - }; + mbgl::LineAnnotation annotation{MultiPoint::toGeometry>(env, polyline.Get(env, points))}; annotation.opacity = polyline.Get(env, alpha); annotation.color = *conversion::convert(env, polyline.Get(env, color)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp index 6178e98cfc2..79335450337 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/annotation/polyline.hpp @@ -16,6 +16,5 @@ class Polyline : private MultiPoint { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp index b87d1895144..8a0fc76e79a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager.hpp @@ -5,9 +5,7 @@ namespace android { class AssetManager { public: - static constexpr auto Name() { - return "android/content/res/AssetManager"; - }; + static constexpr auto Name() { return "android/content/res/AssetManager"; }; }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp index 1c9e4f99b1b..5ebbbf5168c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.cpp @@ -16,10 +16,13 @@ namespace mbgl { class AssetManagerFileSource::Impl { public: - Impl(ActorRef, AAssetManager* assetManager_, const ResourceOptions resourceOptions_, const ClientOptions clientOptions_) : - resourceOptions(resourceOptions_.clone()), - clientOptions(clientOptions_.clone()), - assetManager(assetManager_) {} + Impl(ActorRef, + AAssetManager* assetManager_, + const ResourceOptions resourceOptions_, + const ClientOptions clientOptions_) + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()), + assetManager(assetManager_) {} void request(const std::string& url, ActorRef req) { // Note: AssetManager already prepends "assets" to the filename. @@ -28,8 +31,8 @@ class AssetManagerFileSource::Impl { Response response; if (AAsset* asset = AAssetManager_open(assetManager, path.c_str(), AASSET_MODE_BUFFER)) { - response.data = std::make_shared( - reinterpret_cast(AAsset_getBuffer(asset)), AAsset_getLength64(asset)); + response.data = std::make_shared(reinterpret_cast(AAsset_getBuffer(asset)), + AAsset_getLength64(asset)); AAsset_close(asset); } else { response.error = std::make_unique(Response::Error::Reason::NotFound, @@ -39,21 +42,13 @@ class AssetManagerFileSource::Impl { req.invoke(&FileSourceRequest::setResponse, response); } - void setResourceOptions(ResourceOptions options) { - resourceOptions = options; - } + void setResourceOptions(ResourceOptions options) { resourceOptions = options; } - ResourceOptions getResourceOptions() { - return resourceOptions.clone(); - } + ResourceOptions getResourceOptions() { return resourceOptions.clone(); } - void setClientOptions(ClientOptions options) { - clientOptions = options; - } + void setClientOptions(ClientOptions options) { clientOptions = options; } - ClientOptions getClientOptions() { - return clientOptions.clone(); - } + ClientOptions getClientOptions() { return clientOptions.clone(); } private: AAssetManager* assetManager; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp index edfe0a8e4b6..79202d494d8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/asset_manager_file_source.hpp @@ -11,12 +11,16 @@ namespace mbgl { namespace util { -template class Thread; +template +class Thread; } // namespace util class AssetManagerFileSource : public FileSource { public: - AssetManagerFileSource(jni::JNIEnv&, const jni::Object&, const ResourceOptions, const ClientOptions); + AssetManagerFileSource(jni::JNIEnv&, + const jni::Object&, + const ResourceOptions, + const ClientOptions); ~AssetManagerFileSource() override; std::unique_ptr request(const Resource&, Callback) override; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp index 9c13f1f7490..f7a06d26d67 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.cpp @@ -8,34 +8,33 @@ namespace mbgl { namespace android { - /** - * Invoked when the construction is initiated from the jvm - */ - ConnectivityListener::ConnectivityListener(jni::JNIEnv&) {} - - ConnectivityListener::~ConnectivityListener() {} - - void ConnectivityListener::onConnectivityStateChanged(jni::JNIEnv&, jni::jboolean connected) { - NetworkStatus::Set(connected ? NetworkStatus::Status::Online : NetworkStatus::Status::Offline); - } - - void ConnectivityListener::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - std::make_unique, - "initialize", - "finalize", - METHOD(&ConnectivityListener::onConnectivityStateChanged, "nativeOnConnectivityStateChanged") - ); - } +/** + * Invoked when the construction is initiated from the jvm + */ +ConnectivityListener::ConnectivityListener(jni::JNIEnv&) {} + +ConnectivityListener::~ConnectivityListener() {} + +void ConnectivityListener::onConnectivityStateChanged(jni::JNIEnv&, jni::jboolean connected) { + NetworkStatus::Set(connected ? NetworkStatus::Status::Online : NetworkStatus::Status::Offline); +} + +void ConnectivityListener::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + std::make_unique, + "initialize", + "finalize", + METHOD(&ConnectivityListener::onConnectivityStateChanged, "nativeOnConnectivityStateChanged")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp index a09507c0f7a..9a0cfd21486 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/connectivity_listener.hpp @@ -9,7 +9,6 @@ namespace android { class ConnectivityListener : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/net/NativeConnectivityListener"; }; static void registerNative(jni::JNIEnv&); @@ -22,7 +21,6 @@ class ConnectivityListener : private mbgl::util::noncopyable { ~ConnectivityListener(); void onConnectivityStateChanged(jni::JNIEnv&, jni::jboolean); - }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp index 954a161baff..3137c832f62 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/collection.cpp @@ -27,6 +27,6 @@ jni::Local> toArray(JNIEnv& env, const std::vector toVector(JNIEnv& env, const jni::Array& array); jni::Local> toArray(JNIEnv& env, const std::vector&); -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp index ce85943e61e..5731800653a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.cpp @@ -7,11 +7,11 @@ namespace conversion { Result Converter::operator()(jni::JNIEnv&, const int& color) const { float r = (color >> 16) & 0xFF; float g = (color >> 8) & 0xFF; - float b = (color) & 0xFF; + float b = (color)&0xFF; float a = (color >> 24) & 0xFF; - return { mbgl::Color( r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f ) }; + return {mbgl::Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f)}; } } // namespace conversion -} // namespace style +} // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp index 2b4144b933e..aa61dce57d9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/color.hpp @@ -14,5 +14,5 @@ struct Converter { }; } // namespace conversion -} // namespace style +} // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp index 292e1a4ace3..347b55b545b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.cpp @@ -8,31 +8,38 @@ namespace mbgl { namespace android { namespace conversion { -Result>> Converter>, bool>::operator()(jni::JNIEnv& env, const bool& value) const { +Result>> Converter>, bool>::operator()(jni::JNIEnv& env, + const bool& value) const { return jni::Box(env, value ? jni::jni_true : jni::jni_false); } -Result>> Converter>, float>::operator()(jni::JNIEnv& env, const float& value) const { +Result>> Converter>, float>::operator()(jni::JNIEnv& env, + const float& value) const { return jni::Box(env, value); } -Result>> Converter>, double>::operator()(jni::JNIEnv& env, const double& value) const { +Result>> Converter>, double>::operator()(jni::JNIEnv& env, + const double& value) const { return jni::Box(env, value); } -Result>> Converter>, std::string>::operator()(jni::JNIEnv& env, const std::string& value) const { +Result>> Converter>, std::string>::operator()( + jni::JNIEnv& env, const std::string& value) const { return jni::Make(env, value); } -Result>> Converter>, Color>::operator()(jni::JNIEnv& env, const Color& value) const { +Result>> Converter>, Color>::operator()(jni::JNIEnv& env, + const Color& value) const { return jni::Make(env, value.stringify()); } -Result>> Converter>, style::expression::Formatted>::operator()(jni::JNIEnv& env, const style::expression::Formatted& value) const { +Result>> Converter>, style::expression::Formatted>::operator()( + jni::JNIEnv& env, const style::expression::Formatted& value) const { return Formatted::New(env, value); } -Result>> Converter>, std::vector>::operator()(jni::JNIEnv& env, const std::vector& value) const { +Result>> Converter>, std::vector>::operator()( + jni::JNIEnv& env, const std::vector& value) const { auto result = jni::Array::New(env, value.size()); for (std::size_t i = 0; i < value.size(); i++) { @@ -42,7 +49,8 @@ Result>> Converter>, std::vect return result; } -Result>> Converter>, std::vector>::operator()(jni::JNIEnv& env, const std::vector& value) const { +Result>> Converter>, std::vector>::operator()( + jni::JNIEnv& env, const std::vector& value) const { auto result = jni::Array::New(env, value.size()); for (std::size_t i = 0; i < value.size(); i++) { @@ -52,7 +60,8 @@ Result>> Converter>, std::vect return result; } -Result>> Converter>, std::vector>::operator()(jni::JNIEnv& env, const std::vector& value) const { +Result>> Converter>, std::vector>::operator()( + jni::JNIEnv& env, const std::vector& value) const { auto result = jni::Array::New(env, value.size()); for (std::size_t i = 0; i < value.size(); i++) { @@ -67,10 +76,11 @@ Result>> Converter>, style::ex return jni::Make(env, value.id()); } -Result>> Converter>, mbgl::style::Rotation>::operator()(jni::JNIEnv& env, const mbgl::style::Rotation& value) const { +Result>> Converter>, mbgl::style::Rotation>::operator()( + jni::JNIEnv& env, const mbgl::style::Rotation& value) const { return jni::Box(env, value.getAngle()); } } // namespace conversion -} // namespace style +} // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp index dc78d6f3656..c8ff5228ba4 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/constant.hpp @@ -38,7 +38,7 @@ struct Converter>, double> { * All integrals. java is limited to 64 bit signed, so... * TODO: use BigDecimal for > 64 / unsigned? */ -template +template struct Converter>, T, typename std::enable_if::value>::type> { Result>> operator()(jni::JNIEnv& env, const T& value) const { return jni::Box(env, jni::jlong(value)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp index d1766f9755c..d9256c8d83e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/conversion/conversion.hpp @@ -10,16 +10,16 @@ namespace mbgl { namespace android { namespace conversion { -struct Error { std::string message; }; +struct Error { + std::string message; +}; template class Result : private variant { public: using variant::variant; - explicit operator bool() const { - return this->template is(); - } + explicit operator bool() const { return this->template is(); } T& operator*() { assert(this->template is()); @@ -40,8 +40,8 @@ class Result : private variant { template struct Converter; -template -Result convert(jni::JNIEnv& env, const V& value, Args&&...args) { +template +Result convert(jni::JNIEnv& env, const V& value, Args&&... args) { return Converter()(env, value, std::forward(args)...); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp index dced5a141ef..893eb774379 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.cpp @@ -20,39 +20,43 @@ namespace android { // FileSource // -FileSource::FileSource(jni::JNIEnv& _env, const jni::String& apiKey, const jni::String& _cachePath, const jni::Object& _options) -:activationCounter( std::optional(1)) { +FileSource::FileSource(jni::JNIEnv& _env, + const jni::String& apiKey, + const jni::String& _cachePath, + const jni::Object& _options) + : activationCounter(std::optional(1)) { std::string path = jni::Make(_env, _cachePath); mapbox::sqlite::setTempPath(path); mbgl::FileSourceManager::get()->registerFileSourceFactory( - mbgl::FileSourceType::Asset, [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) { + mbgl::FileSourceType::Asset, + [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) { auto env{android::AttachEnv()}; std::unique_ptr assetFileSource; if (android::Mapbox::hasInstance(*env)) { auto assetManager = android::Mapbox::getAssetManager(*env); - assetFileSource = std::make_unique(*env, assetManager, resourceOptions.clone(), clientOptions.clone()); + assetFileSource = std::make_unique( + *env, assetManager, resourceOptions.clone(), clientOptions.clone()); } return assetFileSource; }); auto tileServerOptions = TileServerOptions::getTileServerOptions(_env, _options); - resourceOptions - .withTileServerOptions(tileServerOptions) - .withApiKey(apiKey ? jni::Make(_env, apiKey) : "") - .withCachePath(path + DATABASE_FILE); + resourceOptions.withTileServerOptions(tileServerOptions) + .withApiKey(apiKey ? jni::Make(_env, apiKey) : "") + .withCachePath(path + DATABASE_FILE); // Create a core file sources // TODO: Split Android FileSource API to smaller interfaces - resourceLoader = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions); + resourceLoader = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions); databaseSource = std::static_pointer_cast(std::shared_ptr( mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, resourceOptions, clientOptions))); - onlineSource = mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Network, resourceOptions, clientOptions); + onlineSource = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::Network, resourceOptions, clientOptions); } -FileSource::~FileSource() { -} +FileSource::~FileSource() {} void FileSource::setTileServerOptions(jni::JNIEnv& _env, const jni::Object& _options) { auto tileServerOptions = TileServerOptions::getTileServerOptions(_env, _options); @@ -96,7 +100,8 @@ jni::Local FileSource::getAPIBaseUrl(jni::JNIEnv& env) { return jni::Make(env, ""); } -void FileSource::setResourceTransform(jni::JNIEnv& env, const jni::Object& transformCallback) { +void FileSource::setResourceTransform(jni::JNIEnv& env, + const jni::Object& transformCallback) { // Core could be built without support for network resource provider. if (!onlineSource) { ThrowNew(env, jni::FindClass(env, "java/lang/IllegalStateException"), "Online functionality is disabled."); @@ -107,11 +112,12 @@ void FileSource::setResourceTransform(jni::JNIEnv& env, const jni::Object(env, transformCallback); resourceTransform = std::make_unique>( *Scheduler::GetCurrent(), - // Capture the ResourceTransformCallback object as a managed global into - // the lambda. It is released automatically when we're setting a new ResourceTransform in - // a subsequent call. - // Note: we're converting it to shared_ptr because this lambda is converted to a std::function, - // which requires copyability of its captured variables. + // Capture the ResourceTransformCallback object as a managed + // global into the lambda. It is released automatically when + // we're setting a new ResourceTransform in a subsequent call. + // Note: we're converting it to shared_ptr because this lambda + // is converted to a std::function, which requires copyability + // of its captured variables. [callback = std::make_shared(std::move(global))]( mbgl::Resource::Kind kind, const std::string& url_, ResourceTransform::FinishedCallback cb) { android::UniqueEnv _env = android::AttachEnv(); @@ -138,7 +144,8 @@ void FileSource::setResourceCachePath(jni::JNIEnv& env, } if (pathChangeCallback) { - FileSource::ResourcesCachePathChangeCallback::onError(env, _callback, jni::Make(env, "Another resources cache path change is in progress")); + FileSource::ResourcesCachePathChangeCallback::onError( + env, _callback, jni::Make(env, "Another resources cache path change is in progress")); return; } @@ -179,14 +186,14 @@ void FileSource::pause(jni::JNIEnv&) { } } -jni::jboolean FileSource::isResumed(jni::JNIEnv &) { - return (jboolean) (activationCounter > 0); +jni::jboolean FileSource::isResumed(jni::JNIEnv&) { + return (jboolean)(activationCounter > 0); } FileSource* FileSource::getNativePeer(jni::JNIEnv& env, const jni::Object& jFileSource) { static auto& javaClass = jni::Class::Singleton(env); static auto field = javaClass.GetField(env, "nativePtr"); - return reinterpret_cast(jFileSource.Get(env, field)); + return reinterpret_cast(jFileSource.Get(env, field)); } mbgl::ResourceOptions FileSource::getSharedResourceOptions(jni::JNIEnv& env, @@ -200,8 +207,7 @@ mbgl::ResourceOptions FileSource::getSharedResourceOptions(jni::JNIEnv& env, return {}; } -mbgl::ClientOptions FileSource::getSharedClientOptions(jni::JNIEnv& env, - const jni::Object& jFileSource) { +mbgl::ClientOptions FileSource::getSharedClientOptions(jni::JNIEnv& env, const jni::Object& jFileSource) { FileSource* fileSource = FileSource::getNativePeer(env, jFileSource); // Core could be compiled without support for any sources. if (fileSource) { @@ -213,20 +219,22 @@ mbgl::ClientOptions FileSource::getSharedClientOptions(jni::JNIEnv& env, // FileSource::ResourcesCachePathChangeCallback // -void FileSource::ResourcesCachePathChangeCallback::onSuccess(jni::JNIEnv& env, - const jni::Object& callback, - const jni::String& path) { +void FileSource::ResourcesCachePathChangeCallback::onSuccess( + jni::JNIEnv& env, + const jni::Object& callback, + const jni::String& path) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onSuccess"); + static auto method = javaClass.GetMethod(env, "onSuccess"); callback.Call(env, method, path); } -void FileSource::ResourcesCachePathChangeCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - const jni::String& message) { +void FileSource::ResourcesCachePathChangeCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + const jni::String& message) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, message); } @@ -240,37 +248,36 @@ void FileSource::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, - javaClass, - "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&FileSource::setTileServerOptions, "setTileServerOptions"), - METHOD(&FileSource::getApiKey, "getApiKey"), - METHOD(&FileSource::setApiKey, "setApiKey"), - METHOD(&FileSource::setAPIBaseUrl, "setApiBaseUrl"), - METHOD(&FileSource::getAPIBaseUrl, "getApiBaseUrl"), - METHOD(&FileSource::setResourceTransform, "setResourceTransform"), - METHOD(&FileSource::setResourceCachePath, "setResourceCachePath"), - METHOD(&FileSource::resume, "activate"), - METHOD(&FileSource::pause, "deactivate"), - METHOD(&FileSource::isResumed, "isActivated")); + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&FileSource::setTileServerOptions, "setTileServerOptions"), + METHOD(&FileSource::getApiKey, "getApiKey"), + METHOD(&FileSource::setApiKey, "setApiKey"), + METHOD(&FileSource::setAPIBaseUrl, "setApiBaseUrl"), + METHOD(&FileSource::getAPIBaseUrl, "getApiBaseUrl"), + METHOD(&FileSource::setResourceTransform, "setResourceTransform"), + METHOD(&FileSource::setResourceCachePath, "setResourceCachePath"), + METHOD(&FileSource::resume, "activate"), + METHOD(&FileSource::pause, "deactivate"), + METHOD(&FileSource::isResumed, "isActivated")); } - // FileSource::ResourceTransformCallback // -std::string FileSource::ResourceTransformCallback::onURL(jni::JNIEnv& env, const jni::Object& callback, int kind, std::string url_) { +std::string FileSource::ResourceTransformCallback::onURL( + jni::JNIEnv& env, const jni::Object& callback, int kind, std::string url_) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onURL"); + static auto method = javaClass.GetMethod(env, "onURL"); - return jni::Make(env, - callback.Call(env, method, kind, - jni::Make(env, url_))); + return jni::Make(env, callback.Call(env, method, kind, jni::Make(env, url_))); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp index b5a9d15d5e8..b0ddd4c02d8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/file_source.hpp @@ -13,35 +13,44 @@ namespace mbgl { -template class Actor; +template +class Actor; namespace android { /** - * Peer class for the Android FileSource holder. Ensures that a single core FileSource - * of a ResourceLoader type is used. + * Peer class for the Android FileSource holder. Ensures that a single core + * FileSource of a ResourceLoader type is used. */ class FileSource { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource"; }; struct ResourceTransformCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource$ResourceTransformCallback"; } - - static std::string onURL(jni::JNIEnv&, const jni::Object&, int, std::string); + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/storage/" + "FileSource$ResourceTransformCallback"; + } + + static std::string onURL(jni::JNIEnv&, + const jni::Object&, + int, + std::string); }; struct ResourcesCachePathChangeCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/storage/FileSource$ResourcesCachePathChangeCallback";} + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/storage/" + "FileSource$ResourcesCachePathChangeCallback"; + } static void onSuccess(jni::JNIEnv&, const jni::Object&, const jni::String&); static void onError(jni::JNIEnv&, - const jni::Object&, - const jni::String&); + const jni::Object&, + const jni::String&); }; FileSource(jni::JNIEnv&, const jni::String&, const jni::String&, const jni::Object&); @@ -60,7 +69,9 @@ class FileSource { void setResourceTransform(jni::JNIEnv&, const jni::Object&); - void setResourceCachePath(jni::JNIEnv&, const jni::String&, const jni::Object&); + void setResourceCachePath(jni::JNIEnv&, + const jni::String&, + const jni::Object&); void resume(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp index afbf1ee11ed..308f8914ae8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature.cpp @@ -12,9 +12,9 @@ using namespace gson; mbgl::GeoJSONFeature Feature::convert(jni::JNIEnv& env, const jni::Object& jFeature) { static auto& javaClass = jni::Class::Singleton(env); - static auto id = javaClass.GetMethod(env, "id"); - static auto geometry = javaClass.GetMethod ()>(env, "geometry"); - static auto properties = javaClass.GetMethod ()>(env, "properties"); + static auto id = javaClass.GetMethod(env, "id"); + static auto geometry = javaClass.GetMethod()>(env, "geometry"); + static auto properties = javaClass.GetMethod()>(env, "properties"); auto jId = jFeature.Call(env, id); @@ -30,35 +30,35 @@ mbgl::GeoJSONFeature Feature::convert(jni::JNIEnv& env, const jni::Object + template std::string operator()(const T& i) const { return util::toString(i); } - std::string operator()(const std::string& i) const { - return i; - } + std::string operator()(const std::string& i) const { return i; } - std::string operator()(const std::nullptr_t&) const { - return {}; - } + std::string operator()(const std::nullptr_t&) const { return {}; } - std::string operator()(const mapbox::feature::null_value_t&) const { - return {}; - } + std::string operator()(const mapbox::feature::null_value_t&) const { return {}; } }; jni::Local> convertFeature(jni::JNIEnv& env, const mbgl::GeoJSONFeature& value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object, jni::Object, jni::String)>(env, "fromGeometry"); + static auto method = + javaClass.GetStaticMethod(jni::Object, jni::Object, jni::String)>( + env, "fromGeometry"); - return javaClass.Call(env, method, + return javaClass.Call( + env, + method, Geometry::New(env, value.geometry), JsonObject::New(env, value.properties), - jni::Make(env, value.id.is() ? std::string {} : value.id.match(FeatureIdVisitor()))); + jni::Make(env, + value.id.is() ? std::string{} : value.id.match(FeatureIdVisitor()))); } -jni::Local>> Feature::convert(jni::JNIEnv& env, const std::vector& value) { +jni::Local>> Feature::convert(jni::JNIEnv& env, + const std::vector& value) { auto features = jni::Array>::New(env, value.size()); for (size_t i = 0; i < value.size(); ++i) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp index f90d5226b78..9681c49b38e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/feature_collection.cpp @@ -6,7 +6,8 @@ namespace mbgl { namespace android { namespace geojson { -mbgl::FeatureCollection FeatureCollection::convert(jni::JNIEnv& env, const jni::Object& jCollection) { +mbgl::FeatureCollection FeatureCollection::convert(jni::JNIEnv& env, + const jni::Object& jCollection) { auto collection = mbgl::FeatureCollection(); if (jCollection) { @@ -22,9 +23,10 @@ mbgl::FeatureCollection FeatureCollection::convert(jni::JNIEnv& env, const jni:: return collection; } -jni::Local> FeatureCollection::features(jni::JNIEnv& env, const jni::Object& jCollection) { +jni::Local> FeatureCollection::features( + jni::JNIEnv& env, const jni::Object& jCollection) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "features"); + static auto method = javaClass.GetMethod()>(env, "features"); return jCollection.Call(env, method); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp index 0598b9fc596..48eb8c4ad0b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry.cpp @@ -19,8 +19,7 @@ namespace geojson { */ class GeometryEvaluator { public: - - jni::JNIEnv& env; + jni::JNIEnv &env; jni::Local> operator()(const mbgl::EmptyGeometry &) const { // FIXME: mapbox-java needs to have its own Empty type. @@ -35,7 +34,7 @@ class GeometryEvaluator { return LineString::New(env, geometry); } - jni::Local> operator()(const mbgl::MultiLineString &geometry) const { + jni::Local> operator()(const mbgl::MultiLineString &geometry) const { return MultiLineString::New(env, geometry); } @@ -47,44 +46,45 @@ class GeometryEvaluator { return Polygon::New(env, geometry); } - jni::Local> operator()(const mbgl::MultiPolygon &geometry) const { + jni::Local> operator()(const mbgl::MultiPolygon &geometry) const { return MultiPolygon::New(env, geometry); } - jni::Local> operator()(const mapbox::geometry::geometry_collection &geometry) const { + jni::Local> operator()(const mapbox::geometry::geometry_collection &geometry) const { return GeometryCollection::New(env, geometry); } }; -jni::Local> Geometry::New(jni::JNIEnv& env, mbgl::Geometry geometry) { - GeometryEvaluator evaluator { env } ; +jni::Local> Geometry::New(jni::JNIEnv &env, mbgl::Geometry geometry) { + GeometryEvaluator evaluator{env}; return mbgl::Geometry::visit(geometry, evaluator); } -mbgl::Geometry Geometry::convert(jni::JNIEnv &env, const jni::Object& jGeometry) { +mbgl::Geometry Geometry::convert(jni::JNIEnv &env, const jni::Object &jGeometry) { auto type = Geometry::getType(env, jGeometry); if (type == Point::Type()) { - return { Point::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {Point::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == MultiPoint::Type()) { - return { MultiPoint::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {MultiPoint::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == LineString::Type()) { - return { LineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {LineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == MultiLineString::Type()) { - return { MultiLineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {MultiLineString::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == Polygon::Type()) { - return { Polygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {Polygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == MultiPolygon::Type()) { - return { MultiPolygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {MultiPolygon::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } else if (type == GeometryCollection::Type()) { - return { GeometryCollection::convert(env, jni::Cast(env, jni::Class::Singleton(env), jGeometry)) }; + return {GeometryCollection::convert(env, + jni::Cast(env, jni::Class::Singleton(env), jGeometry))}; } - throw std::runtime_error(std::string {"Unsupported GeoJSON type: " } + type); + throw std::runtime_error(std::string{"Unsupported GeoJSON type: "} + type); } -std::string Geometry::getType(jni::JNIEnv &env, const jni::Object& jGeometry) { - static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "type"); +std::string Geometry::getType(jni::JNIEnv &env, const jni::Object &jGeometry) { + static auto &javaClass = jni::Class::Singleton(env); + static auto method = javaClass.GetMethod(env, "type"); return jni::Make(env, jGeometry.Call(env, method)); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp index cca909126d4..8522f5fb4b7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.cpp @@ -5,7 +5,8 @@ namespace mbgl { namespace android { namespace geojson { -jni::Local> GeometryCollection::New(jni::JNIEnv& env, const mapbox::geometry::geometry_collection& collection) { +jni::Local> GeometryCollection::New( + jni::JNIEnv& env, const mapbox::geometry::geometry_collection& collection) { // Create an array of geometries auto jarray = jni::Array>::New(env, collection.size()); @@ -15,14 +16,16 @@ jni::Local> GeometryCollection::New(jni::JNIEnv& // create the GeometryCollection static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromGeometries"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromGeometries"); return javaClass.Call(env, method, java::util::Arrays::asList(env, jarray)); } -mapbox::geometry::geometry_collection GeometryCollection::convert(jni::JNIEnv &env, const jni::Object& jCollection) { +mapbox::geometry::geometry_collection GeometryCollection::convert( + jni::JNIEnv& env, const jni::Object& jCollection) { // Get geometries static auto& javaClass = jni::Class::Singleton(env); - static auto getGeometries = javaClass.GetMethod ()>(env, "geometries"); + static auto getGeometries = javaClass.GetMethod()>(env, "geometries"); // Turn into array auto jarray = java::util::List::toArray(env, jCollection.Call(env, getGeometries)); @@ -38,7 +41,7 @@ mapbox::geometry::geometry_collection GeometryCollection::convert(jni::J return collection; } -void GeometryCollection::registerNative(jni::JNIEnv &env) { +void GeometryCollection::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp index 9f02ac848d0..a8e4d41bb27 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/geometry_collection.hpp @@ -14,7 +14,8 @@ class GeometryCollection { static constexpr auto Name() { return "com/mapbox/geojson/GeometryCollection"; }; static constexpr auto Type() { return "GeometryCollection"; }; - static jni::Local> New(jni::JNIEnv&, const mapbox::geometry::geometry_collection&); + static jni::Local> New(jni::JNIEnv&, + const mapbox::geometry::geometry_collection&); static mapbox::geometry::geometry_collection convert(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp index ae1345c9584..8da53fb9a0a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.cpp @@ -9,12 +9,13 @@ namespace geojson { jni::Local> LineString::New(jni::JNIEnv& env, const mbgl::LineString& lineString) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats"); return javaClass.Call(env, method, asPointsList(env, lineString)); } -mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Object& jLineString) { +mapbox::geojson::line_string LineString::convert(jni::JNIEnv& env, const jni::Object& jLineString) { mapbox::geojson::line_string lineString; if (jLineString) { @@ -24,7 +25,8 @@ mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Ob return lineString; } -mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Object*/>& jPointList) { +mapbox::geojson::line_string LineString::convert(jni::JNIEnv& env, + const jni::Object*/>& jPointList) { mapbox::geojson::line_string lineString; if (jPointList) { @@ -40,13 +42,14 @@ mapbox::geojson::line_string LineString::convert(jni::JNIEnv &env, const jni::Ob return lineString; } -jni::Local> LineString::coordinates(jni::JNIEnv &env, const jni::Object& jLineString) { +jni::Local> LineString::coordinates(jni::JNIEnv& env, + const jni::Object& jLineString) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jLineString.Call(env, method); } -void LineString::registerNative(jni::JNIEnv &env) { +void LineString::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp index 906d809fa8d..63d2a1e197a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/line_string.hpp @@ -13,7 +13,6 @@ namespace mbgl { namespace android { namespace geojson { - class LineString { public: using SuperTag = Geometry; @@ -24,7 +23,7 @@ class LineString { static mapbox::geojson::line_string convert(jni::JNIEnv&, const jni::Object&); - static mapbox::geojson::line_string convert(jni::JNIEnv&, const jni::Object*/>&); + static mapbox::geojson::line_string convert(jni::JNIEnv&, const jni::Object*/>&); static jni::Local> coordinates(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp index 1aaf53c01f2..b4c6ccf27cc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.cpp @@ -7,14 +7,17 @@ namespace mbgl { namespace android { namespace geojson { -jni::Local> MultiLineString::New(jni::JNIEnv& env, const mbgl::MultiLineString& multiLineString) { +jni::Local> MultiLineString::New(jni::JNIEnv& env, + const mbgl::MultiLineString& multiLineString) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats"); return javaClass.Call(env, method, asPointsListsList(env, multiLineString)); } -mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, const jni::Object& jMultiLineString) { +mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv& env, + const jni::Object& jMultiLineString) { mapbox::geojson::multi_line_string multiLineString; if (jMultiLineString) { @@ -24,7 +27,8 @@ mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, co return multiLineString; } -mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, const jni::Object>*/>& jPointListsList) { +mapbox::geojson::multi_line_string MultiLineString::convert( + jni::JNIEnv& env, const jni::Object>*/>& jPointListsList) { mapbox::geojson::multi_line_string multiLineString; if (jPointListsList) { @@ -41,13 +45,14 @@ mapbox::geojson::multi_line_string MultiLineString::convert(jni::JNIEnv &env, co return multiLineString; } -jni::Local> MultiLineString::coordinates(jni::JNIEnv &env, const jni::Object& jLineString) { +jni::Local> MultiLineString::coordinates( + jni::JNIEnv& env, const jni::Object& jLineString) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jLineString.Call(env, method); } -void MultiLineString::registerNative(jni::JNIEnv &env) { +void MultiLineString::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp index 65ce43bd1ff..d4e85cd6ebd 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_line_string.hpp @@ -22,7 +22,8 @@ class MultiLineString { static mapbox::geojson::multi_line_string convert(jni::JNIEnv&, const jni::Object&); - static mapbox::geojson::multi_line_string convert(jni::JNIEnv&, const jni::Object>*/>&); + static mapbox::geojson::multi_line_string convert( + jni::JNIEnv&, const jni::Object>*/>&); static jni::Local> coordinates(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp index d530ef721f5..a4b1526b9df 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_point.cpp @@ -10,7 +10,8 @@ namespace geojson { jni::Local> MultiPoint::New(JNIEnv& env, const mbgl::MultiPoint& multiPoint) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats"); return javaClass.Call(env, method, asPointsList(env, multiPoint)); } @@ -26,13 +27,14 @@ mapbox::geojson::multi_point MultiPoint::convert(jni::JNIEnv& env, const jni::Ob return multiPoint; } -jni::Local> MultiPoint::coordinates(jni::JNIEnv& env, const jni::Object& jMultiPoint) { +jni::Local> MultiPoint::coordinates(jni::JNIEnv& env, + const jni::Object& jMultiPoint) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jMultiPoint.Call(env, method); } -void MultiPoint::registerNative(jni::JNIEnv &env) { +void MultiPoint::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp index 3c5c3ec3383..5316a7e0f79 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/multi_polygon.cpp @@ -9,7 +9,8 @@ namespace geojson { jni::Local> MultiPolygon::New(JNIEnv& env, const mbgl::MultiPolygon& multiPolygon) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "fromLngLats"); auto jarray = jni::Array>::New(env, multiPolygon.size()); @@ -38,13 +39,14 @@ mapbox::geojson::multi_polygon MultiPolygon::convert(jni::JNIEnv& env, const jni return multiPolygon; } -jni::Local> MultiPolygon::coordinates(jni::JNIEnv& env, const jni::Object& jPolygon) { +jni::Local> MultiPolygon::coordinates(jni::JNIEnv& env, + const jni::Object& jPolygon) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jPolygon.Call(env, method); } -void MultiPolygon::registerNative(jni::JNIEnv &env) { +void MultiPolygon::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp index 2000447c0fe..020d623858c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/point.cpp @@ -6,26 +6,23 @@ namespace geojson { jni::Local> Point::New(jni::JNIEnv& env, const mbgl::Point& point) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::jdouble, jni::jdouble)>(env, "fromLngLat"); + static auto method = javaClass.GetStaticMethod(jni::jdouble, jni::jdouble)>(env, "fromLngLat"); return javaClass.Call(env, method, point.x, point.y); } -mbgl::Point Point::convert(jni::JNIEnv &env, const jni::Object& jPoint) { +mbgl::Point Point::convert(jni::JNIEnv& env, const jni::Object& jPoint) { static auto& javaClass = jni::Class::Singleton(env); - static auto longitude = javaClass.GetMethod(env, "longitude"); - static auto latitude = javaClass.GetMethod(env, "latitude"); + static auto longitude = javaClass.GetMethod(env, "longitude"); + static auto latitude = javaClass.GetMethod(env, "latitude"); if (!jPoint) { return {}; } - return { - jPoint.Call(env, longitude), - jPoint.Call(env, latitude) - }; + return {jPoint.Call(env, longitude), jPoint.Call(env, latitude)}; } -void Point::registerNative(jni::JNIEnv &env) { +void Point::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp index 4437d134a8a..55018da23e8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.cpp @@ -10,12 +10,13 @@ namespace geojson { jni::Local> Polygon::New(jni::JNIEnv& env, const mbgl::Polygon& polygon) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "fromLngLats"); + static auto method = javaClass.GetStaticMethod(jni::Object)>(env, + "fromLngLats"); return javaClass.Call(env, method, asPointsListsList(env, polygon)); } -mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object& jPolygon) { +mapbox::geojson::polygon Polygon::convert(jni::JNIEnv& env, const jni::Object& jPolygon) { mapbox::geojson::polygon polygon; if (jPolygon) { @@ -25,7 +26,8 @@ mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object>*/>& jPointListsList) { +mapbox::geojson::polygon Polygon::convert( + jni::JNIEnv& env, const jni::Object>*/>& jPointListsList) { mapbox::geojson::polygon polygon; if (jPointListsList) { @@ -39,14 +41,13 @@ mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object> Polygon::coordinates(jni::JNIEnv &env, const jni::Object& jPolygon) { +jni::Local> Polygon::coordinates(jni::JNIEnv& env, const jni::Object& jPolygon) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "coordinates"); + static auto method = javaClass.GetMethod()>(env, "coordinates"); return jPolygon.Call(env, method); } -void Polygon::registerNative(jni::JNIEnv &env) { +void Polygon::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp index 8e1761fedaf..758e0dfb9c8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/polygon.hpp @@ -8,7 +8,6 @@ #include - namespace mbgl { namespace android { namespace geojson { @@ -19,13 +18,14 @@ class Polygon { static constexpr auto Name() { return "com/mapbox/geojson/Polygon"; }; static constexpr auto Type() { return "Polygon"; }; - static jni::Local> New(jni::JNIEnv&, const mbgl::Polygon&); + static jni::Local> New(jni::JNIEnv &, const mbgl::Polygon &); - static mapbox::geojson::polygon convert(jni::JNIEnv &, const jni::Object&); + static mapbox::geojson::polygon convert(jni::JNIEnv &, const jni::Object &); - static mapbox::geojson::polygon convert(jni::JNIEnv&, const jni::Object>*/>&); + static mapbox::geojson::polygon convert(jni::JNIEnv &, + const jni::Object>*/> &); - static jni::Local> coordinates(jni::JNIEnv&, const jni::Object&); + static jni::Local> coordinates(jni::JNIEnv &, const jni::Object &); static void registerNative(jni::JNIEnv &); }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp index 59154516fa4..1e2190c4a78 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geojson/util.hpp @@ -11,11 +11,9 @@ namespace geojson { // Clang 3.8 fails to implicitly convert matching types, so we'll have to do it explicitly. template To convertExplicit(From&& src) { - static_assert(std::is_same::container_type, - typename To::container_type>::value, + static_assert(std::is_same::container_type, typename To::container_type>::value, "container types do not match"); - static_assert(std::is_rvalue_reference::value, - "argument must be rvalue reference"); + static_assert(std::is_rvalue_reference::value, "argument must be rvalue reference"); return *reinterpret_cast>(&src); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp index 30b7db1ef34..d44143d9234 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng.hpp @@ -11,7 +11,6 @@ namespace android { class LatLng : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLng"; }; static jni::Local> New(jni::JNIEnv&, const mbgl::LatLng&); @@ -20,10 +19,8 @@ class LatLng : private mbgl::util::noncopyable { static mbgl::LatLng getLatLng(jni::JNIEnv&, const jni::Object&); - static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp index cf534a06e4f..ca324883061 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.cpp @@ -16,8 +16,8 @@ mbgl::LatLngBounds LatLngBounds::getLatLngBounds(jni::JNIEnv& env, const jni::Ob static auto neLatField = javaClass.GetField(env, "latitudeNorth"); static auto neLonField = javaClass.GetField(env, "longitudeEast"); - mbgl::LatLng sw = { bounds.Get(env, swLatField), bounds.Get(env, swLonField) }; - mbgl::LatLng ne = { bounds.Get(env, neLatField), bounds.Get(env, neLonField) }; + mbgl::LatLng sw = {bounds.Get(env, swLatField), bounds.Get(env, swLonField)}; + mbgl::LatLng ne = {bounds.Get(env, neLatField), bounds.Get(env, neLonField)}; return mbgl::LatLngBounds::hull(sw, ne); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp index d51026711d1..6016061af18 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_bounds.hpp @@ -11,7 +11,6 @@ namespace android { class LatLngBounds : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLngBounds"; }; static jni::Local> New(jni::JNIEnv&, mbgl::LatLngBounds); @@ -21,6 +20,5 @@ class LatLngBounds : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp index 1a1e49048bc..ffb0aca9d34 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.cpp @@ -6,27 +6,28 @@ namespace android { jni::Local> LatLngQuad::New(jni::JNIEnv& env, std::array coordinates) { static auto& javaClass = jni::Class::Singleton(env); - static auto quadConstructor = javaClass.GetConstructor, jni::Object, jni::Object, jni::Object>(env); - return javaClass.New(env, quadConstructor, - LatLng::New(env, coordinates[0]), - LatLng::New(env, coordinates[1]), - LatLng::New(env, coordinates[2]), - LatLng::New(env, coordinates[3])); + static auto quadConstructor = + javaClass.GetConstructor, jni::Object, jni::Object, jni::Object>( + env); + return javaClass.New(env, + quadConstructor, + LatLng::New(env, coordinates[0]), + LatLng::New(env, coordinates[1]), + LatLng::New(env, coordinates[2]), + LatLng::New(env, coordinates[3])); } std::array LatLngQuad::getLatLngArray(jni::JNIEnv& env, const jni::Object& quad) { static auto& javaClass = jni::Class::Singleton(env); - static auto topLeftField = javaClass.GetField >(env, "topLeft"); - static auto topRightField = javaClass.GetField >(env, "topRight"); - static auto bottomRightField = javaClass.GetField >(env, "bottomRight"); - static auto bottomLeftField = javaClass.GetField >(env, "bottomLeft"); + static auto topLeftField = javaClass.GetField>(env, "topLeft"); + static auto topRightField = javaClass.GetField>(env, "topRight"); + static auto bottomRightField = javaClass.GetField>(env, "bottomRight"); + static auto bottomLeftField = javaClass.GetField>(env, "bottomLeft"); - return std::array < mbgl::LatLng, 4 > {{ - LatLng::getLatLng(env, quad.Get(env, topLeftField)), - LatLng::getLatLng(env, quad.Get(env, topRightField)), - LatLng::getLatLng(env, quad.Get(env, bottomRightField)), - LatLng::getLatLng(env, quad.Get(env, bottomLeftField)) - }}; + return std::array{{LatLng::getLatLng(env, quad.Get(env, topLeftField)), + LatLng::getLatLng(env, quad.Get(env, topRightField)), + LatLng::getLatLng(env, quad.Get(env, bottomRightField)), + LatLng::getLatLng(env, quad.Get(env, bottomLeftField))}}; } void LatLngQuad::registerNative(jni::JNIEnv& env) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp index f6560b57ba3..f5d93c731e3 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/geometry/lat_lng_quad.hpp @@ -12,7 +12,6 @@ namespace android { class LatLngQuad : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/geometry/LatLngQuad"; }; static jni::Local> New(jni::JNIEnv&, std::array); @@ -22,6 +21,5 @@ class LatLngQuad : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp index 899468b8e3f..fda823f02f9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/pointf.hpp @@ -9,7 +9,6 @@ namespace android { class PointF : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "android/graphics/PointF"; }; static jni::Local> New(jni::JNIEnv&, float, float); @@ -19,6 +18,5 @@ class PointF : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp index ba611f22622..5f3126295bc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/graphics/rectf.hpp @@ -9,7 +9,6 @@ namespace android { class RectF : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "android/graphics/RectF"; }; static float getLeft(jni::JNIEnv&, const jni::Object&); @@ -23,6 +22,5 @@ class RectF : private mbgl::util::noncopyable { static void registerNative(jni::JNIEnv&); }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp index 8ffa658b764..bcd9c22c435 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_array.cpp @@ -5,14 +5,14 @@ namespace mbgl { namespace android { namespace gson { -jni::Local> JsonArray::New(jni::JNIEnv& env, const std::vector& values){ +jni::Local> JsonArray::New(jni::JNIEnv& env, const std::vector& values) { static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - static auto addMethod = javaClass.GetMethod)>(env, "add"); + static auto addMethod = javaClass.GetMethod)>(env, "add"); auto jsonArray = javaClass.New(env, constructor); - for (const auto &v : values) { + for (const auto& v : values) { jsonArray.Call(env, addMethod, JsonElement::New(env, v)); } @@ -24,8 +24,8 @@ std::vector JsonArray::convert(jni::JNIEnv& env, const jni::Object< if (jsonArray) { static auto& javaClass = jni::Class::Singleton(env); - static auto getMethod = javaClass.GetMethod (jni::jint)>(env, "get"); - static auto sizeMethod = javaClass.GetMethod(env, "size"); + static auto getMethod = javaClass.GetMethod(jni::jint)>(env, "get"); + static auto sizeMethod = javaClass.GetMethod(env, "size"); int size = jsonArray.Call(env, sizeMethod); values.reserve(uint(size)); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp index ba22304d072..c8b32852cb6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_element.cpp @@ -14,50 +14,39 @@ jni::Local> JsonElement::New(jni::JNIEnv& env, const mb static auto booleanConstructor = primitive.GetConstructor(env); return value.match( - [&] (const mbgl::NullValue&) { - return jni::Local>(); - }, - [&] (const std::string& value) { + [&](const mbgl::NullValue&) { return jni::Local>(); }, + [&](const std::string& value) { return primitive.New(env, stringConstructor, jni::Make(env, value)); }, - [&] (const double value) { - return primitive.New(env, numberConstructor, jni::Box(env, value)); - }, - [&] (const int64_t value) { - return primitive.New(env, numberConstructor, jni::Box(env, value)); - }, - [&] (const uint64_t value) { + [&](const double value) { return primitive.New(env, numberConstructor, jni::Box(env, value)); }, + [&](const int64_t value) { return primitive.New(env, numberConstructor, jni::Box(env, value)); }, + [&](const uint64_t value) { return primitive.New(env, numberConstructor, jni::Box(env, int64_t(value))); // TODO: should use BigInteger }, - [&] (const bool value) { + [&](const bool value) { return primitive.New(env, booleanConstructor, jni::Box(env, value ? jni::jni_true : jni::jni_false)); }, - [&] (const std::vector& values) { - return JsonArray::New(env, values); - }, - [&] (const mbgl::PropertyMap& values) { - return JsonObject::New(env, values); - } - ); + [&](const std::vector& values) { return JsonArray::New(env, values); }, + [&](const mbgl::PropertyMap& values) { return JsonObject::New(env, values); }); } -mbgl::Value JsonElement::convert(jni::JNIEnv &env, const jni::Object& jsonElement) { +mbgl::Value JsonElement::convert(jni::JNIEnv& env, const jni::Object& jsonElement) { if (!jsonElement) { return mbgl::NullValue(); } static auto& elementClass = jni::Class::Singleton(env); - static auto isJsonObject = elementClass.GetMethod(env, "isJsonObject"); - static auto isJsonArray = elementClass.GetMethod(env, "isJsonArray"); - static auto isJsonPrimitive = elementClass.GetMethod(env, "isJsonPrimitive"); + static auto isJsonObject = elementClass.GetMethod(env, "isJsonObject"); + static auto isJsonArray = elementClass.GetMethod(env, "isJsonArray"); + static auto isJsonPrimitive = elementClass.GetMethod(env, "isJsonPrimitive"); static auto& primitiveClass = jni::Class::Singleton(env); - static auto isBoolean = primitiveClass.GetMethod(env, "isBoolean"); - static auto isString = primitiveClass.GetMethod(env, "isString"); - static auto isNumber = primitiveClass.GetMethod(env, "isNumber"); - static auto getAsBoolean = primitiveClass.GetMethod(env, "getAsBoolean"); - static auto getAsString = primitiveClass.GetMethod(env, "getAsString"); - static auto getAsDouble = primitiveClass.GetMethod(env, "getAsDouble"); + static auto isBoolean = primitiveClass.GetMethod(env, "isBoolean"); + static auto isString = primitiveClass.GetMethod(env, "isString"); + static auto isNumber = primitiveClass.GetMethod(env, "isNumber"); + static auto getAsBoolean = primitiveClass.GetMethod(env, "getAsBoolean"); + static auto getAsString = primitiveClass.GetMethod(env, "getAsString"); + static auto getAsDouble = primitiveClass.GetMethod(env, "getAsDouble"); if (jsonElement.Call(env, isJsonPrimitive)) { auto primitive = jni::Cast(env, primitiveClass, jsonElement); @@ -79,7 +68,7 @@ mbgl::Value JsonElement::convert(jni::JNIEnv &env, const jni::Object::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp index 10d244ee48e..fb31b5b8816 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/gson/json_object.cpp @@ -8,18 +8,15 @@ namespace mbgl { namespace android { namespace gson { - jni::Local> JsonObject::New(jni::JNIEnv& env, const mbgl::PropertyMap& values) { static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - static auto addMethod = javaClass.GetMethod)>(env, "add"); + static auto addMethod = javaClass.GetMethod)>(env, "add"); auto jsonObject = javaClass.New(env, constructor); - for (auto &item : values) { - jsonObject.Call(env, addMethod, - jni::Make(env, item.first), - JsonElement::New(env, item.second)); + for (auto& item : values) { + jsonObject.Call(env, addMethod, jni::Make(env, item.first), JsonElement::New(env, item.second)); } return jsonObject; @@ -29,7 +26,7 @@ template // void (jni::String, jni::Object) static void iterateEntrySet(jni::JNIEnv& env, const jni::Object& jsonObject, F callback) { // Get Set> static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "entrySet"); + static auto method = javaClass.GetMethod()>(env, "entrySet"); auto entryArray = java::util::Set::toArray(env, jsonObject.Call(env, method)); @@ -37,9 +34,8 @@ static void iterateEntrySet(jni::JNIEnv& env, const jni::Object& jso for (size_t i = 0; i < size; i++) { auto entry = entryArray.Get(env, i); if (entry) { - callback( - java::util::Map::Entry::getKey(env, entry), - java::util::Map::Entry::getValue(env, entry)); + callback(java::util::Map::Entry::getKey(env, entry), + java::util::Map::Entry::getValue(env, entry)); } } } @@ -48,15 +44,16 @@ mbgl::PropertyMap JsonObject::convert(jni::JNIEnv& env, const jni::Object& jsonElement) { - map[jni::Make(env, jId)] = JsonElement::convert(env, jsonElement); - }); + iterateEntrySet( + env, jsonObject, [&map, &env](const jni::String& jId, const jni::Object& jsonElement) { + map[jni::Make(env, jId)] = JsonElement::convert(env, jsonElement); + }); } return map; } -void JsonObject::registerNative(jni::JNIEnv &env) { +void JsonObject::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp index 121d81ab4c1..f417a442538 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/http_file_source.cpp @@ -19,15 +19,16 @@ namespace mbgl { class HTTPFileSource::Impl { public: Impl(const ResourceOptions resourceOptions_, const ClientOptions clientOptions_) - : resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) {}; + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()){}; - android::UniqueEnv env { android::AttachEnv() }; + android::UniqueEnv env{android::AttachEnv()}; - void setResourceOptions(ResourceOptions options) {resourceOptions = options;}; - ResourceOptions getResourceOptions() {return resourceOptions.clone(); }; + void setResourceOptions(ResourceOptions options) { resourceOptions = options; }; + ResourceOptions getResourceOptions() { return resourceOptions.clone(); }; - void setClientOptions(ClientOptions options) {clientOptions = options;}; - ClientOptions getClientOptions() {return clientOptions.clone();}; + void setClientOptions(ClientOptions options) { clientOptions = options; }; + ClientOptions getClientOptions() { return clientOptions.clone(); }; private: ResourceOptions resourceOptions; @@ -42,10 +43,14 @@ class HTTPRequest : public AsyncRequest { ~HTTPRequest(); void onFailure(jni::JNIEnv&, int type, const jni::String& message); - void onResponse(jni::JNIEnv&, int code, - const jni::String& etag, const jni::String& modified, - const jni::String& cacheControl, const jni::String& expires, - const jni::String& retryAfter, const jni::String& xRateLimitReset, + void onResponse(jni::JNIEnv&, + int code, + const jni::String& etag, + const jni::String& modified, + const jni::String& cacheControl, + const jni::String& expires, + const jni::String& retryAfter, + const jni::String& xRateLimitReset, const jni::Array& body); jni::Global> javaRequest; @@ -55,12 +60,12 @@ class HTTPRequest : public AsyncRequest { FileSource::Callback callback; Response response; - util::AsyncTask async { [this] { + util::AsyncTask async{[this] { // Calling `callback` may result in deleting `this`. Copy data to temporaries first. auto callback_ = callback; auto response_ = response; callback_(response_); - } }; + }}; static const int connectionError = 0; static const int temporaryError = 1; @@ -72,11 +77,13 @@ namespace android { void RegisterNativeHTTPRequest(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - jni::RegisterNativePeer(env, javaClass, "nativePtr", - METHOD(&HTTPRequest::onFailure, "nativeOnFailure"), - METHOD(&HTTPRequest::onResponse, "nativeOnResponse")); + jni::RegisterNativePeer(env, + javaClass, + "nativePtr", + METHOD(&HTTPRequest::onFailure, "nativeOnFailure"), + METHOD(&HTTPRequest::onResponse, "nativeOnResponse")); } } // namespace android @@ -100,31 +107,33 @@ HTTPRequest::HTTPRequest(jni::JNIEnv& env, const Resource& resource_, FileSource javaClass.GetConstructor(env); javaRequest = jni::NewGlobal(env, - javaClass.New(env, constructor, - reinterpret_cast(this), - jni::Make(env, resource.url), - jni::Make(env, etagStr), - jni::Make(env, modifiedStr), - (jboolean) (resource_.usage == Resource::Usage::Offline) - ) - ); + javaClass.New(env, + constructor, + reinterpret_cast(this), + jni::Make(env, resource.url), + jni::Make(env, etagStr), + jni::Make(env, modifiedStr), + (jboolean)(resource_.usage == Resource::Usage::Offline))); } HTTPRequest::~HTTPRequest() { android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto cancel = javaClass.GetMethod(*env, "cancel"); + static auto cancel = javaClass.GetMethod(*env, "cancel"); javaRequest.Call(*env, cancel); } -void HTTPRequest::onResponse(jni::JNIEnv& env, int code, - const jni::String& etag, const jni::String& modified, - const jni::String& cacheControl, const jni::String& expires, - const jni::String& jRetryAfter, const jni::String& jXRateLimitReset, +void HTTPRequest::onResponse(jni::JNIEnv& env, + int code, + const jni::String& etag, + const jni::String& modified, + const jni::String& cacheControl, + const jni::String& expires, + const jni::String& jRetryAfter, + const jni::String& jXRateLimitReset, const jni::Array& body) { - using Error = Response::Error; if (etag) { @@ -168,11 +177,14 @@ void HTTPRequest::onResponse(jni::JNIEnv& env, int code, if (jXRateLimitReset) { xRateLimitReset = jni::Make(env, jXRateLimitReset); } - response.error = std::make_unique(Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset)); + response.error = std::make_unique( + Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset)); } else if (code >= 500 && code < 600) { - response.error = std::make_unique(Error::Reason::Server, std::string{ "HTTP status code " } + util::toString(code)); + response.error = std::make_unique(Error::Reason::Server, + std::string{"HTTP status code "} + util::toString(code)); } else { - response.error = std::make_unique(Error::Reason::Other, std::string{ "HTTP status code " } + util::toString(code)); + response.error = std::make_unique(Error::Reason::Other, + std::string{"HTTP status code "} + util::toString(code)); } async.send(); @@ -198,8 +210,7 @@ void HTTPRequest::onFailure(jni::JNIEnv& env, int type, const jni::String& messa } HTTPFileSource::HTTPFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique(resourceOptions.clone(), clientOptions.clone())) { -} + : impl(std::make_unique(resourceOptions.clone(), clientOptions.clone())) {} HTTPFileSource::~HTTPFileSource() = default; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp index 1d8b370fd20..c45d3d6f0da 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator.cpp @@ -15,19 +15,22 @@ void Collator::registerNative(jni::JNIEnv& env) { jni::Local> Collator::getInstance(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "getInstance"); + static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "getInstance"); return javaClass.Call(env, method, locale); } void Collator::setStrength(jni::JNIEnv& env, const jni::Object& collator, jni::jint strength) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "setStrength"); + static auto method = javaClass.GetMethod(env, "setStrength"); collator.Call(env, method, strength); } -jni::jint Collator::compare(jni::JNIEnv& env, const jni::Object& collator, const jni::String& lhs, const jni::String& rhs) { +jni::jint Collator::compare(jni::JNIEnv& env, + const jni::Object& collator, + const jni::String& lhs, + const jni::String& rhs) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "compare"); + static auto method = javaClass.GetMethod(env, "compare"); return collator.Call(env, method, lhs, rhs); } @@ -37,7 +40,7 @@ void StringUtils::registerNative(jni::JNIEnv& env) { jni::Local StringUtils::unaccent(jni::JNIEnv& env, const jni::String& value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod(env, "unaccent"); + static auto method = javaClass.GetStaticMethod(env, "unaccent"); return javaClass.Call(env, method, value); } @@ -63,19 +66,19 @@ jni::String Locale::toLanguageTag(jni::JNIEnv& env, jni::Object locale) jni::Local Locale::getLanguage(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "getLanguage"); + static auto method = javaClass.GetMethod(env, "getLanguage"); return locale.Call(env, method); } jni::Local Locale::getCountry(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "getCountry"); + static auto method = javaClass.GetMethod(env, "getCountry"); return locale.Call(env, method); } jni::Local> Locale::getDefault(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod ()>(env, "getDefault"); + static auto method = javaClass.GetStaticMethod()>(env, "getDefault"); return javaClass.Call(env, method); } @@ -98,21 +101,20 @@ namespace platform { class Collator::Impl { public: Impl(bool caseSensitive_, bool diacriticSensitive_, std::optional locale_) - : caseSensitive(caseSensitive_) - , diacriticSensitive(diacriticSensitive_) - , env(android::AttachEnv()) - { + : caseSensitive(caseSensitive_), + diacriticSensitive(diacriticSensitive_), + env(android::AttachEnv()) { LanguageTag languageTag = locale_ ? LanguageTag::fromBCP47(*locale_) : LanguageTag(); if (!languageTag.language) { - locale = jni::NewGlobal(*env, - android::Locale::getDefault(*env)); + locale = jni::NewGlobal(*env, android::Locale::getDefault(*env)); } else if (!languageTag.region) { locale = jni::NewGlobal(*env, - android::Locale::New(*env, jni::Make(*env, *languageTag.language))); + android::Locale::New(*env, jni::Make(*env, *languageTag.language))); } else { locale = jni::NewGlobal(*env, - android::Locale::New(*env, jni::Make(*env, *languageTag.language), - jni::Make(*env, *languageTag.region))); + android::Locale::New(*env, + jni::Make(*env, *languageTag.language), + jni::Make(*env, *languageTag.region))); } collator = jni::NewGlobal(*env, android::Collator::getInstance(*env, locale)); if (!diacriticSensitive && !caseSensitive) { @@ -120,26 +122,27 @@ class Collator::Impl { } else if (diacriticSensitive && !caseSensitive) { android::Collator::setStrength(*env, collator, 1 /*SECONDARY*/); } else if (caseSensitive) { - // If we're case-sensitive and diacritic-sensitive, we use a case-sensitive collator - // and a fallback implementation of diacritic-insensitivity. + // If we're case-sensitive and diacritic-sensitive, we use a + // case-sensitive collator and a fallback implementation of + // diacritic-insensitivity. android::Collator::setStrength(*env, collator, 2 /*TERTIARY*/); } } bool operator==(const Impl& other) const { - return caseSensitive == other.caseSensitive && - diacriticSensitive == other.diacriticSensitive && - resolvedLocale() == other.resolvedLocale(); + return caseSensitive == other.caseSensitive && diacriticSensitive == other.diacriticSensitive && + resolvedLocale() == other.resolvedLocale(); } int compare(const std::string& lhs, const std::string& rhs) const { bool useUnaccent = !diacriticSensitive && caseSensitive; - // java.text.Collator doesn't support a diacritic-insensitive/case-sensitive collation - // order, so we have to compromise here. We use Android's case-sensitive Collator - // against strings that have been "unaccented" using non-locale-aware nunicode logic. - // Because of the difference in locale-awareness, this means turning on case-sensitivity - // can _potentially_ change compare results for strings that don't actually have any case - // differences. + // java.text.Collator doesn't support a + // diacritic-insensitive/case-sensitive collation order, so we have to + // compromise here. We use Android's case-sensitive Collator against + // strings that have been "unaccented" using non-locale-aware nunicode + // logic. Because of the difference in locale-awareness, this means + // turning on case-sensitivity can _potentially_ change compare results + // for strings that don't actually have any case differences. jni::Local jlhs = useUnaccent ? android::StringUtils::unaccent(*env, jni::Make(*env, lhs)) : jni::Make(*env, lhs); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp index 612f9b49f3c..0567d50e545 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/collator_jni.hpp @@ -29,7 +29,6 @@ class Locale { static jni::Local> New(jni::JNIEnv&, const jni::String&); static jni::Local> New(jni::JNIEnv&, const jni::String&, const jni::String&); - static void registerNative(jni::JNIEnv&); }; @@ -43,18 +42,15 @@ class Collator { static jni::jint compare(jni::JNIEnv&, const jni::Object&, const jni::String&, const jni::String&); - static void registerNative(jni::JNIEnv&); }; - class StringUtils { public: static constexpr auto Name() { return "com/mapbox/mapboxsdk/utils/StringUtils"; }; static jni::Local unaccent(jni::JNIEnv&, const jni::String&); - static void registerNative(jni::JNIEnv&); }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp index a804e74f1ca..662d01512c9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/i18n/number_format.cpp @@ -15,31 +15,35 @@ void NumberFormat::registerNative(jni::JNIEnv& env) { jni::Local> NumberFormat::getInstance(jni::JNIEnv& env, const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "getInstance"); + static auto method = javaClass.GetStaticMethod(jni::Object)>(env, "getInstance"); return javaClass.Call(env, method, locale); } -jni::Local> NumberFormat::getCurrencyInstance(jni::JNIEnv& env, const jni::Object& locale) { +jni::Local> NumberFormat::getCurrencyInstance(jni::JNIEnv& env, + const jni::Object& locale) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jni::Object)>(env, "getCurrencyInstance"); + static auto method = javaClass.GetStaticMethod(jni::Object)>( + env, "getCurrencyInstance"); return javaClass.Call(env, method, locale); } -jni::Local NumberFormat::format(jni::JNIEnv& env, const jni::Object& nf, jni::jdouble number) { +jni::Local NumberFormat::format(jni::JNIEnv& env, + const jni::Object& nf, + jni::jdouble number) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "format"); + static auto method = javaClass.GetMethod(env, "format"); return nf.Call(env, method, number); } void NumberFormat::setMinimumFractionDigits(jni::JNIEnv& env, const jni::Object& nf, jni::jint value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "setMinimumFractionDigits"); + static auto method = javaClass.GetMethod(env, "setMinimumFractionDigits"); return nf.Call(env, method, value); } void NumberFormat::setMaximumFractionDigits(jni::JNIEnv& env, const jni::Object& nf, jni::jint value) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "setMaximumFractionDigits"); + static auto method = javaClass.GetMethod(env, "setMaximumFractionDigits"); return nf.Call(env, method, value); } @@ -47,10 +51,12 @@ void NumberFormat::setMaximumFractionDigits(jni::JNIEnv& env, const jni::Object< namespace platform { -std::string formatNumber(double number, const std::string& localeId, const std::string& currency, - uint8_t minFractionDigits, uint8_t maxFractionDigits) { - - auto env{ android::AttachEnv() }; +std::string formatNumber(double number, + const std::string& localeId, + const std::string& currency, + uint8_t minFractionDigits, + uint8_t maxFractionDigits) { + auto env{android::AttachEnv()}; jni::Global> locale; LanguageTag languageTag = !localeId.empty() ? LanguageTag::fromBCP47(localeId) : LanguageTag(); @@ -59,8 +65,10 @@ std::string formatNumber(double number, const std::string& localeId, const std:: } else if (!languageTag.region) { locale = jni::NewGlobal(*env, android::Locale::New(*env, jni::Make(*env, *languageTag.language))); } else { - locale = jni::NewGlobal(*env, android::Locale::New(*env, jni::Make(*env, *languageTag.language), - jni::Make(*env, *languageTag.region))); + locale = jni::NewGlobal(*env, + android::Locale::New(*env, + jni::Make(*env, *languageTag.language), + jni::Make(*env, *languageTag.region))); } jni::Global> formatter; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp index 9b0c01459eb..f10b394bc6e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/java/util.hpp @@ -13,10 +13,10 @@ class List : private mbgl::util::noncopyable { public: static constexpr auto Name() { return "java/util/List"; }; - template + template static jni::Local>> toArray(jni::JNIEnv& env, const jni::Object& list) { static auto& javaClass = jni::Class::Singleton(env); - static auto toArray = javaClass.GetMethod> ()>(env, "toArray"); + static auto toArray = javaClass.GetMethod>()>(env, "toArray"); return jni::Local>>(env, list.Call(env, toArray).release()); }; @@ -40,10 +40,10 @@ class Set : private mbgl::util::noncopyable { public: static constexpr auto Name() { return "java/util/Set"; }; - template + template static jni::Local>> toArray(jni::JNIEnv& env, const jni::Object& list) { static auto& javaClass = jni::Class::Singleton(env); - static auto toArray = javaClass.GetMethod> ()>(env, "toArray"); + static auto toArray = javaClass.GetMethod>()>(env, "toArray"); return jni::Local>>(env, list.Call(env, toArray).release()); }; @@ -60,14 +60,14 @@ class Map : private mbgl::util::noncopyable { template static jni::Local> getKey(jni::JNIEnv& env, const jni::Object& entry) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "getKey"); + static auto method = javaClass.GetMethod()>(env, "getKey"); return jni::Cast(env, jni::Class::Singleton(env), entry.Call(env, method)); } template static jni::Local> getValue(jni::JNIEnv& env, const jni::Object& entry) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod ()>(env, "getValue"); + static auto method = javaClass.GetMethod()>(env, "getValue"); return jni::Cast(env, jni::Class::Singleton(env), entry.Call(env, method)); } }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp index 7a1ba93a585..e004544ee93 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.cpp @@ -4,46 +4,46 @@ namespace mbgl { namespace android { namespace java { - jni::jclass* ObjectArray::jclass; +jni::jclass* ObjectArray::jclass; - jni::jclass* String::jclass; +jni::jclass* String::jclass; - jni::jclass* Boolean::jclass; - jni::jmethodID* Boolean::booleanValueMethodId; +jni::jclass* Boolean::jclass; +jni::jmethodID* Boolean::booleanValueMethodId; - jni::jclass* Number::jclass; - jni::jmethodID* Number::floatValueMethodId; - jni::jmethodID* Number::doubleValueMethodId; - jni::jmethodID* Number::longValueMethodId; +jni::jclass* Number::jclass; +jni::jmethodID* Number::floatValueMethodId; +jni::jmethodID* Number::doubleValueMethodId; +jni::jmethodID* Number::longValueMethodId; - jni::jclass* Map::jclass; - jni::jmethodID* Map::getMethodId; - jni::jmethodID* Map::keySetMethodId; +jni::jclass* Map::jclass; +jni::jmethodID* Map::getMethodId; +jni::jmethodID* Map::keySetMethodId; - jni::jclass* Set::jclass; - jni::jmethodID* Set::toArrayMethodId; +jni::jclass* Set::jclass; +jni::jmethodID* Set::toArrayMethodId; - void registerNatives(JNIEnv& env) { - ObjectArray::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "[Ljava/lang/Object;")).release(); +void registerNatives(JNIEnv& env) { + ObjectArray::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "[Ljava/lang/Object;")).release(); - String::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/String")).release(); + String::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/String")).release(); - Boolean::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Boolean")).release(); - Boolean::booleanValueMethodId = &jni::GetMethodID(env, *Boolean::jclass, "booleanValue", "()Z"); + Boolean::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Boolean")).release(); + Boolean::booleanValueMethodId = &jni::GetMethodID(env, *Boolean::jclass, "booleanValue", "()Z"); - Number::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Number")).release(); - Number::floatValueMethodId = &jni::GetMethodID(env, *Number::jclass, "floatValue", "()F"); - Number::doubleValueMethodId = &jni::GetMethodID(env, *Number::jclass, "doubleValue", "()D"); - Number::longValueMethodId = &jni::GetMethodID(env, *Number::jclass, "longValue", "()J"); + Number::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/lang/Number")).release(); + Number::floatValueMethodId = &jni::GetMethodID(env, *Number::jclass, "floatValue", "()F"); + Number::doubleValueMethodId = &jni::GetMethodID(env, *Number::jclass, "doubleValue", "()D"); + Number::longValueMethodId = &jni::GetMethodID(env, *Number::jclass, "longValue", "()J"); - Map::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Map")).release(); - Map::getMethodId = &jni::GetMethodID(env, *Map::jclass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); - Map::keySetMethodId = &jni::GetMethodID(env, *Map::jclass, "keySet", "()Ljava/util/Set;"); + Map::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Map")).release(); + Map::getMethodId = &jni::GetMethodID(env, *Map::jclass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); + Map::keySetMethodId = &jni::GetMethodID(env, *Map::jclass, "keySet", "()Ljava/util/Set;"); - Set::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Set")).release(); - Set::toArrayMethodId = &jni::GetMethodID(env, *Set::jclass, "toArray", "()[Ljava/lang/Object;"); - } - -} -} + Set::jclass = jni::NewGlobalRef(env, &jni::FindClass(env, "java/util/Set")).release(); + Set::toArrayMethodId = &jni::GetMethodID(env, *Set::jclass, "toArray", "()[Ljava/lang/Object;"); } + +} // namespace java +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp index c7c93ce71b0..0540fdb9488 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/java_types.hpp @@ -6,38 +6,38 @@ namespace mbgl { namespace android { namespace java { - struct ObjectArray { - static jni::jclass* jclass; - }; - - struct String { - static jni::jclass* jclass; - }; - - struct Boolean { - static jni::jclass* jclass; - static jni::jmethodID* booleanValueMethodId; - }; - - struct Number { - static jni::jclass* jclass; - static jni::jmethodID* floatValueMethodId; - static jni::jmethodID* doubleValueMethodId; - static jni::jmethodID* longValueMethodId; - }; - - struct Map { - static jni::jclass* jclass; - static jni::jmethodID* getMethodId; - static jni::jmethodID* keySetMethodId; - }; - - struct Set { - static jni::jclass* jclass; - static jni::jmethodID* toArrayMethodId; - }; - - void registerNatives(JNIEnv&); -} -} -} +struct ObjectArray { + static jni::jclass* jclass; +}; + +struct String { + static jni::jclass* jclass; +}; + +struct Boolean { + static jni::jclass* jclass; + static jni::jmethodID* booleanValueMethodId; +}; + +struct Number { + static jni::jclass* jclass; + static jni::jmethodID* floatValueMethodId; + static jni::jmethodID* doubleValueMethodId; + static jni::jmethodID* longValueMethodId; +}; + +struct Map { + static jni::jclass* jclass; + static jni::jmethodID* getMethodId; + static jni::jmethodID* keySetMethodId; +}; + +struct Set { + static jni::jclass* jclass; + static jni::jmethodID* toArrayMethodId; +}; + +void registerNatives(JNIEnv&); +} // namespace java +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp index 52b3016ff5c..44aea3074f4 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/jni_native.cpp @@ -62,7 +62,7 @@ namespace android { void RegisterNativeHTTPRequest(JNIEnv&); -void registerNatives(JavaVM *vm) { +void registerNatives(JavaVM* vm) { theJVM = vm; jni::JNIEnv& env = jni::GetEnv(*vm, jni::jni_version_1_6); @@ -101,7 +101,7 @@ void registerNatives(JavaVM *vm) { gson::JsonObject::registerNative(env); gson::JsonPrimitive::registerNative(env); - //Annotation + // Annotation Marker::registerNative(env); Polygon::registerNative(env); Polyline::registerNative(env); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp index f5d78cc83ce..abe5c9211cc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.cpp @@ -8,7 +8,7 @@ void Logger::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } -void Logger::log(jni::JNIEnv& env, EventSeverity severity, const std::string &msg) { +void Logger::log(jni::JNIEnv& env, EventSeverity severity, const std::string& msg) { static auto& _class = jni::Class::Singleton(env); auto tag = jni::Make(env, "Mbgl"); @@ -21,7 +21,7 @@ void Logger::log(jni::JNIEnv& env, EventSeverity severity, const std::string &ms } else if (severity == EventSeverity::Info) { auto static info = _class.GetStaticMethod(env, "i"); _class.Call(env, info, tag, message); - } else if(severity == EventSeverity::Warning) { + } else if (severity == EventSeverity::Warning) { auto static warning = _class.GetStaticMethod(env, "w"); _class.Call(env, warning, tag, message); } else { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp index 7481ecb2658..2eaa2b523be 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/logger.hpp @@ -9,12 +9,10 @@ namespace android { class Logger { public: - static constexpr auto Name() { - return "com/mapbox/mapboxsdk/log/Logger"; - }; - static void registerNative(jni::JNIEnv&); + static constexpr auto Name() { return "com/mapbox/mapboxsdk/log/Logger"; }; + static void registerNative(jni::JNIEnv &); - static void log(jni::JNIEnv&, EventSeverity severity, const std::string &msg); + static void log(jni::JNIEnv &, EventSeverity severity, const std::string &msg); }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp index 1301367280c..46543124bbd 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/logging_android.cpp @@ -6,8 +6,8 @@ namespace mbgl { void Log::platformRecord(EventSeverity severity, const std::string &msg) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; android::Logger::log(*env, severity, msg); } -} \ No newline at end of file +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp index 4266b64fdfe..2d346562d05 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map/camera_position.cpp @@ -4,9 +4,12 @@ namespace mbgl { namespace android { -jni::Local> CameraPosition::New(jni::JNIEnv &env, mbgl::CameraOptions options, float pixelRatio) { +jni::Local> CameraPosition::New(jni::JNIEnv& env, + mbgl::CameraOptions options, + float pixelRatio) { static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, double, double, double, jni::Array>(env); + static auto constructor = + javaClass.GetConstructor, double, double, double, jni::Array>(env); // wrap LatLng values coming from core auto center = options.center.value(); @@ -26,7 +29,7 @@ jni::Local> CameraPosition::New(jni::JNIEnv &env, mb double tilt_degrees = options.pitch.value_or(0); std::vector paddingVect; - auto insets = options.padding.value_or(EdgeInsets {0, 0, 0, 0}); + auto insets = options.padding.value_or(EdgeInsets{0, 0, 0, 0}); auto padding = jni::Array::New(env, 4); paddingVect.push_back(insets.left() * pixelRatio); paddingVect.push_back(insets.top() * pixelRatio); @@ -34,10 +37,13 @@ jni::Local> CameraPosition::New(jni::JNIEnv &env, mb paddingVect.push_back(insets.bottom() * pixelRatio); padding.SetRegion>(env, 0, paddingVect); - return javaClass.New(env, constructor, LatLng::New(env, center), options.zoom.value_or(0), tilt_degrees, bearing_degrees, padding); + return javaClass.New( + env, constructor, LatLng::New(env, center), options.zoom.value_or(0), tilt_degrees, bearing_degrees, padding); } -mbgl::CameraOptions CameraPosition::getCameraOptions(jni::JNIEnv& env, const jni::Object& position, float pixelRatio) { +mbgl::CameraOptions CameraPosition::getCameraOptions(jni::JNIEnv& env, + const jni::Object& position, + float pixelRatio) { static auto& javaClass = jni::Class::Singleton(env); static auto bearing = javaClass.GetField(env, "bearing"); static auto target = javaClass.GetField>(env, "target"); @@ -60,10 +66,9 @@ mbgl::CameraOptions CameraPosition::getCameraOptions(jni::JNIEnv& env, const jni position.Get(env, tilt)}; } -void CameraPosition::registerNative(jni::JNIEnv &env) { +void CameraPosition::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } } // namespace android -} // namespace mb - +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp index 04f5b1a3522..17c98f3612b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map/image.cpp @@ -13,7 +13,7 @@ mbgl::style::Image Image::getImage(jni::JNIEnv& env, const jni::Object& i static auto bufferField = javaClass.GetField>(env, "buffer"); static auto nameField = javaClass.GetField(env, "name"); static auto sdfField = javaClass.GetField(env, "sdf"); - static auto contentField = javaClass.GetField>(env, "content"); + static auto contentField = javaClass.GetField>(env, "content"); static auto stretchXField = javaClass.GetField>(env, "stretchX"); static auto stretchYField = javaClass.GetField>(env, "stretchY"); @@ -22,20 +22,19 @@ mbgl::style::Image Image::getImage(jni::JNIEnv& env, const jni::Object& i auto pixelRatio = image.Get(env, pixelRatioField); auto pixels = image.Get(env, bufferField); auto name = jni::Make(env, image.Get(env, nameField)); - auto sdf = (bool) image.Get(env, sdfField); + auto sdf = (bool)image.Get(env, sdfField); auto content = image.Get(env, contentField); auto stretchX = image.Get(env, stretchXField); auto stretchY = image.Get(env, stretchYField); jni::NullCheck(env, pixels.get()); std::size_t size = pixels.Length(env); - mbgl::PremultipliedImage premultipliedImage({ static_cast(width), static_cast(height) }); + mbgl::PremultipliedImage premultipliedImage({static_cast(width), static_cast(height)}); if (premultipliedImage.bytes() != uint32_t(size)) { throw mbgl::util::StyleImageException("Image pixel count mismatch"); } - jni::GetArrayRegion(env, *pixels, 0, size, - reinterpret_cast(premultipliedImage.data.get())); + jni::GetArrayRegion(env, *pixels, 0, size, reinterpret_cast(premultipliedImage.data.get())); style::ImageStretches imageStretchesX = {}; style::ImageStretches imageStretchesY = {}; @@ -53,24 +52,23 @@ mbgl::style::Image Image::getImage(jni::JNIEnv& env, const jni::Object& i } if (content) { - const style::ImageContent imageContent = style::ImageContent{content.Get(env, 0), - content.Get(env, 1), - content.Get(env, 2), - content.Get(env, 3)}; - return mbgl::style::Image{name, std::move(premultipliedImage), pixelRatio, sdf, + const style::ImageContent imageContent = style::ImageContent{ + content.Get(env, 0), content.Get(env, 1), content.Get(env, 2), content.Get(env, 3)}; + return mbgl::style::Image{name, + std::move(premultipliedImage), + pixelRatio, + sdf, imageStretchesX, imageStretchesY, std::move(imageContent)}; } - return mbgl::style::Image{name, std::move(premultipliedImage), pixelRatio, sdf, - imageStretchesX, - imageStretchesY}; + return mbgl::style::Image{name, std::move(premultipliedImage), pixelRatio, sdf, imageStretchesX, imageStretchesY}; } -void Image::registerNative(jni::JNIEnv &env) { +void Image::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } } // namespace android -} // namespace mb +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp index 051e99410f7..4941e3316f9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.cpp @@ -24,7 +24,8 @@ MapRenderer::MapRenderer(jni::JNIEnv& _env, : std::optional{}), mailboxData(this) {} -MapRenderer::MailboxData::MailboxData(Scheduler* scheduler_) : scheduler(scheduler_) { +MapRenderer::MailboxData::MailboxData(Scheduler* scheduler_) + : scheduler(scheduler_) { assert(scheduler); } @@ -70,8 +71,7 @@ void MapRenderer::schedule(std::function scheduled) { // Queue the event on the Java Peer static auto& javaClass = jni::Class::Singleton(*_env); - static auto queueEvent = javaClass.GetMethod)>(*_env, "queueEvent"); + static auto queueEvent = javaClass.GetMethod)>(*_env, "queueEvent"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, queueEvent, peer); @@ -127,16 +127,17 @@ void MapRenderer::setObserver(std::shared_ptr _rendererObserve void MapRenderer::requestSnapshot(SnapshotCallback callback) { auto self = ActorRef(*this, mailboxData.getMailbox()); self.invoke( - &MapRenderer::scheduleSnapshot, - std::make_unique([&, callback=std::move(callback), runloop=util::RunLoop::Get()](PremultipliedImage image) { - runloop->invoke([callback=std::move(callback), image=std::move(image), renderer=std::move(this)]() mutable { - if (renderer && !renderer->destroyed) { - callback(std::move(image)); - } - }); + &MapRenderer::scheduleSnapshot, + std::make_unique( + [&, callback = std::move(callback), runloop = util::RunLoop::Get()](PremultipliedImage image) { + runloop->invoke( + [callback = std::move(callback), image = std::move(image), renderer = std::move(this)]() mutable { + if (renderer && !renderer->destroyed) { + callback(std::move(image)); + } + }); snapshotCallback.reset(); - }) - ); + })); } // Called on OpenGL thread // @@ -152,7 +153,7 @@ void MapRenderer::scheduleSnapshot(std::unique_ptr callback) { } void MapRenderer::render(JNIEnv&) { - assert (renderer); + assert(renderer); std::shared_ptr params; { @@ -165,7 +166,7 @@ void MapRenderer::render(JNIEnv&) { } // Activate the backend - gfx::BackendScope backendGuard { *backend }; + gfx::BackendScope backendGuard{*backend}; // Ensure that the "current" scheduler on the render thread is // this scheduler. @@ -190,7 +191,7 @@ void MapRenderer::onSurfaceCreated(JNIEnv&) { std::lock_guard lock(initialisationMutex); // The GL context is already active if get a new surface. - gfx::BackendScope backendGuard { *backend, gfx::BackendScope::ScopeType::Implicit }; + gfx::BackendScope backendGuard{*backend, gfx::BackendScope::ScopeType::Implicit}; // The android system will have already destroyed the underlying // GL resources if this is not the first initialization and an @@ -244,17 +245,18 @@ void MapRenderer::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, javaClass, "nativePtr", - jni::MakePeer&, jni::jfloat, const jni::String&>, - "nativeInitialize", "finalize", - METHOD(&MapRenderer::render, "nativeRender"), - METHOD(&MapRenderer::onRendererReset, "nativeReset"), - METHOD(&MapRenderer::onSurfaceCreated, - "nativeOnSurfaceCreated"), - METHOD(&MapRenderer::onSurfaceChanged, - "nativeOnSurfaceChanged"), - METHOD(&MapRenderer::onSurfaceDestroyed, - "nativeOnSurfaceDestroyed")); + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&, jni::jfloat, const jni::String&>, + "nativeInitialize", + "finalize", + METHOD(&MapRenderer::render, "nativeRender"), + METHOD(&MapRenderer::onRendererReset, "nativeReset"), + METHOD(&MapRenderer::onSurfaceCreated, "nativeOnSurfaceCreated"), + METHOD(&MapRenderer::onSurfaceChanged, "nativeOnSurfaceChanged"), + METHOD(&MapRenderer::onSurfaceDestroyed, "nativeOnSurfaceDestroyed")); } MapRenderer& MapRenderer::getNativePeer(JNIEnv& env, const jni::Object& jObject) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp index a7b7ca729af..dc84aaad739 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer.hpp @@ -34,7 +34,6 @@ class AndroidRendererBackend; */ class MapRenderer : public Scheduler { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/maps/renderer/MapRenderer"; }; static void registerNative(jni::JNIEnv&); @@ -73,7 +72,7 @@ class MapRenderer : public Scheduler { void requestRender(); // Snapshot - requires a RunLoop on the calling thread - using SnapshotCallback = std::function; + using SnapshotCallback = std::function; void requestSnapshot(SnapshotCallback); protected: @@ -128,7 +127,7 @@ class MapRenderer : public Scheduler { std::mutex updateMutex; bool framebufferSizeChanged = false; - std::atomic destroyed {false}; + std::atomic destroyed{false}; std::unique_ptr snapshotCallback; mapbox::base::WeakPtrFactory weakFactory{this}; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp index 227f49ee3f3..805bcac8f9f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.cpp @@ -35,14 +35,13 @@ void MapRendererRunnable::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - std::make_unique, - "nativeInitialize", - "finalize", - METHOD(&MapRendererRunnable::run, "run")); + jni::RegisterNativePeer(env, + javaClass, + "nativePtr", + std::make_unique, + "nativeInitialize", + "finalize", + METHOD(&MapRendererRunnable::run, "run")); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp index 24d0f2af49b..06826b4cb46 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/map_renderer_runnable.hpp @@ -19,7 +19,6 @@ namespace android { */ class MapRendererRunnable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/maps/renderer/MapRendererRunnable"; }; static void registerNative(jni::JNIEnv&); @@ -27,9 +26,7 @@ class MapRendererRunnable { MapRendererRunnable(jni::JNIEnv&, std::function); // Only for jni registration, unused - MapRendererRunnable(jni::JNIEnv&) { - assert(false); - } + MapRendererRunnable(jni::JNIEnv&) { assert(false); } ~MapRendererRunnable(); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp index a3da861d442..b80693ed457 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.cpp @@ -63,7 +63,9 @@ NativeMapView::NativeMapView(jni::JNIEnv& _env, const jni::Object& jMapRenderer, jni::jfloat pixelRatio_, jni::jboolean crossSourceCollisions_) - : javaPeer(_env, _obj), mapRenderer(MapRenderer::getNativePeer(_env, jMapRenderer)), pixelRatio(pixelRatio_) { + : javaPeer(_env, _obj), + mapRenderer(MapRenderer::getNativePeer(_env, jMapRenderer)), + pixelRatio(pixelRatio_) { // Get a reference to the JavaVM for callbacks if (_env.GetJavaVM(&vm) < 0) { _env.ExceptionDescribe(); @@ -83,10 +85,11 @@ NativeMapView::NativeMapView(jni::JNIEnv& _env, .withCrossSourceCollisions(crossSourceCollisions_); // Create the core map - map = std::make_unique( - *rendererFrontend, *this, options, - mbgl::android::FileSource::getSharedResourceOptions(_env, jFileSource), - mbgl::android::FileSource::getSharedClientOptions(_env, jFileSource)); + map = std::make_unique(*rendererFrontend, + *this, + options, + mbgl::android::FileSource::getSharedResourceOptions(_env, jFileSource), + mbgl::android::FileSource::getSharedClientOptions(_env, jFileSource)); } /** @@ -102,20 +105,19 @@ void NativeMapView::onCameraWillChange(MapObserver::CameraChangeMode mode) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCameraWillChange = javaClass.GetMethod(*_env, "onCameraWillChange"); + static auto onCameraWillChange = javaClass.GetMethod(*_env, "onCameraWillChange"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onCameraWillChange, (jboolean) (mode != MapObserver::CameraChangeMode::Immediate)); + weakReference.Call(*_env, onCameraWillChange, (jboolean)(mode != MapObserver::CameraChangeMode::Immediate)); } } - void NativeMapView::onCameraIsChanging() { assert(vm != nullptr); android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCameraIsChanging = javaClass.GetMethod(*_env, "onCameraIsChanging"); + static auto onCameraIsChanging = javaClass.GetMethod(*_env, "onCameraIsChanging"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onCameraIsChanging); @@ -127,11 +129,10 @@ void NativeMapView::onCameraDidChange(MapObserver::CameraChangeMode mode) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCameraDidChange = javaClass.GetMethod(*_env, "onCameraDidChange"); + static auto onCameraDidChange = javaClass.GetMethod(*_env, "onCameraDidChange"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onCameraDidChange, - (jboolean) (mode != MapObserver::CameraChangeMode::Immediate)); + weakReference.Call(*_env, onCameraDidChange, (jboolean)(mode != MapObserver::CameraChangeMode::Immediate)); } } @@ -140,7 +141,7 @@ void NativeMapView::onWillStartLoadingMap() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onWillStartLoadingMap = javaClass.GetMethod(*_env, "onWillStartLoadingMap"); + static auto onWillStartLoadingMap = javaClass.GetMethod(*_env, "onWillStartLoadingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onWillStartLoadingMap); @@ -152,7 +153,7 @@ void NativeMapView::onDidFinishLoadingMap() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishLoadingMap = javaClass.GetMethod(*_env, "onDidFinishLoadingMap"); + static auto onDidFinishLoadingMap = javaClass.GetMethod(*_env, "onDidFinishLoadingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidFinishLoadingMap); @@ -164,7 +165,7 @@ void NativeMapView::onDidFailLoadingMap(MapLoadError, const std::string& error) android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFailLoadingMap = javaClass.GetMethod(*_env, "onDidFailLoadingMap"); + static auto onDidFailLoadingMap = javaClass.GetMethod(*_env, "onDidFailLoadingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidFailLoadingMap, jni::Make(*_env, error)); @@ -176,7 +177,7 @@ void NativeMapView::onWillStartRenderingFrame() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onWillStartRenderingFrame = javaClass.GetMethod(*_env, "onWillStartRenderingFrame"); + static auto onWillStartRenderingFrame = javaClass.GetMethod(*_env, "onWillStartRenderingFrame"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onWillStartRenderingFrame); @@ -188,20 +189,20 @@ void NativeMapView::onDidFinishRenderingFrame(MapObserver::RenderFrameStatus sta android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishRenderingFrame = javaClass.GetMethod(*_env, "onDidFinishRenderingFrame"); + static auto onDidFinishRenderingFrame = javaClass.GetMethod(*_env, "onDidFinishRenderingFrame"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onDidFinishRenderingFrame, (jboolean) (status.mode != MapObserver::RenderMode::Partial)); + weakReference.Call( + *_env, onDidFinishRenderingFrame, (jboolean)(status.mode != MapObserver::RenderMode::Partial)); } } - void NativeMapView::onWillStartRenderingMap() { assert(vm != nullptr); android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onWillStartRenderingMap = javaClass.GetMethod(*_env, "onWillStartRenderingMap"); + static auto onWillStartRenderingMap = javaClass.GetMethod(*_env, "onWillStartRenderingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onWillStartRenderingMap); @@ -213,10 +214,10 @@ void NativeMapView::onDidFinishRenderingMap(MapObserver::RenderMode mode) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishRenderingMap = javaClass.GetMethod(*_env, "onDidFinishRenderingMap"); + static auto onDidFinishRenderingMap = javaClass.GetMethod(*_env, "onDidFinishRenderingMap"); auto weakReference = javaPeer.get(*_env); if (weakReference) { - weakReference.Call(*_env, onDidFinishRenderingMap, (jboolean) (mode != MapObserver::RenderMode::Partial)); + weakReference.Call(*_env, onDidFinishRenderingMap, (jboolean)(mode != MapObserver::RenderMode::Partial)); } } @@ -225,7 +226,7 @@ void NativeMapView::onDidBecomeIdle() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidBecomeIdle = javaClass.GetMethod(*_env, "onDidBecomeIdle"); + static auto onDidBecomeIdle = javaClass.GetMethod(*_env, "onDidBecomeIdle"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidBecomeIdle); @@ -237,7 +238,7 @@ void NativeMapView::onDidFinishLoadingStyle() { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onDidFinishLoadingStyle = javaClass.GetMethod(*_env, "onDidFinishLoadingStyle"); + static auto onDidFinishLoadingStyle = javaClass.GetMethod(*_env, "onDidFinishLoadingStyle"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onDidFinishLoadingStyle); @@ -249,7 +250,7 @@ void NativeMapView::onSourceChanged(mbgl::style::Source& source) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onSourceChanged = javaClass.GetMethod(*_env, "onSourceChanged"); + static auto onSourceChanged = javaClass.GetMethod(*_env, "onSourceChanged"); auto sourceId = jni::Make(*_env, source.getID()); auto weakReference = javaPeer.get(*_env); if (weakReference) { @@ -262,7 +263,7 @@ void NativeMapView::onStyleImageMissing(const std::string& imageId) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onStyleImageMissing = javaClass.GetMethod(*_env, "onStyleImageMissing"); + static auto onStyleImageMissing = javaClass.GetMethod(*_env, "onStyleImageMissing"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onStyleImageMissing, jni::Make(*_env, imageId)); @@ -274,7 +275,8 @@ bool NativeMapView::onCanRemoveUnusedStyleImage(const std::string& imageId) { android::UniqueEnv _env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*_env); - static auto onCanRemoveUnusedStyleImage = javaClass.GetMethod(*_env, "onCanRemoveUnusedStyleImage"); + static auto onCanRemoveUnusedStyleImage = javaClass.GetMethod(*_env, + "onCanRemoveUnusedStyleImage"); auto weakReference = javaPeer.get(*_env); if (weakReference) { return weakReference.Call(*_env, onCanRemoveUnusedStyleImage, jni::Make(*_env, imageId)); @@ -288,7 +290,7 @@ bool NativeMapView::onCanRemoveUnusedStyleImage(const std::string& imageId) { void NativeMapView::resizeView(jni::JNIEnv&, int w, int h) { width = util::max(64, w); height = util::max(64, h); - map->setSize({ static_cast(width), static_cast(height) }); + map->setSize({static_cast(width), static_cast(height)}); } jni::Local NativeMapView::getStyleUrl(jni::JNIEnv& env) { @@ -328,13 +330,19 @@ void NativeMapView::setGestureInProgress(jni::JNIEnv&, jni::jboolean inProgress) void NativeMapView::moveBy(jni::JNIEnv&, jni::jdouble dx, jni::jdouble dy, jni::jlong duration) { mbgl::AnimationOptions animationOptions; if (duration > 0) { - animationOptions.duration.emplace(mbgl::Milliseconds(duration)); - animationOptions.easing.emplace(mbgl::util::UnitBezier {0.1, 0.4, 0.35, 1.0}); + animationOptions.duration.emplace(mbgl::Milliseconds(duration)); + animationOptions.easing.emplace(mbgl::util::UnitBezier{0.1, 0.4, 0.35, 1.0}); } map->moveBy({dx, dy}, animationOptions); } -void NativeMapView::jumpTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble latitude, jni::jdouble longitude, jni::jdouble pitch, jni::jdouble zoom, const jni::Array& padding) { +void NativeMapView::jumpTo(jni::JNIEnv& env, + jni::jdouble bearing, + jni::jdouble latitude, + jni::jdouble longitude, + jni::jdouble pitch, + jni::jdouble zoom, + const jni::Array& padding) { mbgl::CameraOptions options; if (bearing != -1) { options.bearing = bearing; @@ -342,8 +350,8 @@ void NativeMapView::jumpTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble options.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - options.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + options.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } if (pitch != -1) { options.pitch = pitch; @@ -355,7 +363,15 @@ void NativeMapView::jumpTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble map->jumpTo(options); } -void NativeMapView::easeTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble latitude, jni::jdouble longitude, jni::jlong duration, jni::jdouble pitch, jni::jdouble zoom, const jni::Array& padding, jni::jboolean easing) { +void NativeMapView::easeTo(jni::JNIEnv& env, + jni::jdouble bearing, + jni::jdouble latitude, + jni::jdouble longitude, + jni::jlong duration, + jni::jdouble pitch, + jni::jdouble zoom, + const jni::Array& padding, + jni::jboolean easing) { mbgl::CameraOptions cameraOptions; if (bearing != -1) { cameraOptions.bearing = bearing; @@ -363,8 +379,8 @@ void NativeMapView::easeTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble cameraOptions.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - cameraOptions.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + cameraOptions.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } if (pitch != -1) { cameraOptions.pitch = pitch; @@ -376,14 +392,21 @@ void NativeMapView::easeTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble mbgl::AnimationOptions animationOptions; animationOptions.duration.emplace(mbgl::Milliseconds(duration)); if (!easing) { - // add a linear interpolator instead of easing - animationOptions.easing.emplace(mbgl::util::UnitBezier { 0, 0, 1, 1 }); + // add a linear interpolator instead of easing + animationOptions.easing.emplace(mbgl::util::UnitBezier{0, 0, 1, 1}); } map->easeTo(cameraOptions, animationOptions); } -void NativeMapView::flyTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble latitude, jni::jdouble longitude, jni::jlong duration, jni::jdouble pitch, jni::jdouble zoom, const jni::Array& padding) { +void NativeMapView::flyTo(jni::JNIEnv& env, + jni::jdouble bearing, + jni::jdouble latitude, + jni::jdouble longitude, + jni::jlong duration, + jni::jdouble pitch, + jni::jdouble zoom, + const jni::Array& padding) { mbgl::CameraOptions cameraOptions; if (bearing != -1) { cameraOptions.bearing = bearing; @@ -391,8 +414,8 @@ void NativeMapView::flyTo(jni::JNIEnv& env, jni::jdouble bearing, jni::jdouble l cameraOptions.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - cameraOptions.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + cameraOptions.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } if (pitch != -1) { cameraOptions.pitch = pitch; @@ -410,23 +433,46 @@ jni::Local> NativeMapView::getLatLng(JNIEnv& env) { return LatLng::New(env, *map->getCameraOptions(std::nullopt).center); } -void NativeMapView::setLatLng(jni::JNIEnv& env, jni::jdouble latitude, jni::jdouble longitude, const jni::Array& padding, jni::jlong duration) { +void NativeMapView::setLatLng(jni::JNIEnv& env, + jni::jdouble latitude, + jni::jdouble longitude, + const jni::Array& padding, + jni::jlong duration) { mbgl::CameraOptions cameraOptions; cameraOptions.center = mbgl::LatLng(latitude, longitude); if (padding) { assert(padding.Length(env) == 4); - cameraOptions.padding = mbgl::EdgeInsets{padding.Get(env, 0), padding.Get(env, 1), - padding.Get(env, 2), padding.Get(env, 3)}; + cameraOptions.padding = mbgl::EdgeInsets{ + padding.Get(env, 0), padding.Get(env, 1), padding.Get(env, 2), padding.Get(env, 3)}; } map->easeTo(cameraOptions, mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } -jni::Local> NativeMapView::getCameraForLatLngBounds(jni::JNIEnv& env, const jni::Object& jBounds, double top, double left, double bottom, double right, double bearing, double tilt) { +jni::Local> NativeMapView::getCameraForLatLngBounds( + jni::JNIEnv& env, + const jni::Object& jBounds, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt) { mbgl::EdgeInsets padding = {top, left, bottom, right}; - return CameraPosition::New(env, map->cameraForLatLngBounds(mbgl::android::LatLngBounds::getLatLngBounds(env, jBounds), padding, bearing, tilt), pixelRatio); -} - -jni::Local> NativeMapView::getCameraForGeometry(jni::JNIEnv& env, const jni::Object& jGeometry, double top, double left, double bottom, double right, double bearing, double tilt) { + return CameraPosition::New( + env, + map->cameraForLatLngBounds(mbgl::android::LatLngBounds::getLatLngBounds(env, jBounds), padding, bearing, tilt), + pixelRatio); +} + +jni::Local> NativeMapView::getCameraForGeometry( + jni::JNIEnv& env, + const jni::Object& jGeometry, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt) { auto geometry = geojson::Geometry::convert(env, jGeometry); mbgl::EdgeInsets padding = {top, left, bottom, right}; return CameraPosition::New(env, map->cameraForGeometry(geometry, padding, bearing, tilt), pixelRatio); @@ -439,7 +485,7 @@ void NativeMapView::setReachability(jni::JNIEnv&, jni::jboolean reachable) { } void NativeMapView::resetPosition(jni::JNIEnv&) { - map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng {}).withZoom(0.0).withBearing(0.0).withPitch(0.0)); + map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng{}).withZoom(0.0).withBearing(0.0).withPitch(0.0)); } jni::jdouble NativeMapView::getPitch(jni::JNIEnv&) { @@ -447,13 +493,12 @@ jni::jdouble NativeMapView::getPitch(jni::JNIEnv&) { } void NativeMapView::setPitch(jni::JNIEnv&, jni::jdouble pitch, jni::jlong duration) { - map->easeTo(mbgl::CameraOptions().withPitch(pitch), - mbgl::AnimationOptions{ mbgl::Milliseconds(duration) }); + map->easeTo(mbgl::CameraOptions().withPitch(pitch), mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } void NativeMapView::setZoom(jni::JNIEnv&, jni::jdouble zoom, jni::jdouble x, jni::jdouble y, jni::jlong duration) { - map->easeTo(mbgl::CameraOptions().withZoom(zoom).withAnchor(mbgl::ScreenCoordinate{ x, y }), - mbgl::AnimationOptions{ mbgl::Milliseconds(duration) }); + map->easeTo(mbgl::CameraOptions().withZoom(zoom).withAnchor(mbgl::ScreenCoordinate{x, y}), + mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } jni::jdouble NativeMapView::getZoom(jni::JNIEnv&) { @@ -496,7 +541,8 @@ jni::jdouble NativeMapView::getMaxPitch(jni::JNIEnv&) { return *map->getBounds().maxPitch; } -void NativeMapView::rotateBy(jni::JNIEnv&, jni::jdouble sx, jni::jdouble sy, jni::jdouble ex, jni::jdouble ey, jni::jlong duration) { +void NativeMapView::rotateBy( + jni::JNIEnv&, jni::jdouble sx, jni::jdouble sy, jni::jdouble ex, jni::jdouble ey, jni::jlong duration) { mbgl::ScreenCoordinate first(sx, sy); mbgl::ScreenCoordinate second(ex, ey); map->rotateBy(first, second, mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); @@ -506,9 +552,11 @@ void NativeMapView::setBearing(jni::JNIEnv&, jni::jdouble degrees, jni::jlong du map->easeTo(mbgl::CameraOptions().withBearing(degrees), mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } -void NativeMapView::setBearingXY(jni::JNIEnv&, jni::jdouble degrees, jni::jdouble cx, jni::jdouble cy, jni::jlong duration) { +void NativeMapView::setBearingXY( + jni::JNIEnv&, jni::jdouble degrees, jni::jdouble cx, jni::jdouble cy, jni::jlong duration) { mbgl::ScreenCoordinate anchor(cx, cy); - map->easeTo(mbgl::CameraOptions().withBearing(degrees).withAnchor(anchor), mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); + map->easeTo(mbgl::CameraOptions().withBearing(degrees).withAnchor(anchor), + mbgl::AnimationOptions{mbgl::Milliseconds(duration)}); } jni::jdouble NativeMapView::getBearing(jni::JNIEnv&) { @@ -516,10 +564,14 @@ jni::jdouble NativeMapView::getBearing(jni::JNIEnv&) { } void NativeMapView::resetNorth(jni::JNIEnv&) { - map->easeTo(mbgl::CameraOptions().withBearing(0.0), mbgl::AnimationOptions {{mbgl::Milliseconds(500)}}); + map->easeTo(mbgl::CameraOptions().withBearing(0.0), mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); } -void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, const jni::Array>& coordinates, const jni::Object& padding, jdouble direction, jni::jlong duration) { +void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, + const jni::Array>& coordinates, + const jni::Object& padding, + jdouble direction, + jni::jlong duration) { NullCheck(env, &coordinates); std::size_t count = coordinates.Length(env); @@ -530,7 +582,10 @@ void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, const jni::ArraycameraForLatLngs(latLngs, mbglInsets); if (direction >= 0) { cameraOptions.bearing = direction; @@ -540,7 +595,7 @@ void NativeMapView::setVisibleCoordinateBounds(JNIEnv& env, const jni::Array 0) { animationOptions.duration.emplace(mbgl::Milliseconds(duration)); // equivalent to kCAMediaTimingFunctionDefault in iOS - animationOptions.easing.emplace(mbgl::util::UnitBezier { 0.25, 0.1, 0.25, 0.1 }); + animationOptions.easing.emplace(mbgl::util::UnitBezier{0.25, 0.1, 0.25, 0.1}); } map->easeTo(cameraOptions, animationOptions); @@ -574,7 +629,7 @@ void NativeMapView::scheduleSnapshot(jni::JNIEnv&) { // invoke Mapview#OnSnapshotReady static auto& javaClass = jni::Class::Singleton(*_env); - static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); + static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onSnapshotReady, bitmap); @@ -586,17 +641,19 @@ jni::Local> NativeMapView::getCameraPosition(jni::JN return CameraPosition::New(env, map->getCameraOptions(std::nullopt), pixelRatio); } -void NativeMapView::updateMarker(jni::JNIEnv& env, jni::jlong markerId, jni::jdouble lat, jni::jdouble lon, const jni::String& jid) { +void NativeMapView::updateMarker( + jni::JNIEnv& env, jni::jlong markerId, jni::jdouble lat, jni::jdouble lon, const jni::String& jid) { if (markerId == -1) { return; } std::string iconId = jni::Make(env, jid); // Because Java only has int, not unsigned int, we need to bump the annotation id up to a long. - map->updateAnnotation(markerId, mbgl::SymbolAnnotation { mbgl::Point(lon, lat), iconId }); + map->updateAnnotation(markerId, mbgl::SymbolAnnotation{mbgl::Point(lon, lat), iconId}); } -jni::Local> NativeMapView::addMarkers(jni::JNIEnv& env, const jni::Array>& jmarkers) { +jni::Local> NativeMapView::addMarkers(jni::JNIEnv& env, + const jni::Array>& jmarkers) { jni::NullCheck(env, &jmarkers); std::size_t len = jmarkers.Length(env); @@ -605,10 +662,8 @@ jni::Local> NativeMapView::addMarkers(jni::JNIEnv& env, c for (std::size_t i = 0; i < len; i++) { auto marker = jmarkers.Get(env, i); - ids.push_back(map->addAnnotation(mbgl::SymbolAnnotation { - Marker::getPosition(env, marker), - Marker::getIconId(env, marker) - })); + ids.push_back(map->addAnnotation( + mbgl::SymbolAnnotation{Marker::getPosition(env, marker), Marker::getIconId(env, marker)})); } auto result = jni::Array::New(env, len); @@ -641,12 +696,17 @@ jni::jdouble NativeMapView::getMetersPerPixelAtLatitude(JNIEnv&, jni::jdouble la return mbgl::Projection::getMetersPerPixelAtLatitude(lat, zoom); } -jni::Local> NativeMapView::projectedMetersForLatLng(JNIEnv& env, jni::jdouble latitude, jni::jdouble longitude) { - mbgl::ProjectedMeters projectedMeters = mbgl::Projection::projectedMetersForLatLng(mbgl::LatLng(latitude, longitude)); +jni::Local> NativeMapView::projectedMetersForLatLng(JNIEnv& env, + jni::jdouble latitude, + jni::jdouble longitude) { + mbgl::ProjectedMeters projectedMeters = mbgl::Projection::projectedMetersForLatLng( + mbgl::LatLng(latitude, longitude)); return ProjectedMeters::New(env, projectedMeters.northing(), projectedMeters.easting()); } -jni::Local> NativeMapView::latLngForProjectedMeters(JNIEnv& env, jdouble northing, jdouble easting) { +jni::Local> NativeMapView::latLngForProjectedMeters(JNIEnv& env, + jdouble northing, + jdouble easting) { return LatLng::New(env, mbgl::Projection::latLngForProjectedMeters(mbgl::ProjectedMeters(northing, easting))); } @@ -711,7 +771,8 @@ void NativeMapView::latLngsForPixels(JNIEnv& env, output.SetRegion>(env, 0, buffer); } -jni::Local> NativeMapView::addPolylines(JNIEnv& env, const jni::Array>& polylines) { +jni::Local> NativeMapView::addPolylines(JNIEnv& env, + const jni::Array>& polylines) { NullCheck(env, &polylines); std::size_t len = polylines.Length(env); @@ -729,8 +790,8 @@ jni::Local> NativeMapView::addPolylines(JNIEnv& env, const jni return result; } - -jni::Local> NativeMapView::addPolygons(JNIEnv& env, const jni::Array>& polygons) { +jni::Local> NativeMapView::addPolygons(JNIEnv& env, + const jni::Array>& polygons) { NullCheck(env, &polygons); std::size_t len = polygons.Length(env); @@ -765,27 +826,28 @@ void NativeMapView::removeAnnotations(JNIEnv& env, const jni::Array& ids) jlong* jids = std::get<0>(elements).get(); for (std::size_t i = 0; i < len; i++) { - if(jids[i] == -1L) { - continue; + if (jids[i] == -1L) { + continue; } map->removeAnnotation(jids[i]); } } -void NativeMapView::addAnnotationIcon(JNIEnv& env, const jni::String& symbol, jint w, jint h, jfloat scale, const jni::Array& jpixels) { +void NativeMapView::addAnnotationIcon( + JNIEnv& env, const jni::String& symbol, jint w, jint h, jfloat scale, const jni::Array& jpixels) { const std::string symbolName = jni::Make(env, symbol); NullCheck(env, &jpixels); std::size_t size = jpixels.Length(env); - mbgl::PremultipliedImage premultipliedImage({ static_cast(w), static_cast(h) }); + mbgl::PremultipliedImage premultipliedImage({static_cast(w), static_cast(h)}); if (premultipliedImage.bytes() != uint32_t(size)) { throw mbgl::util::StyleImageException("Annotation icon image pixel count mismatch"); } jni::GetArrayRegion(env, *jpixels, 0, size, reinterpret_cast(premultipliedImage.data.get())); - map->addAnnotationImage(std::make_unique( - symbolName, std::move(premultipliedImage), static_cast(scale))); + map->addAnnotationImage( + std::make_unique(symbolName, std::move(premultipliedImage), static_cast(scale))); } void NativeMapView::removeAnnotationIcon(JNIEnv& env, const jni::String& symbol) { @@ -799,18 +861,21 @@ jdouble NativeMapView::getTopOffsetPixelsForAnnotationSymbol(JNIEnv& env, const jni::Local> NativeMapView::getTransitionOptions(JNIEnv& env) { const auto transitionOptions = map->getStyle().getTransitionOptions(); - const auto duration = std::chrono::duration_cast(transitionOptions.duration.value_or(mbgl::Duration::zero())).count(); - const auto delay = std::chrono::duration_cast(transitionOptions.delay.value_or(mbgl::Duration::zero())).count(); - const auto enablePlacementTransitions = (jboolean) transitionOptions.enablePlacementTransitions; + const auto duration = std::chrono::duration_cast( + transitionOptions.duration.value_or(mbgl::Duration::zero())) + .count(); + const auto delay = std::chrono::duration_cast( + transitionOptions.delay.value_or(mbgl::Duration::zero())) + .count(); + const auto enablePlacementTransitions = (jboolean)transitionOptions.enablePlacementTransitions; return TransitionOptions::fromTransitionOptions(env, duration, delay, enablePlacementTransitions); } void NativeMapView::setTransitionOptions(JNIEnv& env, const jni::Object& options) { const mbgl::style::TransitionOptions transitionOptions( - Duration(mbgl::Milliseconds(TransitionOptions::getDuration(env, options))), - Duration(mbgl::Milliseconds(TransitionOptions::getDelay(env, options))), - TransitionOptions::isEnablePlacementTransitions(env, options) - ); + Duration(mbgl::Milliseconds(TransitionOptions::getDuration(env, options))), + Duration(mbgl::Milliseconds(TransitionOptions::getDelay(env, options))), + TransitionOptions::isEnablePlacementTransitions(env, options)); map->getStyle().setTransitionOptions(transitionOptions); } @@ -820,8 +885,8 @@ jni::Local> NativeMapView::queryPointAnnotations(JNIEnv& env, // Convert input mbgl::ScreenBox box = { - { RectF::getLeft(env, rect), RectF::getTop(env, rect) }, - { RectF::getRight(env, rect), RectF::getBottom(env, rect) }, + {RectF::getLeft(env, rect), RectF::getTop(env, rect)}, + {RectF::getRight(env, rect), RectF::getBottom(env, rect)}, }; // Assume only points for now @@ -841,8 +906,8 @@ jni::Local> NativeMapView::queryShapeAnnotations(JNIEnv& env, // Convert input mbgl::ScreenBox box = { - {RectF::getLeft(env, rect), RectF::getTop(env, rect)}, - {RectF::getRight(env, rect), RectF::getBottom(env, rect)}, + {RectF::getLeft(env, rect), RectF::getTop(env, rect)}, + {RectF::getRight(env, rect), RectF::getBottom(env, rect)}, }; mbgl::AnnotationIDs ids = rendererFrontend->queryShapeAnnotations(box); @@ -855,9 +920,12 @@ jni::Local> NativeMapView::queryShapeAnnotations(JNIEnv& env, return result; } -jni::Local>> NativeMapView::queryRenderedFeaturesForPoint(JNIEnv& env, jni::jfloat x, jni::jfloat y, - const jni::Array& layerIds, - const jni::Array>& jfilter) { +jni::Local>> NativeMapView::queryRenderedFeaturesForPoint( + JNIEnv& env, + jni::jfloat x, + jni::jfloat y, + const jni::Array& layerIds, + const jni::Array>& jfilter) { using namespace mbgl::android::conversion; using namespace mbgl::android::geojson; @@ -867,14 +935,17 @@ jni::Local>> NativeMapView::queryRender } mapbox::geometry::point point = {x, y}; - return Feature::convert( - env, - rendererFrontend->queryRenderedFeatures(point, { layers, toFilter(env, jfilter) })); + return Feature::convert(env, rendererFrontend->queryRenderedFeatures(point, {layers, toFilter(env, jfilter)})); } -jni::Local>> NativeMapView::queryRenderedFeaturesForBox(JNIEnv& env, jni::jfloat left, jni::jfloat top, - jni::jfloat right, jni::jfloat bottom, const jni::Array& layerIds, - const jni::Array>& jfilter) { +jni::Local>> NativeMapView::queryRenderedFeaturesForBox( + JNIEnv& env, + jni::jfloat left, + jni::jfloat top, + jni::jfloat right, + jni::jfloat bottom, + const jni::Array& layerIds, + const jni::Array>& jfilter) { using namespace mbgl::android::conversion; using namespace mbgl::android::geojson; @@ -882,14 +953,10 @@ jni::Local>> NativeMapView::queryRender if (layerIds && layerIds.Length(env) > 0) { layers = toVector(env, layerIds); } - mapbox::geometry::box box = { - mapbox::geometry::point{ left, top}, - mapbox::geometry::point{ right, bottom } - }; + mapbox::geometry::box box = {mapbox::geometry::point{left, top}, + mapbox::geometry::point{right, bottom}}; - return Feature::convert( - env, - rendererFrontend->queryRenderedFeatures(box, { layers, toFilter(env, jfilter) })); + return Feature::convert(env, rendererFrontend->queryRenderedFeatures(box, {layers, toFilter(env, jfilter)})); } jni::Local> NativeMapView::getLight(JNIEnv& env) { @@ -902,7 +969,6 @@ jni::Local> NativeMapView::getLight(JNIEnv& env) { } jni::Local>> NativeMapView::getLayers(JNIEnv& env) { - // Get the core layers std::vector layers = map->getStyle().getLayers(); @@ -918,12 +984,11 @@ jni::Local>> NativeMapView::getLayers(JNIEnv& env) } jni::Local> NativeMapView::getLayer(JNIEnv& env, const jni::String& layerId) { - // Find the layer mbgl::style::Layer* coreLayer = map->getStyle().getLayer(jni::Make(env, layerId)); if (!coreLayer) { - mbgl::Log::Debug(mbgl::Event::JNI, "No layer found"); - return jni::Local>(); + mbgl::Log::Debug(mbgl::Event::JNI, "No layer found"); + return jni::Local>(); } // Create and return the layer's native peer @@ -933,20 +998,21 @@ jni::Local> NativeMapView::getLayer(JNIEnv& env, const jni::S void NativeMapView::addLayer(JNIEnv& env, jlong nativeLayerPtr, const jni::String& before) { assert(nativeLayerPtr != 0); - Layer *layer = reinterpret_cast(nativeLayerPtr); + Layer* layer = reinterpret_cast(nativeLayerPtr); try { layer->addToStyle( map->getStyle(), before ? std::optional(jni::Make(env, before)) : std::optional()); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); } } void NativeMapView::addLayerAbove(JNIEnv& env, jlong nativeLayerPtr, const jni::String& above) { assert(nativeLayerPtr != 0); - Layer *layer = reinterpret_cast(nativeLayerPtr); + Layer* layer = reinterpret_cast(nativeLayerPtr); // Find the sibling auto layers = map->getStyle().getLayers(); @@ -964,34 +1030,37 @@ void NativeMapView::addLayerAbove(JNIEnv& env, jlong nativeLayerPtr, const jni:: std::optional before; if (index + 1 > layers.size()) { // Not found - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), - std::string("Could not find layer: ").append(siblingId).c_str()); + jni::ThrowNew(env, + jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), + std::string("Could not find layer: ").append(siblingId).c_str()); return; } else if (index + 1 < layers.size()) { // Place before the sibling - before = { layers.at(index + 1)->getID() }; + before = {layers.at(index + 1)->getID()}; } // Add the layer try { layer->addToStyle(map->getStyle(), before); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); } } void NativeMapView::addLayerAt(JNIEnv& env, jlong nativeLayerPtr, jni::jint index) { assert(nativeLayerPtr != 0); - Layer *layer = reinterpret_cast(nativeLayerPtr); + Layer* layer = reinterpret_cast(nativeLayerPtr); auto layers = map->getStyle().getLayers(); // Check index int numLayers = layers.size() - 1; if (index > numLayers || index < 0) { Log::Error(Event::JNI, "Index out of range: " + std::to_string(index)); - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), - std::string("Invalid index").c_str()); + jni::ThrowNew(env, + jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), + std::string("Invalid index").c_str()); return; } @@ -999,11 +1068,11 @@ void NativeMapView::addLayerAt(JNIEnv& env, jlong nativeLayerPtr, jni::jint inde try { layer->addToStyle(map->getStyle(), layers.at(index)->getID()); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/layers/CannotAddLayerException"), error.what()); } } - /** * Remove layer at index. */ @@ -1019,8 +1088,8 @@ jni::jboolean NativeMapView::removeLayerAt(JNIEnv& env, jni::jint index) { std::unique_ptr coreLayer = map->getStyle().removeLayer(layers.at(index)->getID()); if (coreLayer) { - jni::Local> layerObj = - LayerManagerAndroid::get()->createJavaLayerPeer(env, std::move(coreLayer)); + jni::Local> layerObj = LayerManagerAndroid::get()->createJavaLayerPeer(env, + std::move(coreLayer)); return jni::jni_true; } return jni::jni_false; @@ -1032,7 +1101,7 @@ jni::jboolean NativeMapView::removeLayerAt(JNIEnv& env, jni::jint index) { jni::jboolean NativeMapView::removeLayer(JNIEnv&, jlong layerPtr) { assert(layerPtr != 0); - mbgl::android::Layer *layer = reinterpret_cast(layerPtr); + mbgl::android::Layer* layer = reinterpret_cast(layerPtr); std::unique_ptr coreLayer = map->getStyle().removeLayer(layer->get().getID()); if (coreLayer) { layer->setLayer(std::move(coreLayer)); @@ -1060,8 +1129,8 @@ jni::Local> NativeMapView::getSource(JNIEnv& env, const jni: // Find the source mbgl::style::Source* coreSource = map->getStyle().getSource(jni::Make(env, sourceId)); if (!coreSource) { - mbgl::Log::Debug(mbgl::Event::JNI, "No source found"); - return jni::Local>(); + mbgl::Log::Debug(mbgl::Event::JNI, "No source found"); + return jni::Local>(); } // Create and return the source's native peer @@ -1071,18 +1140,19 @@ jni::Local> NativeMapView::getSource(JNIEnv& env, const jni: void NativeMapView::addSource(JNIEnv& env, const jni::Object& obj, jlong sourcePtr) { assert(sourcePtr != 0); - Source *source = reinterpret_cast(sourcePtr); + Source* source = reinterpret_cast(sourcePtr); try { source->addToMap(env, obj, *map, *rendererFrontend); } catch (const std::runtime_error& error) { - jni::ThrowNew(env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what()); + jni::ThrowNew( + env, jni::FindClass(env, "com/mapbox/mapboxsdk/style/sources/CannotAddSourceException"), error.what()); } } jni::jboolean NativeMapView::removeSource(JNIEnv& env, const jni::Object& obj, jlong sourcePtr) { assert(sourcePtr != 0); - mbgl::android::Source *source = reinterpret_cast(sourcePtr); + mbgl::android::Source* source = reinterpret_cast(sourcePtr); if (source->removeFromMap(env, obj, *map)) { source->releaseJavaPeer(); return jni::jni_true; @@ -1091,16 +1161,13 @@ jni::jboolean NativeMapView::removeSource(JNIEnv& env, const jni::Object return jni::jni_false; } -void NativeMapView::addImage(JNIEnv& env, const jni::String& name, const jni::Object& bitmap, jni::jfloat scale, jni::jboolean sdf) { +void NativeMapView::addImage( + JNIEnv& env, const jni::String& name, const jni::Object& bitmap, jni::jfloat scale, jni::jboolean sdf) { jni::NullCheck(env, &bitmap); mbgl::PremultipliedImage premultipliedImage = Bitmap::GetImage(env, bitmap); map->getStyle().addImage(std::make_unique( - jni::Make(env, name), - std::move(premultipliedImage), - static_cast(scale), - sdf) - ); + jni::Make(env, name), std::move(premultipliedImage), static_cast(scale), sdf)); } void NativeMapView::addImages(JNIEnv& env, const jni::Array>& jimages) { @@ -1155,7 +1222,7 @@ void NativeMapView::registerNative(jni::JNIEnv& env) { // Lookup the class static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer jni::RegisterNativePeer( diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp index be632e242da..9a01d4e31a2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/native_map_view.hpp @@ -40,7 +40,6 @@ class MapRenderer; class NativeMapView : public MapObserver { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/maps/NativeMapView"; }; static void registerNative(jni::JNIEnv&); @@ -91,19 +90,54 @@ class NativeMapView : public MapObserver { void moveBy(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jlong); - void jumpTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, jni::jdouble, const jni::Array&); - - void easeTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong, jni::jdouble, jni::jdouble, const jni::Array&, jni::jboolean); - - void flyTo(jni::JNIEnv&, jni::jdouble, jni::jdouble, jni::jdouble, jni::jlong, jni::jdouble, jni::jdouble, const jni::Array&); + void jumpTo(jni::JNIEnv&, + jni::jdouble, + jni::jdouble, + jni::jdouble, + jni::jdouble, + jni::jdouble, + const jni::Array&); + + void easeTo(jni::JNIEnv&, + jni::jdouble, + jni::jdouble, + jni::jdouble, + jni::jlong, + jni::jdouble, + jni::jdouble, + const jni::Array&, + jni::jboolean); + + void flyTo(jni::JNIEnv&, + jni::jdouble, + jni::jdouble, + jni::jdouble, + jni::jlong, + jni::jdouble, + jni::jdouble, + const jni::Array&); jni::Local> getLatLng(JNIEnv&); void setLatLng(jni::JNIEnv&, jni::jdouble, jni::jdouble, const jni::Array&, jni::jlong); - jni::Local> getCameraForLatLngBounds(jni::JNIEnv&, const jni::Object&, double top, double left, double bottom, double right, double bearing, double tilt); - - jni::Local> getCameraForGeometry(jni::JNIEnv&, const jni::Object&, double top, double left, double bottom, double right, double bearing, double tilt); + jni::Local> getCameraForLatLngBounds(jni::JNIEnv&, + const jni::Object&, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt); + + jni::Local> getCameraForGeometry(jni::JNIEnv&, + const jni::Object&, + double top, + double left, + double bottom, + double right, + double bearing, + double tilt); void setReachability(jni::JNIEnv&, jni::jboolean); @@ -145,7 +179,8 @@ class NativeMapView : public MapObserver { void resetNorth(jni::JNIEnv&); - void setVisibleCoordinateBounds(JNIEnv&, const jni::Array>&, const jni::Object&, jni::jdouble, jni::jlong); + void setVisibleCoordinateBounds( + JNIEnv&, const jni::Array>&, const jni::Object&, jni::jdouble, jni::jlong); void getVisibleCoordinateBounds(JNIEnv& env, jni::Array& output); @@ -203,13 +238,17 @@ class NativeMapView : public MapObserver { jni::Local> queryShapeAnnotations(JNIEnv&, const jni::Object&); - jni::Local>> queryRenderedFeaturesForPoint(JNIEnv&, jni::jfloat, jni::jfloat, - const jni::Array&, - const jni::Array>& jfilter); + jni::Local>> queryRenderedFeaturesForPoint( + JNIEnv&, jni::jfloat, jni::jfloat, const jni::Array&, const jni::Array>& jfilter); - jni::Local>> queryRenderedFeaturesForBox(JNIEnv&, jni::jfloat, jni::jfloat, jni::jfloat, - jni::jfloat, const jni::Array&, - const jni::Array>& jfilter); + jni::Local>> queryRenderedFeaturesForBox( + JNIEnv&, + jni::jfloat, + jni::jfloat, + jni::jfloat, + jni::jfloat, + const jni::Array&, + const jni::Array>& jfilter); jni::Local> getLight(JNIEnv&); @@ -258,7 +297,7 @@ class NativeMapView : public MapObserver { private: std::unique_ptr rendererFrontend; - JavaVM *vm = nullptr; + JavaVM* vm = nullptr; jni::WeakReference> javaPeer; MapRenderer& mapRenderer; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp index e2f94eddf68..56a0c7ff6a8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.cpp @@ -25,11 +25,10 @@ void handleException(std::exception_ptr exception, // OfflineManager // OfflineManager::OfflineManager(jni::JNIEnv& env, const jni::Object& jFileSource) - : fileSource(std::static_pointer_cast( - std::shared_ptr(mbgl::FileSourceManager::get()->getFileSource( - mbgl::FileSourceType::Database, - FileSource::getSharedResourceOptions(env, jFileSource), - FileSource::getSharedClientOptions(env, jFileSource))))) { + : fileSource(std::static_pointer_cast(std::shared_ptr( + mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, + FileSource::getSharedResourceOptions(env, jFileSource), + FileSource::getSharedClientOptions(env, jFileSource))))) { if (!fileSource) { ThrowNew(env, jni::FindClass(env, "java/lang/IllegalStateException"), "Offline functionality is disabled."); } @@ -41,27 +40,28 @@ void OfflineManager::setOfflineMapboxTileCountLimit(jni::JNIEnv&, jni::jlong lim fileSource->setOfflineMapboxTileCountLimit(limit); } -void OfflineManager::listOfflineRegions(jni::JNIEnv& env_, const jni::Object& jFileSource_, const jni::Object& callback_) { +void OfflineManager::listOfflineRegions(jni::JNIEnv& env_, + const jni::Object& jFileSource_, + const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); auto globalFilesource = jni::NewGlobal(env_, jFileSource_); - fileSource->listOfflineRegions([ - //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)), - jFileSource = std::make_shared(std::move(globalFilesource)) - ](mbgl::expected regions) mutable { - - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (regions) { - OfflineManager::ListOfflineRegionsCallback::onList( - *env, *jFileSource, *callback, *regions); - } else { - OfflineManager::ListOfflineRegionsCallback::onError( - *env, *callback, regions.error()); - } - }); + fileSource->listOfflineRegions( + [ + // Keep a shared ptr to a global reference of the callback and file + // source so they are not GC'd in the meanwhile + callback = std::make_shared(std::move(globalCallback)), + jFileSource = std::make_shared(std::move(globalFilesource))]( + mbgl::expected regions) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (regions) { + OfflineManager::ListOfflineRegionsCallback::onList(*env, *jFileSource, *callback, *regions); + } else { + OfflineManager::ListOfflineRegionsCallback::onError(*env, *callback, regions.error()); + } + }); } void OfflineManager::createOfflineRegion(jni::JNIEnv& env_, @@ -81,70 +81,71 @@ void OfflineManager::createOfflineRegion(jni::JNIEnv& env_, auto globalFilesource = jni::NewGlobal(env_, jFileSource_); // Create region - fileSource->createOfflineRegion(definition, metadata, [ - //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)), - jFileSource = std::make_shared(std::move(globalFilesource)) - ](mbgl::expected region) mutable { - - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (region) { - OfflineManager::CreateOfflineRegionCallback::onCreate( - *env, *jFileSource, *callback, *region - ); - } else { - OfflineManager::CreateOfflineRegionCallback::onError( - *env, *callback, region.error()); - } - }); + fileSource->createOfflineRegion( + definition, + metadata, + [ + // Keep a shared ptr to a global reference of the callback and file + // source so they are not GC'd in the meanwhile + callback = std::make_shared(std::move(globalCallback)), + jFileSource = std::make_shared(std::move(globalFilesource))]( + mbgl::expected region) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (region) { + OfflineManager::CreateOfflineRegionCallback::onCreate(*env, *jFileSource, *callback, *region); + } else { + OfflineManager::CreateOfflineRegionCallback::onError(*env, *callback, region.error()); + } + }); } -void OfflineManager::mergeOfflineRegions(jni::JNIEnv& env_, const jni::Object& jFileSource_, +void OfflineManager::mergeOfflineRegions(jni::JNIEnv& env_, + const jni::Object& jFileSource_, const jni::String& jString_, const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); auto globalFilesource = jni::NewGlobal(env_, jFileSource_); auto path = jni::Make(env_, jString_); - fileSource->mergeOfflineRegions(path, [ - //Keep a shared ptr to a global reference of the callback and file source so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)), - jFileSource = std::make_shared(std::move(globalFilesource)) - ](mbgl::expected regions) mutable { - - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (regions) { - OfflineManager::MergeOfflineRegionsCallback::onMerge( - *env, *jFileSource, *callback, *regions); - } else { - OfflineManager::MergeOfflineRegionsCallback::onError( - *env, *callback, regions.error()); - } - }); + fileSource->mergeOfflineRegions( + path, + [ + // Keep a shared ptr to a global reference of the callback and file + // source so they are not GC'd in the meanwhile + callback = std::make_shared(std::move(globalCallback)), + jFileSource = std::make_shared(std::move(globalFilesource))]( + mbgl::expected regions) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (regions) { + OfflineManager::MergeOfflineRegionsCallback::onMerge(*env, *jFileSource, *callback, *regions); + } else { + OfflineManager::MergeOfflineRegionsCallback::onError(*env, *callback, regions.error()); + } + }); } void OfflineManager::resetDatabase(jni::JNIEnv& env_, const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->resetDatabase( - [ - // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + fileSource->resetDatabase([ + // Keep a shared ptr to a global reference of the + // callback so they are not GC'd in the meanwhile + callback = std::make_shared(std::move(globalCallback))]( + std::exception_ptr exception) mutable { handleException(exception, *callback); }); } void OfflineManager::packDatabase(jni::JNIEnv& env_, const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->packDatabase( - [ - // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + fileSource->packDatabase([ + // Keep a shared ptr to a global reference of the + // callback so they are not GC'd in the meanwhile + callback = std::make_shared(std::move(globalCallback))]( + std::exception_ptr exception) mutable { handleException(exception, *callback); }); } void OfflineManager::invalidateAmbientCache(jni::JNIEnv& env_, const jni::Object& callback_) { @@ -152,7 +153,8 @@ void OfflineManager::invalidateAmbientCache(jni::JNIEnv& env_, const jni::Object fileSource->invalidateAmbientCache( [ - // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile + // Keep a shared ptr to a global reference of the callback so + // they are not GC'd in the meanwhile callback = std::make_shared(std::move(globalCallback))]( std::exception_ptr exception) mutable { handleException(exception, *callback); }); } @@ -160,20 +162,23 @@ void OfflineManager::invalidateAmbientCache(jni::JNIEnv& env_, const jni::Object void OfflineManager::clearAmbientCache(jni::JNIEnv& env_, const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->clearAmbientCache( - [ - // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile - callback = std::make_shared(std::move(globalCallback))]( - std::exception_ptr exception) mutable { handleException(exception, *callback); }); + fileSource->clearAmbientCache([ + // Keep a shared ptr to a global reference of the callback so + // they are not GC'd in the meanwhile + callback = std::make_shared(std::move(globalCallback))]( + std::exception_ptr exception) mutable { handleException(exception, *callback); }); } -void OfflineManager::setMaximumAmbientCacheSize(jni::JNIEnv& env_, const jni::jlong size_, const jni::Object& callback_) { +void OfflineManager::setMaximumAmbientCacheSize(jni::JNIEnv& env_, + const jni::jlong size_, + const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); fileSource->setMaximumAmbientCacheSize( size_, [ - // Keep a shared ptr to a global reference of the callback so they are not GC'd in the meanwhile + // Keep a shared ptr to a global reference of the callback so + // they are not GC'd in the meanwhile callback = std::make_shared(std::move(globalCallback))]( std::exception_ptr exception) mutable { handleException(exception, *callback); }); } @@ -185,17 +190,17 @@ void OfflineManager::runPackDatabaseAutomatically(jni::JNIEnv&, jboolean autopac // FileSource::FileSourceCallback // void OfflineManager::FileSourceCallback::onSuccess(jni::JNIEnv& env, - const jni::Object& callback) { + const jni::Object& callback) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onSuccess"); + static auto method = javaClass.GetMethod(env, "onSuccess"); callback.Call(env, method); } void OfflineManager::FileSourceCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - const jni::String& message) { + const jni::Object& callback, + const jni::String& message) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, message); } @@ -207,7 +212,7 @@ void OfflineManager::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) jni::RegisterNativePeer( env, @@ -231,21 +236,23 @@ void OfflineManager::registerNative(jni::JNIEnv& env) { // OfflineManager::ListOfflineRegionsCallback // -void OfflineManager::ListOfflineRegionsCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineManager::ListOfflineRegionsCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineManager::ListOfflineRegionsCallback::onList(jni::JNIEnv& env, - const jni::Object& jFileSource, - const jni::Object& callback, - mbgl::OfflineRegions& regions) { +void OfflineManager::ListOfflineRegionsCallback::onList( + jni::JNIEnv& env, + const jni::Object& jFileSource, + const jni::Object& callback, + mbgl::OfflineRegions& regions) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod>)>(env, "onList"); + static auto method = javaClass.GetMethod>)>(env, "onList"); std::size_t index = 0; auto jregions = jni::Array>::New(env, regions.size()); @@ -259,32 +266,35 @@ void OfflineManager::ListOfflineRegionsCallback::onList(jni::JNIEnv& env, // OfflineManager::CreateOfflineRegionCallback // -void OfflineManager::CreateOfflineRegionCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineManager::CreateOfflineRegionCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineManager::CreateOfflineRegionCallback::onCreate(jni::JNIEnv& env, - const jni::Object& jFileSource, - const jni::Object& callback, - mbgl::OfflineRegion& region) { +void OfflineManager::CreateOfflineRegionCallback::onCreate( + jni::JNIEnv& env, + const jni::Object& jFileSource, + const jni::Object& callback, + mbgl::OfflineRegion& region) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod)>(env, "onCreate"); + static auto method = javaClass.GetMethod)>(env, "onCreate"); callback.Call(env, method, OfflineRegion::New(env, jFileSource, std::move(region))); } // OfflineManager::MergeOfflineRegionsCallback // -void OfflineManager::MergeOfflineRegionsCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineManager::MergeOfflineRegionsCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } @@ -294,7 +304,7 @@ void OfflineManager::MergeOfflineRegionsCallback::onMerge(jni::JNIEnv& env, const jni::Object& callback, mbgl::OfflineRegions& regions) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod>)>(env, "onMerge"); + static auto method = javaClass.GetMethod>)>(env, "onMerge"); std::size_t index = 0; auto jregions = jni::Array>::New(env, regions.size()); @@ -313,7 +323,7 @@ void OfflineManager::putResourceWithUrl(jni::JNIEnv& env, jlong expires, const jni::String& eTag_, jboolean mustRevalidate) { - auto url = jni::Make(env, url_); + auto url = jni::Make(env, url_); auto data = std::make_shared(arr.Length(env), char()); jni::GetArrayRegion(env, *arr, 0, data->size(), reinterpret_cast(&(*data)[0])); mbgl::Resource resource(mbgl::Resource::Kind::Unknown, url); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp index 84111a74235..596377e615b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_manager.hpp @@ -16,36 +16,50 @@ namespace android { class OfflineManager { public: - class ListOfflineRegionsCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$ListOfflineRegionsCallback";} + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineManager$ListOfflineRegionsCallback"; + } - static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); + static void onError(jni::JNIEnv&, + const jni::Object&, + std::exception_ptr); static void onList(jni::JNIEnv&, - const jni::Object&, - const jni::Object&, - mbgl::OfflineRegions&); + const jni::Object&, + const jni::Object&, + mbgl::OfflineRegions&); }; class CreateOfflineRegionCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$CreateOfflineRegionCallback"; } + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineManager$CreateOfflineRegionCallback"; + } - static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); + static void onError(jni::JNIEnv&, + const jni::Object&, + std::exception_ptr); static void onCreate(jni::JNIEnv&, - const jni::Object&, - const jni::Object&, - mbgl::OfflineRegion&); + const jni::Object&, + const jni::Object&, + mbgl::OfflineRegion&); }; class MergeOfflineRegionsCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$MergeOfflineRegionsCallback";} + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineManager$MergeOfflineRegionsCallback"; + } - static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); + static void onError(jni::JNIEnv&, + const jni::Object&, + std::exception_ptr); static void onMerge(jni::JNIEnv&, const jni::Object&, @@ -54,7 +68,10 @@ class OfflineManager { }; struct FileSourceCallback { - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineManager$FileSourceCallback";} + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineManager$FileSourceCallback"; + } static void onSuccess(jni::JNIEnv&, const jni::Object&); @@ -70,7 +87,9 @@ class OfflineManager { void setOfflineMapboxTileCountLimit(jni::JNIEnv&, jni::jlong limit); - void listOfflineRegions(jni::JNIEnv&, const jni::Object&, const jni::Object& callback); + void listOfflineRegions(jni::JNIEnv&, + const jni::Object&, + const jni::Object& callback); void createOfflineRegion(jni::JNIEnv&, const jni::Object& jFileSource_, @@ -99,7 +118,9 @@ class OfflineManager { void clearAmbientCache(jni::JNIEnv&, const jni::Object& callback_); - void setMaximumAmbientCacheSize(jni::JNIEnv&, const jni::jlong size, const jni::Object& callback_); + void setMaximumAmbientCacheSize(jni::JNIEnv&, + const jni::jlong size, + const jni::Object& callback_); void runPackDatabaseAutomatically(jni::JNIEnv&, jboolean autopack); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp index ab60a02febb..c9f631289dc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.cpp @@ -16,11 +16,10 @@ namespace android { OfflineRegion::OfflineRegion(jni::JNIEnv& env, jni::jlong offlineRegionPtr, const jni::Object& jFileSource) : region(reinterpret_cast(offlineRegionPtr)), - fileSource(std::static_pointer_cast( - std::shared_ptr(mbgl::FileSourceManager::get()->getFileSource( - mbgl::FileSourceType::Database, - FileSource::getSharedResourceOptions(env, jFileSource), - FileSource::getSharedClientOptions(env, jFileSource))))) { + fileSource(std::static_pointer_cast(std::shared_ptr( + mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Database, + FileSource::getSharedResourceOptions(env, jFileSource), + FileSource::getSharedClientOptions(env, jFileSource))))) { if (!fileSource) { ThrowNew(env, jni::FindClass(env, "java/lang/IllegalStateException"), "Offline functionality is disabled."); } @@ -28,21 +27,20 @@ OfflineRegion::OfflineRegion(jni::JNIEnv& env, jni::jlong offlineRegionPtr, cons OfflineRegion::~OfflineRegion() {} -void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Object& callback) { - +void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, + const jni::Object& callback) { // Define the observer class Observer : public mbgl::OfflineRegionObserver { public: Observer(jni::Global, jni::EnvAttachingDeleter> callback_) - : callback(std::move(callback_)) { - } + : callback(std::move(callback_)) {} void statusChanged(mbgl::OfflineRegionStatus status) override { // Reattach, the callback comes from a different thread android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto method = javaClass.GetMethod)>(*env, "onStatusChanged"); + static auto method = javaClass.GetMethod)>(*env, "onStatusChanged"); callback.Call(*env, method, OfflineRegionStatus::New(*env, status)); } @@ -52,7 +50,8 @@ void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Objec android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto method = javaClass.GetMethod)>(*env, "onError"); + static auto method = javaClass.GetMethod)>(*env, + "onError"); callback.Call(*env, method, OfflineRegionError::New(*env, error)); } @@ -62,7 +61,7 @@ void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Objec android::UniqueEnv env = android::AttachEnv(); static auto& javaClass = jni::Class::Singleton(*env); - static auto method = javaClass.GetMethod(*env, "mapboxTileCountLimitExceeded"); + static auto method = javaClass.GetMethod(*env, "mapboxTileCountLimitExceeded"); callback.Call(*env, method, jlong(limit)); } @@ -71,7 +70,8 @@ void OfflineRegion::setOfflineRegionObserver(jni::JNIEnv& env_, const jni::Objec }; // Set the observer - fileSource->setOfflineRegionObserver(*region, std::make_unique(jni::NewGlobal(env_, callback))); + fileSource->setOfflineRegionObserver( + *region, std::make_unique(jni::NewGlobal(env_, callback))); } void OfflineRegion::setOfflineRegionDownloadState(jni::JNIEnv&, jni::jint jState) { @@ -79,35 +79,38 @@ void OfflineRegion::setOfflineRegionDownloadState(jni::JNIEnv&, jni::jint jState mbgl::OfflineRegionDownloadState state; switch (jState) { case 0: - state = mbgl::OfflineRegionDownloadState::Inactive; - break; + state = mbgl::OfflineRegionDownloadState::Inactive; + break; case 1: - state = mbgl::OfflineRegionDownloadState::Active; - break; + state = mbgl::OfflineRegionDownloadState::Active; + break; default: - mbgl::Log::Error(mbgl::Event::JNI, "State can only be 0 (inactive) or 1 (active)."); - return; + mbgl::Log::Error(mbgl::Event::JNI, "State can only be 0 (inactive) or 1 (active)."); + return; } fileSource->setOfflineRegionDownloadState(*region, state); } -void OfflineRegion::getOfflineRegionStatus(jni::JNIEnv& env_, const jni::Object& callback_) { +void OfflineRegion::getOfflineRegionStatus(jni::JNIEnv& env_, + const jni::Object& callback_) { auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->getOfflineRegionStatus(*region, [ - //Ensure the object is not gc'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)) - ](mbgl::expected status) mutable { - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (status) { - OfflineRegionStatusCallback::onStatus(*env, *callback, std::move(*status)); - } else { - OfflineRegionStatusCallback::onError(*env, *callback, status.error()); - } - }); + fileSource->getOfflineRegionStatus( + *region, + [ + // Ensure the object is not gc'd in the meanwhile + callback = std::make_shared(std::move(globalCallback))]( + mbgl::expected status) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (status) { + OfflineRegionStatusCallback::onStatus(*env, *callback, std::move(*status)); + } else { + OfflineRegionStatusCallback::onError(*env, *callback, status.error()); + } + }); } void OfflineRegion::deleteOfflineRegion(jni::JNIEnv& env_, const jni::Object& callback_) { @@ -149,23 +152,28 @@ void OfflineRegion::invalidateOfflineRegion(jni::JNIEnv& env_, }); } -void OfflineRegion::updateOfflineRegionMetadata(jni::JNIEnv& env_, const jni::Array& jMetadata, const jni::Object& callback_) { +void OfflineRegion::updateOfflineRegionMetadata(jni::JNIEnv& env_, + const jni::Array& jMetadata, + const jni::Object& callback_) { auto metadata = OfflineRegion::metadata(env_, jMetadata); auto globalCallback = jni::NewGlobal(env_, callback_); - fileSource->updateOfflineMetadata(region->getID(), metadata, [ - //Ensure the object is not gc'd in the meanwhile - callback = std::make_shared(std::move(globalCallback)) - ](mbgl::expected data) mutable { - // Reattach, the callback comes from a different thread - android::UniqueEnv env = android::AttachEnv(); - - if (data) { - OfflineRegionUpdateMetadataCallback::onUpdate(*env, *callback, std::move(*data)); - } else { - OfflineRegionUpdateMetadataCallback::onError(*env, *callback, data.error()); - } - }); + fileSource->updateOfflineMetadata( + region->getID(), + metadata, + [ + // Ensure the object is not gc'd in the meanwhile + callback = std::make_shared(std::move(globalCallback))]( + mbgl::expected data) mutable { + // Reattach, the callback comes from a different thread + android::UniqueEnv env = android::AttachEnv(); + + if (data) { + OfflineRegionUpdateMetadataCallback::onUpdate(*env, *callback, std::move(*data)); + } else { + OfflineRegionUpdateMetadataCallback::onError(*env, *callback, data.error()); + } + }); } jni::Local> OfflineRegion::New(jni::JNIEnv& env, @@ -182,10 +190,16 @@ jni::Local> OfflineRegion::New(jni::JNIEnv& env, // Create region java object static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::jlong, jni::Object, jni::Array>(env); + static auto constructor = javaClass.GetConstructor, + jni::jlong, + jni::Object, + jni::Array>(env); - return javaClass.New(env, constructor, - reinterpret_cast(new mbgl::OfflineRegion(std::move(region))), //Copy a region to the heap + return javaClass.New( + env, + constructor, + reinterpret_cast(new mbgl::OfflineRegion(std::move(region))), // Copy a region to the heap jFileSource, jni::jlong(region.getID()), definition, @@ -218,7 +232,7 @@ void OfflineRegion::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) jni::RegisterNativePeer( env, @@ -239,76 +253,84 @@ void OfflineRegion::registerNative(jni::JNIEnv& env) { // OfflineRegionStatusCallback // -void OfflineRegion::OfflineRegionStatusCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionStatusCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error) { static auto& javaClass = jni::Class::Singleton(env); static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionStatusCallback::onStatus(jni::JNIEnv& env, - const jni::Object& callback, - std::optional status) { +void OfflineRegion::OfflineRegionStatusCallback::onStatus( + jni::JNIEnv& env, + const jni::Object& callback, + std::optional status) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod)>(env, "onStatus"); + static auto method = javaClass.GetMethod)>(env, "onStatus"); callback.Call(env, method, OfflineRegionStatus::New(env, std::move(*status))); } // OfflineRegionDeleteCallback // -void OfflineRegion::OfflineRegionDeleteCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionDeleteCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionDeleteCallback::onDelete(jni::JNIEnv& env, const jni::Object& callback) { +void OfflineRegion::OfflineRegionDeleteCallback::onDelete( + jni::JNIEnv& env, const jni::Object& callback) { // Trigger callback static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onDelete"); + static auto method = javaClass.GetMethod(env, "onDelete"); callback.Call(env, method); } // OfflineRegionUpdateMetadataCallback // -void OfflineRegion::OfflineRegionUpdateMetadataCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionUpdateMetadataCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionUpdateMetadataCallback::onUpdate(jni::JNIEnv& env, - const jni::Object& callback, - std::optional metadata) { +void OfflineRegion::OfflineRegionUpdateMetadataCallback::onUpdate( + jni::JNIEnv& env, + const jni::Object& callback, + std::optional metadata) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod)>(env, "onUpdate"); + static auto method = javaClass.GetMethod)>(env, "onUpdate"); callback.Call(env, method, OfflineRegion::metadata(env, std::move(*metadata))); } // OfflineRegionInvalidateCallback // -void OfflineRegion::OfflineRegionInvalidateCallback::onError(jni::JNIEnv& env, - const jni::Object& callback, - std::exception_ptr error) { +void OfflineRegion::OfflineRegionInvalidateCallback::onError( + jni::JNIEnv& env, + const jni::Object& callback, + std::exception_ptr error) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onError"); + static auto method = javaClass.GetMethod(env, "onError"); callback.Call(env, method, jni::Make(env, mbgl::util::toString(error))); } -void OfflineRegion::OfflineRegionInvalidateCallback::onInvalidate(jni::JNIEnv& env, const jni::Object& callback) { +void OfflineRegion::OfflineRegionInvalidateCallback::onInvalidate( + jni::JNIEnv& env, const jni::Object& callback) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetMethod(env, "onInvalidate"); + static auto method = javaClass.GetMethod(env, "onInvalidate"); callback.Call(env, method); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp index 4d161e7d934..848d8b34f81 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region.hpp @@ -14,23 +14,32 @@ class OfflineRegion { public: class OfflineRegionObserver { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionObserver"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineRegion$OfflineRegionObserver"; + }; }; class OfflineRegionStatusCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionStatusCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineRegion$OfflineRegionStatusCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); static void onStatus(jni::JNIEnv&, - const jni::Object&, - std::optional); + const jni::Object&, + std::optional); }; class OfflineRegionDeleteCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionDeleteCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineRegion$OfflineRegionDeleteCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); @@ -39,7 +48,10 @@ class OfflineRegion { class OfflineRegionInvalidateCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionInvalidateCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineRegion$OfflineRegionInvalidateCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); @@ -48,13 +60,16 @@ class OfflineRegion { class OfflineRegionUpdateMetadataCallback { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion$OfflineRegionUpdateMetadataCallback"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineRegion$OfflineRegionUpdateMetadataCallback"; + }; static void onError(jni::JNIEnv&, const jni::Object&, std::exception_ptr); static void onUpdate(jni::JNIEnv&, - const jni::Object&, - std::optional); + const jni::Object&, + std::optional); }; static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineRegion"; }; @@ -73,9 +88,13 @@ class OfflineRegion { void invalidateOfflineRegion(jni::JNIEnv&, const jni::Object&); - void updateOfflineRegionMetadata(jni::JNIEnv&, const jni::Array&, const jni::Object&); + void updateOfflineRegionMetadata(jni::JNIEnv&, + const jni::Array&, + const jni::Object&); - static jni::Local> New(jni::JNIEnv&, const jni::Object&, mbgl::OfflineRegion); + static jni::Local> New(jni::JNIEnv&, + const jni::Object&, + mbgl::OfflineRegion); static jni::Local> metadata(jni::JNIEnv&, mbgl::OfflineRegionMetadata); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp index bb9dfc8dd0a..ef310d0f641 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.cpp @@ -14,12 +14,14 @@ void OfflineRegionDefinition::registerNative(jni::JNIEnv& env) { jni::Class::Singleton(env); } -mbgl::OfflineRegionDefinition OfflineRegionDefinition::getDefinition(JNIEnv& env, - const jni::Object& jDefinition) { +mbgl::OfflineRegionDefinition OfflineRegionDefinition::getDefinition( + JNIEnv& env, const jni::Object& jDefinition) { if (jDefinition.IsInstanceOf(env, jni::Class::Singleton(env))) { - return OfflineTilePyramidRegionDefinition::getDefinition(env, jni::Cast(env, jni::Class::Singleton(env), jDefinition)); + return OfflineTilePyramidRegionDefinition::getDefinition( + env, jni::Cast(env, jni::Class::Singleton(env), jDefinition)); } else if (jDefinition.IsInstanceOf(env, jni::Class::Singleton(env))) { - return OfflineGeometryRegionDefinition::getDefinition(env, jni::Cast(env, jni::Class::Singleton(env), jDefinition)); + return OfflineGeometryRegionDefinition::getDefinition( + env, jni::Cast(env, jni::Class::Singleton(env), jDefinition)); } throw std::runtime_error("Unknown offline region definition java class"); @@ -27,20 +29,28 @@ mbgl::OfflineRegionDefinition OfflineRegionDefinition::getDefinition(JNIEnv& env // OfflineTilePyramidRegionDefinition // -jni::Local> OfflineTilePyramidRegionDefinition::New(jni::JNIEnv& env, const mbgl::OfflineTilePyramidRegionDefinition& definition) { +jni::Local> OfflineTilePyramidRegionDefinition::New( + jni::JNIEnv& env, const mbgl::OfflineTilePyramidRegionDefinition& definition) { static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::jdouble, jni::jdouble, jni::jfloat, jni::jboolean>(env); - - return javaClass.New(env, constructor, - jni::Make(env, definition.styleURL), - LatLngBounds::New(env, definition.bounds), - definition.minZoom, - definition.maxZoom, - definition.pixelRatio, - jni::jboolean(definition.includeIdeographs)); + static auto constructor = javaClass.GetConstructor, + jni::jdouble, + jni::jdouble, + jni::jfloat, + jni::jboolean>(env); + + return javaClass.New(env, + constructor, + jni::Make(env, definition.styleURL), + LatLngBounds::New(env, definition.bounds), + definition.minZoom, + definition.maxZoom, + definition.pixelRatio, + jni::jboolean(definition.includeIdeographs)); } -mbgl::OfflineTilePyramidRegionDefinition OfflineTilePyramidRegionDefinition::getDefinition(jni::JNIEnv& env, const jni::Object& jDefinition) { +mbgl::OfflineTilePyramidRegionDefinition OfflineTilePyramidRegionDefinition::getDefinition( + jni::JNIEnv& env, const jni::Object& jDefinition) { // Field references static auto& javaClass = jni::Class::Singleton(env); static auto styleURLF = javaClass.GetField(env, "styleURL"); @@ -48,16 +58,14 @@ mbgl::OfflineTilePyramidRegionDefinition OfflineTilePyramidRegionDefinition::get static auto minZoomF = javaClass.GetField(env, "minZoom"); static auto maxZoomF = javaClass.GetField(env, "maxZoom"); static auto pixelRatioF = javaClass.GetField(env, "pixelRatio"); - static auto includeIdeographsF = javaClass.GetField(env, "includeIdeographs"); - - return mbgl::OfflineTilePyramidRegionDefinition( - jni::Make(env, jDefinition.Get(env, styleURLF)), - LatLngBounds::getLatLngBounds(env, jDefinition.Get(env, boundsF)), - jDefinition.Get(env, minZoomF), - jDefinition.Get(env, maxZoomF), - jDefinition.Get(env, pixelRatioF), - jDefinition.Get(env, includeIdeographsF) - ); + static auto includeIdeographsF = javaClass.GetField(env, "includeIdeographs"); + + return mbgl::OfflineTilePyramidRegionDefinition(jni::Make(env, jDefinition.Get(env, styleURLF)), + LatLngBounds::getLatLngBounds(env, jDefinition.Get(env, boundsF)), + jDefinition.Get(env, minZoomF), + jDefinition.Get(env, maxZoomF), + jDefinition.Get(env, pixelRatioF), + jDefinition.Get(env, includeIdeographsF)); } void OfflineTilePyramidRegionDefinition::registerNative(jni::JNIEnv& env) { @@ -66,20 +74,28 @@ void OfflineTilePyramidRegionDefinition::registerNative(jni::JNIEnv& env) { // OfflineGeometryRegionDefinition // -jni::Local> OfflineGeometryRegionDefinition::New(jni::JNIEnv& env, const mbgl::OfflineGeometryRegionDefinition& definition) { +jni::Local> OfflineGeometryRegionDefinition::New( + jni::JNIEnv& env, const mbgl::OfflineGeometryRegionDefinition& definition) { static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::jdouble, jni::jdouble, jni::jfloat, jni::jboolean>(env); - - return javaClass.New(env, constructor, - jni::Make(env, definition.styleURL), - geojson::Geometry::New(env, definition.geometry), - definition.minZoom, - definition.maxZoom, - definition.pixelRatio, - jni::jboolean(definition.includeIdeographs)); + static auto constructor = javaClass.GetConstructor, + jni::jdouble, + jni::jdouble, + jni::jfloat, + jni::jboolean>(env); + + return javaClass.New(env, + constructor, + jni::Make(env, definition.styleURL), + geojson::Geometry::New(env, definition.geometry), + definition.minZoom, + definition.maxZoom, + definition.pixelRatio, + jni::jboolean(definition.includeIdeographs)); } -mbgl::OfflineGeometryRegionDefinition OfflineGeometryRegionDefinition::getDefinition(jni::JNIEnv& env, const jni::Object& jDefinition) { +mbgl::OfflineGeometryRegionDefinition OfflineGeometryRegionDefinition::getDefinition( + jni::JNIEnv& env, const jni::Object& jDefinition) { // Field references static auto& javaClass = jni::Class::Singleton(env); static auto styleURLF = javaClass.GetField(env, "styleURL"); @@ -89,14 +105,12 @@ mbgl::OfflineGeometryRegionDefinition OfflineGeometryRegionDefinition::getDefini static auto pixelRatioF = javaClass.GetField(env, "pixelRatio"); static auto includeIdeographsF = javaClass.GetField(env, "includeIdeographs"); - return mbgl::OfflineGeometryRegionDefinition( - jni::Make(env, jDefinition.Get(env, styleURLF)), - geojson::Geometry::convert(env, jDefinition.Get(env, geometryF)), - jDefinition.Get(env, minZoomF), - jDefinition.Get(env, maxZoomF), - jDefinition.Get(env, pixelRatioF), - jDefinition.Get(env, includeIdeographsF) - ); + return mbgl::OfflineGeometryRegionDefinition(jni::Make(env, jDefinition.Get(env, styleURLF)), + geojson::Geometry::convert(env, jDefinition.Get(env, geometryF)), + jDefinition.Get(env, minZoomF), + jDefinition.Get(env, maxZoomF), + jDefinition.Get(env, pixelRatioF), + jDefinition.Get(env, includeIdeographsF)); } void OfflineGeometryRegionDefinition::registerNative(jni::JNIEnv& env) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp index 827fac0a800..cfef3ab215d 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_definition.hpp @@ -12,17 +12,23 @@ class OfflineRegionDefinition { static void registerNative(jni::JNIEnv&); - static mbgl::OfflineRegionDefinition getDefinition(JNIEnv& env, const jni::Object& jDefinition); + static mbgl::OfflineRegionDefinition getDefinition(JNIEnv& env, + const jni::Object& jDefinition); }; class OfflineTilePyramidRegionDefinition { public: using SuperTag = OfflineRegionDefinition; - static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition"; }; + static constexpr auto Name() { + return "com/mapbox/mapboxsdk/offline/" + "OfflineTilePyramidRegionDefinition"; + }; - static jni::Local> New(jni::JNIEnv&, const mbgl::OfflineTilePyramidRegionDefinition&); + static jni::Local> New(jni::JNIEnv&, + const mbgl::OfflineTilePyramidRegionDefinition&); - static mbgl::OfflineTilePyramidRegionDefinition getDefinition(jni::JNIEnv&, const jni::Object&); + static mbgl::OfflineTilePyramidRegionDefinition getDefinition( + jni::JNIEnv&, const jni::Object&); static void registerNative(jni::JNIEnv&); }; @@ -32,9 +38,11 @@ class OfflineGeometryRegionDefinition { using SuperTag = OfflineRegionDefinition; static constexpr auto Name() { return "com/mapbox/mapboxsdk/offline/OfflineGeometryRegionDefinition"; }; - static jni::Local> New(jni::JNIEnv&, const mbgl::OfflineGeometryRegionDefinition&); + static jni::Local> New(jni::JNIEnv&, + const mbgl::OfflineGeometryRegionDefinition&); - static mbgl::OfflineGeometryRegionDefinition getDefinition(jni::JNIEnv&, const jni::Object&); + static mbgl::OfflineGeometryRegionDefinition getDefinition(jni::JNIEnv&, + const jni::Object&); static void registerNative(jni::JNIEnv&); }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp index 199bbafa6b9..40ce67838f6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_error.cpp @@ -4,10 +4,9 @@ namespace mbgl { namespace android { jni::Local> OfflineRegionError::New(jni::JNIEnv& env, mbgl::Response::Error error) { - // Handle the value of reason independently of the underlying int value std::string reason; - switch(error.reason) { + switch (error.reason) { case mbgl::Response::Error::Reason::Success: reason = "REASON_SUCCESS"; break; @@ -31,9 +30,8 @@ jni::Local> OfflineRegionError::New(jni::JNIEnv& static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, - jni::Make(env, reason), - jni::Make(env, error.message)); + return javaClass.New( + env, constructor, jni::Make(env, reason), jni::Make(env, error.message)); } void OfflineRegionError::registerNative(jni::JNIEnv& env) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp index 5dd9f20a7fa..bdba871f605 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/offline/offline_region_status.cpp @@ -3,11 +3,11 @@ namespace mbgl { namespace android { -jni::Local> OfflineRegionStatus::New(jni::JNIEnv& env, mbgl::OfflineRegionStatus status) { - +jni::Local> OfflineRegionStatus::New(jni::JNIEnv& env, + mbgl::OfflineRegionStatus status) { // Convert to jint jint downloadState; - switch(status.downloadState) { + switch (status.downloadState) { case mbgl::OfflineRegionDownloadState::Inactive: downloadState = 0; break; @@ -19,15 +19,15 @@ jni::Local> OfflineRegionStatus::New(jni::JNIEn // Create java object static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, - downloadState, - jlong(status.completedResourceCount), - jlong(status.completedResourceSize), - jlong(status.completedTileCount), - jlong(status.completedTileSize), - jlong(status.requiredResourceCount), - jboolean(status.requiredResourceCountIsPrecise) - ); + return javaClass.New(env, + constructor, + downloadState, + jlong(status.completedResourceCount), + jlong(status.completedResourceSize), + jlong(status.completedTileCount), + jlong(status.completedTileSize), + jlong(status.requiredResourceCount), + jboolean(status.requiredResourceCountIsPrecise)); } void OfflineRegionStatus::registerNative(jni::JNIEnv& env) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp index 03a532a43aa..8943ffc8c20 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.cpp @@ -9,10 +9,9 @@ namespace mbgl { namespace android { MapSnapshot::MapSnapshot(float pixelRatio_, MapSnapshot::PointForFn pointForFn_, MapSnapshot::LatLngForFn latLngForFn_) - : pixelRatio(pixelRatio_) - , pointForFn(std::move(pointForFn_)) - , latLngForFn(std::move(latLngForFn_)) { -} + : pixelRatio(pixelRatio_), + pointForFn(std::move(pointForFn_)), + latLngForFn(std::move(latLngForFn_)) {} MapSnapshot::~MapSnapshot() = default; @@ -28,20 +27,26 @@ jni::Local> MapSnapshot::latLngForPixel(jni::JNIEnv& env, jn // Static methods // jni::Local> MapSnapshot::New(JNIEnv& env, - PremultipliedImage&& image, - float pixelRatio, - std::vector attributions, - bool showLogo, - mbgl::MapSnapshotter::PointForFn pointForFn, - mbgl::MapSnapshotter::LatLngForFn latLngForFn) { + PremultipliedImage&& image, + float pixelRatio, + std::vector attributions, + bool showLogo, + mbgl::MapSnapshotter::PointForFn pointForFn, + mbgl::MapSnapshotter::LatLngForFn latLngForFn) { // Create the bitmap auto bitmap = Bitmap::CreateBitmap(env, std::move(image)); // Create the Mapsnapshot peers static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor, jni::Array, jni::jboolean>(env); + static auto constructor = + javaClass.GetConstructor, jni::Array, jni::jboolean>(env); auto nativePeer = std::make_unique(pixelRatio, pointForFn, latLngForFn); - return javaClass.New(env, constructor, reinterpret_cast(nativePeer.release()), bitmap, conversion::toArray(env, attributions), (jni::jboolean) showLogo); + return javaClass.New(env, + constructor, + reinterpret_cast(nativePeer.release()), + bitmap, + conversion::toArray(env, attributions), + (jni::jboolean)showLogo); } void MapSnapshot::registerNative(jni::JNIEnv& env) { @@ -51,14 +56,14 @@ void MapSnapshot::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, javaClass, - "nativePtr", - std::make_unique, - "initialize", - "finalize", - METHOD(&MapSnapshot::latLngForPixel, "latLngForPixel"), - METHOD(&MapSnapshot::pixelForLatLng, "pixelForLatLng") - ); + jni::RegisterNativePeer(env, + javaClass, + "nativePtr", + std::make_unique, + "initialize", + "finalize", + METHOD(&MapSnapshot::latLngForPixel, "latLngForPixel"), + METHOD(&MapSnapshot::pixelForLatLng, "pixelForLatLng")); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp index 6b82d02835b..271dc455c23 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp @@ -15,7 +15,6 @@ namespace android { class MapSnapshot { public: - using PointForFn = mbgl::MapSnapshotter::PointForFn; using LatLngForFn = mbgl::MapSnapshotter::LatLngForFn; @@ -24,14 +23,14 @@ class MapSnapshot { static void registerNative(jni::JNIEnv&); static jni::Local> New(JNIEnv& env, - PremultipliedImage&& image, - float pixelRatio, - std::vector attributions, - bool showLogo, - PointForFn pointForFn, - LatLngForFn latLngForFn); - - MapSnapshot(jni::JNIEnv&) {}; + PremultipliedImage&& image, + float pixelRatio, + std::vector attributions, + bool showLogo, + PointForFn pointForFn, + LatLngForFn latLngForFn); + + MapSnapshot(jni::JNIEnv&){}; MapSnapshot(float pixelRatio, PointForFn, LatLngForFn); ~MapSnapshot(); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp index 03547c293de..6201cd6ed27 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.cpp @@ -25,9 +25,8 @@ MapSnapshotter::MapSnapshotter(jni::JNIEnv& _env, const jni::Object& position, jni::jboolean _showLogo, const jni::String& _localIdeographFontFamily) - : javaPeer(_env, _obj) - , pixelRatio(_pixelRatio) { - + : javaPeer(_env, _obj), + pixelRatio(_pixelRatio) { // Get a reference to the JavaVM for callbacks if (_env.GetJavaVM(&vm) < 0) { _env.ExceptionDescribe(); @@ -37,7 +36,7 @@ MapSnapshotter::MapSnapshotter(jni::JNIEnv& _env, weakScheduler = mbgl::Scheduler::GetCurrent()->makeWeakPtr(); jFileSource = FileSource::getNativePeer(_env, _jFileSource); - auto size = mbgl::Size { static_cast(width), static_cast(height) }; + auto size = mbgl::Size{static_cast(width), static_cast(height)}; showLogo = _showLogo; @@ -48,7 +47,8 @@ MapSnapshotter::MapSnapshotter(jni::JNIEnv& _env, mbgl::android::FileSource::getSharedResourceOptions(_env, _jFileSource), mbgl::android::FileSource::getSharedClientOptions(_env, _jFileSource), *this, - _localIdeographFontFamily ? jni::Make(_env, _localIdeographFontFamily) : std::optional{}); + _localIdeographFontFamily ? jni::Make(_env, _localIdeographFontFamily) + : std::optional{}); if (position) { snapshotter->setCameraOptions(CameraPosition::getCameraOptions(_env, position, pixelRatio)); @@ -91,17 +91,18 @@ void MapSnapshotter::start(JNIEnv& env) { if (err) { // error handler callback - static auto onSnapshotFailed = javaClass.GetMethod(*_env, "onSnapshotFailed"); + static auto onSnapshotFailed = javaClass.GetMethod(*_env, "onSnapshotFailed"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onSnapshotFailed, jni::Make(*_env, util::toString(err))); } } else { // Create the wrapper - auto mapSnapshot = android::MapSnapshot::New(*_env, std::move(image), pixelRatio, attributions, showLogo, pointForFn, latLngForFn); + auto mapSnapshot = android::MapSnapshot::New( + *_env, std::move(image), pixelRatio, attributions, showLogo, pointForFn, latLngForFn); // invoke callback - static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); + static auto onSnapshotReady = javaClass.GetMethod)>(*_env, "onSnapshotReady"); auto weakReference = javaPeer.get(*_env); if (weakReference) { weakReference.Call(*_env, onSnapshotReady, mapSnapshot); @@ -127,7 +128,7 @@ void MapSnapshotter::setStyleJson(JNIEnv& env, const jni::String& styleJSON) { } void MapSnapshotter::setSize(JNIEnv&, jni::jint width, jni::jint height) { - auto size = mbgl::Size { static_cast(width), static_cast(height) }; + auto size = mbgl::Size{static_cast(width), static_cast(height)}; snapshotter->setSize(size); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp index 4d0186e7f8b..557a9ae9524 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshotter.hpp @@ -19,7 +19,6 @@ namespace android { class MapSnapshotter final : public mbgl::MapSnapshotterObserver { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/snapshotter/MapSnapshotter"; }; static void registerNative(jni::JNIEnv&); @@ -69,13 +68,13 @@ class MapSnapshotter final : public mbgl::MapSnapshotterObserver { private: MBGL_STORE_THREAD(tid); - JavaVM *vm = nullptr; + JavaVM* vm = nullptr; jni::WeakReference, jni::EnvAttachingDeleter> javaPeer; float pixelRatio; bool showLogo; - FileSource *jFileSource; + FileSource* jFileSource; void activateFilesource(JNIEnv&); void deactivateFilesource(JNIEnv&); bool activatedFilesource = false; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp index 8b33a9f8efd..4ecf05722ec 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/android_conversion.hpp @@ -17,25 +17,18 @@ namespace conversion { template <> class ConversionTraits { public: - static bool isUndefined(const mbgl::android::Value& value) { - return value.isNull(); - } + static bool isUndefined(const mbgl::android::Value& value) { return value.isNull(); } - static bool isArray(const mbgl::android::Value& value) { - return value.isArray(); - } + static bool isArray(const mbgl::android::Value& value) { return value.isArray(); } - static bool isObject(const mbgl::android::Value& value) { - return value.isObject(); - } + static bool isObject(const mbgl::android::Value& value) { return value.isObject(); } static std::size_t arrayLength(const mbgl::android::Value& value) { - return value.getLength();; + return value.getLength(); + ; } - static mbgl::android::Value arrayMember(const mbgl::android::Value& value, std::size_t i) { - return value.get(i); - } + static mbgl::android::Value arrayMember(const mbgl::android::Value& value, std::size_t i) { return value.get(i); } static std::optional objectMember(const mbgl::android::Value& value, const char* key) { mbgl::android::Value member = value.get(key); @@ -51,7 +44,7 @@ class ConversionTraits { assert(value.isObject()); mbgl::android::Value keys = value.keyArray(); std::size_t length = arrayLength(keys); - for(std::size_t i = 0; i < length; ++i){ + for (std::size_t i = 0; i < length; ++i) { const auto k = keys.get(i).toString(); auto v = value.get(k.c_str()); std::optional result = fn(k, std::move(v)); @@ -99,19 +92,19 @@ class ConversionTraits { if (value.isNull()) { return {}; } else if (value.isBool()) { - return { value.toBool() }; + return {value.toBool()}; } else if (value.isString()) { - return { value.toString() }; + return {value.toString()}; } else if (value.isNumber()) { - return { value.toDouble() }; + return {value.toDouble()}; } else { return {}; } } - static std::optional toGeoJSON(const mbgl::android::Value &value, Error &error) { + static std::optional toGeoJSON(const mbgl::android::Value& value, Error& error) { if (value.isNull()) { - error = { "no json data found" }; + error = {"no json data found"}; return {}; } @@ -138,8 +131,8 @@ class ConversionTraits { } }; -template -std::optional convert(mbgl::android::Value&& value, Error& error, Args&&...args) { +template +std::optional convert(mbgl::android::Value&& value, Error& error, Args&&... args) { return convert(Convertible(std::move(value)), error, std::forward(args)...); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp index 680c72af971..6d87caac571 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/filter.cpp @@ -11,12 +11,12 @@ namespace conversion { std::optional toFilter(jni::JNIEnv& env, const jni::Array>& jfilter) { std::optional filter; if (jfilter) { - mbgl::style::conversion::Error error; - auto converted = mbgl::style::conversion::convert(Value(env, jfilter), error); - if (!converted) { - mbgl::Log::Error(mbgl::Event::JNI, "Error converting filter: " + error.message); - } - filter = std::move(*converted); + mbgl::style::conversion::Error error; + auto converted = mbgl::style::conversion::convert(Value(env, jfilter), error); + if (!converted) { + mbgl::Log::Error(mbgl::Event::JNI, "Error converting filter: " + error.message); + } + filter = std::move(*converted); } return filter; } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp index e3c334afd2f..f315a09ba88 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.cpp @@ -4,21 +4,24 @@ namespace mbgl { namespace android { namespace conversion { -Result>> Converter>, mbgl::style::Position>::operator()(jni::JNIEnv &env, const mbgl::style::Position &value) const { +Result>> +Converter>, mbgl::style::Position>::operator()( + jni::JNIEnv &env, const mbgl::style::Position &value) const { std::array cartPosition = value.getSpherical(); return Position::fromPosition(env, cartPosition[0], cartPosition[1], cartPosition[2]); } -Result Converter>::operator()(jni::JNIEnv &env, const jni::Object &value) const { +Result Converter>::operator()( + jni::JNIEnv &env, const jni::Object &value) const { float radialCoordinate = Position::getRadialCoordinate(env, value); float azimuthalAngle = Position::getAzimuthalAngle(env, value); float polarAngle = Position::getPolarAngle(env, value); - std::array cartPosition {{radialCoordinate, azimuthalAngle, polarAngle}}; + std::array cartPosition{{radialCoordinate, azimuthalAngle, polarAngle}}; mbgl::style::Position position{}; position.set(cartPosition); return position; } -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp index 90409d527d4..66afb5451f6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/position.hpp @@ -20,6 +20,6 @@ struct Converter> { Result operator()(jni::JNIEnv &env, const jni::Object &value) const; }; -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp index 4e26b11f96b..fbe4db2df18 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_expression.hpp @@ -13,7 +13,8 @@ namespace conversion { template struct Converter>, mbgl::style::PropertyExpression> { - Result>> operator()(jni::JNIEnv& env, const mbgl::style::PropertyExpression& value) const { + Result>> operator()( + jni::JNIEnv& env, const mbgl::style::PropertyExpression& value) const { return gson::JsonElement::New(env, value.getExpression().serialize()); } }; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp index 317705a2865..5d527de33af 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/property_value.hpp @@ -17,7 +17,8 @@ namespace conversion { template class PropertyValueEvaluator { public: - PropertyValueEvaluator(jni::JNIEnv& _env) : env(_env) {} + PropertyValueEvaluator(jni::JNIEnv& _env) + : env(_env) {} jni::Local> operator()(const mbgl::style::Undefined) const { return jni::Local>(env, nullptr); @@ -51,7 +52,8 @@ struct Converter>, mbgl::style::PropertyValue> { */ template <> struct Converter>, mbgl::style::ColorRampPropertyValue> { - Result>> operator()(jni::JNIEnv& env, const mbgl::style::ColorRampPropertyValue& value) const { + Result>> operator()(jni::JNIEnv& env, + const mbgl::style::ColorRampPropertyValue& value) const { PropertyValueEvaluator evaluator(env); return std::move(*convert>>(env, value.evaluate(evaluator))); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp index 75d9b4cc0d9..b37719c5894 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.cpp @@ -4,14 +4,16 @@ namespace mbgl { namespace android { namespace conversion { -Result>> Converter>, mbgl::style::TransitionOptions>::operator()(jni::JNIEnv& env, const mbgl::style::TransitionOptions& value) const { - return TransitionOptions::fromTransitionOptions(env, +Result>> +Converter>, mbgl::style::TransitionOptions>::operator()( + jni::JNIEnv& env, const mbgl::style::TransitionOptions& value) const { + return TransitionOptions::fromTransitionOptions( + env, std::chrono::duration_cast(value.duration.value_or(mbgl::Duration::zero())).count(), std::chrono::duration_cast(value.delay.value_or(mbgl::Duration::zero())).count(), - (jboolean) value.enablePlacementTransitions - ); + (jboolean)value.enablePlacementTransitions); } -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp index 06c042922ed..39c0b7b87bf 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/transition_options.hpp @@ -11,11 +11,12 @@ namespace mbgl { namespace android { namespace conversion { -template<> +template <> struct Converter>, mbgl::style::TransitionOptions> { - Result>> operator()(jni::JNIEnv&, const mbgl::style::TransitionOptions&) const; + Result>> operator()(jni::JNIEnv&, + const mbgl::style::TransitionOptions&) const; }; -} -} -} +} // namespace conversion +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp index 238c3ce070c..be6b665241b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.cpp @@ -20,11 +20,11 @@ variant convertURLOrTileset(mbgl::android::Value&& value) if (!tileset) { throw std::logic_error(error.message); } - return { *tileset }; + return {*tileset}; } else { - return { *toString(convertible) }; + return {*toString(convertible)}; } } -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp index f42a9b9a2a9..63c617eb869 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/conversion/url_or_tileset.hpp @@ -13,4 +13,4 @@ namespace android { variant convertURLOrTileset(mbgl::android::Value&& value); } -} +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp index 69c3454e23a..21c49dd2c1f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.cpp @@ -24,7 +24,7 @@ jni::Local> Formatted::New(jni::JNIEnv& env, const style: if (section.fontScale) { double fontScale = section.fontScale.value(); - static auto method = formattedSectionClass.GetMethod(env, "setFontScale"); + static auto method = formattedSectionClass.GetMethod(env, "setFontScale"); formattedSection.Call(env, method, jni::Box(env, fontScale)); } @@ -33,14 +33,14 @@ jni::Local> Formatted::New(jni::JNIEnv& env, const style: for (std::size_t j = 0; j < section.fontStack.value().size(); j++) { fontStack.Set(env, j, jni::Make(env, section.fontStack.value().at(j))); } - static auto method = formattedSectionClass.GetMethod)>(env, "setFontStack"); + static auto method = formattedSectionClass.GetMethod)>(env, "setFontStack"); formattedSection.Call(env, method, fontStack); } if (section.textColor) { using namespace mbgl::android::conversion; auto textColor = std::move(*convert>>(env, *section.textColor)); - static auto method = formattedSectionClass.GetMethod)>(env, "setTextColor"); + static auto method = formattedSectionClass.GetMethod)>(env, "setTextColor"); formattedSection.Call(env, method, textColor); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp index ca91f6562c9..a7a0f72196f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/formatted.hpp @@ -6,18 +6,17 @@ #include namespace mbgl { - namespace android { +namespace android { - using SuperTag = jni::ObjectTag; - class Formatted : private mbgl::util::noncopyable { - public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/types/Formatted"; }; +using SuperTag = jni::ObjectTag; +class Formatted : private mbgl::util::noncopyable { +public: + static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/types/Formatted"; }; - static jni::Local> - New(jni::JNIEnv&, const style::expression::Formatted &value); + static jni::Local> New(jni::JNIEnv &, const style::expression::Formatted &value); - static void registerNative(jni::JNIEnv &); - }; + static void registerNative(jni::JNIEnv &); +}; - } // namespace android +} // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp index 99fb75cc06e..5269cbb4b72 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.cpp @@ -12,136 +12,136 @@ namespace mbgl { namespace android { - inline mbgl::style::BackgroundLayer& toBackgroundLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - BackgroundLayer::BackgroundLayer(jni::JNIEnv& env, jni::String& layerId) - : Layer(std::make_unique(jni::Make(env, layerId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - BackgroundLayer::BackgroundLayer(mbgl::style::BackgroundLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - BackgroundLayer::BackgroundLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - BackgroundLayer::~BackgroundLayer() = default; - - // Property getters - - jni::Local> BackgroundLayer::getBackgroundColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundColor())); - } - - jni::Local> BackgroundLayer::getBackgroundColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundColorTransition(); - return std::move(*convert>>(env, options)); - } - - void BackgroundLayer::setBackgroundColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toBackgroundLayer(layer).setBackgroundColorTransition(options); - } - - jni::Local> BackgroundLayer::getBackgroundPattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundPattern())); - } - - jni::Local> BackgroundLayer::getBackgroundPatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundPatternTransition(); - return std::move(*convert>>(env, options)); - } - - void BackgroundLayer::setBackgroundPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toBackgroundLayer(layer).setBackgroundPatternTransition(options); - } - - jni::Local> BackgroundLayer::getBackgroundOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundOpacity())); - } - - jni::Local> BackgroundLayer::getBackgroundOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void BackgroundLayer::setBackgroundOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toBackgroundLayer(layer).setBackgroundOpacityTransition(options); - } - - - // BackgroundJavaLayerPeerFactory - - BackgroundJavaLayerPeerFactory::~BackgroundJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new BackgroundLayer(toBackgroundLayer(layer))); - } - - jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new BackgroundLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void BackgroundJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&BackgroundLayer::getBackgroundColorTransition, "nativeGetBackgroundColorTransition"), - METHOD(&BackgroundLayer::setBackgroundColorTransition, "nativeSetBackgroundColorTransition"), - METHOD(&BackgroundLayer::getBackgroundColor, "nativeGetBackgroundColor"), - METHOD(&BackgroundLayer::getBackgroundPatternTransition, "nativeGetBackgroundPatternTransition"), - METHOD(&BackgroundLayer::setBackgroundPatternTransition, "nativeSetBackgroundPatternTransition"), - METHOD(&BackgroundLayer::getBackgroundPattern, "nativeGetBackgroundPattern"), - METHOD(&BackgroundLayer::getBackgroundOpacityTransition, "nativeGetBackgroundOpacityTransition"), - METHOD(&BackgroundLayer::setBackgroundOpacityTransition, "nativeSetBackgroundOpacityTransition"), - METHOD(&BackgroundLayer::getBackgroundOpacity, "nativeGetBackgroundOpacity")); - } +inline mbgl::style::BackgroundLayer& toBackgroundLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +BackgroundLayer::BackgroundLayer(jni::JNIEnv& env, jni::String& layerId) + : Layer(std::make_unique(jni::Make(env, layerId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +BackgroundLayer::BackgroundLayer(mbgl::style::BackgroundLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +BackgroundLayer::BackgroundLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +BackgroundLayer::~BackgroundLayer() = default; + +// Property getters + +jni::Local> BackgroundLayer::getBackgroundColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundColor())); +} + +jni::Local> BackgroundLayer::getBackgroundColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundColorTransition(); + return std::move(*convert>>(env, options)); +} + +void BackgroundLayer::setBackgroundColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toBackgroundLayer(layer).setBackgroundColorTransition(options); +} + +jni::Local> BackgroundLayer::getBackgroundPattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundPattern())); +} + +jni::Local> BackgroundLayer::getBackgroundPatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundPatternTransition(); + return std::move(*convert>>(env, options)); +} + +void BackgroundLayer::setBackgroundPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toBackgroundLayer(layer).setBackgroundPatternTransition(options); +} + +jni::Local> BackgroundLayer::getBackgroundOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toBackgroundLayer(layer).getBackgroundOpacity())); +} + +jni::Local> BackgroundLayer::getBackgroundOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toBackgroundLayer(layer).getBackgroundOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void BackgroundLayer::setBackgroundOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toBackgroundLayer(layer).setBackgroundOpacityTransition(options); +} + +// BackgroundJavaLayerPeerFactory + +BackgroundJavaLayerPeerFactory::~BackgroundJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new BackgroundLayer(toBackgroundLayer(layer))); +} + +jni::Local> BackgroundJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new BackgroundLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void BackgroundJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&BackgroundLayer::getBackgroundColorTransition, "nativeGetBackgroundColorTransition"), + METHOD(&BackgroundLayer::setBackgroundColorTransition, "nativeSetBackgroundColorTransition"), + METHOD(&BackgroundLayer::getBackgroundColor, "nativeGetBackgroundColor"), + METHOD(&BackgroundLayer::getBackgroundPatternTransition, "nativeGetBackgroundPatternTransition"), + METHOD(&BackgroundLayer::setBackgroundPatternTransition, "nativeSetBackgroundPatternTransition"), + METHOD(&BackgroundLayer::getBackgroundPattern, "nativeGetBackgroundPattern"), + METHOD(&BackgroundLayer::getBackgroundOpacityTransition, "nativeGetBackgroundOpacityTransition"), + METHOD(&BackgroundLayer::setBackgroundOpacityTransition, "nativeSetBackgroundOpacityTransition"), + METHOD(&BackgroundLayer::getBackgroundOpacity, "nativeGetBackgroundOpacity")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp index 8958c929e6f..94cf41b4d09 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/background_layer.hpp @@ -40,7 +40,7 @@ class BackgroundLayer : public Layer { }; // class BackgroundLayer -class BackgroundJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::BackgroundLayerFactory { +class BackgroundJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::BackgroundLayerFactory { public: ~BackgroundJavaLayerPeerFactory() override; @@ -52,7 +52,7 @@ class BackgroundJavaLayerPeerFactory final : public JavaLayerPeerFactory, publi LayerFactory* getLayerFactory() final { return this; } -}; // class BackgroundJavaLayerPeerFactory +}; // class BackgroundJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp index f51e2dae99b..d7acc91ec22 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.cpp @@ -12,265 +12,266 @@ namespace mbgl { namespace android { - inline mbgl::style::CircleLayer& toCircleLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - CircleLayer::CircleLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - CircleLayer::CircleLayer(mbgl::style::CircleLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - CircleLayer::CircleLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - CircleLayer::~CircleLayer() = default; - - // Property getters - - jni::Local> CircleLayer::getCircleSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleSortKey())); - } - - jni::Local> CircleLayer::getCircleRadius(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleRadius())); - } - - jni::Local> CircleLayer::getCircleRadiusTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleRadiusTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleRadiusTransition(options); - } - - jni::Local> CircleLayer::getCircleColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleColor())); - } - - jni::Local> CircleLayer::getCircleColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleColorTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleColorTransition(options); - } - - jni::Local> CircleLayer::getCircleBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleBlur())); - } - - jni::Local> CircleLayer::getCircleBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleBlurTransition(options); - } - - jni::Local> CircleLayer::getCircleOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleOpacity())); - } - - jni::Local> CircleLayer::getCircleOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleOpacityTransition(options); - } - - jni::Local> CircleLayer::getCircleTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslate())); - } - - jni::Local> CircleLayer::getCircleTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleTranslateTransition(options); - } - - jni::Local> CircleLayer::getCircleTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslateAnchor())); - } - - jni::Local> CircleLayer::getCirclePitchScale(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchScale())); - } - - jni::Local> CircleLayer::getCirclePitchAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchAlignment())); - } - - jni::Local> CircleLayer::getCircleStrokeWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeWidth())); - } - - jni::Local> CircleLayer::getCircleStrokeWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleStrokeWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleStrokeWidthTransition(options); - } - - jni::Local> CircleLayer::getCircleStrokeColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeColor())); - } - - jni::Local> CircleLayer::getCircleStrokeColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeColorTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleStrokeColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleStrokeColorTransition(options); - } - - jni::Local> CircleLayer::getCircleStrokeOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeOpacity())); - } - - jni::Local> CircleLayer::getCircleStrokeOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void CircleLayer::setCircleStrokeOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toCircleLayer(layer).setCircleStrokeOpacityTransition(options); - } - - - // CircleJavaLayerPeerFactory - - CircleJavaLayerPeerFactory::~CircleJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new CircleLayer(toCircleLayer(layer))); - } - - jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new CircleLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void CircleJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&CircleLayer::getCircleSortKey, "nativeGetCircleSortKey"), - METHOD(&CircleLayer::getCircleRadiusTransition, "nativeGetCircleRadiusTransition"), - METHOD(&CircleLayer::setCircleRadiusTransition, "nativeSetCircleRadiusTransition"), - METHOD(&CircleLayer::getCircleRadius, "nativeGetCircleRadius"), - METHOD(&CircleLayer::getCircleColorTransition, "nativeGetCircleColorTransition"), - METHOD(&CircleLayer::setCircleColorTransition, "nativeSetCircleColorTransition"), - METHOD(&CircleLayer::getCircleColor, "nativeGetCircleColor"), - METHOD(&CircleLayer::getCircleBlurTransition, "nativeGetCircleBlurTransition"), - METHOD(&CircleLayer::setCircleBlurTransition, "nativeSetCircleBlurTransition"), - METHOD(&CircleLayer::getCircleBlur, "nativeGetCircleBlur"), - METHOD(&CircleLayer::getCircleOpacityTransition, "nativeGetCircleOpacityTransition"), - METHOD(&CircleLayer::setCircleOpacityTransition, "nativeSetCircleOpacityTransition"), - METHOD(&CircleLayer::getCircleOpacity, "nativeGetCircleOpacity"), - METHOD(&CircleLayer::getCircleTranslateTransition, "nativeGetCircleTranslateTransition"), - METHOD(&CircleLayer::setCircleTranslateTransition, "nativeSetCircleTranslateTransition"), - METHOD(&CircleLayer::getCircleTranslate, "nativeGetCircleTranslate"), - METHOD(&CircleLayer::getCircleTranslateAnchor, "nativeGetCircleTranslateAnchor"), - METHOD(&CircleLayer::getCirclePitchScale, "nativeGetCirclePitchScale"), - METHOD(&CircleLayer::getCirclePitchAlignment, "nativeGetCirclePitchAlignment"), - METHOD(&CircleLayer::getCircleStrokeWidthTransition, "nativeGetCircleStrokeWidthTransition"), - METHOD(&CircleLayer::setCircleStrokeWidthTransition, "nativeSetCircleStrokeWidthTransition"), - METHOD(&CircleLayer::getCircleStrokeWidth, "nativeGetCircleStrokeWidth"), - METHOD(&CircleLayer::getCircleStrokeColorTransition, "nativeGetCircleStrokeColorTransition"), - METHOD(&CircleLayer::setCircleStrokeColorTransition, "nativeSetCircleStrokeColorTransition"), - METHOD(&CircleLayer::getCircleStrokeColor, "nativeGetCircleStrokeColor"), - METHOD(&CircleLayer::getCircleStrokeOpacityTransition, "nativeGetCircleStrokeOpacityTransition"), - METHOD(&CircleLayer::setCircleStrokeOpacityTransition, "nativeSetCircleStrokeOpacityTransition"), - METHOD(&CircleLayer::getCircleStrokeOpacity, "nativeGetCircleStrokeOpacity")); - } +inline mbgl::style::CircleLayer& toCircleLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +CircleLayer::CircleLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +CircleLayer::CircleLayer(mbgl::style::CircleLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +CircleLayer::CircleLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +CircleLayer::~CircleLayer() = default; + +// Property getters + +jni::Local> CircleLayer::getCircleSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleSortKey())); +} + +jni::Local> CircleLayer::getCircleRadius(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleRadius())); +} + +jni::Local> CircleLayer::getCircleRadiusTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleRadiusTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleRadiusTransition(options); +} + +jni::Local> CircleLayer::getCircleColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleColor())); +} + +jni::Local> CircleLayer::getCircleColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleColorTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleColorTransition(options); +} + +jni::Local> CircleLayer::getCircleBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleBlur())); +} + +jni::Local> CircleLayer::getCircleBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleBlurTransition(options); +} + +jni::Local> CircleLayer::getCircleOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleOpacity())); +} + +jni::Local> CircleLayer::getCircleOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleOpacityTransition(options); +} + +jni::Local> CircleLayer::getCircleTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslate())); +} + +jni::Local> CircleLayer::getCircleTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleTranslateTransition(options); +} + +jni::Local> CircleLayer::getCircleTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleTranslateAnchor())); +} + +jni::Local> CircleLayer::getCirclePitchScale(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchScale())); +} + +jni::Local> CircleLayer::getCirclePitchAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCirclePitchAlignment())); +} + +jni::Local> CircleLayer::getCircleStrokeWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeWidth())); +} + +jni::Local> CircleLayer::getCircleStrokeWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleStrokeWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleStrokeWidthTransition(options); +} + +jni::Local> CircleLayer::getCircleStrokeColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeColor())); +} + +jni::Local> CircleLayer::getCircleStrokeColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeColorTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleStrokeColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleStrokeColorTransition(options); +} + +jni::Local> CircleLayer::getCircleStrokeOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toCircleLayer(layer).getCircleStrokeOpacity())); +} + +jni::Local> CircleLayer::getCircleStrokeOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toCircleLayer(layer).getCircleStrokeOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void CircleLayer::setCircleStrokeOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toCircleLayer(layer).setCircleStrokeOpacityTransition(options); +} + +// CircleJavaLayerPeerFactory + +CircleJavaLayerPeerFactory::~CircleJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new CircleLayer(toCircleLayer(layer))); +} + +jni::Local> CircleJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new CircleLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void CircleJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&CircleLayer::getCircleSortKey, "nativeGetCircleSortKey"), + METHOD(&CircleLayer::getCircleRadiusTransition, "nativeGetCircleRadiusTransition"), + METHOD(&CircleLayer::setCircleRadiusTransition, "nativeSetCircleRadiusTransition"), + METHOD(&CircleLayer::getCircleRadius, "nativeGetCircleRadius"), + METHOD(&CircleLayer::getCircleColorTransition, "nativeGetCircleColorTransition"), + METHOD(&CircleLayer::setCircleColorTransition, "nativeSetCircleColorTransition"), + METHOD(&CircleLayer::getCircleColor, "nativeGetCircleColor"), + METHOD(&CircleLayer::getCircleBlurTransition, "nativeGetCircleBlurTransition"), + METHOD(&CircleLayer::setCircleBlurTransition, "nativeSetCircleBlurTransition"), + METHOD(&CircleLayer::getCircleBlur, "nativeGetCircleBlur"), + METHOD(&CircleLayer::getCircleOpacityTransition, "nativeGetCircleOpacityTransition"), + METHOD(&CircleLayer::setCircleOpacityTransition, "nativeSetCircleOpacityTransition"), + METHOD(&CircleLayer::getCircleOpacity, "nativeGetCircleOpacity"), + METHOD(&CircleLayer::getCircleTranslateTransition, "nativeGetCircleTranslateTransition"), + METHOD(&CircleLayer::setCircleTranslateTransition, "nativeSetCircleTranslateTransition"), + METHOD(&CircleLayer::getCircleTranslate, "nativeGetCircleTranslate"), + METHOD(&CircleLayer::getCircleTranslateAnchor, "nativeGetCircleTranslateAnchor"), + METHOD(&CircleLayer::getCirclePitchScale, "nativeGetCirclePitchScale"), + METHOD(&CircleLayer::getCirclePitchAlignment, "nativeGetCirclePitchAlignment"), + METHOD(&CircleLayer::getCircleStrokeWidthTransition, "nativeGetCircleStrokeWidthTransition"), + METHOD(&CircleLayer::setCircleStrokeWidthTransition, "nativeSetCircleStrokeWidthTransition"), + METHOD(&CircleLayer::getCircleStrokeWidth, "nativeGetCircleStrokeWidth"), + METHOD(&CircleLayer::getCircleStrokeColorTransition, "nativeGetCircleStrokeColorTransition"), + METHOD(&CircleLayer::setCircleStrokeColorTransition, "nativeSetCircleStrokeColorTransition"), + METHOD(&CircleLayer::getCircleStrokeColor, "nativeGetCircleStrokeColor"), + METHOD(&CircleLayer::getCircleStrokeOpacityTransition, "nativeGetCircleStrokeOpacityTransition"), + METHOD(&CircleLayer::setCircleStrokeOpacityTransition, "nativeSetCircleStrokeOpacityTransition"), + METHOD(&CircleLayer::getCircleStrokeOpacity, "nativeGetCircleStrokeOpacity")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp index ee95656d616..4a54bc39aa9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/circle_layer.hpp @@ -68,7 +68,7 @@ class CircleLayer : public Layer { }; // class CircleLayer -class CircleJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CircleLayerFactory { +class CircleJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CircleLayerFactory { public: ~CircleJavaLayerPeerFactory() override; @@ -80,7 +80,7 @@ class CircleJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class CircleJavaLayerPeerFactory +}; // class CircleJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp index 5a8b239a8d5..12c63fb1c62 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.cpp @@ -7,55 +7,55 @@ namespace mbgl { namespace android { - CustomLayer::CustomLayer(jni::JNIEnv& env, const jni::String& layerId, jni::jlong host) - : Layer(std::make_unique( - jni::Make(env, layerId), - std::unique_ptr(reinterpret_cast(host))) - ) { - } - - CustomLayer::CustomLayer(mbgl::style::CustomLayer& coreLayer) : Layer(coreLayer) {} - - CustomLayer::CustomLayer(std::unique_ptr coreLayer) : Layer(std::move(coreLayer)) {} - - CustomLayer::~CustomLayer() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } - - CustomJavaLayerPeerFactory::~CustomJavaLayerPeerFactory() = default; - - jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, - mbgl::style::Layer& layer) { - return createJavaPeer(env, new CustomLayer(static_cast(layer))); - } - - jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer( - jni::JNIEnv& env, std::unique_ptr layer) { - return createJavaPeer(env, - new CustomLayer(std::unique_ptr( - static_cast(layer.release())))); - } - - void CustomJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer(env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize"); - } +CustomLayer::CustomLayer(jni::JNIEnv& env, const jni::String& layerId, jni::jlong host) + : Layer(std::make_unique( + jni::Make(env, layerId), + std::unique_ptr(reinterpret_cast(host)))) {} + +CustomLayer::CustomLayer(mbgl::style::CustomLayer& coreLayer) + : Layer(coreLayer) {} + +CustomLayer::CustomLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +CustomLayer::~CustomLayer() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +CustomJavaLayerPeerFactory::~CustomJavaLayerPeerFactory() = default; + +jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + return createJavaPeer(env, new CustomLayer(static_cast(layer))); +} + +jni::Local> CustomJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + return createJavaPeer(env, + new CustomLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void CustomJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer(env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize"); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp index 3856ea73ae8..88c1cbc2c28 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/custom_layer.hpp @@ -23,7 +23,7 @@ class CustomLayer : public Layer { jni::Local> createJavaPeer(jni::JNIEnv&); }; // class CustomLayer -class CustomJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CustomLayerFactory { +class CustomJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::CustomLayerFactory { public: ~CustomJavaLayerPeerFactory() override; @@ -35,7 +35,7 @@ class CustomJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class CustomJavaLayerPeerFactory +}; // class CustomJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp index 0d1d107b120..5a427b9094e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.cpp @@ -12,211 +12,214 @@ namespace mbgl { namespace android { - inline mbgl::style::FillExtrusionLayer& toFillExtrusionLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - FillExtrusionLayer::FillExtrusionLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - FillExtrusionLayer::FillExtrusionLayer(mbgl::style::FillExtrusionLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - FillExtrusionLayer::FillExtrusionLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - FillExtrusionLayer::~FillExtrusionLayer() = default; - - // Property getters - - jni::Local> FillExtrusionLayer::getFillExtrusionOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionOpacity())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionOpacityTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionColor())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionColorTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionColorTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslate())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionTranslateTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslateAnchor())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionPattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionPattern())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionPatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionPatternTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionPatternTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionHeight(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionHeight())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionHeightTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionHeightTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionHeightTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionHeightTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionBase(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionBase())); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionBaseTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionBaseTransition(); - return std::move(*convert>>(env, options)); - } - - void FillExtrusionLayer::setFillExtrusionBaseTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillExtrusionLayer(layer).setFillExtrusionBaseTransition(options); - } - - jni::Local> FillExtrusionLayer::getFillExtrusionVerticalGradient(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionVerticalGradient())); - } - - - // FillExtrusionJavaLayerPeerFactory - - FillExtrusionJavaLayerPeerFactory::~FillExtrusionJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillExtrusionLayer(toFillExtrusionLayer(layer))); - } - - jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillExtrusionLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void FillExtrusionJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&FillExtrusionLayer::getFillExtrusionOpacityTransition, "nativeGetFillExtrusionOpacityTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionOpacityTransition, "nativeSetFillExtrusionOpacityTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionOpacity, "nativeGetFillExtrusionOpacity"), - METHOD(&FillExtrusionLayer::getFillExtrusionColorTransition, "nativeGetFillExtrusionColorTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionColorTransition, "nativeSetFillExtrusionColorTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionColor, "nativeGetFillExtrusionColor"), - METHOD(&FillExtrusionLayer::getFillExtrusionTranslateTransition, "nativeGetFillExtrusionTranslateTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionTranslateTransition, "nativeSetFillExtrusionTranslateTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionTranslate, "nativeGetFillExtrusionTranslate"), - METHOD(&FillExtrusionLayer::getFillExtrusionTranslateAnchor, "nativeGetFillExtrusionTranslateAnchor"), - METHOD(&FillExtrusionLayer::getFillExtrusionPatternTransition, "nativeGetFillExtrusionPatternTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionPatternTransition, "nativeSetFillExtrusionPatternTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionPattern, "nativeGetFillExtrusionPattern"), - METHOD(&FillExtrusionLayer::getFillExtrusionHeightTransition, "nativeGetFillExtrusionHeightTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionHeightTransition, "nativeSetFillExtrusionHeightTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionHeight, "nativeGetFillExtrusionHeight"), - METHOD(&FillExtrusionLayer::getFillExtrusionBaseTransition, "nativeGetFillExtrusionBaseTransition"), - METHOD(&FillExtrusionLayer::setFillExtrusionBaseTransition, "nativeSetFillExtrusionBaseTransition"), - METHOD(&FillExtrusionLayer::getFillExtrusionBase, "nativeGetFillExtrusionBase"), - METHOD(&FillExtrusionLayer::getFillExtrusionVerticalGradient, "nativeGetFillExtrusionVerticalGradient")); - } +inline mbgl::style::FillExtrusionLayer& toFillExtrusionLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +FillExtrusionLayer::FillExtrusionLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +FillExtrusionLayer::FillExtrusionLayer(mbgl::style::FillExtrusionLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +FillExtrusionLayer::FillExtrusionLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +FillExtrusionLayer::~FillExtrusionLayer() = default; + +// Property getters + +jni::Local> FillExtrusionLayer::getFillExtrusionOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionOpacity())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionOpacityTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionColor())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionColorTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionColorTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslate())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionTranslateTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionTranslateAnchor())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionPattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionPattern())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionPatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionPatternTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionPatternTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionHeight(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionHeight())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionHeightTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionHeightTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionHeightTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionHeightTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionBase(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionBase())); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionBaseTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillExtrusionLayer(layer).getFillExtrusionBaseTransition(); + return std::move(*convert>>(env, options)); +} + +void FillExtrusionLayer::setFillExtrusionBaseTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillExtrusionLayer(layer).setFillExtrusionBaseTransition(options); +} + +jni::Local> FillExtrusionLayer::getFillExtrusionVerticalGradient(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toFillExtrusionLayer(layer).getFillExtrusionVerticalGradient())); +} + +// FillExtrusionJavaLayerPeerFactory + +FillExtrusionJavaLayerPeerFactory::~FillExtrusionJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new FillExtrusionLayer(toFillExtrusionLayer(layer))); +} + +jni::Local> FillExtrusionJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new FillExtrusionLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void FillExtrusionJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&FillExtrusionLayer::getFillExtrusionOpacityTransition, "nativeGetFillExtrusionOpacityTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionOpacityTransition, "nativeSetFillExtrusionOpacityTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionOpacity, "nativeGetFillExtrusionOpacity"), + METHOD(&FillExtrusionLayer::getFillExtrusionColorTransition, "nativeGetFillExtrusionColorTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionColorTransition, "nativeSetFillExtrusionColorTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionColor, "nativeGetFillExtrusionColor"), + METHOD(&FillExtrusionLayer::getFillExtrusionTranslateTransition, "nativeGetFillExtrusionTranslateTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionTranslateTransition, "nativeSetFillExtrusionTranslateTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionTranslate, "nativeGetFillExtrusionTranslate"), + METHOD(&FillExtrusionLayer::getFillExtrusionTranslateAnchor, "nativeGetFillExtrusionTranslateAnchor"), + METHOD(&FillExtrusionLayer::getFillExtrusionPatternTransition, "nativeGetFillExtrusionPatternTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionPatternTransition, "nativeSetFillExtrusionPatternTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionPattern, "nativeGetFillExtrusionPattern"), + METHOD(&FillExtrusionLayer::getFillExtrusionHeightTransition, "nativeGetFillExtrusionHeightTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionHeightTransition, "nativeSetFillExtrusionHeightTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionHeight, "nativeGetFillExtrusionHeight"), + METHOD(&FillExtrusionLayer::getFillExtrusionBaseTransition, "nativeGetFillExtrusionBaseTransition"), + METHOD(&FillExtrusionLayer::setFillExtrusionBaseTransition, "nativeSetFillExtrusionBaseTransition"), + METHOD(&FillExtrusionLayer::getFillExtrusionBase, "nativeGetFillExtrusionBase"), + METHOD(&FillExtrusionLayer::getFillExtrusionVerticalGradient, "nativeGetFillExtrusionVerticalGradient")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp index aa478e422af..6aa0130ddc0 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_extrusion_layer.hpp @@ -56,7 +56,7 @@ class FillExtrusionLayer : public Layer { }; // class FillExtrusionLayer -class FillExtrusionJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillExtrusionLayerFactory { +class FillExtrusionJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillExtrusionLayerFactory { public: ~FillExtrusionJavaLayerPeerFactory() override; @@ -68,7 +68,7 @@ class FillExtrusionJavaLayerPeerFactory final : public JavaLayerPeerFactory, pu LayerFactory* getLayerFactory() final { return this; } -}; // class FillExtrusionJavaLayerPeerFactory +}; // class FillExtrusionJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp index 8b33c80772c..d22d923c168 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.cpp @@ -12,196 +12,197 @@ namespace mbgl { namespace android { - inline mbgl::style::FillLayer& toFillLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - FillLayer::FillLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - FillLayer::FillLayer(mbgl::style::FillLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - FillLayer::FillLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - FillLayer::~FillLayer() = default; - - // Property getters - - jni::Local> FillLayer::getFillSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillSortKey())); - } - - jni::Local> FillLayer::getFillAntialias(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillAntialias())); - } - - jni::Local> FillLayer::getFillOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillOpacity())); - } - - jni::Local> FillLayer::getFillOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillOpacityTransition(options); - } - - jni::Local> FillLayer::getFillColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillColor())); - } - - jni::Local> FillLayer::getFillColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillColorTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillColorTransition(options); - } - - jni::Local> FillLayer::getFillOutlineColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillOutlineColor())); - } - - jni::Local> FillLayer::getFillOutlineColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOutlineColorTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillOutlineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillOutlineColorTransition(options); - } - - jni::Local> FillLayer::getFillTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillTranslate())); - } - - jni::Local> FillLayer::getFillTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillTranslateTransition(options); - } - - jni::Local> FillLayer::getFillTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillTranslateAnchor())); - } - - jni::Local> FillLayer::getFillPattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toFillLayer(layer).getFillPattern())); - } - - jni::Local> FillLayer::getFillPatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toFillLayer(layer).getFillPatternTransition(); - return std::move(*convert>>(env, options)); - } - - void FillLayer::setFillPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toFillLayer(layer).setFillPatternTransition(options); - } - - - // FillJavaLayerPeerFactory - - FillJavaLayerPeerFactory::~FillJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillLayer(toFillLayer(layer))); - } - - jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new FillLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void FillJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&FillLayer::getFillSortKey, "nativeGetFillSortKey"), - METHOD(&FillLayer::getFillAntialias, "nativeGetFillAntialias"), - METHOD(&FillLayer::getFillOpacityTransition, "nativeGetFillOpacityTransition"), - METHOD(&FillLayer::setFillOpacityTransition, "nativeSetFillOpacityTransition"), - METHOD(&FillLayer::getFillOpacity, "nativeGetFillOpacity"), - METHOD(&FillLayer::getFillColorTransition, "nativeGetFillColorTransition"), - METHOD(&FillLayer::setFillColorTransition, "nativeSetFillColorTransition"), - METHOD(&FillLayer::getFillColor, "nativeGetFillColor"), - METHOD(&FillLayer::getFillOutlineColorTransition, "nativeGetFillOutlineColorTransition"), - METHOD(&FillLayer::setFillOutlineColorTransition, "nativeSetFillOutlineColorTransition"), - METHOD(&FillLayer::getFillOutlineColor, "nativeGetFillOutlineColor"), - METHOD(&FillLayer::getFillTranslateTransition, "nativeGetFillTranslateTransition"), - METHOD(&FillLayer::setFillTranslateTransition, "nativeSetFillTranslateTransition"), - METHOD(&FillLayer::getFillTranslate, "nativeGetFillTranslate"), - METHOD(&FillLayer::getFillTranslateAnchor, "nativeGetFillTranslateAnchor"), - METHOD(&FillLayer::getFillPatternTransition, "nativeGetFillPatternTransition"), - METHOD(&FillLayer::setFillPatternTransition, "nativeSetFillPatternTransition"), - METHOD(&FillLayer::getFillPattern, "nativeGetFillPattern")); - } +inline mbgl::style::FillLayer& toFillLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +FillLayer::FillLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +FillLayer::FillLayer(mbgl::style::FillLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +FillLayer::FillLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +FillLayer::~FillLayer() = default; + +// Property getters + +jni::Local> FillLayer::getFillSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillSortKey())); +} + +jni::Local> FillLayer::getFillAntialias(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillAntialias())); +} + +jni::Local> FillLayer::getFillOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillOpacity())); +} + +jni::Local> FillLayer::getFillOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillOpacityTransition(options); +} + +jni::Local> FillLayer::getFillColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillColor())); +} + +jni::Local> FillLayer::getFillColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillColorTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillColorTransition(options); +} + +jni::Local> FillLayer::getFillOutlineColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillOutlineColor())); +} + +jni::Local> FillLayer::getFillOutlineColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillOutlineColorTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillOutlineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillOutlineColorTransition(options); +} + +jni::Local> FillLayer::getFillTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillTranslate())); +} + +jni::Local> FillLayer::getFillTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillTranslateTransition(options); +} + +jni::Local> FillLayer::getFillTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillTranslateAnchor())); +} + +jni::Local> FillLayer::getFillPattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toFillLayer(layer).getFillPattern())); +} + +jni::Local> FillLayer::getFillPatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toFillLayer(layer).getFillPatternTransition(); + return std::move(*convert>>(env, options)); +} + +void FillLayer::setFillPatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toFillLayer(layer).setFillPatternTransition(options); +} + +// FillJavaLayerPeerFactory + +FillJavaLayerPeerFactory::~FillJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new FillLayer(toFillLayer(layer))); +} + +jni::Local> FillJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new FillLayer(std::unique_ptr(static_cast(layer.release())))); +} + +void FillJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&FillLayer::getFillSortKey, "nativeGetFillSortKey"), + METHOD(&FillLayer::getFillAntialias, "nativeGetFillAntialias"), + METHOD(&FillLayer::getFillOpacityTransition, "nativeGetFillOpacityTransition"), + METHOD(&FillLayer::setFillOpacityTransition, "nativeSetFillOpacityTransition"), + METHOD(&FillLayer::getFillOpacity, "nativeGetFillOpacity"), + METHOD(&FillLayer::getFillColorTransition, "nativeGetFillColorTransition"), + METHOD(&FillLayer::setFillColorTransition, "nativeSetFillColorTransition"), + METHOD(&FillLayer::getFillColor, "nativeGetFillColor"), + METHOD(&FillLayer::getFillOutlineColorTransition, "nativeGetFillOutlineColorTransition"), + METHOD(&FillLayer::setFillOutlineColorTransition, "nativeSetFillOutlineColorTransition"), + METHOD(&FillLayer::getFillOutlineColor, "nativeGetFillOutlineColor"), + METHOD(&FillLayer::getFillTranslateTransition, "nativeGetFillTranslateTransition"), + METHOD(&FillLayer::setFillTranslateTransition, "nativeSetFillTranslateTransition"), + METHOD(&FillLayer::getFillTranslate, "nativeGetFillTranslate"), + METHOD(&FillLayer::getFillTranslateAnchor, "nativeGetFillTranslateAnchor"), + METHOD(&FillLayer::getFillPatternTransition, "nativeGetFillPatternTransition"), + METHOD(&FillLayer::setFillPatternTransition, "nativeSetFillPatternTransition"), + METHOD(&FillLayer::getFillPattern, "nativeGetFillPattern")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp index 592d951f2a7..6fd29284586 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/fill_layer.hpp @@ -54,7 +54,7 @@ class FillLayer : public Layer { }; // class FillLayer -class FillJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillLayerFactory { +class FillJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::FillLayerFactory { public: ~FillJavaLayerPeerFactory() override; @@ -66,7 +66,7 @@ class FillJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl LayerFactory* getLayerFactory() final { return this; } -}; // class FillJavaLayerPeerFactory +}; // class FillJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp index 686e44c3a9d..c3945a54a03 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.cpp @@ -12,152 +12,153 @@ namespace mbgl { namespace android { - inline mbgl::style::HeatmapLayer& toHeatmapLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - HeatmapLayer::HeatmapLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - HeatmapLayer::HeatmapLayer(mbgl::style::HeatmapLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - HeatmapLayer::HeatmapLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - HeatmapLayer::~HeatmapLayer() = default; - - // Property getters - - jni::Local> HeatmapLayer::getHeatmapRadius(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapRadius())); - } - - jni::Local> HeatmapLayer::getHeatmapRadiusTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapRadiusTransition(); - return std::move(*convert>>(env, options)); - } - - void HeatmapLayer::setHeatmapRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHeatmapLayer(layer).setHeatmapRadiusTransition(options); - } - - jni::Local> HeatmapLayer::getHeatmapWeight(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapWeight())); - } - - jni::Local> HeatmapLayer::getHeatmapIntensity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapIntensity())); - } - - jni::Local> HeatmapLayer::getHeatmapIntensityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapIntensityTransition(); - return std::move(*convert>>(env, options)); - } - - void HeatmapLayer::setHeatmapIntensityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHeatmapLayer(layer).setHeatmapIntensityTransition(options); - } - - jni::Local> HeatmapLayer::getHeatmapColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - auto propertyValue = toHeatmapLayer(layer).getHeatmapColor(); - if (propertyValue.isUndefined()) { - propertyValue = toHeatmapLayer(layer).getDefaultHeatmapColor(); - } - return std::move(*convert>>(env, propertyValue)); - } - - jni::Local> HeatmapLayer::getHeatmapOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapOpacity())); - } - - jni::Local> HeatmapLayer::getHeatmapOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void HeatmapLayer::setHeatmapOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHeatmapLayer(layer).setHeatmapOpacityTransition(options); - } - - - // HeatmapJavaLayerPeerFactory - - HeatmapJavaLayerPeerFactory::~HeatmapJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HeatmapLayer(toHeatmapLayer(layer))); - } - - jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HeatmapLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void HeatmapJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&HeatmapLayer::getHeatmapRadiusTransition, "nativeGetHeatmapRadiusTransition"), - METHOD(&HeatmapLayer::setHeatmapRadiusTransition, "nativeSetHeatmapRadiusTransition"), - METHOD(&HeatmapLayer::getHeatmapRadius, "nativeGetHeatmapRadius"), - METHOD(&HeatmapLayer::getHeatmapWeight, "nativeGetHeatmapWeight"), - METHOD(&HeatmapLayer::getHeatmapIntensityTransition, "nativeGetHeatmapIntensityTransition"), - METHOD(&HeatmapLayer::setHeatmapIntensityTransition, "nativeSetHeatmapIntensityTransition"), - METHOD(&HeatmapLayer::getHeatmapIntensity, "nativeGetHeatmapIntensity"), - METHOD(&HeatmapLayer::getHeatmapColor, "nativeGetHeatmapColor"), - METHOD(&HeatmapLayer::getHeatmapOpacityTransition, "nativeGetHeatmapOpacityTransition"), - METHOD(&HeatmapLayer::setHeatmapOpacityTransition, "nativeSetHeatmapOpacityTransition"), - METHOD(&HeatmapLayer::getHeatmapOpacity, "nativeGetHeatmapOpacity")); - } +inline mbgl::style::HeatmapLayer& toHeatmapLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +HeatmapLayer::HeatmapLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +HeatmapLayer::HeatmapLayer(mbgl::style::HeatmapLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +HeatmapLayer::HeatmapLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +HeatmapLayer::~HeatmapLayer() = default; + +// Property getters + +jni::Local> HeatmapLayer::getHeatmapRadius(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapRadius())); +} + +jni::Local> HeatmapLayer::getHeatmapRadiusTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapRadiusTransition(); + return std::move(*convert>>(env, options)); +} + +void HeatmapLayer::setHeatmapRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHeatmapLayer(layer).setHeatmapRadiusTransition(options); +} + +jni::Local> HeatmapLayer::getHeatmapWeight(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapWeight())); +} + +jni::Local> HeatmapLayer::getHeatmapIntensity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapIntensity())); +} + +jni::Local> HeatmapLayer::getHeatmapIntensityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapIntensityTransition(); + return std::move(*convert>>(env, options)); +} + +void HeatmapLayer::setHeatmapIntensityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHeatmapLayer(layer).setHeatmapIntensityTransition(options); +} + +jni::Local> HeatmapLayer::getHeatmapColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + auto propertyValue = toHeatmapLayer(layer).getHeatmapColor(); + if (propertyValue.isUndefined()) { + propertyValue = toHeatmapLayer(layer).getDefaultHeatmapColor(); + } + return std::move(*convert>>(env, propertyValue)); +} + +jni::Local> HeatmapLayer::getHeatmapOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHeatmapLayer(layer).getHeatmapOpacity())); +} + +jni::Local> HeatmapLayer::getHeatmapOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHeatmapLayer(layer).getHeatmapOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void HeatmapLayer::setHeatmapOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHeatmapLayer(layer).setHeatmapOpacityTransition(options); +} + +// HeatmapJavaLayerPeerFactory + +HeatmapJavaLayerPeerFactory::~HeatmapJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new HeatmapLayer(toHeatmapLayer(layer))); +} + +jni::Local> HeatmapJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new HeatmapLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void HeatmapJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&HeatmapLayer::getHeatmapRadiusTransition, "nativeGetHeatmapRadiusTransition"), + METHOD(&HeatmapLayer::setHeatmapRadiusTransition, "nativeSetHeatmapRadiusTransition"), + METHOD(&HeatmapLayer::getHeatmapRadius, "nativeGetHeatmapRadius"), + METHOD(&HeatmapLayer::getHeatmapWeight, "nativeGetHeatmapWeight"), + METHOD(&HeatmapLayer::getHeatmapIntensityTransition, "nativeGetHeatmapIntensityTransition"), + METHOD(&HeatmapLayer::setHeatmapIntensityTransition, "nativeSetHeatmapIntensityTransition"), + METHOD(&HeatmapLayer::getHeatmapIntensity, "nativeGetHeatmapIntensity"), + METHOD(&HeatmapLayer::getHeatmapColor, "nativeGetHeatmapColor"), + METHOD(&HeatmapLayer::getHeatmapOpacityTransition, "nativeGetHeatmapOpacityTransition"), + METHOD(&HeatmapLayer::setHeatmapOpacityTransition, "nativeSetHeatmapOpacityTransition"), + METHOD(&HeatmapLayer::getHeatmapOpacity, "nativeGetHeatmapOpacity")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp index 15b24b14722..bf88367df35 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/heatmap_layer.hpp @@ -44,7 +44,7 @@ class HeatmapLayer : public Layer { }; // class HeatmapLayer -class HeatmapJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HeatmapLayerFactory { +class HeatmapJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HeatmapLayerFactory { public: ~HeatmapJavaLayerPeerFactory() override; @@ -56,7 +56,7 @@ class HeatmapJavaLayerPeerFactory final : public JavaLayerPeerFactory, public m LayerFactory* getLayerFactory() final { return this; } -}; // class HeatmapJavaLayerPeerFactory +}; // class HeatmapJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp index fa094f9ae7e..52332ee13ac 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.cpp @@ -12,169 +12,172 @@ namespace mbgl { namespace android { - inline mbgl::style::HillshadeLayer& toHillshadeLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - HillshadeLayer::HillshadeLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - HillshadeLayer::HillshadeLayer(mbgl::style::HillshadeLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - HillshadeLayer::HillshadeLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - HillshadeLayer::~HillshadeLayer() = default; - - // Property getters - - jni::Local> HillshadeLayer::getHillshadeIlluminationDirection(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationDirection())); - } - - jni::Local> HillshadeLayer::getHillshadeIlluminationAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationAnchor())); - } - - jni::Local> HillshadeLayer::getHillshadeExaggeration(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeExaggeration())); - } - - jni::Local> HillshadeLayer::getHillshadeExaggerationTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeExaggerationTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeExaggerationTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeExaggerationTransition(options); - } - - jni::Local> HillshadeLayer::getHillshadeShadowColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeShadowColor())); - } - - jni::Local> HillshadeLayer::getHillshadeShadowColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeShadowColorTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeShadowColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeShadowColorTransition(options); - } - - jni::Local> HillshadeLayer::getHillshadeHighlightColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeHighlightColor())); - } - - jni::Local> HillshadeLayer::getHillshadeHighlightColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeHighlightColorTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeHighlightColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeHighlightColorTransition(options); - } - - jni::Local> HillshadeLayer::getHillshadeAccentColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeAccentColor())); - } - - jni::Local> HillshadeLayer::getHillshadeAccentColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeAccentColorTransition(); - return std::move(*convert>>(env, options)); - } - - void HillshadeLayer::setHillshadeAccentColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toHillshadeLayer(layer).setHillshadeAccentColorTransition(options); - } - - - // HillshadeJavaLayerPeerFactory - - HillshadeJavaLayerPeerFactory::~HillshadeJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HillshadeLayer(toHillshadeLayer(layer))); - } - - jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new HillshadeLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void HillshadeJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&HillshadeLayer::getHillshadeIlluminationDirection, "nativeGetHillshadeIlluminationDirection"), - METHOD(&HillshadeLayer::getHillshadeIlluminationAnchor, "nativeGetHillshadeIlluminationAnchor"), - METHOD(&HillshadeLayer::getHillshadeExaggerationTransition, "nativeGetHillshadeExaggerationTransition"), - METHOD(&HillshadeLayer::setHillshadeExaggerationTransition, "nativeSetHillshadeExaggerationTransition"), - METHOD(&HillshadeLayer::getHillshadeExaggeration, "nativeGetHillshadeExaggeration"), - METHOD(&HillshadeLayer::getHillshadeShadowColorTransition, "nativeGetHillshadeShadowColorTransition"), - METHOD(&HillshadeLayer::setHillshadeShadowColorTransition, "nativeSetHillshadeShadowColorTransition"), - METHOD(&HillshadeLayer::getHillshadeShadowColor, "nativeGetHillshadeShadowColor"), - METHOD(&HillshadeLayer::getHillshadeHighlightColorTransition, "nativeGetHillshadeHighlightColorTransition"), - METHOD(&HillshadeLayer::setHillshadeHighlightColorTransition, "nativeSetHillshadeHighlightColorTransition"), - METHOD(&HillshadeLayer::getHillshadeHighlightColor, "nativeGetHillshadeHighlightColor"), - METHOD(&HillshadeLayer::getHillshadeAccentColorTransition, "nativeGetHillshadeAccentColorTransition"), - METHOD(&HillshadeLayer::setHillshadeAccentColorTransition, "nativeSetHillshadeAccentColorTransition"), - METHOD(&HillshadeLayer::getHillshadeAccentColor, "nativeGetHillshadeAccentColor")); - } +inline mbgl::style::HillshadeLayer& toHillshadeLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +HillshadeLayer::HillshadeLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +HillshadeLayer::HillshadeLayer(mbgl::style::HillshadeLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +HillshadeLayer::HillshadeLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +HillshadeLayer::~HillshadeLayer() = default; + +// Property getters + +jni::Local> HillshadeLayer::getHillshadeIlluminationDirection(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationDirection())); +} + +jni::Local> HillshadeLayer::getHillshadeIlluminationAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toHillshadeLayer(layer).getHillshadeIlluminationAnchor())); +} + +jni::Local> HillshadeLayer::getHillshadeExaggeration(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeExaggeration())); +} + +jni::Local> HillshadeLayer::getHillshadeExaggerationTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeExaggerationTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeExaggerationTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeExaggerationTransition(options); +} + +jni::Local> HillshadeLayer::getHillshadeShadowColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeShadowColor())); +} + +jni::Local> HillshadeLayer::getHillshadeShadowColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeShadowColorTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeShadowColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeShadowColorTransition(options); +} + +jni::Local> HillshadeLayer::getHillshadeHighlightColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeHighlightColor())); +} + +jni::Local> HillshadeLayer::getHillshadeHighlightColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeHighlightColorTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeHighlightColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeHighlightColorTransition(options); +} + +jni::Local> HillshadeLayer::getHillshadeAccentColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toHillshadeLayer(layer).getHillshadeAccentColor())); +} + +jni::Local> HillshadeLayer::getHillshadeAccentColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toHillshadeLayer(layer).getHillshadeAccentColorTransition(); + return std::move(*convert>>(env, options)); +} + +void HillshadeLayer::setHillshadeAccentColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toHillshadeLayer(layer).setHillshadeAccentColorTransition(options); +} + +// HillshadeJavaLayerPeerFactory + +HillshadeJavaLayerPeerFactory::~HillshadeJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new HillshadeLayer(toHillshadeLayer(layer))); +} + +jni::Local> HillshadeJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new HillshadeLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void HillshadeJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&HillshadeLayer::getHillshadeIlluminationDirection, "nativeGetHillshadeIlluminationDirection"), + METHOD(&HillshadeLayer::getHillshadeIlluminationAnchor, "nativeGetHillshadeIlluminationAnchor"), + METHOD(&HillshadeLayer::getHillshadeExaggerationTransition, "nativeGetHillshadeExaggerationTransition"), + METHOD(&HillshadeLayer::setHillshadeExaggerationTransition, "nativeSetHillshadeExaggerationTransition"), + METHOD(&HillshadeLayer::getHillshadeExaggeration, "nativeGetHillshadeExaggeration"), + METHOD(&HillshadeLayer::getHillshadeShadowColorTransition, "nativeGetHillshadeShadowColorTransition"), + METHOD(&HillshadeLayer::setHillshadeShadowColorTransition, "nativeSetHillshadeShadowColorTransition"), + METHOD(&HillshadeLayer::getHillshadeShadowColor, "nativeGetHillshadeShadowColor"), + METHOD(&HillshadeLayer::getHillshadeHighlightColorTransition, "nativeGetHillshadeHighlightColorTransition"), + METHOD(&HillshadeLayer::setHillshadeHighlightColorTransition, "nativeSetHillshadeHighlightColorTransition"), + METHOD(&HillshadeLayer::getHillshadeHighlightColor, "nativeGetHillshadeHighlightColor"), + METHOD(&HillshadeLayer::getHillshadeAccentColorTransition, "nativeGetHillshadeAccentColorTransition"), + METHOD(&HillshadeLayer::setHillshadeAccentColorTransition, "nativeSetHillshadeAccentColorTransition"), + METHOD(&HillshadeLayer::getHillshadeAccentColor, "nativeGetHillshadeAccentColor")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp index 0c5d489ee56..260a71f1d13 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/hillshade_layer.hpp @@ -48,7 +48,7 @@ class HillshadeLayer : public Layer { }; // class HillshadeLayer -class HillshadeJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HillshadeLayerFactory { +class HillshadeJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::HillshadeLayerFactory { public: ~HillshadeJavaLayerPeerFactory() override; @@ -60,7 +60,7 @@ class HillshadeJavaLayerPeerFactory final : public JavaLayerPeerFactory, public LayerFactory* getLayerFactory() final { return this; } -}; // class HillshadeJavaLayerPeerFactory +}; // class HillshadeJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp index a4bf2dd52d6..9edbc8b3053 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.cpp @@ -24,145 +24,145 @@ namespace mbgl { namespace android { - /** - * Invoked when the construction is initiated from the jvm through a subclass - */ - Layer::Layer(std::unique_ptr coreLayer) - : ownedLayer(std::move(coreLayer)) - , layer(*ownedLayer) { - } - - /** - * Takes a non-owning reference. For lookup methods - */ - Layer::Layer(mbgl::style::Layer& coreLayer) : layer(coreLayer) {} - - Layer::~Layer() { - } - - void Layer::addToStyle(mbgl::style::Style& style, std::optional before) { - // Check to see if we own the layer first - if (!ownedLayer) { - throw std::runtime_error("Cannot add layer twice"); - } - - // Add layer to map - style.addLayer(releaseCoreLayer(), before); - } - - void Layer::setLayer(std::unique_ptr sourceLayer) { - this->ownedLayer = std::move(sourceLayer); - } - - std::unique_ptr Layer::releaseCoreLayer() { - assert(ownedLayer != nullptr); - return std::move(ownedLayer); - } - - jni::Local Layer::getId(jni::JNIEnv& env) { - return jni::Make(env, layer.getID()); - } - - style::Layer& Layer::get() { - return layer; - } - - void Layer::setProperty(jni::JNIEnv& env, const jni::String& jname, const jni::Object<>& jvalue) { - // Convert and set property - std::optional error = - layer.setProperty(jni::Make(env, jname), Value(env, jvalue)); - if (error) { - mbgl::Log::Error(mbgl::Event::JNI, "Error setting property: " + jni::Make(env, jname) + " " + error->message); - return; - } - } - - void Layer::setFilter(jni::JNIEnv& env, const jni::Array>& jfilter) { - using namespace mbgl::style; - using namespace mbgl::style::conversion; - - Error error; - std::optional converted = convert(Value(env, jfilter), error); - if (!converted) { - mbgl::Log::Error(mbgl::Event::JNI, "Error setting filter: " + error.message); - return; - } - - layer.setFilter(std::move(*converted)); - } - - jni::Local> Layer::getFilter(jni::JNIEnv& env) { - using namespace mbgl::style; - using namespace mbgl::style::conversion; - - Filter filter = layer.getFilter(); - if (filter.expression) { - mbgl::Value expressionValue = (*filter.expression)->serialize(); - return gson::JsonElement::New(env, expressionValue); - } else { - return jni::Local>(env, nullptr); - } - } - - void Layer::setSourceLayer(jni::JNIEnv& env, const jni::String& sourceLayer) { - layer.setSourceLayer(jni::Make(env, sourceLayer)); - } - - jni::Local Layer::getSourceLayer(jni::JNIEnv& env) { - return jni::Make(env, layer.getSourceLayer()); - } - - jni::Local Layer::getSourceId(jni::JNIEnv& env) { - return jni::Make(env, layer.getSourceID()); - } - - jni::jfloat Layer::getMinZoom(jni::JNIEnv&){ - return layer.getMinZoom(); - } - - jni::jfloat Layer::getMaxZoom(jni::JNIEnv&) { - return layer.getMaxZoom(); - } - - void Layer::setMinZoom(jni::JNIEnv&, jni::jfloat zoom) { - layer.setMinZoom(zoom); - } - - void Layer::setMaxZoom(jni::JNIEnv&, jni::jfloat zoom) { - layer.setMaxZoom(zoom); - } - - jni::Local> Layer::getVisibility(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, layer.getVisibility())); - } - - void Layer::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - METHOD(&Layer::getId, "nativeGetId"), - METHOD(&Layer::setProperty, - "nativeSetLayoutProperty"), // TODO : Export only nativeSetProperty() when #15970 lands. - METHOD(&Layer::setProperty, "nativeSetPaintProperty"), - METHOD(&Layer::setFilter, "nativeSetFilter"), - METHOD(&Layer::getFilter, "nativeGetFilter"), - METHOD(&Layer::setSourceLayer, "nativeSetSourceLayer"), - METHOD(&Layer::getSourceLayer, "nativeGetSourceLayer"), - METHOD(&Layer::getSourceId, "nativeGetSourceId"), - METHOD(&Layer::getMinZoom, "nativeGetMinZoom"), - METHOD(&Layer::getMaxZoom, "nativeGetMaxZoom"), - METHOD(&Layer::setMinZoom, "nativeSetMinZoom"), - METHOD(&Layer::setMaxZoom, "nativeSetMaxZoom"), - METHOD(&Layer::getVisibility, "nativeGetVisibility")); - } +/** + * Invoked when the construction is initiated from the jvm through a subclass + */ +Layer::Layer(std::unique_ptr coreLayer) + : ownedLayer(std::move(coreLayer)), + layer(*ownedLayer) {} + +/** + * Takes a non-owning reference. For lookup methods + */ +Layer::Layer(mbgl::style::Layer& coreLayer) + : layer(coreLayer) {} + +Layer::~Layer() {} + +void Layer::addToStyle(mbgl::style::Style& style, std::optional before) { + // Check to see if we own the layer first + if (!ownedLayer) { + throw std::runtime_error("Cannot add layer twice"); + } + + // Add layer to map + style.addLayer(releaseCoreLayer(), before); +} + +void Layer::setLayer(std::unique_ptr sourceLayer) { + this->ownedLayer = std::move(sourceLayer); +} + +std::unique_ptr Layer::releaseCoreLayer() { + assert(ownedLayer != nullptr); + return std::move(ownedLayer); +} + +jni::Local Layer::getId(jni::JNIEnv& env) { + return jni::Make(env, layer.getID()); +} + +style::Layer& Layer::get() { + return layer; +} + +void Layer::setProperty(jni::JNIEnv& env, const jni::String& jname, const jni::Object<>& jvalue) { + // Convert and set property + std::optional error = layer.setProperty(jni::Make(env, jname), + Value(env, jvalue)); + if (error) { + mbgl::Log::Error(mbgl::Event::JNI, + "Error setting property: " + jni::Make(env, jname) + " " + error->message); + return; + } +} + +void Layer::setFilter(jni::JNIEnv& env, const jni::Array>& jfilter) { + using namespace mbgl::style; + using namespace mbgl::style::conversion; + + Error error; + std::optional converted = convert(Value(env, jfilter), error); + if (!converted) { + mbgl::Log::Error(mbgl::Event::JNI, "Error setting filter: " + error.message); + return; + } + + layer.setFilter(std::move(*converted)); +} + +jni::Local> Layer::getFilter(jni::JNIEnv& env) { + using namespace mbgl::style; + using namespace mbgl::style::conversion; + + Filter filter = layer.getFilter(); + if (filter.expression) { + mbgl::Value expressionValue = (*filter.expression)->serialize(); + return gson::JsonElement::New(env, expressionValue); + } else { + return jni::Local>(env, nullptr); + } +} + +void Layer::setSourceLayer(jni::JNIEnv& env, const jni::String& sourceLayer) { + layer.setSourceLayer(jni::Make(env, sourceLayer)); +} + +jni::Local Layer::getSourceLayer(jni::JNIEnv& env) { + return jni::Make(env, layer.getSourceLayer()); +} + +jni::Local Layer::getSourceId(jni::JNIEnv& env) { + return jni::Make(env, layer.getSourceID()); +} + +jni::jfloat Layer::getMinZoom(jni::JNIEnv&) { + return layer.getMinZoom(); +} + +jni::jfloat Layer::getMaxZoom(jni::JNIEnv&) { + return layer.getMaxZoom(); +} + +void Layer::setMinZoom(jni::JNIEnv&, jni::jfloat zoom) { + layer.setMinZoom(zoom); +} + +void Layer::setMaxZoom(jni::JNIEnv&, jni::jfloat zoom) { + layer.setMaxZoom(zoom); +} + +jni::Local> Layer::getVisibility(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, layer.getVisibility())); +} + +void Layer::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + METHOD(&Layer::getId, "nativeGetId"), + METHOD(&Layer::setProperty, + "nativeSetLayoutProperty"), // TODO : Export only nativeSetProperty() when #15970 lands. + METHOD(&Layer::setProperty, "nativeSetPaintProperty"), + METHOD(&Layer::setFilter, "nativeSetFilter"), + METHOD(&Layer::getFilter, "nativeGetFilter"), + METHOD(&Layer::setSourceLayer, "nativeSetSourceLayer"), + METHOD(&Layer::getSourceLayer, "nativeGetSourceLayer"), + METHOD(&Layer::getSourceId, "nativeGetSourceId"), + METHOD(&Layer::getMinZoom, "nativeGetMinZoom"), + METHOD(&Layer::getMaxZoom, "nativeGetMaxZoom"), + METHOD(&Layer::setMinZoom, "nativeSetMinZoom"), + METHOD(&Layer::setMaxZoom, "nativeSetMaxZoom"), + METHOD(&Layer::getVisibility, "nativeGetVisibility")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp index d0ebf37fc41..d46b9cce10b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer.hpp @@ -15,7 +15,6 @@ namespace android { class Layer { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/layers/Layer"; }; static void registerNative(jni::JNIEnv&); @@ -106,12 +105,11 @@ class JavaLayerPeerFactory { /** * @brief Get the corresponding layer factory. - * + * * @return style::LayerFactory* must not be \c nullptr. */ virtual LayerFactory* getLayerFactory() = 0; }; - } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp index 1e72b151630..e53c4604444 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.cpp @@ -102,7 +102,7 @@ void LayerManagerAndroid::registerNative(jni::JNIEnv& env) { } Layer::registerNative(env); - for (const auto& factory: peerFactories) { + for (const auto& factory : peerFactories) { factory->registerNative(env); } } @@ -129,7 +129,7 @@ void LayerManagerAndroid::registerCoreFactory(mbgl::LayerFactory* factory) { JavaLayerPeerFactory* LayerManagerAndroid::getPeerFactory(const mbgl::style::LayerTypeInfo* typeInfo) { assert(typeInfo); - for (const auto& factory: peerFactories) { + for (const auto& factory : peerFactories) { if (factory->getLayerFactory()->getTypeInfo() == typeInfo) { return factory.get(); } @@ -147,7 +147,7 @@ LayerFactory* LayerManagerAndroid::getFactory(const mbgl::style::LayerTypeInfo* return peerFactory->getLayerFactory(); } - for (const auto& factory: coreFactories) { + for (const auto& factory : coreFactories) { if (factory->getTypeInfo() == info) { return factory.get(); } @@ -168,7 +168,8 @@ LayerManager* LayerManager::get() noexcept { return android::LayerManagerAndroid::get(); } -#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || defined(MBGL_LAYER_FILL_DISABLE_ALL) +#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || \ + defined(MBGL_LAYER_FILL_DISABLE_ALL) const bool LayerManager::annotationsEnabled = false; #else const bool LayerManager::annotationsEnabled = true; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp index f7379f6de64..900da8c926f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/layer_manager.hpp @@ -15,7 +15,8 @@ namespace mbgl { namespace android { /** - * @brief A singleton class forwarding calls to the corresponding \c JavaLayerPeerFactory instance. + * @brief A singleton class forwarding calls to the corresponding \c + * JavaLayerPeerFactory instance. */ class LayerManagerAndroid final : public mbgl::LayerManager { public: @@ -32,13 +33,13 @@ class LayerManagerAndroid final : public mbgl::LayerManager { /** * @brief Enables a layer type for both JSON style and runtime API. */ - void addLayerType(std::unique_ptr); + void addLayerType(std::unique_ptr); /** * @brief Enables a layer type for JSON style only. * * We might not want to expose runtime API for some layer types * in order to save binary size - JNI glue code for these layer types - * won't be added to the binary. + * won't be added to the binary. */ void addLayerTypeCoreOnly(std::unique_ptr); @@ -53,5 +54,5 @@ class LayerManagerAndroid final : public mbgl::LayerManager { std::map typeToFactory; }; -} // namespace android -} // namespace mbgl +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp index bc05c41a173..09149f22396 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.cpp @@ -12,304 +12,305 @@ namespace mbgl { namespace android { - inline mbgl::style::LineLayer& toLineLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - LineLayer::LineLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - LineLayer::LineLayer(mbgl::style::LineLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - LineLayer::LineLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - LineLayer::~LineLayer() = default; - - // Property getters - - jni::Local> LineLayer::getLineCap(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineCap())); - } - - jni::Local> LineLayer::getLineJoin(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineJoin())); - } - - jni::Local> LineLayer::getLineMiterLimit(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineMiterLimit())); - } - - jni::Local> LineLayer::getLineRoundLimit(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineRoundLimit())); - } - - jni::Local> LineLayer::getLineSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineSortKey())); - } - - jni::Local> LineLayer::getLineOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineOpacity())); - } - - jni::Local> LineLayer::getLineOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineOpacityTransition(options); - } - - jni::Local> LineLayer::getLineColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineColor())); - } - - jni::Local> LineLayer::getLineColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineColorTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineColorTransition(options); - } - - jni::Local> LineLayer::getLineTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineTranslate())); - } - - jni::Local> LineLayer::getLineTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineTranslateTransition(options); - } - - jni::Local> LineLayer::getLineTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineTranslateAnchor())); - } - - jni::Local> LineLayer::getLineWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineWidth())); - } - - jni::Local> LineLayer::getLineWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineWidthTransition(options); - } - - jni::Local> LineLayer::getLineGapWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineGapWidth())); - } - - jni::Local> LineLayer::getLineGapWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineGapWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineGapWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineGapWidthTransition(options); - } - - jni::Local> LineLayer::getLineOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineOffset())); - } - - jni::Local> LineLayer::getLineOffsetTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOffsetTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineOffsetTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineOffsetTransition(options); - } - - jni::Local> LineLayer::getLineBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineBlur())); - } - - jni::Local> LineLayer::getLineBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineBlurTransition(options); - } - - jni::Local> LineLayer::getLineDasharray(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineDasharray())); - } - - jni::Local> LineLayer::getLineDasharrayTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLineDasharrayTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLineDasharrayTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLineDasharrayTransition(options); - } - - jni::Local> LineLayer::getLinePattern(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLinePattern())); - } - - jni::Local> LineLayer::getLinePatternTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLineLayer(layer).getLinePatternTransition(); - return std::move(*convert>>(env, options)); - } - - void LineLayer::setLinePatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLineLayer(layer).setLinePatternTransition(options); - } - - jni::Local> LineLayer::getLineGradient(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLineLayer(layer).getLineGradient())); - } - - - // LineJavaLayerPeerFactory - - LineJavaLayerPeerFactory::~LineJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LineLayer(toLineLayer(layer))); - } - - jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LineLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void LineJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&LineLayer::getLineCap, "nativeGetLineCap"), - METHOD(&LineLayer::getLineJoin, "nativeGetLineJoin"), - METHOD(&LineLayer::getLineMiterLimit, "nativeGetLineMiterLimit"), - METHOD(&LineLayer::getLineRoundLimit, "nativeGetLineRoundLimit"), - METHOD(&LineLayer::getLineSortKey, "nativeGetLineSortKey"), - METHOD(&LineLayer::getLineOpacityTransition, "nativeGetLineOpacityTransition"), - METHOD(&LineLayer::setLineOpacityTransition, "nativeSetLineOpacityTransition"), - METHOD(&LineLayer::getLineOpacity, "nativeGetLineOpacity"), - METHOD(&LineLayer::getLineColorTransition, "nativeGetLineColorTransition"), - METHOD(&LineLayer::setLineColorTransition, "nativeSetLineColorTransition"), - METHOD(&LineLayer::getLineColor, "nativeGetLineColor"), - METHOD(&LineLayer::getLineTranslateTransition, "nativeGetLineTranslateTransition"), - METHOD(&LineLayer::setLineTranslateTransition, "nativeSetLineTranslateTransition"), - METHOD(&LineLayer::getLineTranslate, "nativeGetLineTranslate"), - METHOD(&LineLayer::getLineTranslateAnchor, "nativeGetLineTranslateAnchor"), - METHOD(&LineLayer::getLineWidthTransition, "nativeGetLineWidthTransition"), - METHOD(&LineLayer::setLineWidthTransition, "nativeSetLineWidthTransition"), - METHOD(&LineLayer::getLineWidth, "nativeGetLineWidth"), - METHOD(&LineLayer::getLineGapWidthTransition, "nativeGetLineGapWidthTransition"), - METHOD(&LineLayer::setLineGapWidthTransition, "nativeSetLineGapWidthTransition"), - METHOD(&LineLayer::getLineGapWidth, "nativeGetLineGapWidth"), - METHOD(&LineLayer::getLineOffsetTransition, "nativeGetLineOffsetTransition"), - METHOD(&LineLayer::setLineOffsetTransition, "nativeSetLineOffsetTransition"), - METHOD(&LineLayer::getLineOffset, "nativeGetLineOffset"), - METHOD(&LineLayer::getLineBlurTransition, "nativeGetLineBlurTransition"), - METHOD(&LineLayer::setLineBlurTransition, "nativeSetLineBlurTransition"), - METHOD(&LineLayer::getLineBlur, "nativeGetLineBlur"), - METHOD(&LineLayer::getLineDasharrayTransition, "nativeGetLineDasharrayTransition"), - METHOD(&LineLayer::setLineDasharrayTransition, "nativeSetLineDasharrayTransition"), - METHOD(&LineLayer::getLineDasharray, "nativeGetLineDasharray"), - METHOD(&LineLayer::getLinePatternTransition, "nativeGetLinePatternTransition"), - METHOD(&LineLayer::setLinePatternTransition, "nativeSetLinePatternTransition"), - METHOD(&LineLayer::getLinePattern, "nativeGetLinePattern"), - METHOD(&LineLayer::getLineGradient, "nativeGetLineGradient")); - } +inline mbgl::style::LineLayer& toLineLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +LineLayer::LineLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +LineLayer::LineLayer(mbgl::style::LineLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +LineLayer::LineLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +LineLayer::~LineLayer() = default; + +// Property getters + +jni::Local> LineLayer::getLineCap(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineCap())); +} + +jni::Local> LineLayer::getLineJoin(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineJoin())); +} + +jni::Local> LineLayer::getLineMiterLimit(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineMiterLimit())); +} + +jni::Local> LineLayer::getLineRoundLimit(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineRoundLimit())); +} + +jni::Local> LineLayer::getLineSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineSortKey())); +} + +jni::Local> LineLayer::getLineOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineOpacity())); +} + +jni::Local> LineLayer::getLineOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineOpacityTransition(options); +} + +jni::Local> LineLayer::getLineColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineColor())); +} + +jni::Local> LineLayer::getLineColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineColorTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineColorTransition(options); +} + +jni::Local> LineLayer::getLineTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineTranslate())); +} + +jni::Local> LineLayer::getLineTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineTranslateTransition(options); +} + +jni::Local> LineLayer::getLineTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineTranslateAnchor())); +} + +jni::Local> LineLayer::getLineWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineWidth())); +} + +jni::Local> LineLayer::getLineWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineWidthTransition(options); +} + +jni::Local> LineLayer::getLineGapWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineGapWidth())); +} + +jni::Local> LineLayer::getLineGapWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineGapWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineGapWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineGapWidthTransition(options); +} + +jni::Local> LineLayer::getLineOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineOffset())); +} + +jni::Local> LineLayer::getLineOffsetTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineOffsetTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineOffsetTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineOffsetTransition(options); +} + +jni::Local> LineLayer::getLineBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineBlur())); +} + +jni::Local> LineLayer::getLineBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineBlurTransition(options); +} + +jni::Local> LineLayer::getLineDasharray(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineDasharray())); +} + +jni::Local> LineLayer::getLineDasharrayTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLineDasharrayTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLineDasharrayTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLineDasharrayTransition(options); +} + +jni::Local> LineLayer::getLinePattern(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLinePattern())); +} + +jni::Local> LineLayer::getLinePatternTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLineLayer(layer).getLinePatternTransition(); + return std::move(*convert>>(env, options)); +} + +void LineLayer::setLinePatternTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLineLayer(layer).setLinePatternTransition(options); +} + +jni::Local> LineLayer::getLineGradient(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLineLayer(layer).getLineGradient())); +} + +// LineJavaLayerPeerFactory + +LineJavaLayerPeerFactory::~LineJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new LineLayer(toLineLayer(layer))); +} + +jni::Local> LineJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer( + env, + new LineLayer(std::unique_ptr(static_cast(layer.release())))); +} + +void LineJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&LineLayer::getLineCap, "nativeGetLineCap"), + METHOD(&LineLayer::getLineJoin, "nativeGetLineJoin"), + METHOD(&LineLayer::getLineMiterLimit, "nativeGetLineMiterLimit"), + METHOD(&LineLayer::getLineRoundLimit, "nativeGetLineRoundLimit"), + METHOD(&LineLayer::getLineSortKey, "nativeGetLineSortKey"), + METHOD(&LineLayer::getLineOpacityTransition, "nativeGetLineOpacityTransition"), + METHOD(&LineLayer::setLineOpacityTransition, "nativeSetLineOpacityTransition"), + METHOD(&LineLayer::getLineOpacity, "nativeGetLineOpacity"), + METHOD(&LineLayer::getLineColorTransition, "nativeGetLineColorTransition"), + METHOD(&LineLayer::setLineColorTransition, "nativeSetLineColorTransition"), + METHOD(&LineLayer::getLineColor, "nativeGetLineColor"), + METHOD(&LineLayer::getLineTranslateTransition, "nativeGetLineTranslateTransition"), + METHOD(&LineLayer::setLineTranslateTransition, "nativeSetLineTranslateTransition"), + METHOD(&LineLayer::getLineTranslate, "nativeGetLineTranslate"), + METHOD(&LineLayer::getLineTranslateAnchor, "nativeGetLineTranslateAnchor"), + METHOD(&LineLayer::getLineWidthTransition, "nativeGetLineWidthTransition"), + METHOD(&LineLayer::setLineWidthTransition, "nativeSetLineWidthTransition"), + METHOD(&LineLayer::getLineWidth, "nativeGetLineWidth"), + METHOD(&LineLayer::getLineGapWidthTransition, "nativeGetLineGapWidthTransition"), + METHOD(&LineLayer::setLineGapWidthTransition, "nativeSetLineGapWidthTransition"), + METHOD(&LineLayer::getLineGapWidth, "nativeGetLineGapWidth"), + METHOD(&LineLayer::getLineOffsetTransition, "nativeGetLineOffsetTransition"), + METHOD(&LineLayer::setLineOffsetTransition, "nativeSetLineOffsetTransition"), + METHOD(&LineLayer::getLineOffset, "nativeGetLineOffset"), + METHOD(&LineLayer::getLineBlurTransition, "nativeGetLineBlurTransition"), + METHOD(&LineLayer::setLineBlurTransition, "nativeSetLineBlurTransition"), + METHOD(&LineLayer::getLineBlur, "nativeGetLineBlur"), + METHOD(&LineLayer::getLineDasharrayTransition, "nativeGetLineDasharrayTransition"), + METHOD(&LineLayer::setLineDasharrayTransition, "nativeSetLineDasharrayTransition"), + METHOD(&LineLayer::getLineDasharray, "nativeGetLineDasharray"), + METHOD(&LineLayer::getLinePatternTransition, "nativeGetLinePatternTransition"), + METHOD(&LineLayer::setLinePatternTransition, "nativeSetLinePatternTransition"), + METHOD(&LineLayer::getLinePattern, "nativeGetLinePattern"), + METHOD(&LineLayer::getLineGradient, "nativeGetLineGradient")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp index 1a53b9e3288..2e878d689a2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/line_layer.hpp @@ -78,7 +78,7 @@ class LineLayer : public Layer { }; // class LineLayer -class LineJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::LineLayerFactory { +class LineJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::LineLayerFactory { public: ~LineJavaLayerPeerFactory() override; @@ -90,7 +90,7 @@ class LineJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl LayerFactory* getLayerFactory() final { return this; } -}; // class LineJavaLayerPeerFactory +}; // class LineJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp index 9e642979290..a7abba30deb 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.cpp @@ -12,256 +12,263 @@ namespace mbgl { namespace android { - inline mbgl::style::LocationIndicatorLayer& toLocationIndicatorLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - LocationIndicatorLayer::LocationIndicatorLayer(jni::JNIEnv& env, jni::String& layerId) - : Layer(std::make_unique(jni::Make(env, layerId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - LocationIndicatorLayer::LocationIndicatorLayer(mbgl::style::LocationIndicatorLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - LocationIndicatorLayer::LocationIndicatorLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - LocationIndicatorLayer::~LocationIndicatorLayer() = default; - - // Property getters - - jni::Local> LocationIndicatorLayer::getTopImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImage())); - } - - jni::Local> LocationIndicatorLayer::getBearingImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImage())); - } - - jni::Local> LocationIndicatorLayer::getShadowImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImage())); - } - - jni::Local> LocationIndicatorLayer::getPerspectiveCompensation(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getPerspectiveCompensation())); - } - - jni::Local> LocationIndicatorLayer::getImageTiltDisplacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getImageTiltDisplacement())); - } - - jni::Local> LocationIndicatorLayer::getBearing(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearing())); - } - - jni::Local> LocationIndicatorLayer::getLocation(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getLocation())); - } - - jni::Local> LocationIndicatorLayer::getLocationTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getLocationTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setLocationTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setLocationTransition(options); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadius(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadius())); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setAccuracyRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setAccuracyRadiusTransition(options); - } - - jni::Local> LocationIndicatorLayer::getTopImageSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImageSize())); - } - - jni::Local> LocationIndicatorLayer::getTopImageSizeTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getTopImageSizeTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setTopImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setTopImageSizeTransition(options); - } - - jni::Local> LocationIndicatorLayer::getBearingImageSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImageSize())); - } - - jni::Local> LocationIndicatorLayer::getBearingImageSizeTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getBearingImageSizeTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setBearingImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setBearingImageSizeTransition(options); - } - - jni::Local> LocationIndicatorLayer::getShadowImageSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImageSize())); - } - - jni::Local> LocationIndicatorLayer::getShadowImageSizeTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getShadowImageSizeTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setShadowImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setShadowImageSizeTransition(options); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusColor())); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusColorTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setAccuracyRadiusColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setAccuracyRadiusColorTransition(options); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColor())); - } - - jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColorTransition(); - return std::move(*convert>>(env, options)); - } - - void LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toLocationIndicatorLayer(layer).setAccuracyRadiusBorderColorTransition(options); - } - - - // LocationIndicatorJavaLayerPeerFactory - - LocationIndicatorJavaLayerPeerFactory::~LocationIndicatorJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LocationIndicatorLayer(toLocationIndicatorLayer(layer))); - } - - jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new LocationIndicatorLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void LocationIndicatorJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&LocationIndicatorLayer::getTopImage, "nativeGetTopImage"), - METHOD(&LocationIndicatorLayer::getBearingImage, "nativeGetBearingImage"), - METHOD(&LocationIndicatorLayer::getShadowImage, "nativeGetShadowImage"), - METHOD(&LocationIndicatorLayer::getPerspectiveCompensation, "nativeGetPerspectiveCompensation"), - METHOD(&LocationIndicatorLayer::getImageTiltDisplacement, "nativeGetImageTiltDisplacement"), - METHOD(&LocationIndicatorLayer::getBearing, "nativeGetBearing"), - METHOD(&LocationIndicatorLayer::getLocationTransition, "nativeGetLocationTransition"), - METHOD(&LocationIndicatorLayer::setLocationTransition, "nativeSetLocationTransition"), - METHOD(&LocationIndicatorLayer::getLocation, "nativeGetLocation"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusTransition, "nativeGetAccuracyRadiusTransition"), - METHOD(&LocationIndicatorLayer::setAccuracyRadiusTransition, "nativeSetAccuracyRadiusTransition"), - METHOD(&LocationIndicatorLayer::getAccuracyRadius, "nativeGetAccuracyRadius"), - METHOD(&LocationIndicatorLayer::getTopImageSizeTransition, "nativeGetTopImageSizeTransition"), - METHOD(&LocationIndicatorLayer::setTopImageSizeTransition, "nativeSetTopImageSizeTransition"), - METHOD(&LocationIndicatorLayer::getTopImageSize, "nativeGetTopImageSize"), - METHOD(&LocationIndicatorLayer::getBearingImageSizeTransition, "nativeGetBearingImageSizeTransition"), - METHOD(&LocationIndicatorLayer::setBearingImageSizeTransition, "nativeSetBearingImageSizeTransition"), - METHOD(&LocationIndicatorLayer::getBearingImageSize, "nativeGetBearingImageSize"), - METHOD(&LocationIndicatorLayer::getShadowImageSizeTransition, "nativeGetShadowImageSizeTransition"), - METHOD(&LocationIndicatorLayer::setShadowImageSizeTransition, "nativeSetShadowImageSizeTransition"), - METHOD(&LocationIndicatorLayer::getShadowImageSize, "nativeGetShadowImageSize"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusColorTransition, "nativeGetAccuracyRadiusColorTransition"), - METHOD(&LocationIndicatorLayer::setAccuracyRadiusColorTransition, "nativeSetAccuracyRadiusColorTransition"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusColor, "nativeGetAccuracyRadiusColor"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition, "nativeGetAccuracyRadiusBorderColorTransition"), - METHOD(&LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition, "nativeSetAccuracyRadiusBorderColorTransition"), - METHOD(&LocationIndicatorLayer::getAccuracyRadiusBorderColor, "nativeGetAccuracyRadiusBorderColor")); - } +inline mbgl::style::LocationIndicatorLayer& toLocationIndicatorLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +LocationIndicatorLayer::LocationIndicatorLayer(jni::JNIEnv& env, jni::String& layerId) + : Layer(std::make_unique(jni::Make(env, layerId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +LocationIndicatorLayer::LocationIndicatorLayer(mbgl::style::LocationIndicatorLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +LocationIndicatorLayer::LocationIndicatorLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +LocationIndicatorLayer::~LocationIndicatorLayer() = default; + +// Property getters + +jni::Local> LocationIndicatorLayer::getTopImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImage())); +} + +jni::Local> LocationIndicatorLayer::getBearingImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImage())); +} + +jni::Local> LocationIndicatorLayer::getShadowImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImage())); +} + +jni::Local> LocationIndicatorLayer::getPerspectiveCompensation(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toLocationIndicatorLayer(layer).getPerspectiveCompensation())); +} + +jni::Local> LocationIndicatorLayer::getImageTiltDisplacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toLocationIndicatorLayer(layer).getImageTiltDisplacement())); +} + +jni::Local> LocationIndicatorLayer::getBearing(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearing())); +} + +jni::Local> LocationIndicatorLayer::getLocation(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getLocation())); +} + +jni::Local> LocationIndicatorLayer::getLocationTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getLocationTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setLocationTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setLocationTransition(options); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadius(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadius())); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setAccuracyRadiusTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setAccuracyRadiusTransition(options); +} + +jni::Local> LocationIndicatorLayer::getTopImageSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getTopImageSize())); +} + +jni::Local> LocationIndicatorLayer::getTopImageSizeTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getTopImageSizeTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setTopImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setTopImageSizeTransition(options); +} + +jni::Local> LocationIndicatorLayer::getBearingImageSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getBearingImageSize())); +} + +jni::Local> LocationIndicatorLayer::getBearingImageSizeTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getBearingImageSizeTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setBearingImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setBearingImageSizeTransition(options); +} + +jni::Local> LocationIndicatorLayer::getShadowImageSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toLocationIndicatorLayer(layer).getShadowImageSize())); +} + +jni::Local> LocationIndicatorLayer::getShadowImageSizeTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getShadowImageSizeTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setShadowImageSizeTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setShadowImageSizeTransition(options); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusColor())); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusColorTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setAccuracyRadiusColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setAccuracyRadiusColorTransition(options); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move( + *convert>>(env, toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColor())); +} + +jni::Local> LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition( + jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toLocationIndicatorLayer(layer).getAccuracyRadiusBorderColorTransition(); + return std::move(*convert>>(env, options)); +} + +void LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toLocationIndicatorLayer(layer).setAccuracyRadiusBorderColorTransition(options); +} + +// LocationIndicatorJavaLayerPeerFactory + +LocationIndicatorJavaLayerPeerFactory::~LocationIndicatorJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new LocationIndicatorLayer(toLocationIndicatorLayer(layer))); +} + +jni::Local> LocationIndicatorJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new LocationIndicatorLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void LocationIndicatorJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&LocationIndicatorLayer::getTopImage, "nativeGetTopImage"), + METHOD(&LocationIndicatorLayer::getBearingImage, "nativeGetBearingImage"), + METHOD(&LocationIndicatorLayer::getShadowImage, "nativeGetShadowImage"), + METHOD(&LocationIndicatorLayer::getPerspectiveCompensation, "nativeGetPerspectiveCompensation"), + METHOD(&LocationIndicatorLayer::getImageTiltDisplacement, "nativeGetImageTiltDisplacement"), + METHOD(&LocationIndicatorLayer::getBearing, "nativeGetBearing"), + METHOD(&LocationIndicatorLayer::getLocationTransition, "nativeGetLocationTransition"), + METHOD(&LocationIndicatorLayer::setLocationTransition, "nativeSetLocationTransition"), + METHOD(&LocationIndicatorLayer::getLocation, "nativeGetLocation"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusTransition, "nativeGetAccuracyRadiusTransition"), + METHOD(&LocationIndicatorLayer::setAccuracyRadiusTransition, "nativeSetAccuracyRadiusTransition"), + METHOD(&LocationIndicatorLayer::getAccuracyRadius, "nativeGetAccuracyRadius"), + METHOD(&LocationIndicatorLayer::getTopImageSizeTransition, "nativeGetTopImageSizeTransition"), + METHOD(&LocationIndicatorLayer::setTopImageSizeTransition, "nativeSetTopImageSizeTransition"), + METHOD(&LocationIndicatorLayer::getTopImageSize, "nativeGetTopImageSize"), + METHOD(&LocationIndicatorLayer::getBearingImageSizeTransition, "nativeGetBearingImageSizeTransition"), + METHOD(&LocationIndicatorLayer::setBearingImageSizeTransition, "nativeSetBearingImageSizeTransition"), + METHOD(&LocationIndicatorLayer::getBearingImageSize, "nativeGetBearingImageSize"), + METHOD(&LocationIndicatorLayer::getShadowImageSizeTransition, "nativeGetShadowImageSizeTransition"), + METHOD(&LocationIndicatorLayer::setShadowImageSizeTransition, "nativeSetShadowImageSizeTransition"), + METHOD(&LocationIndicatorLayer::getShadowImageSize, "nativeGetShadowImageSize"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusColorTransition, "nativeGetAccuracyRadiusColorTransition"), + METHOD(&LocationIndicatorLayer::setAccuracyRadiusColorTransition, "nativeSetAccuracyRadiusColorTransition"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusColor, "nativeGetAccuracyRadiusColor"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusBorderColorTransition, + "nativeGetAccuracyRadiusBorderColorTransition"), + METHOD(&LocationIndicatorLayer::setAccuracyRadiusBorderColorTransition, + "nativeSetAccuracyRadiusBorderColorTransition"), + METHOD(&LocationIndicatorLayer::getAccuracyRadiusBorderColor, "nativeGetAccuracyRadiusBorderColor")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp index 81a20d79318..8da3e556519 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/location_indicator_layer.hpp @@ -68,7 +68,8 @@ class LocationIndicatorLayer : public Layer { }; // class LocationIndicatorLayer -class LocationIndicatorJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::LocationIndicatorLayerFactory { +class LocationIndicatorJavaLayerPeerFactory final : public JavaLayerPeerFactory, + public mbgl::LocationIndicatorLayerFactory { public: ~LocationIndicatorJavaLayerPeerFactory() override; @@ -80,7 +81,7 @@ class LocationIndicatorJavaLayerPeerFactory final : public JavaLayerPeerFactory, LayerFactory* getLayerFactory() final { return this; } -}; // class LocationIndicatorJavaLayerPeerFactory +}; // class LocationIndicatorJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp index 759161aeb1b..d325a615eaa 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.cpp @@ -12,211 +12,212 @@ namespace mbgl { namespace android { - inline mbgl::style::RasterLayer& toRasterLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - RasterLayer::RasterLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - RasterLayer::RasterLayer(mbgl::style::RasterLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - RasterLayer::RasterLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - RasterLayer::~RasterLayer() = default; - - // Property getters - - jni::Local> RasterLayer::getRasterOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterOpacity())); - } - - jni::Local> RasterLayer::getRasterOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterOpacityTransition(options); - } - - jni::Local> RasterLayer::getRasterHueRotate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterHueRotate())); - } - - jni::Local> RasterLayer::getRasterHueRotateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterHueRotateTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterHueRotateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterHueRotateTransition(options); - } - - jni::Local> RasterLayer::getRasterBrightnessMin(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMin())); - } - - jni::Local> RasterLayer::getRasterBrightnessMinTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMinTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterBrightnessMinTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterBrightnessMinTransition(options); - } - - jni::Local> RasterLayer::getRasterBrightnessMax(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMax())); - } - - jni::Local> RasterLayer::getRasterBrightnessMaxTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMaxTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterBrightnessMaxTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterBrightnessMaxTransition(options); - } - - jni::Local> RasterLayer::getRasterSaturation(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterSaturation())); - } - - jni::Local> RasterLayer::getRasterSaturationTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterSaturationTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterSaturationTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterSaturationTransition(options); - } - - jni::Local> RasterLayer::getRasterContrast(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterContrast())); - } - - jni::Local> RasterLayer::getRasterContrastTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterContrastTransition(); - return std::move(*convert>>(env, options)); - } - - void RasterLayer::setRasterContrastTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toRasterLayer(layer).setRasterContrastTransition(options); - } - - jni::Local> RasterLayer::getRasterResampling(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterResampling())); - } - - jni::Local> RasterLayer::getRasterFadeDuration(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toRasterLayer(layer).getRasterFadeDuration())); - } - - - // RasterJavaLayerPeerFactory - - RasterJavaLayerPeerFactory::~RasterJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new RasterLayer(toRasterLayer(layer))); - } - - jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new RasterLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void RasterJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&RasterLayer::getRasterOpacityTransition, "nativeGetRasterOpacityTransition"), - METHOD(&RasterLayer::setRasterOpacityTransition, "nativeSetRasterOpacityTransition"), - METHOD(&RasterLayer::getRasterOpacity, "nativeGetRasterOpacity"), - METHOD(&RasterLayer::getRasterHueRotateTransition, "nativeGetRasterHueRotateTransition"), - METHOD(&RasterLayer::setRasterHueRotateTransition, "nativeSetRasterHueRotateTransition"), - METHOD(&RasterLayer::getRasterHueRotate, "nativeGetRasterHueRotate"), - METHOD(&RasterLayer::getRasterBrightnessMinTransition, "nativeGetRasterBrightnessMinTransition"), - METHOD(&RasterLayer::setRasterBrightnessMinTransition, "nativeSetRasterBrightnessMinTransition"), - METHOD(&RasterLayer::getRasterBrightnessMin, "nativeGetRasterBrightnessMin"), - METHOD(&RasterLayer::getRasterBrightnessMaxTransition, "nativeGetRasterBrightnessMaxTransition"), - METHOD(&RasterLayer::setRasterBrightnessMaxTransition, "nativeSetRasterBrightnessMaxTransition"), - METHOD(&RasterLayer::getRasterBrightnessMax, "nativeGetRasterBrightnessMax"), - METHOD(&RasterLayer::getRasterSaturationTransition, "nativeGetRasterSaturationTransition"), - METHOD(&RasterLayer::setRasterSaturationTransition, "nativeSetRasterSaturationTransition"), - METHOD(&RasterLayer::getRasterSaturation, "nativeGetRasterSaturation"), - METHOD(&RasterLayer::getRasterContrastTransition, "nativeGetRasterContrastTransition"), - METHOD(&RasterLayer::setRasterContrastTransition, "nativeSetRasterContrastTransition"), - METHOD(&RasterLayer::getRasterContrast, "nativeGetRasterContrast"), - METHOD(&RasterLayer::getRasterResampling, "nativeGetRasterResampling"), - METHOD(&RasterLayer::getRasterFadeDuration, "nativeGetRasterFadeDuration")); - } +inline mbgl::style::RasterLayer& toRasterLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +RasterLayer::RasterLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +RasterLayer::RasterLayer(mbgl::style::RasterLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +RasterLayer::RasterLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +RasterLayer::~RasterLayer() = default; + +// Property getters + +jni::Local> RasterLayer::getRasterOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterOpacity())); +} + +jni::Local> RasterLayer::getRasterOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterOpacityTransition(options); +} + +jni::Local> RasterLayer::getRasterHueRotate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterHueRotate())); +} + +jni::Local> RasterLayer::getRasterHueRotateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterHueRotateTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterHueRotateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterHueRotateTransition(options); +} + +jni::Local> RasterLayer::getRasterBrightnessMin(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMin())); +} + +jni::Local> RasterLayer::getRasterBrightnessMinTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMinTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterBrightnessMinTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterBrightnessMinTransition(options); +} + +jni::Local> RasterLayer::getRasterBrightnessMax(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterBrightnessMax())); +} + +jni::Local> RasterLayer::getRasterBrightnessMaxTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterBrightnessMaxTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterBrightnessMaxTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterBrightnessMaxTransition(options); +} + +jni::Local> RasterLayer::getRasterSaturation(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterSaturation())); +} + +jni::Local> RasterLayer::getRasterSaturationTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterSaturationTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterSaturationTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterSaturationTransition(options); +} + +jni::Local> RasterLayer::getRasterContrast(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterContrast())); +} + +jni::Local> RasterLayer::getRasterContrastTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toRasterLayer(layer).getRasterContrastTransition(); + return std::move(*convert>>(env, options)); +} + +void RasterLayer::setRasterContrastTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toRasterLayer(layer).setRasterContrastTransition(options); +} + +jni::Local> RasterLayer::getRasterResampling(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterResampling())); +} + +jni::Local> RasterLayer::getRasterFadeDuration(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toRasterLayer(layer).getRasterFadeDuration())); +} + +// RasterJavaLayerPeerFactory + +RasterJavaLayerPeerFactory::~RasterJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new RasterLayer(toRasterLayer(layer))); +} + +jni::Local> RasterJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new RasterLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void RasterJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&RasterLayer::getRasterOpacityTransition, "nativeGetRasterOpacityTransition"), + METHOD(&RasterLayer::setRasterOpacityTransition, "nativeSetRasterOpacityTransition"), + METHOD(&RasterLayer::getRasterOpacity, "nativeGetRasterOpacity"), + METHOD(&RasterLayer::getRasterHueRotateTransition, "nativeGetRasterHueRotateTransition"), + METHOD(&RasterLayer::setRasterHueRotateTransition, "nativeSetRasterHueRotateTransition"), + METHOD(&RasterLayer::getRasterHueRotate, "nativeGetRasterHueRotate"), + METHOD(&RasterLayer::getRasterBrightnessMinTransition, "nativeGetRasterBrightnessMinTransition"), + METHOD(&RasterLayer::setRasterBrightnessMinTransition, "nativeSetRasterBrightnessMinTransition"), + METHOD(&RasterLayer::getRasterBrightnessMin, "nativeGetRasterBrightnessMin"), + METHOD(&RasterLayer::getRasterBrightnessMaxTransition, "nativeGetRasterBrightnessMaxTransition"), + METHOD(&RasterLayer::setRasterBrightnessMaxTransition, "nativeSetRasterBrightnessMaxTransition"), + METHOD(&RasterLayer::getRasterBrightnessMax, "nativeGetRasterBrightnessMax"), + METHOD(&RasterLayer::getRasterSaturationTransition, "nativeGetRasterSaturationTransition"), + METHOD(&RasterLayer::setRasterSaturationTransition, "nativeSetRasterSaturationTransition"), + METHOD(&RasterLayer::getRasterSaturation, "nativeGetRasterSaturation"), + METHOD(&RasterLayer::getRasterContrastTransition, "nativeGetRasterContrastTransition"), + METHOD(&RasterLayer::setRasterContrastTransition, "nativeSetRasterContrastTransition"), + METHOD(&RasterLayer::getRasterContrast, "nativeGetRasterContrast"), + METHOD(&RasterLayer::getRasterResampling, "nativeGetRasterResampling"), + METHOD(&RasterLayer::getRasterFadeDuration, "nativeGetRasterFadeDuration")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp index 4c3d6b19c96..152f9aeffb3 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/raster_layer.hpp @@ -56,7 +56,7 @@ class RasterLayer : public Layer { }; // class RasterLayer -class RasterJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::RasterLayerFactory { +class RasterJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::RasterLayerFactory { public: ~RasterJavaLayerPeerFactory() override; @@ -68,7 +68,7 @@ class RasterJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class RasterJavaLayerPeerFactory +}; // class RasterJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp index 6abf5fd733f..2068aa4c209 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.cpp @@ -12,583 +12,584 @@ namespace mbgl { namespace android { - inline mbgl::style::SymbolLayer& toSymbolLayer(mbgl::style::Layer& layer) { - return static_cast(layer); - } - - /** - * Creates an owning peer object (for layers not attached to the map) from the JVM side - */ - SymbolLayer::SymbolLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) - : Layer(std::make_unique(jni::Make(env, layerId), jni::Make(env, sourceId))) { - } - - /** - * Creates a non-owning peer object (for layers currently attached to the map) - */ - SymbolLayer::SymbolLayer(mbgl::style::SymbolLayer& coreLayer) - : Layer(coreLayer) { - } - - /** - * Creates an owning peer object (for layers not attached to the map) - */ - SymbolLayer::SymbolLayer(std::unique_ptr coreLayer) - : Layer(std::move(coreLayer)) { - } - - SymbolLayer::~SymbolLayer() = default; - - // Property getters - - jni::Local> SymbolLayer::getSymbolPlacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolPlacement())); - } - - jni::Local> SymbolLayer::getSymbolSpacing(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSpacing())); - } - - jni::Local> SymbolLayer::getSymbolAvoidEdges(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolAvoidEdges())); - } - - jni::Local> SymbolLayer::getSymbolSortKey(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSortKey())); - } - - jni::Local> SymbolLayer::getSymbolZOrder(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolZOrder())); - } - - jni::Local> SymbolLayer::getIconAllowOverlap(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconAllowOverlap())); - } - - jni::Local> SymbolLayer::getIconIgnorePlacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconIgnorePlacement())); - } - - jni::Local> SymbolLayer::getIconOptional(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconOptional())); - } - - jni::Local> SymbolLayer::getIconRotationAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotationAlignment())); - } - - jni::Local> SymbolLayer::getIconSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconSize())); - } - - jni::Local> SymbolLayer::getIconTextFit(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFit())); - } - - jni::Local> SymbolLayer::getIconTextFitPadding(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFitPadding())); - } - - jni::Local> SymbolLayer::getIconImage(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconImage())); - } - - jni::Local> SymbolLayer::getIconRotate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotate())); - } - - jni::Local> SymbolLayer::getIconPadding(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconPadding())); - } - - jni::Local> SymbolLayer::getIconKeepUpright(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconKeepUpright())); - } - - jni::Local> SymbolLayer::getIconOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconOffset())); - } - - jni::Local> SymbolLayer::getIconAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconAnchor())); - } - - jni::Local> SymbolLayer::getIconPitchAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconPitchAlignment())); - } - - jni::Local> SymbolLayer::getTextPitchAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextPitchAlignment())); - } - - jni::Local> SymbolLayer::getTextRotationAlignment(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotationAlignment())); - } - - jni::Local> SymbolLayer::getTextField(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextField())); - } - - jni::Local> SymbolLayer::getTextFont(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextFont())); - } - - jni::Local> SymbolLayer::getTextSize(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextSize())); - } - - jni::Local> SymbolLayer::getTextMaxWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxWidth())); - } - - jni::Local> SymbolLayer::getTextLineHeight(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextLineHeight())); - } - - jni::Local> SymbolLayer::getTextLetterSpacing(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextLetterSpacing())); - } - - jni::Local> SymbolLayer::getTextJustify(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextJustify())); - } - - jni::Local> SymbolLayer::getTextRadialOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextRadialOffset())); - } - - jni::Local> SymbolLayer::getTextVariableAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextVariableAnchor())); - } - - jni::Local> SymbolLayer::getTextAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextAnchor())); - } - - jni::Local> SymbolLayer::getTextMaxAngle(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxAngle())); - } - - jni::Local> SymbolLayer::getTextWritingMode(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextWritingMode())); - } - - jni::Local> SymbolLayer::getTextRotate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotate())); - } - - jni::Local> SymbolLayer::getTextPadding(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextPadding())); - } - - jni::Local> SymbolLayer::getTextKeepUpright(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextKeepUpright())); - } - - jni::Local> SymbolLayer::getTextTransform(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextTransform())); - } - - jni::Local> SymbolLayer::getTextOffset(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextOffset())); - } - - jni::Local> SymbolLayer::getTextAllowOverlap(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextAllowOverlap())); - } - - jni::Local> SymbolLayer::getTextIgnorePlacement(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextIgnorePlacement())); - } - - jni::Local> SymbolLayer::getTextOptional(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextOptional())); - } - - jni::Local> SymbolLayer::getIconOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconOpacity())); - } - - jni::Local> SymbolLayer::getIconOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconOpacityTransition(options); - } - - jni::Local> SymbolLayer::getIconColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconColor())); - } - - jni::Local> SymbolLayer::getIconColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconColorTransition(options); - } - - jni::Local> SymbolLayer::getIconHaloColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloColor())); - } - - jni::Local> SymbolLayer::getIconHaloColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconHaloColorTransition(options); - } - - jni::Local> SymbolLayer::getIconHaloWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloWidth())); - } - - jni::Local> SymbolLayer::getIconHaloWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconHaloWidthTransition(options); - } - - jni::Local> SymbolLayer::getIconHaloBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloBlur())); - } - - jni::Local> SymbolLayer::getIconHaloBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconHaloBlurTransition(options); - } - - jni::Local> SymbolLayer::getIconTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslate())); - } - - jni::Local> SymbolLayer::getIconTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setIconTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setIconTranslateTransition(options); - } - - jni::Local> SymbolLayer::getIconTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslateAnchor())); - } - - jni::Local> SymbolLayer::getTextOpacity(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextOpacity())); - } - - jni::Local> SymbolLayer::getTextOpacityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextOpacityTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextOpacityTransition(options); - } - - jni::Local> SymbolLayer::getTextColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextColor())); - } - - jni::Local> SymbolLayer::getTextColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextColorTransition(options); - } - - jni::Local> SymbolLayer::getTextHaloColor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloColor())); - } - - jni::Local> SymbolLayer::getTextHaloColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloColorTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextHaloColorTransition(options); - } - - jni::Local> SymbolLayer::getTextHaloWidth(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloWidth())); - } - - jni::Local> SymbolLayer::getTextHaloWidthTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloWidthTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextHaloWidthTransition(options); - } - - jni::Local> SymbolLayer::getTextHaloBlur(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloBlur())); - } - - jni::Local> SymbolLayer::getTextHaloBlurTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloBlurTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextHaloBlurTransition(options); - } - - jni::Local> SymbolLayer::getTextTranslate(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslate())); - } - - jni::Local> SymbolLayer::getTextTranslateTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextTranslateTransition(); - return std::move(*convert>>(env, options)); - } - - void SymbolLayer::setTextTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - toSymbolLayer(layer).setTextTranslateTransition(options); - } - - jni::Local> SymbolLayer::getTextTranslateAnchor(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslateAnchor())); - } - - - // SymbolJavaLayerPeerFactory - - SymbolJavaLayerPeerFactory::~SymbolJavaLayerPeerFactory() = default; - - namespace { - jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(layer)); - } - } // namespace - - jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, mbgl::style::Layer& layer) { - assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new SymbolLayer(toSymbolLayer(layer))); - } - - jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, std::unique_ptr layer) { - assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); - return createJavaPeer(env, new SymbolLayer(std::unique_ptr(static_cast(layer.release())))); - } - - void SymbolJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - jni::MakePeer, - "initialize", - "finalize", - METHOD(&SymbolLayer::getSymbolPlacement, "nativeGetSymbolPlacement"), - METHOD(&SymbolLayer::getSymbolSpacing, "nativeGetSymbolSpacing"), - METHOD(&SymbolLayer::getSymbolAvoidEdges, "nativeGetSymbolAvoidEdges"), - METHOD(&SymbolLayer::getSymbolSortKey, "nativeGetSymbolSortKey"), - METHOD(&SymbolLayer::getSymbolZOrder, "nativeGetSymbolZOrder"), - METHOD(&SymbolLayer::getIconAllowOverlap, "nativeGetIconAllowOverlap"), - METHOD(&SymbolLayer::getIconIgnorePlacement, "nativeGetIconIgnorePlacement"), - METHOD(&SymbolLayer::getIconOptional, "nativeGetIconOptional"), - METHOD(&SymbolLayer::getIconRotationAlignment, "nativeGetIconRotationAlignment"), - METHOD(&SymbolLayer::getIconSize, "nativeGetIconSize"), - METHOD(&SymbolLayer::getIconTextFit, "nativeGetIconTextFit"), - METHOD(&SymbolLayer::getIconTextFitPadding, "nativeGetIconTextFitPadding"), - METHOD(&SymbolLayer::getIconImage, "nativeGetIconImage"), - METHOD(&SymbolLayer::getIconRotate, "nativeGetIconRotate"), - METHOD(&SymbolLayer::getIconPadding, "nativeGetIconPadding"), - METHOD(&SymbolLayer::getIconKeepUpright, "nativeGetIconKeepUpright"), - METHOD(&SymbolLayer::getIconOffset, "nativeGetIconOffset"), - METHOD(&SymbolLayer::getIconAnchor, "nativeGetIconAnchor"), - METHOD(&SymbolLayer::getIconPitchAlignment, "nativeGetIconPitchAlignment"), - METHOD(&SymbolLayer::getTextPitchAlignment, "nativeGetTextPitchAlignment"), - METHOD(&SymbolLayer::getTextRotationAlignment, "nativeGetTextRotationAlignment"), - METHOD(&SymbolLayer::getTextField, "nativeGetTextField"), - METHOD(&SymbolLayer::getTextFont, "nativeGetTextFont"), - METHOD(&SymbolLayer::getTextSize, "nativeGetTextSize"), - METHOD(&SymbolLayer::getTextMaxWidth, "nativeGetTextMaxWidth"), - METHOD(&SymbolLayer::getTextLineHeight, "nativeGetTextLineHeight"), - METHOD(&SymbolLayer::getTextLetterSpacing, "nativeGetTextLetterSpacing"), - METHOD(&SymbolLayer::getTextJustify, "nativeGetTextJustify"), - METHOD(&SymbolLayer::getTextRadialOffset, "nativeGetTextRadialOffset"), - METHOD(&SymbolLayer::getTextVariableAnchor, "nativeGetTextVariableAnchor"), - METHOD(&SymbolLayer::getTextAnchor, "nativeGetTextAnchor"), - METHOD(&SymbolLayer::getTextMaxAngle, "nativeGetTextMaxAngle"), - METHOD(&SymbolLayer::getTextWritingMode, "nativeGetTextWritingMode"), - METHOD(&SymbolLayer::getTextRotate, "nativeGetTextRotate"), - METHOD(&SymbolLayer::getTextPadding, "nativeGetTextPadding"), - METHOD(&SymbolLayer::getTextKeepUpright, "nativeGetTextKeepUpright"), - METHOD(&SymbolLayer::getTextTransform, "nativeGetTextTransform"), - METHOD(&SymbolLayer::getTextOffset, "nativeGetTextOffset"), - METHOD(&SymbolLayer::getTextAllowOverlap, "nativeGetTextAllowOverlap"), - METHOD(&SymbolLayer::getTextIgnorePlacement, "nativeGetTextIgnorePlacement"), - METHOD(&SymbolLayer::getTextOptional, "nativeGetTextOptional"), - METHOD(&SymbolLayer::getIconOpacityTransition, "nativeGetIconOpacityTransition"), - METHOD(&SymbolLayer::setIconOpacityTransition, "nativeSetIconOpacityTransition"), - METHOD(&SymbolLayer::getIconOpacity, "nativeGetIconOpacity"), - METHOD(&SymbolLayer::getIconColorTransition, "nativeGetIconColorTransition"), - METHOD(&SymbolLayer::setIconColorTransition, "nativeSetIconColorTransition"), - METHOD(&SymbolLayer::getIconColor, "nativeGetIconColor"), - METHOD(&SymbolLayer::getIconHaloColorTransition, "nativeGetIconHaloColorTransition"), - METHOD(&SymbolLayer::setIconHaloColorTransition, "nativeSetIconHaloColorTransition"), - METHOD(&SymbolLayer::getIconHaloColor, "nativeGetIconHaloColor"), - METHOD(&SymbolLayer::getIconHaloWidthTransition, "nativeGetIconHaloWidthTransition"), - METHOD(&SymbolLayer::setIconHaloWidthTransition, "nativeSetIconHaloWidthTransition"), - METHOD(&SymbolLayer::getIconHaloWidth, "nativeGetIconHaloWidth"), - METHOD(&SymbolLayer::getIconHaloBlurTransition, "nativeGetIconHaloBlurTransition"), - METHOD(&SymbolLayer::setIconHaloBlurTransition, "nativeSetIconHaloBlurTransition"), - METHOD(&SymbolLayer::getIconHaloBlur, "nativeGetIconHaloBlur"), - METHOD(&SymbolLayer::getIconTranslateTransition, "nativeGetIconTranslateTransition"), - METHOD(&SymbolLayer::setIconTranslateTransition, "nativeSetIconTranslateTransition"), - METHOD(&SymbolLayer::getIconTranslate, "nativeGetIconTranslate"), - METHOD(&SymbolLayer::getIconTranslateAnchor, "nativeGetIconTranslateAnchor"), - METHOD(&SymbolLayer::getTextOpacityTransition, "nativeGetTextOpacityTransition"), - METHOD(&SymbolLayer::setTextOpacityTransition, "nativeSetTextOpacityTransition"), - METHOD(&SymbolLayer::getTextOpacity, "nativeGetTextOpacity"), - METHOD(&SymbolLayer::getTextColorTransition, "nativeGetTextColorTransition"), - METHOD(&SymbolLayer::setTextColorTransition, "nativeSetTextColorTransition"), - METHOD(&SymbolLayer::getTextColor, "nativeGetTextColor"), - METHOD(&SymbolLayer::getTextHaloColorTransition, "nativeGetTextHaloColorTransition"), - METHOD(&SymbolLayer::setTextHaloColorTransition, "nativeSetTextHaloColorTransition"), - METHOD(&SymbolLayer::getTextHaloColor, "nativeGetTextHaloColor"), - METHOD(&SymbolLayer::getTextHaloWidthTransition, "nativeGetTextHaloWidthTransition"), - METHOD(&SymbolLayer::setTextHaloWidthTransition, "nativeSetTextHaloWidthTransition"), - METHOD(&SymbolLayer::getTextHaloWidth, "nativeGetTextHaloWidth"), - METHOD(&SymbolLayer::getTextHaloBlurTransition, "nativeGetTextHaloBlurTransition"), - METHOD(&SymbolLayer::setTextHaloBlurTransition, "nativeSetTextHaloBlurTransition"), - METHOD(&SymbolLayer::getTextHaloBlur, "nativeGetTextHaloBlur"), - METHOD(&SymbolLayer::getTextTranslateTransition, "nativeGetTextTranslateTransition"), - METHOD(&SymbolLayer::setTextTranslateTransition, "nativeSetTextTranslateTransition"), - METHOD(&SymbolLayer::getTextTranslate, "nativeGetTextTranslate"), - METHOD(&SymbolLayer::getTextTranslateAnchor, "nativeGetTextTranslateAnchor")); - } +inline mbgl::style::SymbolLayer& toSymbolLayer(mbgl::style::Layer& layer) { + return static_cast(layer); +} + +/** + * Creates an owning peer object (for layers not attached to the map) from the JVM side + */ +SymbolLayer::SymbolLayer(jni::JNIEnv& env, jni::String& layerId, jni::String& sourceId) + : Layer(std::make_unique(jni::Make(env, layerId), + jni::Make(env, sourceId))) {} + +/** + * Creates a non-owning peer object (for layers currently attached to the map) + */ +SymbolLayer::SymbolLayer(mbgl::style::SymbolLayer& coreLayer) + : Layer(coreLayer) {} + +/** + * Creates an owning peer object (for layers not attached to the map) + */ +SymbolLayer::SymbolLayer(std::unique_ptr coreLayer) + : Layer(std::move(coreLayer)) {} + +SymbolLayer::~SymbolLayer() = default; + +// Property getters + +jni::Local> SymbolLayer::getSymbolPlacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolPlacement())); +} + +jni::Local> SymbolLayer::getSymbolSpacing(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSpacing())); +} + +jni::Local> SymbolLayer::getSymbolAvoidEdges(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolAvoidEdges())); +} + +jni::Local> SymbolLayer::getSymbolSortKey(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolSortKey())); +} + +jni::Local> SymbolLayer::getSymbolZOrder(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getSymbolZOrder())); +} + +jni::Local> SymbolLayer::getIconAllowOverlap(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconAllowOverlap())); +} + +jni::Local> SymbolLayer::getIconIgnorePlacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconIgnorePlacement())); +} + +jni::Local> SymbolLayer::getIconOptional(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconOptional())); +} + +jni::Local> SymbolLayer::getIconRotationAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotationAlignment())); +} + +jni::Local> SymbolLayer::getIconSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconSize())); +} + +jni::Local> SymbolLayer::getIconTextFit(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFit())); +} + +jni::Local> SymbolLayer::getIconTextFitPadding(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTextFitPadding())); +} + +jni::Local> SymbolLayer::getIconImage(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconImage())); +} + +jni::Local> SymbolLayer::getIconRotate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconRotate())); +} + +jni::Local> SymbolLayer::getIconPadding(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconPadding())); +} + +jni::Local> SymbolLayer::getIconKeepUpright(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconKeepUpright())); +} + +jni::Local> SymbolLayer::getIconOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconOffset())); +} + +jni::Local> SymbolLayer::getIconAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconAnchor())); +} + +jni::Local> SymbolLayer::getIconPitchAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconPitchAlignment())); +} + +jni::Local> SymbolLayer::getTextPitchAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextPitchAlignment())); +} + +jni::Local> SymbolLayer::getTextRotationAlignment(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotationAlignment())); +} + +jni::Local> SymbolLayer::getTextField(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextField())); +} + +jni::Local> SymbolLayer::getTextFont(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextFont())); +} + +jni::Local> SymbolLayer::getTextSize(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextSize())); +} + +jni::Local> SymbolLayer::getTextMaxWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxWidth())); +} + +jni::Local> SymbolLayer::getTextLineHeight(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextLineHeight())); +} + +jni::Local> SymbolLayer::getTextLetterSpacing(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextLetterSpacing())); +} + +jni::Local> SymbolLayer::getTextJustify(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextJustify())); +} + +jni::Local> SymbolLayer::getTextRadialOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextRadialOffset())); +} + +jni::Local> SymbolLayer::getTextVariableAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextVariableAnchor())); +} + +jni::Local> SymbolLayer::getTextAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextAnchor())); +} + +jni::Local> SymbolLayer::getTextMaxAngle(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextMaxAngle())); +} + +jni::Local> SymbolLayer::getTextWritingMode(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextWritingMode())); +} + +jni::Local> SymbolLayer::getTextRotate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextRotate())); +} + +jni::Local> SymbolLayer::getTextPadding(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextPadding())); +} + +jni::Local> SymbolLayer::getTextKeepUpright(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextKeepUpright())); +} + +jni::Local> SymbolLayer::getTextTransform(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextTransform())); +} + +jni::Local> SymbolLayer::getTextOffset(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextOffset())); +} + +jni::Local> SymbolLayer::getTextAllowOverlap(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextAllowOverlap())); +} + +jni::Local> SymbolLayer::getTextIgnorePlacement(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextIgnorePlacement())); +} + +jni::Local> SymbolLayer::getTextOptional(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextOptional())); +} + +jni::Local> SymbolLayer::getIconOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconOpacity())); +} + +jni::Local> SymbolLayer::getIconOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconOpacityTransition(options); +} + +jni::Local> SymbolLayer::getIconColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconColor())); +} + +jni::Local> SymbolLayer::getIconColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconColorTransition(options); +} + +jni::Local> SymbolLayer::getIconHaloColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloColor())); +} + +jni::Local> SymbolLayer::getIconHaloColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconHaloColorTransition(options); +} + +jni::Local> SymbolLayer::getIconHaloWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloWidth())); +} + +jni::Local> SymbolLayer::getIconHaloWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconHaloWidthTransition(options); +} + +jni::Local> SymbolLayer::getIconHaloBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconHaloBlur())); +} + +jni::Local> SymbolLayer::getIconHaloBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconHaloBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconHaloBlurTransition(options); +} + +jni::Local> SymbolLayer::getIconTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslate())); +} + +jni::Local> SymbolLayer::getIconTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getIconTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setIconTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setIconTranslateTransition(options); +} + +jni::Local> SymbolLayer::getIconTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getIconTranslateAnchor())); +} + +jni::Local> SymbolLayer::getTextOpacity(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextOpacity())); +} + +jni::Local> SymbolLayer::getTextOpacityTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextOpacityTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextOpacityTransition(options); +} + +jni::Local> SymbolLayer::getTextColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextColor())); +} + +jni::Local> SymbolLayer::getTextColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextColorTransition(options); +} + +jni::Local> SymbolLayer::getTextHaloColor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloColor())); +} + +jni::Local> SymbolLayer::getTextHaloColorTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloColorTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextHaloColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextHaloColorTransition(options); +} + +jni::Local> SymbolLayer::getTextHaloWidth(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloWidth())); +} + +jni::Local> SymbolLayer::getTextHaloWidthTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloWidthTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextHaloWidthTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextHaloWidthTransition(options); +} + +jni::Local> SymbolLayer::getTextHaloBlur(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextHaloBlur())); +} + +jni::Local> SymbolLayer::getTextHaloBlurTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextHaloBlurTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextHaloBlurTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextHaloBlurTransition(options); +} + +jni::Local> SymbolLayer::getTextTranslate(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslate())); +} + +jni::Local> SymbolLayer::getTextTranslateTransition(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = toSymbolLayer(layer).getTextTranslateTransition(); + return std::move(*convert>>(env, options)); +} + +void SymbolLayer::setTextTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay) { + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + toSymbolLayer(layer).setTextTranslateTransition(options); +} + +jni::Local> SymbolLayer::getTextTranslateAnchor(jni::JNIEnv& env) { + using namespace mbgl::android::conversion; + return std::move(*convert>>(env, toSymbolLayer(layer).getTextTranslateAnchor())); +} + +// SymbolJavaLayerPeerFactory + +SymbolJavaLayerPeerFactory::~SymbolJavaLayerPeerFactory() = default; + +namespace { +jni::Local> createJavaPeer(jni::JNIEnv& env, Layer* layer) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(layer)); +} +} // namespace + +jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer(jni::JNIEnv& env, + mbgl::style::Layer& layer) { + assert(layer.baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, new SymbolLayer(toSymbolLayer(layer))); +} + +jni::Local> SymbolJavaLayerPeerFactory::createJavaLayerPeer( + jni::JNIEnv& env, std::unique_ptr layer) { + assert(layer->baseImpl->getTypeInfo() == getTypeInfo()); + return createJavaPeer(env, + new SymbolLayer(std::unique_ptr( + static_cast(layer.release())))); +} + +void SymbolJavaLayerPeerFactory::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer, + "initialize", + "finalize", + METHOD(&SymbolLayer::getSymbolPlacement, "nativeGetSymbolPlacement"), + METHOD(&SymbolLayer::getSymbolSpacing, "nativeGetSymbolSpacing"), + METHOD(&SymbolLayer::getSymbolAvoidEdges, "nativeGetSymbolAvoidEdges"), + METHOD(&SymbolLayer::getSymbolSortKey, "nativeGetSymbolSortKey"), + METHOD(&SymbolLayer::getSymbolZOrder, "nativeGetSymbolZOrder"), + METHOD(&SymbolLayer::getIconAllowOverlap, "nativeGetIconAllowOverlap"), + METHOD(&SymbolLayer::getIconIgnorePlacement, "nativeGetIconIgnorePlacement"), + METHOD(&SymbolLayer::getIconOptional, "nativeGetIconOptional"), + METHOD(&SymbolLayer::getIconRotationAlignment, "nativeGetIconRotationAlignment"), + METHOD(&SymbolLayer::getIconSize, "nativeGetIconSize"), + METHOD(&SymbolLayer::getIconTextFit, "nativeGetIconTextFit"), + METHOD(&SymbolLayer::getIconTextFitPadding, "nativeGetIconTextFitPadding"), + METHOD(&SymbolLayer::getIconImage, "nativeGetIconImage"), + METHOD(&SymbolLayer::getIconRotate, "nativeGetIconRotate"), + METHOD(&SymbolLayer::getIconPadding, "nativeGetIconPadding"), + METHOD(&SymbolLayer::getIconKeepUpright, "nativeGetIconKeepUpright"), + METHOD(&SymbolLayer::getIconOffset, "nativeGetIconOffset"), + METHOD(&SymbolLayer::getIconAnchor, "nativeGetIconAnchor"), + METHOD(&SymbolLayer::getIconPitchAlignment, "nativeGetIconPitchAlignment"), + METHOD(&SymbolLayer::getTextPitchAlignment, "nativeGetTextPitchAlignment"), + METHOD(&SymbolLayer::getTextRotationAlignment, "nativeGetTextRotationAlignment"), + METHOD(&SymbolLayer::getTextField, "nativeGetTextField"), + METHOD(&SymbolLayer::getTextFont, "nativeGetTextFont"), + METHOD(&SymbolLayer::getTextSize, "nativeGetTextSize"), + METHOD(&SymbolLayer::getTextMaxWidth, "nativeGetTextMaxWidth"), + METHOD(&SymbolLayer::getTextLineHeight, "nativeGetTextLineHeight"), + METHOD(&SymbolLayer::getTextLetterSpacing, "nativeGetTextLetterSpacing"), + METHOD(&SymbolLayer::getTextJustify, "nativeGetTextJustify"), + METHOD(&SymbolLayer::getTextRadialOffset, "nativeGetTextRadialOffset"), + METHOD(&SymbolLayer::getTextVariableAnchor, "nativeGetTextVariableAnchor"), + METHOD(&SymbolLayer::getTextAnchor, "nativeGetTextAnchor"), + METHOD(&SymbolLayer::getTextMaxAngle, "nativeGetTextMaxAngle"), + METHOD(&SymbolLayer::getTextWritingMode, "nativeGetTextWritingMode"), + METHOD(&SymbolLayer::getTextRotate, "nativeGetTextRotate"), + METHOD(&SymbolLayer::getTextPadding, "nativeGetTextPadding"), + METHOD(&SymbolLayer::getTextKeepUpright, "nativeGetTextKeepUpright"), + METHOD(&SymbolLayer::getTextTransform, "nativeGetTextTransform"), + METHOD(&SymbolLayer::getTextOffset, "nativeGetTextOffset"), + METHOD(&SymbolLayer::getTextAllowOverlap, "nativeGetTextAllowOverlap"), + METHOD(&SymbolLayer::getTextIgnorePlacement, "nativeGetTextIgnorePlacement"), + METHOD(&SymbolLayer::getTextOptional, "nativeGetTextOptional"), + METHOD(&SymbolLayer::getIconOpacityTransition, "nativeGetIconOpacityTransition"), + METHOD(&SymbolLayer::setIconOpacityTransition, "nativeSetIconOpacityTransition"), + METHOD(&SymbolLayer::getIconOpacity, "nativeGetIconOpacity"), + METHOD(&SymbolLayer::getIconColorTransition, "nativeGetIconColorTransition"), + METHOD(&SymbolLayer::setIconColorTransition, "nativeSetIconColorTransition"), + METHOD(&SymbolLayer::getIconColor, "nativeGetIconColor"), + METHOD(&SymbolLayer::getIconHaloColorTransition, "nativeGetIconHaloColorTransition"), + METHOD(&SymbolLayer::setIconHaloColorTransition, "nativeSetIconHaloColorTransition"), + METHOD(&SymbolLayer::getIconHaloColor, "nativeGetIconHaloColor"), + METHOD(&SymbolLayer::getIconHaloWidthTransition, "nativeGetIconHaloWidthTransition"), + METHOD(&SymbolLayer::setIconHaloWidthTransition, "nativeSetIconHaloWidthTransition"), + METHOD(&SymbolLayer::getIconHaloWidth, "nativeGetIconHaloWidth"), + METHOD(&SymbolLayer::getIconHaloBlurTransition, "nativeGetIconHaloBlurTransition"), + METHOD(&SymbolLayer::setIconHaloBlurTransition, "nativeSetIconHaloBlurTransition"), + METHOD(&SymbolLayer::getIconHaloBlur, "nativeGetIconHaloBlur"), + METHOD(&SymbolLayer::getIconTranslateTransition, "nativeGetIconTranslateTransition"), + METHOD(&SymbolLayer::setIconTranslateTransition, "nativeSetIconTranslateTransition"), + METHOD(&SymbolLayer::getIconTranslate, "nativeGetIconTranslate"), + METHOD(&SymbolLayer::getIconTranslateAnchor, "nativeGetIconTranslateAnchor"), + METHOD(&SymbolLayer::getTextOpacityTransition, "nativeGetTextOpacityTransition"), + METHOD(&SymbolLayer::setTextOpacityTransition, "nativeSetTextOpacityTransition"), + METHOD(&SymbolLayer::getTextOpacity, "nativeGetTextOpacity"), + METHOD(&SymbolLayer::getTextColorTransition, "nativeGetTextColorTransition"), + METHOD(&SymbolLayer::setTextColorTransition, "nativeSetTextColorTransition"), + METHOD(&SymbolLayer::getTextColor, "nativeGetTextColor"), + METHOD(&SymbolLayer::getTextHaloColorTransition, "nativeGetTextHaloColorTransition"), + METHOD(&SymbolLayer::setTextHaloColorTransition, "nativeSetTextHaloColorTransition"), + METHOD(&SymbolLayer::getTextHaloColor, "nativeGetTextHaloColor"), + METHOD(&SymbolLayer::getTextHaloWidthTransition, "nativeGetTextHaloWidthTransition"), + METHOD(&SymbolLayer::setTextHaloWidthTransition, "nativeSetTextHaloWidthTransition"), + METHOD(&SymbolLayer::getTextHaloWidth, "nativeGetTextHaloWidth"), + METHOD(&SymbolLayer::getTextHaloBlurTransition, "nativeGetTextHaloBlurTransition"), + METHOD(&SymbolLayer::setTextHaloBlurTransition, "nativeSetTextHaloBlurTransition"), + METHOD(&SymbolLayer::getTextHaloBlur, "nativeGetTextHaloBlur"), + METHOD(&SymbolLayer::getTextTranslateTransition, "nativeGetTextTranslateTransition"), + METHOD(&SymbolLayer::setTextTranslateTransition, "nativeSetTextTranslateTransition"), + METHOD(&SymbolLayer::getTextTranslate, "nativeGetTextTranslate"), + METHOD(&SymbolLayer::getTextTranslateAnchor, "nativeGetTextTranslateAnchor")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp index f51cdb4e323..382c3865387 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/layers/symbol_layer.hpp @@ -162,7 +162,7 @@ class SymbolLayer : public Layer { }; // class SymbolLayer -class SymbolJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::SymbolLayerFactory { +class SymbolJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mbgl::SymbolLayerFactory { public: ~SymbolJavaLayerPeerFactory() override; @@ -174,7 +174,7 @@ class SymbolJavaLayerPeerFactory final : public JavaLayerPeerFactory, public mb LayerFactory* getLayerFactory() final { return this; } -}; // class SymbolJavaLayerPeerFactory +}; // class SymbolJavaLayerPeerFactory } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp index d8ed4d9d963..e5f5104328f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.cpp @@ -7,8 +7,8 @@ namespace mbgl { namespace android { Light::Light(mbgl::Map& coreMap, mbgl::style::Light& coreLight) - : light(coreLight) , map(&coreMap) { -} + : light(coreLight), + map(&coreMap) {} static Light* initializeLightPeer(mbgl::Map& map, mbgl::style::Light& coreLight) { return new Light(map, coreLight); @@ -58,16 +58,16 @@ jni::Local> Light::getPosition(jni::JNIEnv& env) { } jni::Local> Light::getPositionTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = light.getPositionTransition(); - return std::move(*convert>>(env, options)); + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = light.getPositionTransition(); + return std::move(*convert>>(env, options)); } void Light::setPositionTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - light.setPositionTransition(options); + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + light.setPositionTransition(options); } void Light::setColor(jni::JNIEnv& env, const jni::String& property) { @@ -77,22 +77,22 @@ void Light::setColor(jni::JNIEnv& env, const jni::String& property) { } } -jni::Local Light::getColor(jni::JNIEnv &env) { +jni::Local Light::getColor(jni::JNIEnv& env) { auto color = light.getColor().asConstant(); return jni::Make(env, color.stringify()); } jni::Local> Light::getColorTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = light.getColorTransition(); - return std::move(*convert>>(env, options)); + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = light.getColorTransition(); + return std::move(*convert>>(env, options)); } void Light::setColorTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - light.setColorTransition(options); + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + light.setColorTransition(options); } void Light::setIntensity(jni::JNIEnv&, jni::jfloat property) { @@ -104,16 +104,16 @@ jni::jfloat Light::getIntensity(jni::JNIEnv&) { } jni::Local> Light::getIntensityTransition(jni::JNIEnv& env) { - using namespace mbgl::android::conversion; - mbgl::style::TransitionOptions options = light.getIntensityTransition(); - return std::move(*convert>>(env, options)); + using namespace mbgl::android::conversion; + mbgl::style::TransitionOptions options = light.getIntensityTransition(); + return std::move(*convert>>(env, options)); } void Light::setIntensityTransition(jni::JNIEnv&, jlong duration, jlong delay) { - mbgl::style::TransitionOptions options; - options.duration.emplace(mbgl::Milliseconds(duration)); - options.delay.emplace(mbgl::Milliseconds(delay)); - light.setIntensityTransition(options); + mbgl::style::TransitionOptions options; + options.duration.emplace(mbgl::Milliseconds(duration)); + options.delay.emplace(mbgl::Milliseconds(delay)); + light.setIntensityTransition(options); } void Light::registerNative(jni::JNIEnv& env) { @@ -122,22 +122,24 @@ void Light::registerNative(jni::JNIEnv& env) { #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) // Register the peer - jni::RegisterNativePeer(env, javaClass, "nativePtr", - METHOD(&Light::getAnchor, "nativeGetAnchor"), - METHOD(&Light::setAnchor, "nativeSetAnchor"), - METHOD(&Light::getPositionTransition, "nativeGetPositionTransition"), - METHOD(&Light::setPositionTransition, "nativeSetPositionTransition"), - METHOD(&Light::getPosition, "nativeGetPosition"), - METHOD(&Light::setPosition, "nativeSetPosition"), - METHOD(&Light::getColorTransition, "nativeGetColorTransition"), - METHOD(&Light::setColorTransition, "nativeSetColorTransition"), - METHOD(&Light::getColor, "nativeGetColor"), - METHOD(&Light::setColor, "nativeSetColor"), - METHOD(&Light::getIntensityTransition, "nativeGetIntensityTransition"), - METHOD(&Light::setIntensityTransition, "nativeSetIntensityTransition"), - METHOD(&Light::getIntensity, "nativeGetIntensity"), - METHOD(&Light::setIntensity, "nativeSetIntensity")); + jni::RegisterNativePeer(env, + javaClass, + "nativePtr", + METHOD(&Light::getAnchor, "nativeGetAnchor"), + METHOD(&Light::setAnchor, "nativeSetAnchor"), + METHOD(&Light::getPositionTransition, "nativeGetPositionTransition"), + METHOD(&Light::setPositionTransition, "nativeSetPositionTransition"), + METHOD(&Light::getPosition, "nativeGetPosition"), + METHOD(&Light::setPosition, "nativeSetPosition"), + METHOD(&Light::getColorTransition, "nativeGetColorTransition"), + METHOD(&Light::setColorTransition, "nativeSetColorTransition"), + METHOD(&Light::getColor, "nativeGetColor"), + METHOD(&Light::setColor, "nativeSetColor"), + METHOD(&Light::getIntensityTransition, "nativeGetIntensityTransition"), + METHOD(&Light::setIntensityTransition, "nativeSetIntensityTransition"), + METHOD(&Light::getIntensity, "nativeGetIntensity"), + METHOD(&Light::setIntensity, "nativeSetIntensity")); } } // namespace android -} // namespace mb +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp index 97767c4f761..d21849a3686 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/light.hpp @@ -16,7 +16,6 @@ using namespace style; class Light : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/light/Light"; }; static void registerNative(jni::JNIEnv&); @@ -42,7 +41,6 @@ class Light : private mbgl::util::noncopyable { jni::Local> createJavaPeer(jni::JNIEnv&); protected: - // Raw reference to the light mbgl::style::Light& light; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp index 326310be075..1c19805ba47 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/position.cpp @@ -3,9 +3,12 @@ namespace mbgl { namespace android { -jni::Local> Position::fromPosition(jni::JNIEnv& env, jfloat radialCoordinate, jfloat azimuthalAngle, jfloat polarAngle) { +jni::Local> Position::fromPosition(jni::JNIEnv& env, + jfloat radialCoordinate, + jfloat azimuthalAngle, + jfloat polarAngle) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jfloat, jfloat, jfloat)>(env, "fromPosition"); + static auto method = javaClass.GetStaticMethod(jfloat, jfloat, jfloat)>(env, "fromPosition"); return javaClass.Call(env, method, radialCoordinate, azimuthalAngle, polarAngle); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp index 679201deddf..79b3116efcb 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.cpp @@ -18,192 +18,196 @@ namespace mbgl { namespace android { - // This conversion is expected not to fail because it's used only in contexts where - // the value was originally a CustomGeometrySourceOptions object on the Java side. If it fails - // to convert, it's a bug in our serialization or Java-side static typing. - static style::CustomGeometrySource::Options convertCustomGeometrySourceOptions(jni::JNIEnv& env, - const jni::Object<>& options, - style::TileFunction fetchFn, - style::TileFunction cancelFn) { - using namespace mbgl::style::conversion; - if (!options) { - return style::CustomGeometrySource::Options(); - } - Error error; - std::optional result = convert(Value(env, options), error); - if (!result) { - throw std::logic_error(error.message); - } - result->fetchTileFunction = fetchFn; - result->cancelTileFunction = cancelFn; - return *result; +// This conversion is expected not to fail because it's used only in contexts +// where the value was originally a CustomGeometrySourceOptions object on the +// Java side. If it fails to convert, it's a bug in our serialization or +// Java-side static typing. +static style::CustomGeometrySource::Options convertCustomGeometrySourceOptions(jni::JNIEnv& env, + const jni::Object<>& options, + style::TileFunction fetchFn, + style::TileFunction cancelFn) { + using namespace mbgl::style::conversion; + if (!options) { + return style::CustomGeometrySource::Options(); } - - CustomGeometrySource::CustomGeometrySource(jni::JNIEnv& env, - const jni::String& sourceId, - const jni::Object<>& options) - : Source(env, std::make_unique( - jni::Make(env, sourceId), - convertCustomGeometrySourceOptions(env, options, - std::bind(&CustomGeometrySource::fetchTile, this, std::placeholders::_1), - std::bind(&CustomGeometrySource::cancelTile, this, std::placeholders::_1)))) { + Error error; + std::optional result = convert( + Value(env, options), error); + if (!result) { + throw std::logic_error(error.message); } - - CustomGeometrySource::CustomGeometrySource(jni::JNIEnv& env, - mbgl::style::Source& coreSource, - AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - CustomGeometrySource::~CustomGeometrySource() { - releaseThreads(); + result->fetchTileFunction = fetchFn; + result->cancelTileFunction = cancelFn; + return *result; +} + +CustomGeometrySource::CustomGeometrySource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& options) + : Source(env, + std::make_unique( + jni::Make(env, sourceId), + convertCustomGeometrySourceOptions( + env, + options, + std::bind(&CustomGeometrySource::fetchTile, this, std::placeholders::_1), + std::bind(&CustomGeometrySource::cancelTile, this, std::placeholders::_1)))) {} + +CustomGeometrySource::CustomGeometrySource(jni::JNIEnv& env, + mbgl::style::Source& coreSource, + AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +CustomGeometrySource::~CustomGeometrySource() { + releaseThreads(); +} + +void CustomGeometrySource::fetchTile(const mbgl::CanonicalTileID& tileID) { + android::UniqueEnv _env = android::AttachEnv(); + + static auto& javaClass = jni::Class::Singleton(*_env); + static auto fetchTile = javaClass.GetMethod(*_env, "fetchTile"); + + // The source is removed on the main thread, but it still exists on the Render + // thread until the frame is complete. This might cause fetchTile/cancelTile + // invocations when the Java thread is shutting down and the peer has already + // been released. See https://github.com/mapbox/mapbox-gl-native/issues/12551. + if (!javaPeer) { + return; } - void CustomGeometrySource::fetchTile (const mbgl::CanonicalTileID& tileID) { - android::UniqueEnv _env = android::AttachEnv(); + auto peer = jni::Cast(*_env, javaClass, javaPeer); + peer.Call(*_env, fetchTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); +}; - static auto& javaClass = jni::Class::Singleton(*_env); - static auto fetchTile = javaClass.GetMethod(*_env, "fetchTile"); +void CustomGeometrySource::cancelTile(const mbgl::CanonicalTileID& tileID) { + android::UniqueEnv _env = android::AttachEnv(); - // The source is removed on the main thread, but it still exists on the Render thread until the frame is complete. - // This might cause fetchTile/cancelTile invocations when the Java thread is shutting down and the peer has already been released. - // See https://github.com/mapbox/mapbox-gl-native/issues/12551. - if(!javaPeer) { - return; - } + static auto& javaClass = jni::Class::Singleton(*_env); + static auto cancelTile = javaClass.GetMethod(*_env, "cancelTile"); - auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, fetchTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); - }; + // The source is removed on the main thread, but it still exists on the Render + // thread until the frame is complete. This might cause fetchTile/cancelTile + // invocations when the Java thread is shutting down and the peer has already + // been released. See https://github.com/mapbox/mapbox-gl-native/issues/12551. + if (!javaPeer) { + return; + } - void CustomGeometrySource::cancelTile(const mbgl::CanonicalTileID& tileID) { - android::UniqueEnv _env = android::AttachEnv(); + auto peer = jni::Cast(*_env, javaClass, javaPeer); + peer.Call(*_env, cancelTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); +}; - static auto& javaClass = jni::Class::Singleton(*_env); - static auto cancelTile = javaClass.GetMethod(*_env, "cancelTile"); +void CustomGeometrySource::startThreads() { + android::UniqueEnv _env = android::AttachEnv(); - // The source is removed on the main thread, but it still exists on the Render thread until the frame is complete. - // This might cause fetchTile/cancelTile invocations when the Java thread is shutting down and the peer has already been released. - // See https://github.com/mapbox/mapbox-gl-native/issues/12551. - if(!javaPeer) { - return; - } + static auto& javaClass = jni::Class::Singleton(*_env); + static auto startThreads = javaClass.GetMethod(*_env, "startThreads"); - auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, cancelTile, (int)tileID.z, (int)tileID.x, (int)tileID.y); - }; + assert(javaPeer); - void CustomGeometrySource::startThreads() { - android::UniqueEnv _env = android::AttachEnv(); + auto peer = jni::Cast(*_env, javaClass, javaPeer); + peer.Call(*_env, startThreads); +} - static auto& javaClass = jni::Class::Singleton(*_env); - static auto startThreads = javaClass.GetMethod(*_env, "startThreads"); +void CustomGeometrySource::releaseThreads() { + android::UniqueEnv _env = android::AttachEnv(); - assert(javaPeer); + static auto& javaClass = jni::Class::Singleton(*_env); + static auto releaseThreads = javaClass.GetMethod(*_env, "releaseThreads"); + if (javaPeer) { auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, startThreads); + peer.Call(*_env, releaseThreads); } +}; - void CustomGeometrySource::releaseThreads() { - android::UniqueEnv _env = android::AttachEnv(); - - static auto& javaClass = jni::Class::Singleton(*_env); - static auto releaseThreads = javaClass.GetMethod(*_env, "releaseThreads"); - - if(javaPeer) { - auto peer = jni::Cast(*_env, javaClass, javaPeer); - peer.Call(*_env, releaseThreads); - } - }; +bool CustomGeometrySource::isCancelled(jni::jint z, jni::jint x, jni::jint y) { + android::UniqueEnv _env = android::AttachEnv(); - bool CustomGeometrySource::isCancelled(jni::jint z, - jni::jint x, - jni::jint y) { - android::UniqueEnv _env = android::AttachEnv(); + static auto& javaClass = jni::Class::Singleton(*_env); + static auto isCancelled = javaClass.GetMethod(*_env, "isCancelled"); - static auto& javaClass = jni::Class::Singleton(*_env); - static auto isCancelled = javaClass.GetMethod(*_env, "isCancelled"); + assert(javaPeer); - assert(javaPeer); + auto peer = jni::Cast(*_env, javaClass, javaPeer); + return peer.Call(*_env, isCancelled, z, x, y); +}; - auto peer = jni::Cast(*_env, javaClass, javaPeer); - return peer.Call(*_env, isCancelled, z, x, y); - }; - - void CustomGeometrySource::setTileData(jni::JNIEnv& env, - jni::jint z, - jni::jint x, - jni::jint y, - const jni::Object& jFeatures) { - using namespace mbgl::android::geojson; - - // Convert the jni object - auto geometry = geojson::FeatureCollection::convert(env, jFeatures); - - // Update the core source if not cancelled - if (!isCancelled(z, x ,y)) { - source.as()->CustomGeometrySource::setTileData(CanonicalTileID(z, x, y), GeoJSON(geometry)); - } - } +void CustomGeometrySource::setTileData( + jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y, const jni::Object& jFeatures) { + using namespace mbgl::android::geojson; - void CustomGeometrySource::invalidateTile(jni::JNIEnv&, jni::jint z, jni::jint x, jni::jint y) { - source.as()->CustomGeometrySource::invalidateTile(CanonicalTileID(z, x, y)); - } + // Convert the jni object + auto geometry = geojson::FeatureCollection::convert(env, jFeatures); - void CustomGeometrySource::invalidateBounds(jni::JNIEnv& env, const jni::Object& jBounds) { - auto bounds = LatLngBounds::getLatLngBounds(env, jBounds); - source.as()->CustomGeometrySource::invalidateRegion(bounds); + // Update the core source if not cancelled + if (!isCancelled(z, x, y)) { + source.as()->CustomGeometrySource::setTileData(CanonicalTileID(z, x, y), + GeoJSON(geometry)); } +} - jni::Local>> CustomGeometrySource::querySourceFeatures(jni::JNIEnv& env, - const jni::Array>& jfilter) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; +void CustomGeometrySource::invalidateTile(jni::JNIEnv&, jni::jint z, jni::jint x, jni::jint y) { + source.as()->CustomGeometrySource::invalidateTile(CanonicalTileID(z, x, y)); +} - std::vector features; - if (rendererFrontend) { - features = rendererFrontend->querySourceFeatures(source.getID(), { {}, toFilter(env, jfilter) }); - } - return Feature::convert(env, features); - } +void CustomGeometrySource::invalidateBounds(jni::JNIEnv& env, const jni::Object& jBounds) { + auto bounds = LatLngBounds::getLatLngBounds(env, jBounds); + source.as()->CustomGeometrySource::invalidateRegion(bounds); +} - jni::Local> CustomGeometrySource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } +jni::Local>> CustomGeometrySource::querySourceFeatures( + jni::JNIEnv& env, const jni::Array>& jfilter) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; - void CustomGeometrySource::addToMap(JNIEnv& env, const jni::Object& obj, mbgl::Map& map, AndroidRendererFrontend& frontend) { - Source::addToMap(env, obj, map, frontend); - startThreads(); + std::vector features; + if (rendererFrontend) { + features = rendererFrontend->querySourceFeatures(source.getID(), {{}, toFilter(env, jfilter)}); } - - bool CustomGeometrySource::removeFromMap(JNIEnv& env, const jni::Object& source, mbgl::Map& map) { - bool successfullyRemoved = Source::removeFromMap(env, source, map); - if (successfullyRemoved) { - releaseThreads(); - } - return successfullyRemoved; - } - - void CustomGeometrySource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&CustomGeometrySource::querySourceFeatures, "querySourceFeatures"), - METHOD(&CustomGeometrySource::setTileData, "nativeSetTileData"), - METHOD(&CustomGeometrySource::invalidateTile, "nativeInvalidateTile"), - METHOD(&CustomGeometrySource::invalidateBounds, "nativeInvalidateBounds") - ); + return Feature::convert(env, features); +} + +jni::Local> CustomGeometrySource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void CustomGeometrySource::addToMap(JNIEnv& env, + const jni::Object& obj, + mbgl::Map& map, + AndroidRendererFrontend& frontend) { + Source::addToMap(env, obj, map, frontend); + startThreads(); +} + +bool CustomGeometrySource::removeFromMap(JNIEnv& env, const jni::Object& source, mbgl::Map& map) { + bool successfullyRemoved = Source::removeFromMap(env, source, map); + if (successfullyRemoved) { + releaseThreads(); } + return successfullyRemoved; +} + +void CustomGeometrySource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&CustomGeometrySource::querySourceFeatures, "querySourceFeatures"), + METHOD(&CustomGeometrySource::setTileData, "nativeSetTileData"), + METHOD(&CustomGeometrySource::invalidateTile, "nativeInvalidateTile"), + METHOD(&CustomGeometrySource::invalidateBounds, "nativeInvalidateBounds")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp index 6979ecc25d4..c403367ceed 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/custom_geometry_source.hpp @@ -34,13 +34,14 @@ class CustomGeometrySource : public Source { void releaseThreads(); private: - void setTileData(jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y, const jni::Object& jf); + void setTileData( + jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y, const jni::Object& jf); void invalidateTile(jni::JNIEnv& env, jni::jint z, jni::jint x, jni::jint y); void invalidateBounds(jni::JNIEnv& env, const jni::Object& bounds); jni::Local>> querySourceFeatures(jni::JNIEnv&, - const jni::Array>& ); + const jni::Array>&); jni::Local> createJavaPeer(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp index 9993f009ba3..0a27b3b8535 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.cpp @@ -19,24 +19,26 @@ #include -// GeoJSONSource uses a "coalescing" model for high frequency asynchronous data update calls, -// which in practice means, that any update that started processing is going to finish -// and the last scheduled update is going to finish as well. Any updates scheduled during processing can be canceled. -// Conversion from Java features to core ones is done on a worker thread and once finished, +// GeoJSONSource uses a "coalescing" model for high frequency asynchronous data +// update calls, which in practice means, that any update that started +// processing is going to finish and the last scheduled update is going to +// finish as well. Any updates scheduled during processing can be canceled. Conversion +// from Java features to core ones is done on a worker thread and once finished, // the ownership of the converted features is returned to the calling thread. namespace mbgl { namespace android { - // This conversion is expected not to fail because it's used only in contexts where - // the value was originally a GeoJsonOptions object on the Java side. If it fails - // to convert, it's a bug in our serialization or Java-side static typing. +// This conversion is expected not to fail because it's used only in contexts where +// the value was originally a GeoJsonOptions object on the Java side. If it fails +// to convert, it's a bug in our serialization or Java-side static typing. static Immutable convertGeoJSONOptions(jni::JNIEnv& env, const jni::Object<>& options) { using namespace mbgl::style::conversion; if (!options) { return style::GeoJSONOptions::defaultOptions(); } Error error; - std::optional result = convert(mbgl::android::Value(env, options), error); + std::optional result = convert(mbgl::android::Value(env, options), + error); if (!result) { throw std::logic_error(error.message); } @@ -67,193 +69,200 @@ void GeoJSONSource::setGeoJSONString(jni::JNIEnv& env, const jni::String& jStrin setAsync(converterFn); } - void GeoJSONSource::setFeatureCollection(jni::JNIEnv& env, const jni::Object& jFeatures) { - setCollectionAsync(env, jFeatures); - } +void GeoJSONSource::setFeatureCollection(jni::JNIEnv& env, const jni::Object& jFeatures) { + setCollectionAsync(env, jFeatures); +} - void GeoJSONSource::setFeature(jni::JNIEnv& env, const jni::Object& jFeature) { - setCollectionAsync(env, jFeature); - } +void GeoJSONSource::setFeature(jni::JNIEnv& env, const jni::Object& jFeature) { + setCollectionAsync(env, jFeature); +} - void GeoJSONSource::setGeometry(jni::JNIEnv& env, const jni::Object& jGeometry) { - setCollectionAsync(env, jGeometry); - } +void GeoJSONSource::setGeometry(jni::JNIEnv& env, const jni::Object& jGeometry) { + setCollectionAsync(env, jGeometry); +} - void GeoJSONSource::setURL(jni::JNIEnv& env, const jni::String& url) { - // Update the core source - source.as()->setURL(jni::Make(env, url)); - } +void GeoJSONSource::setURL(jni::JNIEnv& env, const jni::String& url) { + // Update the core source + source.as()->setURL(jni::Make(env, url)); +} - jni::Local GeoJSONSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } +jni::Local GeoJSONSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} - jni::Local>> GeoJSONSource::querySourceFeatures(jni::JNIEnv& env, - const jni::Array>& jfilter) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; +jni::Local>> GeoJSONSource::querySourceFeatures( + jni::JNIEnv& env, const jni::Array>& jfilter) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; - std::vector features; - if (rendererFrontend) { - features = rendererFrontend->querySourceFeatures(source.getID(), - { {}, toFilter(env, jfilter) }); - } - return Feature::convert(env, features); + std::vector features; + if (rendererFrontend) { + features = rendererFrontend->querySourceFeatures(source.getID(), {{}, toFilter(env, jfilter)}); } + return Feature::convert(env, features); +} - jni::Local>> GeoJSONSource::getClusterChildren(jni::JNIEnv& env, const jni::Object& feature) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - if (rendererFrontend) { - mbgl::Feature _feature = Feature::convert(env, feature); - _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); - const auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "children", {}); - if (featureExtension.is()) { - return Feature::convert(env, featureExtension.get()); - } +jni::Local>> GeoJSONSource::getClusterChildren( + jni::JNIEnv& env, const jni::Object& feature) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + if (rendererFrontend) { + mbgl::Feature _feature = Feature::convert(env, feature); + _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); + const auto featureExtension = rendererFrontend->queryFeatureExtensions( + source.getID(), _feature, "supercluster", "children", {}); + if (featureExtension.is()) { + return Feature::convert(env, featureExtension.get()); } - return jni::Array>::New(env, 0); } + return jni::Array>::New(env, 0); +} - jni::Local>> GeoJSONSource::getClusterLeaves(jni::JNIEnv& env, const jni::Object& feature, jni::jlong limit, jni::jlong offset) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - if (rendererFrontend) { - mbgl::Feature _feature = Feature::convert(env, feature); - _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); - const std::map options = { {"limit", static_cast(limit)}, - {"offset", static_cast(offset)} }; - auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "leaves", options); - if (featureExtension.is()) { - return Feature::convert(env, featureExtension.get()); - } +jni::Local>> GeoJSONSource::getClusterLeaves( + jni::JNIEnv& env, const jni::Object& feature, jni::jlong limit, jni::jlong offset) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + if (rendererFrontend) { + mbgl::Feature _feature = Feature::convert(env, feature); + _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); + const std::map options = {{"limit", static_cast(limit)}, + {"offset", static_cast(offset)}}; + auto featureExtension = rendererFrontend->queryFeatureExtensions( + source.getID(), _feature, "supercluster", "leaves", options); + if (featureExtension.is()) { + return Feature::convert(env, featureExtension.get()); } - return jni::Array>::New(env, 0);; } + return jni::Array>::New(env, 0); + ; +} - jint GeoJSONSource::getClusterExpansionZoom(jni::JNIEnv& env, const jni::Object& feature) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - if (rendererFrontend) { - mbgl::Feature _feature = Feature::convert(env, feature); - _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); - auto featureExtension = rendererFrontend->queryFeatureExtensions(source.getID(), _feature, "supercluster", "expansion-zoom", {}); - if (featureExtension.is()) { - auto value = featureExtension.get(); - if (value.is()) { - return value.get(); - } +jint GeoJSONSource::getClusterExpansionZoom(jni::JNIEnv& env, const jni::Object& feature) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + if (rendererFrontend) { + mbgl::Feature _feature = Feature::convert(env, feature); + _feature.properties["cluster_id"] = static_cast(_feature.properties["cluster_id"].get()); + auto featureExtension = rendererFrontend->queryFeatureExtensions( + source.getID(), _feature, "supercluster", "expansion-zoom", {}); + if (featureExtension.is()) { + auto value = featureExtension.get(); + if (value.is()) { + return value.get(); } } - return 0; } + return 0; +} - jni::Local> GeoJSONSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } +jni::Local> GeoJSONSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} - template - void GeoJSONSource::setCollectionAsync(jni::JNIEnv& env, const jni::Object& jObject) { - auto global = jni::NewGlobal(env, jObject); - auto object = std::make_shared(std::move(global)); +template +void GeoJSONSource::setCollectionAsync(jni::JNIEnv& env, const jni::Object& jObject) { + auto global = jni::NewGlobal(env, jObject); + auto object = std::make_shared(std::move(global)); - Update::Converter converterFn = [this, object](ActorRef _callback) { - converter->self().invoke(&FeatureConverter::convertObject, object, _callback); - }; + Update::Converter converterFn = [this, object](ActorRef _callback) { + converter->self().invoke(&FeatureConverter::convertObject, object, _callback); + }; - setAsync(converterFn); - } + setAsync(converterFn); +} - void GeoJSONSource::setAsync(Update::Converter converterFn) { - awaitingUpdate = std::make_unique( - std::move(converterFn), - std::make_unique>( - *Scheduler::GetCurrent(), [this](std::shared_ptr geoJSONData) { - // conversion from Java features to core ones finished - android::UniqueEnv _env = android::AttachEnv(); - - // Update the core source - source.as()->setGeoJSONData(std::move(geoJSONData)); - - // if there is an awaiting update, execute it, otherwise, release resources - if (awaitingUpdate) { - update = std::move(awaitingUpdate); - update->converterFn(update->callback->self()); - } else { - update.reset(); - } - })); - - // If another update is running, wait - if (update) { - return; - } +void GeoJSONSource::setAsync(Update::Converter converterFn) { + awaitingUpdate = std::make_unique( + std::move(converterFn), + std::make_unique>( + *Scheduler::GetCurrent(), [this](std::shared_ptr geoJSONData) { + // conversion from Java features to core ones finished + android::UniqueEnv _env = android::AttachEnv(); + + // Update the core source + source.as()->setGeoJSONData(std::move(geoJSONData)); + + // if there is an awaiting update, execute it, otherwise, release resources + if (awaitingUpdate) { + update = std::move(awaitingUpdate); + update->converterFn(update->callback->self()); + } else { + update.reset(); + } + })); - // no updates are being processed, execute this one - update = std::move(awaitingUpdate); - update->converterFn(update->callback->self()); + // If another update is running, wait + if (update) { + return; } - void GeoJSONSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&GeoJSONSource::setGeoJSONString, "nativeSetGeoJsonString"), - METHOD(&GeoJSONSource::setFeatureCollection, "nativeSetFeatureCollection"), - METHOD(&GeoJSONSource::setFeature, "nativeSetFeature"), - METHOD(&GeoJSONSource::setGeometry, "nativeSetGeometry"), - METHOD(&GeoJSONSource::setURL, "nativeSetUrl"), - METHOD(&GeoJSONSource::getURL, "nativeGetUrl"), - METHOD(&GeoJSONSource::querySourceFeatures, "querySourceFeatures"), - METHOD(&GeoJSONSource::getClusterChildren, "nativeGetClusterChildren"), - METHOD(&GeoJSONSource::getClusterLeaves, "nativeGetClusterLeaves"), - METHOD(&GeoJSONSource::getClusterExpansionZoom, "nativeGetClusterExpansionZoom") - ); - } + // no updates are being processed, execute this one + update = std::move(awaitingUpdate); + update->converterFn(update->callback->self()); +} - void FeatureConverter::convertJson(std::shared_ptr json, ActorRef callback) { - using namespace mbgl::style::conversion; +void GeoJSONSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&GeoJSONSource::setGeoJSONString, "nativeSetGeoJsonString"), + METHOD(&GeoJSONSource::setFeatureCollection, "nativeSetFeatureCollection"), + METHOD(&GeoJSONSource::setFeature, "nativeSetFeature"), + METHOD(&GeoJSONSource::setGeometry, "nativeSetGeometry"), + METHOD(&GeoJSONSource::setURL, "nativeSetUrl"), + METHOD(&GeoJSONSource::getURL, "nativeGetUrl"), + METHOD(&GeoJSONSource::querySourceFeatures, "querySourceFeatures"), + METHOD(&GeoJSONSource::getClusterChildren, "nativeGetClusterChildren"), + METHOD(&GeoJSONSource::getClusterLeaves, "nativeGetClusterLeaves"), + METHOD(&GeoJSONSource::getClusterExpansionZoom, "nativeGetClusterExpansionZoom")); +} - android::UniqueEnv _env = android::AttachEnv(); - // Convert the jni object - Error error; - std::optional converted = parseGeoJSON(*json, error); - if(!converted) { - mbgl::Log::Error(mbgl::Event::JNI, "Error setting geo json: " + error.message); - return; - } +void FeatureConverter::convertJson(std::shared_ptr json, ActorRef callback) { + using namespace mbgl::style::conversion; - callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(*converted, options)); + android::UniqueEnv _env = android::AttachEnv(); + // Convert the jni object + Error error; + std::optional converted = parseGeoJSON(*json, error); + if (!converted) { + mbgl::Log::Error(mbgl::Event::JNI, "Error setting geo json: " + error.message); + return; } - template - void FeatureConverter::convertObject( - std::shared_ptr, jni::EnvAttachingDeleter>> jObject, - ActorRef callback) { - using namespace mbgl::android::geojson; + callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(*converted, options)); +} - android::UniqueEnv _env = android::AttachEnv(); - // Convert the jni object - auto geometry = JNIType::convert(*_env, *jObject); - callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(geometry, options)); - } +template +void FeatureConverter::convertObject( + std::shared_ptr, jni::EnvAttachingDeleter>> jObject, + ActorRef callback) { + using namespace mbgl::android::geojson; + + android::UniqueEnv _env = android::AttachEnv(); + // Convert the jni object + auto geometry = JNIType::convert(*_env, *jObject); + callback.invoke(&GeoJSONDataCallback::operator(), style::GeoJSONData::create(geometry, options)); +} - Update::Update(Converter _converterFn, std::unique_ptr> _callback) - : converterFn(std::move(_converterFn)), callback(std::move(_callback)) {} +Update::Update(Converter _converterFn, std::unique_ptr> _callback) + : converterFn(std::move(_converterFn)), + callback(std::move(_callback)) {} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp index c7ef6e54dea..ad7365778c2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/geojson_source.hpp @@ -15,7 +15,8 @@ using GeoJSONDataCallback = std::function options_) : options(std::move(options_)) {} + explicit FeatureConverter(Immutable options_) + : options(std::move(options_)) {} void convertJson(std::shared_ptr, ActorRef); template @@ -54,10 +55,14 @@ class GeoJSONSource : public Source { void setURL(jni::JNIEnv&, const jni::String&); jni::Local>> querySourceFeatures(jni::JNIEnv&, - const jni::Array>&); - - jni::Local>> getClusterChildren(jni::JNIEnv&, const jni::Object&); - jni::Local>> getClusterLeaves(jni::JNIEnv&, const jni::Object&, jni::jlong, jni::jlong); + const jni::Array>&); + + jni::Local>> getClusterChildren(jni::JNIEnv&, + const jni::Object&); + jni::Local>> getClusterLeaves(jni::JNIEnv&, + const jni::Object&, + jni::jlong, + jni::jlong); jint getClusterExpansionZoom(jni::JNIEnv&, const jni::Object&); jni::Local getURL(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp index 85924b7cce2..8d278b31866 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/image_source.cpp @@ -15,62 +15,60 @@ namespace mbgl { namespace android { - ImageSource::ImageSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object& coordinatesObject) - : Source(env, std::make_unique( - jni::Make(env, sourceId), - LatLngQuad::getLatLngArray(env, coordinatesObject) - ) - ) { - } - - ImageSource::ImageSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - ImageSource::~ImageSource() = default; - - void ImageSource::setURL(jni::JNIEnv& env, const jni::String& url) { - // Update the core source - source.as()->ImageSource::setURL(jni::Make(env, url)); - } - - jni::Local ImageSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->ImageSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - void ImageSource::setImage(jni::JNIEnv& env, const jni::Object& bitmap) { - source.as()->setImage(Bitmap::GetImage(env, bitmap)); - } - - void ImageSource::setCoordinates(jni::JNIEnv& env, const jni::Object& coordinatesObject) { - source.as()->setCoordinates( - LatLngQuad::getLatLngArray(env, coordinatesObject)); - } - - jni::Local> ImageSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void ImageSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&ImageSource::setURL, "nativeSetUrl"), - METHOD(&ImageSource::getURL, "nativeGetUrl"), - METHOD(&ImageSource::setImage, "nativeSetImage"), - METHOD(&ImageSource::setCoordinates, "nativeSetCoordinates") - ); - } +ImageSource::ImageSource(jni::JNIEnv& env, + const jni::String& sourceId, + const jni::Object& coordinatesObject) + : Source(env, + std::make_unique(jni::Make(env, sourceId), + LatLngQuad::getLatLngArray(env, coordinatesObject))) {} + +ImageSource::ImageSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +ImageSource::~ImageSource() = default; + +void ImageSource::setURL(jni::JNIEnv& env, const jni::String& url) { + // Update the core source + source.as()->ImageSource::setURL(jni::Make(env, url)); +} + +jni::Local ImageSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->ImageSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +void ImageSource::setImage(jni::JNIEnv& env, const jni::Object& bitmap) { + source.as()->setImage(Bitmap::GetImage(env, bitmap)); +} + +void ImageSource::setCoordinates(jni::JNIEnv& env, const jni::Object& coordinatesObject) { + source.as()->setCoordinates(LatLngQuad::getLatLngArray(env, coordinatesObject)); +} + +jni::Local> ImageSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void ImageSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer(env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&ImageSource::setURL, "nativeSetUrl"), + METHOD(&ImageSource::getURL, "nativeGetUrl"), + METHOD(&ImageSource::setImage, "nativeSetImage"), + METHOD(&ImageSource::setCoordinates, "nativeSetCoordinates")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp index f456c030f5a..107c96a066e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_dem_source.cpp @@ -12,50 +12,46 @@ namespace mbgl { namespace android { - RasterDEMSource::RasterDEMSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet, jni::jint tileSize) - : Source( - env, - std::make_unique( - jni::Make(env, sourceId), - convertURLOrTileset(Value(env, urlOrTileSet)), - tileSize - ) - ) { - } - - RasterDEMSource::RasterDEMSource(jni::JNIEnv& env, - mbgl::style::Source& coreSource, - AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - RasterDEMSource::~RasterDEMSource() = default; - - jni::Local RasterDEMSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->RasterDEMSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - jni::Local> RasterDEMSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void RasterDEMSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&, jni::jint>, - "initialize", - "finalize", - METHOD(&RasterDEMSource::getURL, "nativeGetUrl") - ); - } +RasterDEMSource::RasterDEMSource(jni::JNIEnv& env, + const jni::String& sourceId, + const jni::Object<>& urlOrTileSet, + jni::jint tileSize) + : Source(env, + std::make_unique( + jni::Make(env, sourceId), convertURLOrTileset(Value(env, urlOrTileSet)), tileSize)) {} + +RasterDEMSource::RasterDEMSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +RasterDEMSource::~RasterDEMSource() = default; + +jni::Local RasterDEMSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->RasterDEMSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +jni::Local> RasterDEMSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void RasterDEMSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&, jni::jint>, + "initialize", + "finalize", + METHOD(&RasterDEMSource::getURL, "nativeGetUrl")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp index c7462f7d95e..d023fca6dcd 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/raster_source.cpp @@ -11,48 +11,46 @@ namespace mbgl { namespace android { - RasterSource::RasterSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet, jni::jint tileSize) - : Source( - env, - std::make_unique( - jni::Make(env, sourceId), - convertURLOrTileset(Value(env, urlOrTileSet)), - tileSize - ) - ) { - } - - RasterSource::RasterSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - RasterSource::~RasterSource() = default; - - jni::Local RasterSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->RasterSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - jni::Local> RasterSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void RasterSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&, jni::jint>, - "initialize", - "finalize", - METHOD(&RasterSource::getURL, "nativeGetUrl") - ); - } +RasterSource::RasterSource(jni::JNIEnv& env, + const jni::String& sourceId, + const jni::Object<>& urlOrTileSet, + jni::jint tileSize) + : Source(env, + std::make_unique( + jni::Make(env, sourceId), convertURLOrTileset(Value(env, urlOrTileSet)), tileSize)) {} + +RasterSource::RasterSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +RasterSource::~RasterSource() = default; + +jni::Local RasterSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->RasterSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +jni::Local> RasterSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void RasterSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + jni::MakePeer&, jni::jint>, + "initialize", + "finalize", + METHOD(&RasterSource::getURL, "nativeGetUrl")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp index f4386336344..ec7026d441b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.cpp @@ -50,205 +50,208 @@ static std::unique_ptr createSourcePeer(jni::JNIEnv& env, } } - const jni::Object& Source::peerForCoreSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend& frontend) { - if (!coreSource.peer.has_value()) { - coreSource.peer = createSourcePeer(env, coreSource, &frontend); - } - return coreSource.peer.get>()->javaPeer; +const jni::Object& Source::peerForCoreSource(jni::JNIEnv& env, + mbgl::style::Source& coreSource, + AndroidRendererFrontend& frontend) { + if (!coreSource.peer.has_value()) { + coreSource.peer = createSourcePeer(env, coreSource, &frontend); } + return coreSource.peer.get>()->javaPeer; +} - const jni::Object& Source::peerForCoreSource(jni::JNIEnv& env, mbgl::style::Source& coreSource) { - if (!coreSource.peer.has_value()) { - coreSource.peer = createSourcePeer(env, coreSource, nullptr); - } - return coreSource.peer.get>()->javaPeer; +const jni::Object& Source::peerForCoreSource(jni::JNIEnv& env, mbgl::style::Source& coreSource) { + if (!coreSource.peer.has_value()) { + coreSource.peer = createSourcePeer(env, coreSource, nullptr); } + return coreSource.peer.get>()->javaPeer; +} - Source::Source(jni::JNIEnv& env, - mbgl::style::Source& coreSource, - const jni::Object& obj, - AndroidRendererFrontend* frontend) - : source(coreSource), javaPeer(jni::NewGlobal(env, obj)), rendererFrontend(frontend) {} - - Source::Source(jni::JNIEnv&, std::unique_ptr coreSource) - : ownedSource(std::move(coreSource)) - , source(*ownedSource) { +Source::Source(jni::JNIEnv& env, + mbgl::style::Source& coreSource, + const jni::Object& obj, + AndroidRendererFrontend* frontend) + : source(coreSource), + javaPeer(jni::NewGlobal(env, obj)), + rendererFrontend(frontend) {} + +Source::Source(jni::JNIEnv&, std::unique_ptr coreSource) + : ownedSource(std::move(coreSource)), + source(*ownedSource) {} + +Source::~Source() { + if (ownedSource) { + ownedSource.reset(); + ownedSource.release(); } - - Source::~Source() { - if (ownedSource) { - ownedSource.reset(); - ownedSource.release(); - } - // Before being added to a map, the Java peer owns this C++ peer and cleans - // up after itself correctly through the jni native peer bindings. - // After being added to the map, the ownership is flipped and the C++ peer has a strong reference - // to it's Java peer, preventing the Java peer from being GC'ed. - // In this case, the core source initiates the destruction, which requires releasing the Java peer, - // while also resetting it's nativePtr to 0 to prevent the subsequent GC of the Java peer from - // re-entering this dtor. - if (ownedSource.get() == nullptr && javaPeer.get() != nullptr) { - // Manually clear the java peer - android::UniqueEnv env = android::AttachEnv(); - static auto& javaClass = jni::Class::Singleton(*env); - static auto nativePtrField = javaClass.GetField(*env, "nativePtr"); - javaPeer.Set(*env, nativePtrField, (jlong) 0); - javaPeer.reset(); - } + // Before being added to a map, the Java peer owns this C++ peer and cleans + // up after itself correctly through the jni native peer bindings. + // After being added to the map, the ownership is flipped and the C++ peer + // has a strong reference + // to it's Java peer, preventing the Java peer from being GC'ed. + // In this case, the core source initiates the destruction, which requires + // releasing the Java peer, while also resetting it's nativePtr to 0 to + // prevent the subsequent GC of the Java peer from re-entering this dtor. + if (ownedSource.get() == nullptr && javaPeer.get() != nullptr) { + // Manually clear the java peer + android::UniqueEnv env = android::AttachEnv(); + static auto& javaClass = jni::Class::Singleton(*env); + static auto nativePtrField = javaClass.GetField(*env, "nativePtr"); + javaPeer.Set(*env, nativePtrField, (jlong)0); + javaPeer.reset(); } +} - jni::Local Source::getId(jni::JNIEnv& env) { - return jni::Make(env, source.getID()); - } +jni::Local Source::getId(jni::JNIEnv& env) { + return jni::Make(env, source.getID()); +} - jni::Local Source::getAttribution(jni::JNIEnv& env) { - auto attribution = source.getAttribution(); - return attribution ? jni::Make(env, attribution.value()) : jni::Make(env,""); +jni::Local Source::getAttribution(jni::JNIEnv& env) { + auto attribution = source.getAttribution(); + return attribution ? jni::Make(env, attribution.value()) : jni::Make(env, ""); +} + +void Source::setPrefetchZoomDelta(jni::JNIEnv& env, jni::Integer& delta) { + if (!delta) { + source.setPrefetchZoomDelta(std::nullopt); + } else { + source.setPrefetchZoomDelta(jni::Unbox(env, delta)); } +} - void Source::setPrefetchZoomDelta(jni::JNIEnv& env, jni::Integer& delta) { - if (!delta) { - source.setPrefetchZoomDelta(std::nullopt); - } else { - source.setPrefetchZoomDelta(jni::Unbox(env, delta)); - } +jni::Local Source::getPrefetchZoomDelta(jni::JNIEnv& env) { + auto delta = source.getPrefetchZoomDelta(); + if (delta.has_value()) { + return jni::Box(env, jni::jint(delta.value())); } + return jni::Local(env, nullptr); +} - jni::Local Source::getPrefetchZoomDelta(jni::JNIEnv& env) { - auto delta = source.getPrefetchZoomDelta(); - if (delta.has_value()) { - return jni::Box(env, jni::jint(delta.value())); - } - return jni::Local(env, nullptr); +void Source::setMaxOverscaleFactorForParentTiles(jni::JNIEnv& env, jni::Integer& maxOverscaleFactor) { + if (!maxOverscaleFactor) { + source.setMaxOverscaleFactorForParentTiles(std::nullopt); + } else { + source.setMaxOverscaleFactorForParentTiles(jni::Unbox(env, maxOverscaleFactor)); } +} - void Source::setMaxOverscaleFactorForParentTiles(jni::JNIEnv& env, jni::Integer& maxOverscaleFactor) { - if (!maxOverscaleFactor) { - source.setMaxOverscaleFactorForParentTiles(std::nullopt); - } else { - source.setMaxOverscaleFactorForParentTiles(jni::Unbox(env, maxOverscaleFactor)); - } +jni::Local Source::getMaxOverscaleFactorForParentTiles(jni::JNIEnv& env) { + auto maxOverscaleFactor = source.getMaxOverscaleFactorForParentTiles(); + if (maxOverscaleFactor) { + return jni::Box(env, jni::jint(*maxOverscaleFactor)); } + return jni::Local(env, nullptr); +} - jni::Local Source::getMaxOverscaleFactorForParentTiles(jni::JNIEnv& env) { - auto maxOverscaleFactor = source.getMaxOverscaleFactorForParentTiles(); - if (maxOverscaleFactor) { - return jni::Box(env, jni::jint(*maxOverscaleFactor)); - } - return jni::Local(env, nullptr); +void Source::addToStyle(JNIEnv& env, const jni::Object& obj, mbgl::style::Style& style) { + if (!ownedSource) { + throw std::runtime_error("Cannot add source twice"); } - void Source::addToStyle(JNIEnv& env, const jni::Object& obj, mbgl::style::Style& style) { - if (!ownedSource) { - throw std::runtime_error("Cannot add source twice"); - } + // Add source to style and release ownership + style.addSource(std::move(ownedSource)); - // Add source to style and release ownership - style.addSource(std::move(ownedSource)); + // Add peer to core source + source.peer = std::unique_ptr(this); - // Add peer to core source - source.peer = std::unique_ptr(this); + // Add strong reference to java source + javaPeer = jni::NewGlobal(env, obj); +} - // Add strong reference to java source - javaPeer = jni::NewGlobal(env, obj); +void Source::addToMap(JNIEnv& env, const jni::Object& obj, mbgl::Map& map, AndroidRendererFrontend& frontend) { + // Check to see if we own the source first + if (!ownedSource) { + throw std::runtime_error("Cannot add source twice"); } - void Source::addToMap(JNIEnv& env, const jni::Object& obj, mbgl::Map& map, AndroidRendererFrontend& frontend) { - // Check to see if we own the source first - if (!ownedSource) { - throw std::runtime_error("Cannot add source twice"); - } + // Add source to map and release ownership + map.getStyle().addSource(std::move(ownedSource)); - // Add source to map and release ownership - map.getStyle().addSource(std::move(ownedSource)); + // Add peer to core source + source.peer = std::unique_ptr(this); - // Add peer to core source - source.peer = std::unique_ptr(this); + // Add strong reference to java source + javaPeer = jni::NewGlobal(env, obj); - // Add strong reference to java source - javaPeer = jni::NewGlobal(env, obj); + rendererFrontend = &frontend; +} - rendererFrontend = &frontend; +bool Source::removeFromMap(JNIEnv&, const jni::Object&, mbgl::Map& map) { + // Cannot remove if not attached yet + if (ownedSource) { + throw std::runtime_error("Cannot remove detached source"); } - bool Source::removeFromMap(JNIEnv&, const jni::Object&, mbgl::Map& map) { - // Cannot remove if not attached yet - if (ownedSource) { - throw std::runtime_error("Cannot remove detached source"); - } + // Remove the source from the map and take ownership + ownedSource = map.getStyle().removeSource(source.getID()); - // Remove the source from the map and take ownership - ownedSource = map.getStyle().removeSource(source.getID()); + // The source may not be removed if any layers still reference it + return ownedSource != nullptr; +} - // The source may not be removed if any layers still reference it - return ownedSource != nullptr; - } +jni::Local Source::isVolatile(jni::JNIEnv& env) { + return jni::Box(env, jni::jboolean(source.isVolatile())); +} - jni::Local Source::isVolatile(jni::JNIEnv& env) { - return jni::Box(env, jni::jboolean(source.isVolatile())); - } +void Source::setVolatile(JNIEnv& env, jni::Boolean& value) { + source.setVolatile(jni::Unbox(env, value)); +} - void Source::setVolatile(JNIEnv& env, jni::Boolean& value) { - source.setVolatile(jni::Unbox(env, value)); - } +void Source::setMinimumTileUpdateInterval(JNIEnv& env, jni::Long& interval) { + source.setMinimumTileUpdateInterval(Milliseconds(jni::Unbox(env, interval))); +} - void Source::setMinimumTileUpdateInterval(JNIEnv& env, jni::Long& interval) { - source.setMinimumTileUpdateInterval(Milliseconds(jni::Unbox(env, interval))); - } +jni::Local Source::getMinimumTileUpdateInterval(JNIEnv& env) { + return jni::Box(env, jni::jlong(source.getMinimumTileUpdateInterval().count() / 1000000)); +} - jni::Local Source::getMinimumTileUpdateInterval(JNIEnv& env) { - return jni::Box(env, jni::jlong(source.getMinimumTileUpdateInterval().count() / 1000000)); +void Source::releaseJavaPeer() { + // We can't release the peer if the source was not removed from the map + if (!ownedSource) { + return; } - void Source::releaseJavaPeer() { - // We can't release the peer if the source was not removed from the map - if (!ownedSource) { - return; - } + // Release the peer relationships. These will be re-established when the source is added to a map + assert(ownedSource->peer.has_value()); + ownedSource->peer.get>().release(); + ownedSource->peer = mapbox::base::TypeWrapper(); - // Release the peer relationships. These will be re-established when the source is added to a map - assert(ownedSource->peer.has_value()); - ownedSource->peer.get>().release(); - ownedSource->peer = mapbox::base::TypeWrapper(); - - // Release the strong reference to the java peer - assert(javaPeer); - javaPeer.reset(); + // Release the strong reference to the java peer + assert(javaPeer); + javaPeer.reset(); - rendererFrontend = nullptr; - } + rendererFrontend = nullptr; +} - void Source::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, - javaClass, - "nativePtr", - METHOD(&Source::getId, "nativeGetId"), - METHOD(&Source::getAttribution, "nativeGetAttribution"), - METHOD(&Source::setPrefetchZoomDelta, "nativeSetPrefetchZoomDelta"), - METHOD(&Source::getPrefetchZoomDelta, "nativeGetPrefetchZoomDelta"), - METHOD(&Source::setMaxOverscaleFactorForParentTiles, "nativeSetMaxOverscaleFactorForParentTiles"), - METHOD(&Source::getMaxOverscaleFactorForParentTiles, "nativeGetMaxOverscaleFactorForParentTiles"), - METHOD(&Source::isVolatile, "nativeIsVolatile"), - METHOD(&Source::setVolatile, "nativeSetVolatile"), - METHOD(&Source::setMinimumTileUpdateInterval, "nativeSetMinimumTileUpdateInterval"), - METHOD(&Source::getMinimumTileUpdateInterval, "nativeGetMinimumTileUpdateInterval")); - - - // Register subclasses - GeoJSONSource::registerNative(env); - ImageSource::registerNative(env); - RasterSource::registerNative(env); - UnknownSource::registerNative(env); - VectorSource::registerNative(env); - CustomGeometrySource::registerNative(env); - RasterDEMSource::registerNative(env); - } +void Source::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer( + env, + javaClass, + "nativePtr", + METHOD(&Source::getId, "nativeGetId"), + METHOD(&Source::getAttribution, "nativeGetAttribution"), + METHOD(&Source::setPrefetchZoomDelta, "nativeSetPrefetchZoomDelta"), + METHOD(&Source::getPrefetchZoomDelta, "nativeGetPrefetchZoomDelta"), + METHOD(&Source::setMaxOverscaleFactorForParentTiles, "nativeSetMaxOverscaleFactorForParentTiles"), + METHOD(&Source::getMaxOverscaleFactorForParentTiles, "nativeGetMaxOverscaleFactorForParentTiles"), + METHOD(&Source::isVolatile, "nativeIsVolatile"), + METHOD(&Source::setVolatile, "nativeSetVolatile"), + METHOD(&Source::setMinimumTileUpdateInterval, "nativeSetMinimumTileUpdateInterval"), + METHOD(&Source::getMinimumTileUpdateInterval, "nativeGetMinimumTileUpdateInterval")); + + // Register subclasses + GeoJSONSource::registerNative(env); + ImageSource::registerNative(env); + RasterSource::registerNative(env); + UnknownSource::registerNative(env); + VectorSource::registerNative(env); + CustomGeometrySource::registerNative(env); + RasterDEMSource::registerNative(env); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp index bb398bf2afd..400ec1df4c9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/source.hpp @@ -14,7 +14,6 @@ namespace android { class Source : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/sources/Source"; }; static void registerNative(jni::JNIEnv&); @@ -28,7 +27,8 @@ class Source : private mbgl::util::noncopyable { Source(jni::JNIEnv&, mbgl::style::Source&, const jni::Object&, AndroidRendererFrontend*); /* - * Called when a Java object is created for a new core source that does not belong to a map. + * Called when a Java object is created for a new core source that does not + * belong to a map. */ Source(jni::JNIEnv&, std::unique_ptr); @@ -54,11 +54,11 @@ class Source : private mbgl::util::noncopyable { void addToStyle(JNIEnv& env, const jni::Object& obj, mbgl::style::Style& style); - jni::Local isVolatile(JNIEnv&); + jni::Local isVolatile(JNIEnv&); void setVolatile(JNIEnv&, jni::Boolean&); - void setMinimumTileUpdateInterval(JNIEnv&, jni::Long &); + void setMinimumTileUpdateInterval(JNIEnv&, jni::Long&); jni::Local getMinimumTileUpdateInterval(JNIEnv&); @@ -73,7 +73,7 @@ class Source : private mbgl::util::noncopyable { jni::Global> javaPeer; // RendererFrontend pointer is valid only when added to the map. - AndroidRendererFrontend* rendererFrontend { nullptr }; + AndroidRendererFrontend* rendererFrontend{nullptr}; }; } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp index acfd52db8df..925d6b9a575 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/unknown_source.cpp @@ -2,10 +2,10 @@ namespace { - // Dummy initializer (We don't support initializing this from the JVM) - std::unique_ptr init(jni::JNIEnv&) { - throw std::runtime_error("UnknownSource should not be initialized from the JVM"); - } +// Dummy initializer (We don't support initializing this from the JVM) +std::unique_ptr init(jni::JNIEnv&) { + throw std::runtime_error("UnknownSource should not be initialized from the JVM"); +} } // namespace @@ -21,20 +21,15 @@ jni::Local> UnknownSource::createJavaPeer(jni::JNIEnv& env) return javaClass.New(env, constructor, reinterpret_cast(this)); } - void UnknownSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); +void UnknownSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - init, - "initialize", - "finalize" - ); - } + // Register the peer + jni::RegisterNativePeer(env, javaClass, "nativePtr", init, "initialize", "finalize"); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp index 1c34aba5551..01e092f8391 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.cpp @@ -20,62 +20,56 @@ namespace mbgl { namespace android { - VectorSource::VectorSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet) - : Source( - env, - std::make_unique( - jni::Make(env, sourceId), - convertURLOrTileset(Value(env, urlOrTileSet)) - ) - ) { - } - - VectorSource::VectorSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) - : Source(env, coreSource, createJavaPeer(env), frontend) {} - - VectorSource::~VectorSource() = default; - - jni::Local VectorSource::getURL(jni::JNIEnv& env) { - std::optional url = source.as()->VectorSource::getURL(); - return url ? jni::Make(env, *url) : jni::Local(); - } - - jni::Local>> VectorSource::querySourceFeatures(jni::JNIEnv& env, - const jni::Array& jSourceLayerIds, - const jni::Array>& jfilter) { - using namespace mbgl::android::conversion; - using namespace mbgl::android::geojson; - - std::vector features; - if (rendererFrontend) { - features = rendererFrontend->querySourceFeatures(source.getID(), - { toVector(env, jSourceLayerIds), toFilter(env, jfilter) }); - } - return Feature::convert(env, features); - } - - jni::Local> VectorSource::createJavaPeer(jni::JNIEnv& env) { - static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor(env); - return javaClass.New(env, constructor, reinterpret_cast(this)); - } - - void VectorSource::registerNative(jni::JNIEnv& env) { - // Lookup the class - static auto& javaClass = jni::Class::Singleton(env); - - #define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) - - // Register the peer - jni::RegisterNativePeer( - env, javaClass, "nativePtr", - jni::MakePeer&>, - "initialize", - "finalize", - METHOD(&VectorSource::querySourceFeatures, "querySourceFeatures"), - METHOD(&VectorSource::getURL, "nativeGetUrl") - ); +VectorSource::VectorSource(jni::JNIEnv& env, const jni::String& sourceId, const jni::Object<>& urlOrTileSet) + : Source(env, + std::make_unique(jni::Make(env, sourceId), + convertURLOrTileset(Value(env, urlOrTileSet)))) {} + +VectorSource::VectorSource(jni::JNIEnv& env, mbgl::style::Source& coreSource, AndroidRendererFrontend* frontend) + : Source(env, coreSource, createJavaPeer(env), frontend) {} + +VectorSource::~VectorSource() = default; + +jni::Local VectorSource::getURL(jni::JNIEnv& env) { + std::optional url = source.as()->VectorSource::getURL(); + return url ? jni::Make(env, *url) : jni::Local(); +} + +jni::Local>> VectorSource::querySourceFeatures( + jni::JNIEnv& env, const jni::Array& jSourceLayerIds, const jni::Array>& jfilter) { + using namespace mbgl::android::conversion; + using namespace mbgl::android::geojson; + + std::vector features; + if (rendererFrontend) { + features = rendererFrontend->querySourceFeatures(source.getID(), + {toVector(env, jSourceLayerIds), toFilter(env, jfilter)}); } + return Feature::convert(env, features); +} + +jni::Local> VectorSource::createJavaPeer(jni::JNIEnv& env) { + static auto& javaClass = jni::Class::Singleton(env); + static auto constructor = javaClass.GetConstructor(env); + return javaClass.New(env, constructor, reinterpret_cast(this)); +} + +void VectorSource::registerNative(jni::JNIEnv& env) { + // Lookup the class + static auto& javaClass = jni::Class::Singleton(env); + +#define METHOD(MethodPtr, name) jni::MakeNativePeerMethod(name) + + // Register the peer + jni::RegisterNativePeer(env, + javaClass, + "nativePtr", + jni::MakePeer&>, + "initialize", + "finalize", + METHOD(&VectorSource::querySourceFeatures, "querySourceFeatures"), + METHOD(&VectorSource::getURL, "nativeGetUrl")); +} } // namespace android } // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp index 7ae2e8c9e74..ed14dc89655 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/sources/vector_source.hpp @@ -20,8 +20,9 @@ class VectorSource : public Source { ~VectorSource(); private: - jni::Local>> querySourceFeatures(jni::JNIEnv&, const jni::Array&, - const jni::Array>& jfilter); + jni::Local>> querySourceFeatures(jni::JNIEnv&, + const jni::Array&, + const jni::Array>& jfilter); jni::Local getURL(jni::JNIEnv&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp index d70a04e0d55..6d2cb3bc9c2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.cpp @@ -3,9 +3,11 @@ namespace mbgl { namespace android { -jni::Local> TransitionOptions::fromTransitionOptions(jni::JNIEnv& env, jlong duration, jlong delay, jboolean enablePlacementTransitions) { +jni::Local> TransitionOptions::fromTransitionOptions( + jni::JNIEnv& env, jlong duration, jlong delay, jboolean enablePlacementTransitions) { static auto& javaClass = jni::Class::Singleton(env); - static auto method = javaClass.GetStaticMethod (jlong, jlong, jboolean)>(env, "fromTransitionOptions"); + static auto method = javaClass.GetStaticMethod(jlong, jlong, jboolean)>( + env, "fromTransitionOptions"); return javaClass.Call(env, method, duration, delay, enablePlacementTransitions); } @@ -21,9 +23,10 @@ long TransitionOptions::getDelay(jni::JNIEnv& env, const jni::Object& transitionOptions) { +bool TransitionOptions::isEnablePlacementTransitions( + jni::JNIEnv& env, const jni::Object& transitionOptions) { static auto& javaClass = jni::Class::Singleton(env); - static auto field = javaClass.GetField(env, "enablePlacementTransitions"); + static auto field = javaClass.GetField(env, "enablePlacementTransitions"); return transitionOptions.Get(env, field); } diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp index 58656a94638..fc54f0813f2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/transition_options.hpp @@ -11,7 +11,10 @@ class TransitionOptions : private mbgl::util::noncopyable { public: static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/layers/TransitionOptions"; }; - static jni::Local> fromTransitionOptions(jni::JNIEnv&, jlong duration, jlong delay, jboolean enablePlacementTransitions); + static jni::Local> fromTransitionOptions(jni::JNIEnv&, + jlong duration, + jlong delay, + jboolean enablePlacementTransitions); static long getDuration(jni::JNIEnv&, const jni::Object&); diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp index 2f048407299..ab1a368cd7d 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.cpp @@ -4,80 +4,80 @@ namespace mbgl { namespace android { - // Instance - - Value::Value(jni::JNIEnv& _env, jni::Local> _value) - : env(_env), - value(std::move(_value)) {} - - Value::Value(jni::JNIEnv& _env, const jni::Object<>& _value) - : env(_env), - value(jni::NewLocal(_env, _value)) {} - - bool Value::isNull() const { - return !value; - } - - bool Value::isArray() const { - return jni::IsInstanceOf(env, value.get(), *java::ObjectArray::jclass); - } - - bool Value::isObject() const { - return jni::IsInstanceOf(env, value.get(), *java::Map::jclass); - } - - bool Value::isString() const { - return jni::IsInstanceOf(env, value.get(), *java::String::jclass); - } - - bool Value::isBool() const { - return jni::IsInstanceOf(env, value.get(), *java::Boolean::jclass); - } - - bool Value::isNumber() const { - return jni::IsInstanceOf(env, value.get(), *java::Number::jclass); - } - - std::string Value::toString() const { - return jni::Make(env, jni::Cast(env, jni::Class::Singleton(env), value)); - } - - float Value::toFloat() const { - return jni::CallMethod(env, value.get(), *java::Number::floatValueMethodId); - } - - double Value::toDouble() const { - return jni::CallMethod(env, value.get(), *java::Number::doubleValueMethodId); - } - - long Value::toLong() const { - return jni::CallMethod(env, value.get(), *java::Number::longValueMethodId); - } - - bool Value::toBool() const { - return jni::CallMethod(env, value.get(), *java::Boolean::booleanValueMethodId); - } - - Value Value::get(const char* key) const { - jni::jobject* member = jni::CallMethod(env, value.get(), *java::Map::getMethodId, jni::Make(env, std::string(key)).get()); - return Value(env, jni::Local>(env, member)); - } - - Value Value::keyArray() const{ - jni::jobject* set = jni::CallMethod(env, value.get(), *java::Map::keySetMethodId); - jni::jobject* array = jni::CallMethod(env, set, *java::Set::toArrayMethodId); - return Value(env, jni::Local>(env, array)); - } - - int Value::getLength() const { - auto array = (jni::jarray*) value.get(); - return jni::GetArrayLength(env, *array); - } - - Value Value::get(const int index) const { - auto array = (jni::jarray*) value.get(); - return Value(env, jni::Local>(env, jni::GetObjectArrayElement(env, *array, index))); - } +// Instance + +Value::Value(jni::JNIEnv& _env, jni::Local> _value) + : env(_env), + value(std::move(_value)) {} + +Value::Value(jni::JNIEnv& _env, const jni::Object<>& _value) + : env(_env), + value(jni::NewLocal(_env, _value)) {} + +bool Value::isNull() const { + return !value; +} + +bool Value::isArray() const { + return jni::IsInstanceOf(env, value.get(), *java::ObjectArray::jclass); +} + +bool Value::isObject() const { + return jni::IsInstanceOf(env, value.get(), *java::Map::jclass); } + +bool Value::isString() const { + return jni::IsInstanceOf(env, value.get(), *java::String::jclass); } +bool Value::isBool() const { + return jni::IsInstanceOf(env, value.get(), *java::Boolean::jclass); +} + +bool Value::isNumber() const { + return jni::IsInstanceOf(env, value.get(), *java::Number::jclass); +} + +std::string Value::toString() const { + return jni::Make(env, jni::Cast(env, jni::Class::Singleton(env), value)); +} + +float Value::toFloat() const { + return jni::CallMethod(env, value.get(), *java::Number::floatValueMethodId); +} + +double Value::toDouble() const { + return jni::CallMethod(env, value.get(), *java::Number::doubleValueMethodId); +} + +long Value::toLong() const { + return jni::CallMethod(env, value.get(), *java::Number::longValueMethodId); +} + +bool Value::toBool() const { + return jni::CallMethod(env, value.get(), *java::Boolean::booleanValueMethodId); +} + +Value Value::get(const char* key) const { + jni::jobject* member = jni::CallMethod( + env, value.get(), *java::Map::getMethodId, jni::Make(env, std::string(key)).get()); + return Value(env, jni::Local>(env, member)); +} + +Value Value::keyArray() const { + jni::jobject* set = jni::CallMethod(env, value.get(), *java::Map::keySetMethodId); + jni::jobject* array = jni::CallMethod(env, set, *java::Set::toArrayMethodId); + return Value(env, jni::Local>(env, array)); +} + +int Value::getLength() const { + auto array = (jni::jarray*)value.get(); + return jni::GetArrayLength(env, *array); +} + +Value Value::get(const int index) const { + auto array = (jni::jarray*)value.get(); + return Value(env, jni::Local>(env, jni::GetObjectArrayElement(env, *array, index))); +} +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp index b507c5ed11c..5df4f10b6a7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/style/value.hpp @@ -12,10 +12,10 @@ class Value { Value(jni::JNIEnv&, jni::Local>); Value(jni::JNIEnv&, const jni::Object<>&); - Value(Value&&) = default; - Value& operator=(Value&&) = delete; + Value(Value&&) = default; + Value& operator=(Value&&) = delete; - Value(const Value&) = delete; + Value(const Value&) = delete; Value& operator=(const Value&) = delete; bool isNull() const; @@ -33,11 +33,11 @@ class Value { Value get(const char* key) const; Value keyArray() const; int getLength() const; - Value get(const int index ) const; + Value get(const int index) const; jni::JNIEnv& env; jni::Local> value; }; -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp index 67e5caf0539..c72325a5fd3 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/text/local_glyph_rasterizer.cpp @@ -34,7 +34,7 @@ namespace mbgl { namespace android { LocalGlyphRasterizer::LocalGlyphRasterizer() { - UniqueEnv env { AttachEnv() }; + UniqueEnv env{AttachEnv()}; static auto& javaClass = jni::Class::Singleton(*env); static auto constructor = javaClass.GetConstructor(*env); @@ -42,18 +42,21 @@ LocalGlyphRasterizer::LocalGlyphRasterizer() { javaObject = jni::NewGlobal(*env, javaClass.New(*env, constructor)); } -PremultipliedImage LocalGlyphRasterizer::drawGlyphBitmap(const std::string& fontFamily, const bool bold, const GlyphID glyphID) { - UniqueEnv env { AttachEnv() }; +PremultipliedImage LocalGlyphRasterizer::drawGlyphBitmap(const std::string& fontFamily, + const bool bold, + const GlyphID glyphID) { + UniqueEnv env{AttachEnv()}; static auto& javaClass = jni::Class::Singleton(*env); - static auto drawGlyphBitmap = javaClass.GetMethod (jni::String, jni::jboolean, jni::jchar)>(*env, "drawGlyphBitmap"); + static auto drawGlyphBitmap = javaClass.GetMethod(jni::String, jni::jboolean, jni::jchar)>( + *env, "drawGlyphBitmap"); return Bitmap::GetImage(*env, - javaObject.Call(*env, - drawGlyphBitmap, - jni::Make(*env, fontFamily), - static_cast(bold), - static_cast(glyphID))); + javaObject.Call(*env, + drawGlyphBitmap, + jni::Make(*env, fontFamily), + static_cast(bold), + static_cast(glyphID))); } void LocalGlyphRasterizer::registerNative(jni::JNIEnv& env) { @@ -65,12 +68,9 @@ void LocalGlyphRasterizer::registerNative(jni::JNIEnv& env) { class LocalGlyphRasterizer::Impl { public: Impl(const std::optional fontFamily_) - : fontFamily(fontFamily_) - {} + : fontFamily(fontFamily_) {} - bool isConfigured() const { - return bool(fontFamily); - } + bool isConfigured() const { return bool(fontFamily); } PremultipliedImage drawGlyphBitmap(const FontStack& fontStack, GlyphID glyphID) { bool bold = false; @@ -92,11 +92,10 @@ class LocalGlyphRasterizer::Impl { LocalGlyphRasterizer::LocalGlyphRasterizer(const std::optional& fontFamily) : impl(std::make_unique(fontFamily)) {} -LocalGlyphRasterizer::~LocalGlyphRasterizer() -{} +LocalGlyphRasterizer::~LocalGlyphRasterizer() {} bool LocalGlyphRasterizer::canRasterizeGlyph(const FontStack&, GlyphID glyphID) { - return util::i18n::allowsFixedWidthGlyphGeneration(glyphID) && impl->isConfigured(); + return util::i18n::allowsFixedWidthGlyphGeneration(glyphID) && impl->isConfigured(); } Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack& fontStack, GlyphID glyphID) { @@ -120,9 +119,9 @@ Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack& fontStack, GlyphID g // Copy alpha values from RGBA bitmap into the AlphaImage output fixedMetrics.bitmap = AlphaImage(size); for (uint32_t i = 0; i < size.width * size.height; i++) { - fixedMetrics.bitmap.data[i] = - 0xff - round(0.2126 * rgbaBitmap.data[4 * i] + 0.7152 * rgbaBitmap.data[4 * i + 1] + - 0.0722 * rgbaBitmap.data[4 * i + 2]); + fixedMetrics.bitmap.data[i] = 0xff - + round(0.2126 * rgbaBitmap.data[4 * i] + 0.7152 * rgbaBitmap.data[4 * i + 1] + + 0.0722 * rgbaBitmap.data[4 * i + 2]); } return fixedMetrics; diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp index fa5c9730afe..d3dca99447a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.cpp @@ -3,24 +3,23 @@ namespace mbgl { namespace android { -jni::Local> DefaultStyle::New(jni::JNIEnv& env, const mbgl::util::DefaultStyle& jDefaultStyle) { +jni::Local> DefaultStyle::New(jni::JNIEnv& env, + const mbgl::util::DefaultStyle& jDefaultStyle) { static auto& javaClass = jni::Class::Singleton(env); static auto constructor = javaClass.GetConstructor(env); - return javaClass.New( - env, - constructor, - jni::Make(env, jDefaultStyle.getUrl()), - jni::Make(env, jDefaultStyle.getName()), - jDefaultStyle.getCurrentVersion()); + return javaClass.New(env, + constructor, + jni::Make(env, jDefaultStyle.getUrl()), + jni::Make(env, jDefaultStyle.getName()), + jDefaultStyle.getCurrentVersion()); } mbgl::util::DefaultStyle DefaultStyle::getDefaultStyle(jni::JNIEnv& env, const jni::Object& options) { static auto& javaClass = jni::Class::Singleton(env); - return mbgl::util::DefaultStyle ( + return mbgl::util::DefaultStyle( jni::Make(env, options.Get(env, javaClass.GetField(env, "url"))), jni::Make(env, options.Get(env, javaClass.GetField(env, "name"))), - options.Get(env, javaClass.GetField(env, "version")) - ); + options.Get(env, javaClass.GetField(env, "version"))); } void DefaultStyle::registerNative(jni::JNIEnv& env) { diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp index 5b788361f75..ba5352d6ab8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/default_style.hpp @@ -10,16 +10,13 @@ namespace android { class DefaultStyle : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/util/DefaultStyle"; }; static jni::Local> New(jni::JNIEnv&, const mbgl::util::DefaultStyle&); static mbgl::util::DefaultStyle getDefaultStyle(jni::JNIEnv&, const jni::Object&); static void registerNative(jni::JNIEnv&); - }; - } // namespace android } // namespace mbgl \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp index 339c6e6636a..08b42cff3fa 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.cpp @@ -3,21 +3,40 @@ namespace mbgl { namespace android { -jni::Local> TileServerOptions::New(jni::JNIEnv& env, const mbgl::TileServerOptions& tileServerOptions) { +jni::Local> TileServerOptions::New(jni::JNIEnv& env, + const mbgl::TileServerOptions& tileServerOptions) { static auto& javaClass = jni::Class::Singleton(env); - static auto constructor = javaClass.GetConstructor< - jni::String, jni::String, jni::String, jni::String, jni::String, jni::String, - jni::String, jni::String, jni::String, jni::String, jni::String, - jni::String, jni::String, jni::String, jni::String, jni::String, - jni::String, jni::String, jni::jboolean, jni::String, jni::Array>>(env); - + static auto constructor = javaClass.GetConstructor>>(env); + std::optional sourceVersionPrefixValue = tileServerOptions.sourceVersionPrefix(); std::optional styleVersionPrefixValue = tileServerOptions.styleVersionPrefix(); std::optional spritesVersionPrefixValue = tileServerOptions.spritesVersionPrefix(); std::optional glyphsVersionPrefixValue = tileServerOptions.glyphsVersionPrefix(); std::optional tileVersionPrefixValue = tileServerOptions.tileVersionPrefix(); - return javaClass.New(env, constructor, + return javaClass.New( + env, + constructor, jni::Make(env, tileServerOptions.baseURL()), jni::Make(env, tileServerOptions.uriSchemeAlias()), jni::Make(env, tileServerOptions.sourceTemplate()), @@ -38,13 +57,12 @@ jni::Local> TileServerOptions::New(jni::JNIEnv& e jni::Make(env, tileServerOptions.apiKeyParameterName()), jni::jboolean(tileServerOptions.requiresApiKey()), jni::Make(env, tileServerOptions.defaultStyle()), - TileServerOptions::NewStyles(env, tileServerOptions.defaultStyles()) - ); + TileServerOptions::NewStyles(env, tileServerOptions.defaultStyles())); } -jni::Local>> TileServerOptions::NewStyles(jni::JNIEnv& env, const std::vector &nativeStyles) { - - auto retVal = jni::Array>::New(env, nativeStyles.size()); +jni::Local>> TileServerOptions::NewStyles( + jni::JNIEnv& env, const std::vector& nativeStyles) { + auto retVal = jni::Array>::New(env, nativeStyles.size()); for (auto it = begin(nativeStyles); it != end(nativeStyles); ++it) { auto converted = DefaultStyle::New(env, *it); retVal.Set(env, it - nativeStyles.begin(), converted); @@ -53,27 +71,32 @@ jni::Local>> TileServerOptions::NewStyles(j return retVal; } -jni::Local> TileServerOptions::DefaultConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::DefaultConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions) { auto options = mbgl::TileServerOptions::DefaultConfiguration(); return TileServerOptions::New(env, options); } -jni::Local> TileServerOptions::MapboxConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::MapboxConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions) { auto options = mbgl::TileServerOptions::MapboxConfiguration(); return TileServerOptions::New(env, options); } -jni::Local> TileServerOptions::MapTilerConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::MapTilerConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions) { auto options = mbgl::TileServerOptions::MapTilerConfiguration(); return TileServerOptions::New(env, options); } -jni::Local> TileServerOptions::MapLibreConfiguration(jni::JNIEnv& env, const jni::Class& jOptions) { +jni::Local> TileServerOptions::MapLibreConfiguration( + jni::JNIEnv& env, const jni::Class& jOptions) { auto options = mbgl::TileServerOptions::MapLibreConfiguration(); return TileServerOptions::New(env, options); } -mbgl::TileServerOptions TileServerOptions::getTileServerOptions(jni::JNIEnv& env, const jni::Object& options) { +mbgl::TileServerOptions TileServerOptions::getTileServerOptions(jni::JNIEnv& env, + const jni::Object& options) { auto opts = mbgl::TileServerOptions(); static auto& javaClass = jni::Class::Singleton(env); @@ -107,43 +130,44 @@ mbgl::TileServerOptions TileServerOptions::getTileServerOptions(jni::JNIEnv& env static auto defaultStyleField = javaClass.GetField(env, "defaultStyle"); static auto defaultStylesField = javaClass.GetField>>(env, "defaultStyles"); - std::vector defaultStyles = TileServerOptions::getDefaultStyles(env, options.Get(env, defaultStylesField)); + std::vector defaultStyles = TileServerOptions::getDefaultStyles( + env, options.Get(env, defaultStylesField)); auto retVal = mbgl::TileServerOptions() - .withBaseURL(jni::Make(env, options.Get(env, baseURLField))) - .withUriSchemeAlias(jni::Make(env, options.Get(env, uriSchemeAliasField))) - .withApiKeyParameterName(jni::Make(env, options.Get(env, apiKeyParameterNameField))) - .setRequiresApiKey(options.Get(env, apiKeyRequiredField)); - + .withBaseURL(jni::Make(env, options.Get(env, baseURLField))) + .withUriSchemeAlias(jni::Make(env, options.Get(env, uriSchemeAliasField))) + .withApiKeyParameterName(jni::Make(env, options.Get(env, apiKeyParameterNameField))) + .setRequiresApiKey(options.Get(env, apiKeyRequiredField)); + auto sourcePrefixValue = options.Get(env, sourceVersionPrefixField); retVal.withSourceTemplate( jni::Make(env, options.Get(env, sourceTemplateField)), jni::Make(env, options.Get(env, sourceDomainNameField)), - sourcePrefixValue ? jni::Make(env, sourcePrefixValue): std::optional{}); + sourcePrefixValue ? jni::Make(env, sourcePrefixValue) : std::optional{}); auto styleVersionPrefixValue = options.Get(env, styleVersionPrefixField); retVal.withStyleTemplate( jni::Make(env, options.Get(env, styleTemplateField)), jni::Make(env, options.Get(env, styleDomainNameField)), - styleVersionPrefixValue ? jni::Make(env, styleVersionPrefixValue): std::optional{}); + styleVersionPrefixValue ? jni::Make(env, styleVersionPrefixValue) : std::optional{}); auto spritesVersionPrefixValue = options.Get(env, spritesVersionPrefixField); - retVal.withSpritesTemplate( - jni::Make(env, options.Get(env, spritesTemplateField)), - jni::Make(env, options.Get(env, spritesDomainNameField)), - spritesVersionPrefixValue ? jni::Make(env, spritesVersionPrefixValue): std::optional{}); - - auto glyphsVersionPrefixValue = options.Get(env, glyphsVersionPrefixField); - retVal.withGlyphsTemplate( - jni::Make(env, options.Get(env, glyphsTemplateField)), - jni::Make(env, options.Get(env, glyphsDomainNameField)), - glyphsVersionPrefixValue ? jni::Make(env, glyphsVersionPrefixValue) : std::optional{}); - - auto tileVersionPrefixValue = options.Get(env, tileVersionPrefixField); + retVal.withSpritesTemplate(jni::Make(env, options.Get(env, spritesTemplateField)), + jni::Make(env, options.Get(env, spritesDomainNameField)), + spritesVersionPrefixValue ? jni::Make(env, spritesVersionPrefixValue) + : std::optional{}); + + auto glyphsVersionPrefixValue = options.Get(env, glyphsVersionPrefixField); + retVal.withGlyphsTemplate(jni::Make(env, options.Get(env, glyphsTemplateField)), + jni::Make(env, options.Get(env, glyphsDomainNameField)), + glyphsVersionPrefixValue ? jni::Make(env, glyphsVersionPrefixValue) + : std::optional{}); + + auto tileVersionPrefixValue = options.Get(env, tileVersionPrefixField); retVal.withTileTemplate( - jni::Make(env, options.Get(env, tileTemplateField)), - jni::Make(env, options.Get(env, tileDomainNameField)), - tileVersionPrefixValue ? jni::Make(env, tileVersionPrefixValue): std::optional{}); + jni::Make(env, options.Get(env, tileTemplateField)), + jni::Make(env, options.Get(env, tileDomainNameField)), + tileVersionPrefixValue ? jni::Make(env, tileVersionPrefixValue) : std::optional{}); retVal.withDefaultStyle(jni::Make(env, options.Get(env, defaultStyleField))); retVal.withDefaultStyles(defaultStyles); @@ -151,11 +175,11 @@ mbgl::TileServerOptions TileServerOptions::getTileServerOptions(jni::JNIEnv& env return retVal; } -std::vector TileServerOptions::getDefaultStyles(jni::JNIEnv& env, const jni::Array>& styles_) { - +std::vector TileServerOptions::getDefaultStyles( + jni::JNIEnv& env, const jni::Array>& styles_) { std::size_t length = styles_.Length(env); std::vector convertedStyles; - //convertedStyles.reserve(length); + // convertedStyles.reserve(length); for (std::size_t i = 0; i < length; i++) { mbgl::util::DefaultStyle converted = DefaultStyle::getDefaultStyle(env, styles_.Get(env, i)); convertedStyles.push_back(converted); @@ -167,11 +191,15 @@ std::vector TileServerOptions::getDefaultStyles(jni::J void TileServerOptions::registerNative(jni::JNIEnv& env) { static auto& javaClass = jni::Class::Singleton(env); jni::RegisterNatives(env, - *javaClass, - jni::MakeNativeMethod("defaultConfiguration"), - jni::MakeNativeMethod("mapboxConfiguration"), - jni::MakeNativeMethod("mapTilerConfiguration"), - jni::MakeNativeMethod("mapLibreConfiguration")); + *javaClass, + jni::MakeNativeMethod("defaultConfiguration"), + jni::MakeNativeMethod("mapboxConfiguration"), + jni::MakeNativeMethod("mapTilerConfiguration"), + jni::MakeNativeMethod("mapLibreConfiguration")); } } // namespace android diff --git a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp index 310580871ff..a2ebf21a33d 100644 --- a/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp +++ b/platform/android/MapboxGLAndroidSDK/src/cpp/util/tile_server_options.hpp @@ -13,26 +13,28 @@ namespace android { class TileServerOptions : private mbgl::util::noncopyable { public: - static constexpr auto Name() { return "com/mapbox/mapboxsdk/util/TileServerOptions"; }; static jni::Local> New(jni::JNIEnv&, const mbgl::TileServerOptions&); - static jni::Local> DefaultConfiguration(jni::JNIEnv&, const jni::Class&); - static jni::Local> MapboxConfiguration(jni::JNIEnv&, const jni::Class&); - static jni::Local> MapTilerConfiguration(jni::JNIEnv&, const jni::Class&); - static jni::Local> MapLibreConfiguration(jni::JNIEnv&, const jni::Class&); + static jni::Local> DefaultConfiguration(jni::JNIEnv&, + const jni::Class&); + static jni::Local> MapboxConfiguration(jni::JNIEnv&, + const jni::Class&); + static jni::Local> MapTilerConfiguration(jni::JNIEnv&, + const jni::Class&); + static jni::Local> MapLibreConfiguration(jni::JNIEnv&, + const jni::Class&); static mbgl::TileServerOptions getTileServerOptions(jni::JNIEnv&, const jni::Object&); - - static void registerNative(jni::JNIEnv&); - static jni::Local>> NewStyles(jni::JNIEnv& env, const std::vector &); - static std::vector getDefaultStyles(jni::JNIEnv& env, const jni::Array>& styles_); - + static void registerNative(jni::JNIEnv&); + static jni::Local>> NewStyles(jni::JNIEnv& env, + const std::vector&); + static std::vector getDefaultStyles(jni::JNIEnv& env, + const jni::Array>& styles_); }; - } // namespace android } // namespace mbgl diff --git a/platform/android/src/async_task.cpp b/platform/android/src/async_task.cpp index 0a4d90a275f..cef046bd993 100644 --- a/platform/android/src/async_task.cpp +++ b/platform/android/src/async_task.cpp @@ -12,8 +12,8 @@ namespace util { class AsyncTask::Impl : public RunLoop::Impl::Runnable { public: Impl(std::function&& fn) - : queued(true), task(std::move(fn)) { - } + : queued(true), + task(std::move(fn)) {} ~Impl() { queued = true; @@ -27,9 +27,7 @@ class AsyncTask::Impl : public RunLoop::Impl::Runnable { } } - TimePoint dueTime() const override { - return due; - } + TimePoint dueTime() const override { return due; } void runTask() override { if (!queued) { @@ -52,8 +50,7 @@ class AsyncTask::Impl : public RunLoop::Impl::Runnable { }; AsyncTask::AsyncTask(std::function&& fn) - : impl(std::make_unique(std::move(fn))) { -} + : impl(std::make_unique(std::move(fn))) {} AsyncTask::~AsyncTask() = default; diff --git a/platform/android/src/attach_env.cpp b/platform/android/src/attach_env.cpp index 6da075ee3e1..f07f5afc34e 100644 --- a/platform/android/src/attach_env.cpp +++ b/platform/android/src/attach_env.cpp @@ -9,14 +9,14 @@ UniqueEnv AttachEnv() { jint err = theJVM->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); switch (err) { - case JNI_OK: - return UniqueEnv(env, JNIEnvDeleter(*theJVM, false)); - case JNI_EDETACHED: - return UniqueEnv(jni::AttachCurrentThread(*theJVM).release(), JNIEnvDeleter(*theJVM, true)); - default: - throw std::system_error(err, jni::ErrorCategory()); + case JNI_OK: + return UniqueEnv(env, JNIEnvDeleter(*theJVM, false)); + case JNI_EDETACHED: + return UniqueEnv(jni::AttachCurrentThread(*theJVM).release(), JNIEnvDeleter(*theJVM, true)); + default: + throw std::system_error(err, jni::ErrorCategory()); } } -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/attach_env.hpp b/platform/android/src/attach_env.hpp index 8a9f4a7f8b2..03c03dd5c41 100644 --- a/platform/android/src/attach_env.hpp +++ b/platform/android/src/attach_env.hpp @@ -13,19 +13,20 @@ class JNIEnvDeleter { public: JNIEnvDeleter() = default; JNIEnvDeleter(jni::JavaVM& v, bool d) - : vm(&v), detach(d) {} + : vm(&v), + detach(d) {} void operator()(jni::JNIEnv* p) const { if (p && detach) { - assert(vm); - vm->DetachCurrentThread(); + assert(vm); + vm->DetachCurrentThread(); } - } + } }; using UniqueEnv = std::unique_ptr; UniqueEnv AttachEnv(); -} -} +} // namespace android +} // namespace mbgl diff --git a/platform/android/src/bitmap.cpp b/platform/android/src/bitmap.cpp index eb7c676b12b..af61d5cae34 100644 --- a/platform/android/src/bitmap.cpp +++ b/platform/android/src/bitmap.cpp @@ -8,9 +8,10 @@ namespace android { class PixelGuard { public: - PixelGuard(jni::JNIEnv& env_, const jni::Object& bitmap_) : env(env_), bitmap(bitmap_) { - const int result = AndroidBitmap_lockPixels(&env, jni::Unwrap(*bitmap), - reinterpret_cast(&address)); + PixelGuard(jni::JNIEnv& env_, const jni::Object& bitmap_) + : env(env_), + bitmap(bitmap_) { + const int result = AndroidBitmap_lockPixels(&env, jni::Unwrap(*bitmap), reinterpret_cast(&address)); if (result != ANDROID_BITMAP_RESULT_SUCCESS) { throw std::runtime_error("bitmap decoding: could not lock pixels"); } @@ -23,9 +24,7 @@ class PixelGuard { } } - auto* get() { - return address; - } + auto* get() { return address; } private: jni::JNIEnv& env; @@ -36,16 +35,16 @@ class PixelGuard { jni::Local> Bitmap::Config::Create(jni::JNIEnv& env, Value value) { static auto& _class = jni::Class::Singleton(env); switch (value) { - case ALPHA_8: - return _class.Get(env, _class.GetStaticField>(env, "ALPHA_8")); - case ARGB_4444: - return _class.Get(env, _class.GetStaticField>(env, "ARGB_4444")); - case ARGB_8888: - return _class.Get(env, _class.GetStaticField>(env, "ARGB_8888")); - case RGB_565: - return _class.Get(env, _class.GetStaticField>(env, "RGB_565")); - default: - throw std::runtime_error("invalid enum value for Bitmap.Config"); + case ALPHA_8: + return _class.Get(env, _class.GetStaticField>(env, "ALPHA_8")); + case ARGB_4444: + return _class.Get(env, _class.GetStaticField>(env, "ARGB_4444")); + case ARGB_8888: + return _class.Get(env, _class.GetStaticField>(env, "ARGB_8888")); + case RGB_565: + return _class.Get(env, _class.GetStaticField>(env, "RGB_565")); + default: + throw std::runtime_error("invalid enum value for Bitmap.Config"); } } @@ -59,7 +58,8 @@ jni::Local> Bitmap::CreateBitmap(jni::JNIEnv& env, jni::jint height, const jni::Object& config) { static auto& _class = jni::Class::Singleton(env); - static auto method = _class.GetStaticMethod (jni::jint, jni::jint, jni::Object)>(env, "createBitmap"); + static auto method = _class.GetStaticMethod(jni::jint, jni::jint, jni::Object)>( + env, "createBitmap"); return _class.Call(env, method, width, height, config); } @@ -77,15 +77,15 @@ PremultipliedImage Bitmap::GetImage(jni::JNIEnv& env, const jni::Object& PixelGuard guard(env, bitmap); // Copy the Android Bitmap into the PremultipliedImage. - auto pixels = - std::make_unique(info.width * info.height * PremultipliedImage::channels); + auto pixels = std::make_unique(info.width * info.height * PremultipliedImage::channels); for (uint32_t y = 0; y < info.height; y++) { auto begin = guard.get() + y * info.stride; - std::copy(begin, begin + info.width * PremultipliedImage::channels, - pixels.get() + y * info.width * PremultipliedImage::channels); + std::copy(begin, + begin + info.width * PremultipliedImage::channels, + pixels.get() + y * info.width * PremultipliedImage::channels); } - return { Size{ info.width, info.height }, std::move(pixels) }; + return {Size{info.width, info.height}, std::move(pixels)}; } jni::Local> Bitmap::CreateBitmap(jni::JNIEnv& env, const PremultipliedImage& image) { @@ -115,7 +115,7 @@ jni::Local> Bitmap::CreateBitmap(jni::JNIEnv& env, const Pre jni::Local> Bitmap::Copy(jni::JNIEnv& env, const jni::Object& bitmap) { static auto& klass = jni::Class::Singleton(env); - static auto copy = klass.GetMethod (jni::Object, jni::jboolean)>(env, "copy"); + static auto copy = klass.GetMethod(jni::Object, jni::jboolean)>(env, "copy"); return bitmap.Call(env, copy, Bitmap::Config::Create(env, Bitmap::Config::Value::ARGB_8888), jni::jni_false); } diff --git a/platform/android/src/bitmap.hpp b/platform/android/src/bitmap.hpp index 9d96405c26d..21d85287b44 100644 --- a/platform/android/src/bitmap.hpp +++ b/platform/android/src/bitmap.hpp @@ -26,11 +26,15 @@ class Bitmap { static constexpr auto Name() { return "android/graphics/Bitmap"; }; static void registerNative(jni::JNIEnv&); - static jni::Local> - CreateBitmap(jni::JNIEnv&, jni::jint width, jni::jint height, const jni::Object&); - - static jni::Local> - CreateBitmap(jni::JNIEnv& env, jni::jint width, jni::jint height, Config::Value config) { + static jni::Local> CreateBitmap(jni::JNIEnv&, + jni::jint width, + jni::jint height, + const jni::Object&); + + static jni::Local> CreateBitmap(jni::JNIEnv& env, + jni::jint width, + jni::jint height, + Config::Value config) { return CreateBitmap(env, width, height, Config::Create(env, config)); } diff --git a/platform/android/src/bitmap_factory.cpp b/platform/android/src/bitmap_factory.cpp index 170bd52ea5a..04a90453a7d 100644 --- a/platform/android/src/bitmap_factory.cpp +++ b/platform/android/src/bitmap_factory.cpp @@ -13,9 +13,10 @@ jni::Local> BitmapFactory::DecodeByteArray(jni::JNIEnv& env, jni::jint length) { static auto& _class = jni::Class::Singleton(env); - // Images are loaded with ARGB_8888 config, and premultiplied by default, which is exactly - // what we want, so we're not providing a BitmapFactory.Options object. - using Signature = jni::Object (jni::Array, jni::jint, jni::jint); + // Images are loaded with ARGB_8888 config, and premultiplied by default, + // which is exactly what we want, so we're not providing a + // BitmapFactory.Options object. + using Signature = jni::Object(jni::Array, jni::jint, jni::jint); static auto method = _class.GetStaticMethod(env, "decodeByteArray"); return _class.Call(env, method, data, offset, length); diff --git a/platform/android/src/bitmap_factory.hpp b/platform/android/src/bitmap_factory.hpp index f73b7a29067..005c28be699 100644 --- a/platform/android/src/bitmap_factory.hpp +++ b/platform/android/src/bitmap_factory.hpp @@ -12,8 +12,10 @@ class BitmapFactory { static constexpr auto Name() { return "android/graphics/BitmapFactory"; }; static void registerNative(jni::JNIEnv&); - static jni::Local> - DecodeByteArray(jni::JNIEnv&, jni::Array& data, jni::jint offset, jni::jint length); + static jni::Local> DecodeByteArray(jni::JNIEnv&, + jni::Array& data, + jni::jint offset, + jni::jint length); }; } // namespace android diff --git a/platform/android/src/example_custom_layer.cpp b/platform/android/src/example_custom_layer.cpp index 159df486595..93e6ed76325 100644 --- a/platform/android/src/example_custom_layer.cpp +++ b/platform/android/src/example_custom_layer.cpp @@ -6,9 +6,9 @@ // DEBUGGING -const char* LOG_TAG = "Custom Layer Example"; +const char *LOG_TAG = "Custom Layer Example"; -const char* stringFromError(GLenum err) { +const char *stringFromError(GLenum err) { switch (err) { case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; @@ -27,22 +27,22 @@ const char* stringFromError(GLenum err) { #ifdef GL_TABLE_TOO_LARGE case GL_TABLE_TOO_LARGE: - return "GL_TABLE_TOO_LARGE"; + return "GL_TABLE_TOO_LARGE"; #endif #ifdef GL_STACK_OVERFLOW case GL_STACK_OVERFLOW: - return "GL_STACK_OVERFLOW"; + return "GL_STACK_OVERFLOW"; #endif #ifdef GL_STACK_UNDERFLOW case GL_STACK_UNDERFLOW: - return "GL_STACK_UNDERFLOW"; + return "GL_STACK_UNDERFLOW"; #endif #ifdef GL_CONTEXT_LOST case GL_CONTEXT_LOST: - return "GL_CONTEXT_LOST"; + return "GL_CONTEXT_LOST"; #endif default: @@ -55,11 +55,10 @@ struct Error : std::runtime_error { }; void checkError(const char *cmd, const char *file, int line) { - GLenum err = GL_NO_ERROR; if ((err = glGetError()) != GL_NO_ERROR) { std::ostringstream message; - message << cmd << ": Error " << stringFromError(err); + message << cmd << ": Error " << stringFromError(err); // Check for further errors while ((err = glGetError()) != GL_NO_ERROR) { @@ -73,7 +72,13 @@ void checkError(const char *cmd, const char *file, int line) { } #ifndef NDEBUG -#define GL_CHECK_ERROR(cmd) ([&]() { struct __MBGL_C_E { ~__MBGL_C_E() noexcept(false) { checkError(#cmd, __FILE__, __LINE__); } } __MBGL_C_E; return cmd; }()) +#define GL_CHECK_ERROR(cmd) \ + ([&]() { \ + struct __MBGL_C_E { \ + ~__MBGL_C_E() noexcept(false) { checkError(#cmd, __FILE__, __LINE__); } \ + } __MBGL_C_E; \ + return cmd; \ + }()) #else #define GL_CHECK_ERROR(cmd) (cmd) #endif @@ -89,7 +94,6 @@ void checkLinkStatus(GLuint program) { __android_log_write(ANDROID_LOG_ERROR, LOG_TAG, &infoLog[0]); throw Error(infoLog); } - } void checkCompileStatus(GLuint shader) { @@ -109,13 +113,16 @@ void checkCompileStatus(GLuint shader) { // /DEBUGGING -static const GLchar * vertexShaderSource = "#version 300 es\nlayout (location = 0) in vec2 a_pos; void main() { gl_Position = vec4(a_pos, 0, 1); }"; -static const GLchar * fragmentShaderSource = "#version 300 es\nuniform highp vec4 fill_color; out highp vec4 fragColor; void main() { fragColor = fill_color; }"; +static const GLchar *vertexShaderSource = + "#version 300 es\nlayout (location = 0) in vec2 a_pos; void main() { " + "gl_Position = vec4(a_pos, 0, 1); }"; +static const GLchar *fragmentShaderSource = + "#version 300 es\nuniform highp vec4 fill_color; out highp vec4 fragColor; " + "void main() { fragColor = fill_color; }"; -class ExampleCustomLayer: mbgl::style::CustomLayerHost { +class ExampleCustomLayer : mbgl::style::CustomLayerHost { public: - ~ExampleCustomLayer() { - } + ~ExampleCustomLayer() {} void initialize() { __android_log_write(ANDROID_LOG_INFO, LOG_TAG, "Initialize"); @@ -143,13 +150,13 @@ class ExampleCustomLayer: mbgl::style::CustomLayerHost { a_pos = GL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); fill_color = GL_CHECK_ERROR(glGetUniformLocation(program, "fill_color")); - GLfloat background[] = { -1, -1, 1, -1, -1, 1, 1, 1 }; + GLfloat background[] = {-1, -1, 1, -1, -1, 1, 1, 1}; GL_CHECK_ERROR(glGenBuffers(1, &buffer)); GL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, buffer)); GL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), background, GL_STATIC_DRAW)); } - void render(const mbgl::style::CustomLayerRenderParameters&) { + void render(const mbgl::style::CustomLayerRenderParameters &) { __android_log_write(ANDROID_LOG_INFO, LOG_TAG, "Render"); glUseProgram(program); glBindBuffer(GL_ARRAY_BUFFER, buffer); @@ -167,7 +174,6 @@ class ExampleCustomLayer: mbgl::style::CustomLayerHost { GL_CHECK_ERROR(glDisable(GL_DEPTH_TEST)); GL_CHECK_ERROR(glUniform4fv(fill_color, 1, color)); GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)); - } void contextLost() { @@ -197,15 +203,15 @@ class ExampleCustomLayer: mbgl::style::CustomLayerHost { static GLfloat color[]; }; -GLfloat ExampleCustomLayer::color[] = { 0.0f, 1.0f, 0.0f, 1.0f }; +GLfloat ExampleCustomLayer::color[] = {0.0f, 1.0f, 0.0f, 1.0f}; -jlong JNICALL nativeCreateContext(JNIEnv*, jobject) { +jlong JNICALL nativeCreateContext(JNIEnv *, jobject) { __android_log_write(ANDROID_LOG_INFO, LOG_TAG, "nativeCreateContext"); auto exampleCustomLayer = std::make_unique(); return reinterpret_cast(exampleCustomLayer.release()); } -void JNICALL nativeSetColor(JNIEnv*, jobject, jfloat red, jfloat green, jfloat blue, jfloat alpha) { +void JNICALL nativeSetColor(JNIEnv *, jobject, jfloat red, jfloat green, jfloat blue, jfloat alpha) { __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "nativeSetColor: %.2f, %.2f, %.2f, %.2f", red, green, blue, alpha); ExampleCustomLayer::color[0] = red; ExampleCustomLayer::color[1] = green; @@ -221,10 +227,8 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { jclass customLayerClass = env->FindClass("com/mapbox/mapboxsdk/testapp/model/customlayer/ExampleCustomLayer"); - JNINativeMethod methods[] = { - {"createContext", "()J", reinterpret_cast(&nativeCreateContext)}, - {"setColor", "(FFFF)V", reinterpret_cast(&nativeSetColor)} - }; + JNINativeMethod methods[] = {{"createContext", "()J", reinterpret_cast(&nativeCreateContext)}, + {"setColor", "(FFFF)V", reinterpret_cast(&nativeSetColor)}}; if (env->RegisterNatives(customLayerClass, methods, 2) < 0) { env->ExceptionDescribe(); @@ -234,5 +238,4 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { return JNI_VERSION_1_6; } -extern "C" JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *, void *) { -} +extern "C" JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *, void *) {} diff --git a/platform/android/src/gl_functions.cpp b/platform/android/src/gl_functions.cpp index de72ba38b27..1a8a66e6c2a 100644 --- a/platform/android/src/gl_functions.cpp +++ b/platform/android/src/gl_functions.cpp @@ -7,255 +7,274 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = ::glActiveTexture; -void (* const glAttachShader)(GLuint, GLuint) = ::glAttachShader; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = ::glBindAttribLocation; -void (* const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; -void (* const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; -void (* const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; -void (* const glBindTexture)(GLenum, GLuint) = ::glBindTexture; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; -void (* const glBlendEquation)(GLenum) = ::glBlendEquation; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; -void (* const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = ::glBufferData; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = ::glBufferSubData; -GLenum (* const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; -void (* const glClear)(GLbitfield) = ::glClear; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; -void (* const glClearDepthf)(GLfloat) = ::glClearDepthf; -void (* const glClearStencil)(GLint) = ::glClearStencil; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; -void (* const glCompileShader)(GLuint) = ::glCompileShader; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = ::glCompressedTexImage2D; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = ::glCompressedTexSubImage2D; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; -GLuint (* const glCreateProgram)() = ::glCreateProgram; -GLuint (* const glCreateShader)(GLenum) = ::glCreateShader; -void (* const glCullFace)(GLenum) = ::glCullFace; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = ::glDeleteBuffers; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = ::glDeleteFramebuffers; -void (* const glDeleteProgram)(GLuint) = ::glDeleteProgram; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = ::glDeleteRenderbuffers; -void (* const glDeleteShader)(GLuint) = ::glDeleteShader; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = ::glDeleteTextures; -void (* const glDepthFunc)(GLenum) = ::glDepthFunc; -void (* const glDepthMask)(GLboolean) = ::glDepthMask; -void (* const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; -void (* const glDetachShader)(GLuint, GLuint) = ::glDetachShader; -void (* const glDisable)(GLenum) = ::glDisable; -void (* const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = ::glDrawElements; -void (* const glEnable)(GLenum) = ::glEnable; -void (* const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; -void (* const glFinish)() = ::glFinish; -void (* const glFlush)() = ::glFlush; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; -void (* const glFrontFace)(GLenum) = ::glFrontFace; -void (* const glGenBuffers)(GLsizei, GLuint *) = ::glGenBuffers; -void (* const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = ::glGenFramebuffers; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = ::glGenRenderbuffers; -void (* const glGenTextures)(GLsizei, GLuint *) = ::glGenTextures; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveAttrib; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveUniform; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = ::glGetAttachedShaders; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = ::glGetAttribLocation; -void (* const glGetBooleanv)(GLenum, GLboolean *) = ::glGetBooleanv; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetBufferParameteriv; -GLenum (* const glGetError)() = ::glGetError; -void (* const glGetFloatv)(GLenum, GLfloat *) = ::glGetFloatv; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = ::glGetFramebufferAttachmentParameteriv; -void (* const glGetIntegerv)(GLenum, GLint *) = ::glGetIntegerv; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetProgramInfoLog; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = ::glGetProgramiv; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetRenderbufferParameteriv; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderInfoLog; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = ::glGetShaderiv; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = ::glGetShaderPrecisionFormat; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderSource; -const GLubyte *(* const glGetString)(GLenum) = ::glGetString; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = ::glGetTexParameterfv; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = ::glGetTexParameteriv; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = ::glGetUniformfv; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = ::glGetUniformiv; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = ::glGetUniformLocation; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = ::glGetVertexAttribfv; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribiv; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = ::glGetVertexAttribPointerv; -void (* const glHint)(GLenum, GLenum) = ::glHint; -GLboolean (* const glIsBuffer)(GLuint) = ::glIsBuffer; -GLboolean (* const glIsEnabled)(GLenum) = ::glIsEnabled; -GLboolean (* const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; -GLboolean (* const glIsProgram)(GLuint) = ::glIsProgram; -GLboolean (* const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; -GLboolean (* const glIsShader)(GLuint) = ::glIsShader; -GLboolean (* const glIsTexture)(GLuint) = ::glIsTexture; -void (* const glLineWidth)(GLfloat) = ::glLineWidth; -void (* const glLinkProgram)(GLuint) = ::glLinkProgram; -void (* const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; -void (* const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = ::glReadPixels; -void (* const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; -void (* const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = ::glShaderBinary; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = ::glShaderSource; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; -void (* const glStencilMask)(GLuint) = ::glStencilMask; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = ::glTexImage2D; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = ::glTexParameterfv; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = ::glTexParameteriv; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = ::glTexSubImage2D; -void (* const glUniform1f)(GLint, GLfloat) = ::glUniform1f; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = ::glUniform1fv; -void (* const glUniform1i)(GLint, GLint) = ::glUniform1i; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = ::glUniform1iv; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = ::glUniform2fv; -void (* const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = ::glUniform2iv; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = ::glUniform3fv; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = ::glUniform3iv; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = ::glUniform4fv; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = ::glUniform4iv; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2fv; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3fv; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4fv; -void (* const glUseProgram)(GLuint) = ::glUseProgram; -void (* const glValidateProgram)(GLuint) = ::glValidateProgram; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = ::glVertexAttrib1fv; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = ::glVertexAttrib2fv; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = ::glVertexAttrib3fv; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = ::glVertexAttrib4fv; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = ::glVertexAttribPointer; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; +void (*const glActiveTexture)(GLenum) = ::glActiveTexture; +void (*const glAttachShader)(GLuint, GLuint) = ::glAttachShader; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = ::glBindAttribLocation; +void (*const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; +void (*const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; +void (*const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; +void (*const glBindTexture)(GLenum, GLuint) = ::glBindTexture; +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; +void (*const glBlendEquation)(GLenum) = ::glBlendEquation; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; +void (*const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = ::glBufferData; +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = ::glBufferSubData; +GLenum (*const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; +void (*const glClear)(GLbitfield) = ::glClear; +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; +void (*const glClearDepthf)(GLfloat) = ::glClearDepthf; +void (*const glClearStencil)(GLint) = ::glClearStencil; +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; +void (*const glCompileShader)(GLuint) = ::glCompileShader; +void (*const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = + ::glCompressedTexImage2D; +void (*const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = + ::glCompressedTexSubImage2D; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; +GLuint (*const glCreateProgram)() = ::glCreateProgram; +GLuint (*const glCreateShader)(GLenum) = ::glCreateShader; +void (*const glCullFace)(GLenum) = ::glCullFace; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = ::glDeleteBuffers; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = ::glDeleteFramebuffers; +void (*const glDeleteProgram)(GLuint) = ::glDeleteProgram; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = ::glDeleteRenderbuffers; +void (*const glDeleteShader)(GLuint) = ::glDeleteShader; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = ::glDeleteTextures; +void (*const glDepthFunc)(GLenum) = ::glDepthFunc; +void (*const glDepthMask)(GLboolean) = ::glDepthMask; +void (*const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; +void (*const glDetachShader)(GLuint, GLuint) = ::glDetachShader; +void (*const glDisable)(GLenum) = ::glDisable; +void (*const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = ::glDrawElements; +void (*const glEnable)(GLenum) = ::glEnable; +void (*const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; +void (*const glFinish)() = ::glFinish; +void (*const glFlush)() = ::glFlush; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; +void (*const glFrontFace)(GLenum) = ::glFrontFace; +void (*const glGenBuffers)(GLsizei, GLuint*) = ::glGenBuffers; +void (*const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = ::glGenFramebuffers; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = ::glGenRenderbuffers; +void (*const glGenTextures)(GLsizei, GLuint*) = ::glGenTextures; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveAttrib; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveUniform; +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = ::glGetAttachedShaders; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = ::glGetAttribLocation; +void (*const glGetBooleanv)(GLenum, GLboolean*) = ::glGetBooleanv; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetBufferParameteriv; +GLenum (*const glGetError)() = ::glGetError; +void (*const glGetFloatv)(GLenum, GLfloat*) = ::glGetFloatv; +void (*const glGetFramebufferAttachmentParameteriv)(GLenum, + GLenum, + GLenum, + GLint*) = ::glGetFramebufferAttachmentParameteriv; +void (*const glGetIntegerv)(GLenum, GLint*) = ::glGetIntegerv; +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetProgramInfoLog; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = ::glGetProgramiv; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetRenderbufferParameteriv; +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderInfoLog; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = ::glGetShaderiv; +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = ::glGetShaderPrecisionFormat; +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderSource; +const GLubyte* (*const glGetString)(GLenum) = ::glGetString; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = ::glGetTexParameterfv; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = ::glGetTexParameteriv; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = ::glGetUniformfv; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = ::glGetUniformiv; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = ::glGetUniformLocation; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = ::glGetVertexAttribfv; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribiv; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = ::glGetVertexAttribPointerv; +void (*const glHint)(GLenum, GLenum) = ::glHint; +GLboolean (*const glIsBuffer)(GLuint) = ::glIsBuffer; +GLboolean (*const glIsEnabled)(GLenum) = ::glIsEnabled; +GLboolean (*const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; +GLboolean (*const glIsProgram)(GLuint) = ::glIsProgram; +GLboolean (*const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; +GLboolean (*const glIsShader)(GLuint) = ::glIsShader; +GLboolean (*const glIsTexture)(GLuint) = ::glIsTexture; +void (*const glLineWidth)(GLfloat) = ::glLineWidth; +void (*const glLinkProgram)(GLuint) = ::glLinkProgram; +void (*const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; +void (*const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = ::glReadPixels; +void (*const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; +void (*const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = ::glShaderBinary; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = ::glShaderSource; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; +void (*const glStencilMask)(GLuint) = ::glStencilMask; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = ::glTexImage2D; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = ::glTexParameterfv; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = ::glTexParameteriv; +void (*const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = + ::glTexSubImage2D; +void (*const glUniform1f)(GLint, GLfloat) = ::glUniform1f; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = ::glUniform1fv; +void (*const glUniform1i)(GLint, GLint) = ::glUniform1i; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = ::glUniform1iv; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = ::glUniform2fv; +void (*const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = ::glUniform2iv; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = ::glUniform3fv; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = ::glUniform3iv; +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = ::glUniform4fv; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = ::glUniform4iv; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2fv; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3fv; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4fv; +void (*const glUseProgram)(GLuint) = ::glUseProgram; +void (*const glValidateProgram)(GLuint) = ::glValidateProgram; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = ::glVertexAttrib1fv; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = ::glVertexAttrib2fv; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = ::glVertexAttrib3fv; +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = ::glVertexAttrib4fv; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = ::glVertexAttribPointer; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = ::glReadBuffer; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *) = ::glDrawRangeElements; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *) = ::glTexImage3D; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *) = ::glTexSubImage3D; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *) = ::glCompressedTexImage3D; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *) = ::glCompressedTexSubImage3D; -void (* const glGenQueries)(GLsizei, GLuint *) = ::glGenQueries; -void (* const glDeleteQueries)(GLsizei, const GLuint *) = ::glDeleteQueries; -GLboolean (* const glIsQuery)(GLuint) = ::glIsQuery; -void (* const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; -void (* const glEndQuery)(GLenum) = ::glEndQuery; -void (* const glGetQueryiv)(GLenum, GLenum, GLint *) = ::glGetQueryiv; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *) = ::glGetQueryObjectuiv; -GLboolean (* const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **) = ::glGetBufferPointerv; -void (* const glDrawBuffers)(GLsizei, const GLenum *) = ::glDrawBuffers; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x3fv; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x2fv; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x4fv; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x2fv; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x4fv; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x3fv; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; -void (* const glBindVertexArray)(GLuint) = ::glBindVertexArray; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint *) = ::glDeleteVertexArrays; -void (* const glGenVertexArrays)(GLsizei, GLuint *) = ::glGenVertexArrays; -GLboolean (* const glIsVertexArray)(GLuint) = ::glIsVertexArray; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *) = ::glGetIntegeri_v; -void (* const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; -void (* const glEndTransformFeedback)() = ::glEndTransformFeedback; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum) = ::glTransformFeedbackVaryings; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *) = ::glGetTransformFeedbackVarying; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *) = ::glVertexAttribIPointer; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribIiv; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *) = ::glGetVertexAttribIuiv; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; -void (* const glVertexAttribI4iv)(GLuint, const GLint *) = ::glVertexAttribI4iv; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint *) = ::glVertexAttribI4uiv; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint *) = ::glGetUniformuiv; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar *) = ::glGetFragDataLocation; -void (* const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *) = ::glUniform1uiv; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *) = ::glUniform2uiv; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *) = ::glUniform3uiv; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *) = ::glUniform4uiv; -void (* const glClearBufferiv)(GLenum, GLint, const GLint *) = ::glClearBufferiv; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *) = ::glClearBufferuiv; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *) = ::glClearBufferfv; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = ::glGetStringi; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *) = ::glGetUniformIndices; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *) = ::glGetActiveUniformsiv; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *) = ::glGetUniformBlockIndex; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *) = ::glGetActiveUniformBlockiv; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetActiveUniformBlockName; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei) = ::glDrawElementsInstanced; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; -GLboolean (* const glIsSync)(GLsync) = ::glIsSync; -void (* const glDeleteSync)(GLsync) = ::glDeleteSync; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; -void (* const glGetInteger64v)(GLenum, GLint64 *) = ::glGetInteger64v; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *) = ::glGetSynciv; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *) = ::glGetInteger64i_v; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *) = ::glGetBufferParameteri64v; -void (* const glGenSamplers)(GLsizei, GLuint *) = ::glGenSamplers; -void (* const glDeleteSamplers)(GLsizei, const GLuint *) = ::glDeleteSamplers; -GLboolean (* const glIsSampler)(GLuint) = ::glIsSampler; -void (* const glBindSampler)(GLuint, GLuint) = ::glBindSampler; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *) = ::glSamplerParameteriv; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *) = ::glSamplerParameterfv; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *) = ::glGetSamplerParameteriv; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *) = ::glGetSamplerParameterfv; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; -void (* const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *) = ::glDeleteTransformFeedbacks; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint *) = ::glGenTransformFeedbacks; -GLboolean (* const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; -void (* const glPauseTransformFeedback)() = ::glPauseTransformFeedback; -void (* const glResumeTransformFeedback)() = ::glResumeTransformFeedback; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *) = ::glGetProgramBinary; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei) = ::glProgramBinary; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *) = ::glInvalidateFramebuffer; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *) = ::glGetInternalformativ; +void (*const glReadBuffer)(GLenum) = ::glReadBuffer; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = ::glDrawRangeElements; +void (*const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = + ::glTexImage3D; +void (*const glTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = ::glTexSubImage3D; +void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = + ::glCopyTexSubImage3D; +void (*const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = + ::glCompressedTexImage3D; +void (*const glCompressedTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = + ::glCompressedTexSubImage3D; +void (*const glGenQueries)(GLsizei, GLuint*) = ::glGenQueries; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = ::glDeleteQueries; +GLboolean (*const glIsQuery)(GLuint) = ::glIsQuery; +void (*const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; +void (*const glEndQuery)(GLenum) = ::glEndQuery; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = ::glGetQueryiv; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = ::glGetQueryObjectuiv; +GLboolean (*const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = ::glGetBufferPointerv; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = ::glDrawBuffers; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x3fv; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x2fv; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x4fv; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x2fv; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x4fv; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x3fv; +void (*const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = + ::glBlitFramebuffer; +void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = + ::glRenderbufferStorageMultisample; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; +void (*const glBindVertexArray)(GLuint) = ::glBindVertexArray; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = ::glDeleteVertexArrays; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = ::glGenVertexArrays; +GLboolean (*const glIsVertexArray)(GLuint) = ::glIsVertexArray; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = ::glGetIntegeri_v; +void (*const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; +void (*const glEndTransformFeedback)() = ::glEndTransformFeedback; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; +void (*const glTransformFeedbackVaryings)(GLuint, + GLsizei, + const GLchar* const*, + GLenum) = ::glTransformFeedbackVaryings; +void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = + ::glGetTransformFeedbackVarying; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = ::glVertexAttribIPointer; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribIiv; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = ::glGetVertexAttribIuiv; +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = ::glVertexAttribI4iv; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = ::glVertexAttribI4uiv; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = ::glGetUniformuiv; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = ::glGetFragDataLocation; +void (*const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = ::glUniform1uiv; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = ::glUniform2uiv; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = ::glUniform3uiv; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = ::glUniform4uiv; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = ::glClearBufferiv; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = ::glClearBufferuiv; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = ::glClearBufferfv; +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = ::glGetStringi; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = ::glGetUniformIndices; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = ::glGetActiveUniformsiv; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = ::glGetUniformBlockIndex; +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = ::glGetActiveUniformBlockiv; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetActiveUniformBlockName; +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = ::glDrawElementsInstanced; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; +GLboolean (*const glIsSync)(GLsync) = ::glIsSync; +void (*const glDeleteSync)(GLsync) = ::glDeleteSync; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; +void (*const glGetInteger64v)(GLenum, GLint64*) = ::glGetInteger64v; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = ::glGetSynciv; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = ::glGetInteger64i_v; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = ::glGetBufferParameteri64v; +void (*const glGenSamplers)(GLsizei, GLuint*) = ::glGenSamplers; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = ::glDeleteSamplers; +GLboolean (*const glIsSampler)(GLuint) = ::glIsSampler; +void (*const glBindSampler)(GLuint, GLuint) = ::glBindSampler; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = ::glSamplerParameteriv; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = ::glSamplerParameterfv; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = ::glGetSamplerParameteriv; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = ::glGetSamplerParameterfv; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; +void (*const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = ::glDeleteTransformFeedbacks; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = ::glGenTransformFeedbacks; +GLboolean (*const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; +void (*const glPauseTransformFeedback)() = ::glPauseTransformFeedback; +void (*const glResumeTransformFeedback)() = ::glResumeTransformFeedback; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = ::glGetProgramBinary; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = ::glProgramBinary; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = ::glInvalidateFramebuffer; +void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = + ::glInvalidateSubFramebuffer; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = ::glGetInternalformativ; -} // namespace platform -} // namespace mbgl \ No newline at end of file +} // namespace platform +} // namespace mbgl \ No newline at end of file diff --git a/platform/android/src/image.cpp b/platform/android/src/image.cpp index 31515ff16fd..0c756155db9 100644 --- a/platform/android/src/image.cpp +++ b/platform/android/src/image.cpp @@ -9,11 +9,10 @@ namespace mbgl { PremultipliedImage decodeImage(const std::string& string) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; auto array = jni::Array::New(*env, string.size()); - jni::SetArrayRegion(*env, *array, 0, string.size(), - reinterpret_cast(string.data())); + jni::SetArrayRegion(*env, *array, 0, string.size(), reinterpret_cast(string.data())); return android::Bitmap::GetImage(*env, android::BitmapFactory::DecodeByteArray(*env, array, 0, string.size())); } diff --git a/platform/android/src/jni.cpp b/platform/android/src/jni.cpp old mode 100755 new mode 100644 index 1c958c0ff88..9c5a7199065 --- a/platform/android/src/jni.cpp +++ b/platform/android/src/jni.cpp @@ -7,7 +7,7 @@ namespace android { JavaVM* theJVM; -//TODO: remove +// TODO: remove bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { assert(vm != nullptr); assert(env != nullptr); @@ -17,7 +17,7 @@ bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { jint ret; *env = nullptr; bool detach = false; - ret = vm->GetEnv(reinterpret_cast(env), JNI_VERSION_1_6); + ret = vm->GetEnv(reinterpret_cast(env), JNI_VERSION_1_6); if (ret != JNI_OK) { if (ret != JNI_EDETACHED) { mbgl::Log::Error(mbgl::Event::JNI, "GetEnv() failed with " + std::to_string(ret)); @@ -35,7 +35,7 @@ bool attach_jni_thread(JavaVM* vm, JNIEnv** env, std::string threadName) { return detach; } -//TODO: remove +// TODO: remove void detach_jni_thread(JavaVM* vm, JNIEnv** env, bool detach) { if (detach) { assert(vm != nullptr); diff --git a/platform/android/src/run_loop.cpp b/platform/android/src/run_loop.cpp index c344353fc92..8fcf2fb30e8 100644 --- a/platform/android/src/run_loop.cpp +++ b/platform/android/src/run_loop.cpp @@ -21,7 +21,7 @@ #include #define PIPE_OUT 0 -#define PIPE_IN 1 +#define PIPE_IN 1 namespace { @@ -29,7 +29,8 @@ using namespace mbgl::util; int looperCallbackNew(int fd, int, void* data) { int buffer[1]; - while (read(fd, buffer, sizeof(buffer)) > 0) {} + while (read(fd, buffer, sizeof(buffer)) > 0) { + } auto runLoopImpl = reinterpret_cast(data); @@ -41,7 +42,8 @@ int looperCallbackNew(int fd, int, void* data) { int looperCallbackDefault(int fd, int, void* data) { int buffer[1]; - while (read(fd, buffer, sizeof(buffer)) > 0) {} + while (read(fd, buffer, sizeof(buffer)) > 0) { + } auto runLoopImpl = reinterpret_cast(data); @@ -82,7 +84,8 @@ namespace util { // efficient way of waking up the RunLoop and it is also thread-safe. class Alarm { public: - Alarm(ActorRef, RunLoop::Impl* loop_) : loop(loop_) {} + Alarm(ActorRef, RunLoop::Impl* loop_) + : loop(loop_) {} void set(const Milliseconds& timeout) { alarm.start(timeout, mbgl::Duration::zero(), [this]() { loop->wake(); }); @@ -93,7 +96,8 @@ class Alarm { RunLoop::Impl* loop; }; -RunLoop::Impl::Impl(RunLoop* runLoop_, RunLoop::Type type) : runLoop(runLoop_) { +RunLoop::Impl::Impl(RunLoop* runLoop_, RunLoop::Type type) + : runLoop(runLoop_) { loop = ALooper_prepare(0); assert(loop); @@ -110,16 +114,16 @@ RunLoop::Impl::Impl(RunLoop* runLoop_, RunLoop::Type type) : runLoop(runLoop_) { int ret = 0; switch (type) { - case Type::New: - ret = ALooper_addFd(loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, - ALOOPER_EVENT_INPUT, looperCallbackNew, this); - break; - case Type::Default: - ret = ALooper_addFd(loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, - ALOOPER_EVENT_INPUT, looperCallbackDefault, this); - alarm = std::make_unique>("Alarm", this); - running = true; - break; + case Type::New: + ret = ALooper_addFd( + loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallbackNew, this); + break; + case Type::Default: + ret = ALooper_addFd( + loop, fds[PIPE_OUT], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallbackDefault, this); + alarm = std::make_unique>("Alarm", this); + running = true; + break; } if (ret != 1) { @@ -209,7 +213,8 @@ RunLoop* RunLoop::Get() { return static_cast(Scheduler::GetCurrent()); } -RunLoop::RunLoop(Type type) : impl(std::make_unique(this, type)) { +RunLoop::RunLoop(Type type) + : impl(std::make_unique(this, type)) { Scheduler::SetCurrent(this); } @@ -231,7 +236,7 @@ void RunLoop::run() { impl->running = true; int outFd, outEvents; - char *outData = nullptr; + char* outData = nullptr; while (impl->running) { process(); diff --git a/platform/android/src/run_loop_impl.hpp b/platform/android/src/run_loop_impl.hpp index 8f0a07f8ba2..8bbf6dfc2e3 100644 --- a/platform/android/src/run_loop_impl.hpp +++ b/platform/android/src/run_loop_impl.hpp @@ -18,7 +18,8 @@ namespace util { using WatchCallback = std::function; -template class Thread; +template +class Thread; class Alarm; class RunLoop::Impl { diff --git a/platform/android/src/string_util.cpp b/platform/android/src/string_util.cpp index f02155caff0..9a0dcb27b38 100644 --- a/platform/android/src/string_util.cpp +++ b/platform/android/src/string_util.cpp @@ -6,7 +6,7 @@ namespace mbgl { namespace platform { std::string uppercase(const std::string& str) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; jni::Local value = jni::Make(*env, str.c_str()); static auto toUpperCase = jni::Class::Singleton(*env).GetMethod(*env, "toUpperCase"); auto result = value.Call(*env, toUpperCase); @@ -14,7 +14,7 @@ std::string uppercase(const std::string& str) { } std::string lowercase(const std::string& str) { - auto env{ android::AttachEnv() }; + auto env{android::AttachEnv()}; jni::Local value = jni::Make(*env, str.c_str()); static auto toLowerCase = jni::Class::Singleton(*env).GetMethod(*env, "toLowerCase"); auto result = value.Call(*env, toLowerCase); diff --git a/platform/android/src/test/collator_test_stub.cpp b/platform/android/src/test/collator_test_stub.cpp index 137909d06b5..780785fda75 100644 --- a/platform/android/src/test/collator_test_stub.cpp +++ b/platform/android/src/test/collator_test_stub.cpp @@ -16,7 +16,8 @@ class Collator::Impl { std::string resolvedLocale() const { return ""; } }; -Collator::Collator(bool, bool, const std::optional& locale_) : impl(std::make_shared(locale_)) {} +Collator::Collator(bool, bool, const std::optional& locale_) + : impl(std::make_shared(locale_)) {} int Collator::compare(const std::string& lhs, const std::string& rhs) const { return impl->compare(lhs, rhs); diff --git a/platform/android/src/test/http_file_source_test_stub.cpp b/platform/android/src/test/http_file_source_test_stub.cpp index 53648c3fd5e..2ab1855c82a 100644 --- a/platform/android/src/test/http_file_source_test_stub.cpp +++ b/platform/android/src/test/http_file_source_test_stub.cpp @@ -8,20 +8,17 @@ namespace mbgl { class HTTPFileSource::Impl {}; HTTPFileSource::HTTPFileSource(const ResourceOptions& /*resourceOptions*/, const ClientOptions& /*clientOptions*/) - : impl(std::make_unique()) { -} + : impl(std::make_unique()) {} HTTPFileSource::~HTTPFileSource() = default; -void HTTPFileSource::setResourceOptions(ResourceOptions /*options*/) { -} +void HTTPFileSource::setResourceOptions(ResourceOptions /*options*/) {} ResourceOptions HTTPFileSource::getResourceOptions() { return ResourceOptions::Default(); } -void HTTPFileSource::setClientOptions(ClientOptions /*options*/) { -} +void HTTPFileSource::setClientOptions(ClientOptions /*options*/) {} ClientOptions HTTPFileSource::getClientOptions() { return ClientOptions(); diff --git a/platform/android/src/test/number_format_test_stub.cpp b/platform/android/src/test/number_format_test_stub.cpp index 57710c8558e..08518a41f23 100644 --- a/platform/android/src/test/number_format_test_stub.cpp +++ b/platform/android/src/test/number_format_test_stub.cpp @@ -7,7 +7,8 @@ std::string formatNumber(double /*number*/, const std::string& /*localeId */, const std::string& /*currency*/, uint8_t /*minFractionDigits*/, - uint8_t /*maxFractionDigits*/) { + uint8_t /*maxFractionDigits*/ +) { return ""; } diff --git a/platform/android/src/test/runtime.cpp b/platform/android/src/test/runtime.cpp index 1f8f16da3cc..10f203db207 100644 --- a/platform/android/src/test/runtime.cpp +++ b/platform/android/src/test/runtime.cpp @@ -9,9 +9,9 @@ #include // Required for art / libsigchain -extern "C" JNIEXPORT void EnsureFrontOfChain(int, struct sigaction*) { } -extern "C" JNIEXPORT void AddSpecialSignalHandlerFn(int, void*) { } -extern "C" JNIEXPORT void RemoveSpecialSignalHandlerFn(int, bool (*) (int, siginfo_t*, void*)) { } +extern "C" JNIEXPORT void EnsureFrontOfChain(int, struct sigaction*) {} +extern "C" JNIEXPORT void AddSpecialSignalHandlerFn(int, void*) {} +extern "C" JNIEXPORT void RemoveSpecialSignalHandlerFn(int, bool (*)(int, siginfo_t*, void*)) {} namespace { const std::string kClassPathCommand{"--class_path="}; @@ -22,11 +22,11 @@ const std::string kDefaultDex{"/data/local/tmp/core-tests/classes.dex"}; namespace mbgl { namespace android { -bool initRuntime(int argc, char *argv[]) { +bool initRuntime(int argc, char* argv[]) { void* vmHandle = dlopen("libart.so", RTLD_NOW); assert(vmHandle != nullptr); - using CreateJavaVMFn = jint (*)(JavaVM** vm, JNIEnv** env, void* vmArgs); + using CreateJavaVMFn = jint (*)(JavaVM * *vm, JNIEnv * *env, void* vmArgs); CreateJavaVMFn createJavaVMFn = reinterpret_cast(dlsym(vmHandle, "JNI_CreateJavaVM")); assert(createJavaVMFn != nullptr); @@ -58,8 +58,9 @@ bool initRuntime(int argc, char *argv[]) { void* runtimeHandle = dlopen("libandroid_runtime.so", RTLD_NOW); assert(runtimeHandle != nullptr); - using RegisterNativesFn = jint (*)(JNIEnv* env); - RegisterNativesFn registerNativesFn = reinterpret_cast(dlsym(runtimeHandle, "registerFrameworkNatives")); + using RegisterNativesFn = jint (*)(JNIEnv * env); + RegisterNativesFn registerNativesFn = reinterpret_cast( + dlsym(runtimeHandle, "registerFrameworkNatives")); assert(registerNativesFn != nullptr); if (registerNativesFn(env) != JNI_OK) { diff --git a/platform/android/src/test/test_runner.cpp b/platform/android/src/test/test_runner.cpp index 03faa72c107..49d5d31f50a 100644 --- a/platform/android/src/test/test_runner.cpp +++ b/platform/android/src/test/test_runner.cpp @@ -23,7 +23,7 @@ void runner() { mbgl::Log::Info(mbgl::Event::General, "Start TestRunner"); int status = mbgl::runTests(argv.size(), argv.data()); - mbgl::Log::Info(mbgl::Event::General, "TestRunner finished with status: '" + std::to_string(status) + "'"); + mbgl::Log::Info(mbgl::Event::General, "TestRunner finished with status: '" + std::to_string(status) + "'"); running = false; success = (status == 0); ALooper_wake(looper); diff --git a/platform/android/src/test/test_runner_common.cpp b/platform/android/src/test/test_runner_common.cpp index 600e24ce97c..12809c167d9 100644 --- a/platform/android/src/test/test_runner_common.cpp +++ b/platform/android/src/test/test_runner_common.cpp @@ -27,7 +27,9 @@ int severityToPriority(EventSeverity severity) { template class JavaWrapper { public: - JavaWrapper(JNIEnv* env_, T obj_) : env(env_), obj(obj_) {} + JavaWrapper(JNIEnv* env_, T obj_) + : env(env_), + obj(obj_) {} ~JavaWrapper() { env->DeleteLocalRef(obj); env = nullptr; @@ -115,8 +117,7 @@ bool copyFile(JNIEnv* env, } else { auto res = static_cast(std::fwrite(fileData, sizeof(char), fileLen, newFile.get())); if (fileLen != res) { - mbgl::Log::Warning( - mbgl::Event::General, "Failed to generate file entry" + fileName + "from assets"); + mbgl::Log::Warning(mbgl::Event::General, "Failed to generate file entry" + fileName + "from assets"); } } } @@ -179,22 +180,21 @@ void unZipFile(JNIEnv* env, const std::string& zipFilePath, const std::string& d if (!(env->CallBooleanMethod(f, fileIsDirectory))) { jmethodID mkdirs = env->GetMethodID(fileClass, "mkdirs", "()Z"); bool success = (env->CallBooleanMethod(f, mkdirs)); - std::string fileNameStr = - jstringToStdString(env, static_cast(env->CallObjectMethod(f, fileGetName))); + std::string fileNameStr = jstringToStdString( + env, static_cast(env->CallObjectMethod(f, fileGetName))); if (!success) { - mbgl::Log::Warning( - mbgl::Event::General, "Failed to create folder entry " + fileNameStr + " from zip"); + mbgl::Log::Warning(mbgl::Event::General, + "Failed to create folder entry " + fileNameStr + " from zip"); } } } else if (!(env->CallBooleanMethod(f, fileExists))) { bool success = env->CallBooleanMethod(f, createNewFile); - std::string fileNameStr = - jstringToStdString(env, static_cast(env->CallObjectMethod(f, fileGetName))); + std::string fileNameStr = jstringToStdString(env, + static_cast(env->CallObjectMethod(f, fileGetName))); if (!success) { - mbgl::Log::Warning( - mbgl::Event::General, "Failed to create folder entry" + fileNameStr + "from zip"); + mbgl::Log::Warning(mbgl::Event::General, "Failed to create folder entry" + fileNameStr + "from zip"); continue; } diff --git a/platform/android/src/timer.cpp b/platform/android/src/timer.cpp index 1d3d05c8437..81b1ea1f913 100644 --- a/platform/android/src/timer.cpp +++ b/platform/android/src/timer.cpp @@ -11,11 +11,10 @@ namespace util { class Timer::Impl : public RunLoop::Impl::Runnable { public: - Impl() : active(false) {} + Impl() + : active(false) {} - ~Impl() { - stop(); - } + ~Impl() { stop(); } void start(Duration timeout, Duration repeat_, std::function&& task_) { stop(); @@ -23,8 +22,7 @@ class Timer::Impl : public RunLoop::Impl::Runnable { repeat = repeat_; task = std::move(task_); // Prevent overflows when timeout is set to Duration::max() - due = (timeout == Duration::max()) ? std::chrono::time_point::max() : Clock::now() + - timeout; + due = (timeout == Duration::max()) ? std::chrono::time_point::max() : Clock::now() + timeout; loop->addRunnable(this); active = true; } @@ -43,9 +41,7 @@ class Timer::Impl : public RunLoop::Impl::Runnable { } } - TimePoint dueTime() const override { - return due; - } + TimePoint dueTime() const override { return due; } void runTask() override { if (active) { @@ -64,8 +60,8 @@ class Timer::Impl : public RunLoop::Impl::Runnable { std::atomic active; }; -Timer::Timer() : impl(std::make_unique()) { -} +Timer::Timer() + : impl(std::make_unique()) {} Timer::~Timer() = default; diff --git a/platform/default/include/mbgl/gfx/headless_backend.hpp b/platform/default/include/mbgl/gfx/headless_backend.hpp index 5167e6a465f..1dc7755317d 100644 --- a/platform/default/include/mbgl/gfx/headless_backend.hpp +++ b/platform/default/include/mbgl/gfx/headless_backend.hpp @@ -15,7 +15,10 @@ namespace gfx { // of readStillImage. class HeadlessBackend : public gfx::Renderable { public: - enum class SwapBehaviour { NoFlush, Flush }; + enum class SwapBehaviour { + NoFlush, + Flush + }; // Factory. static std::unique_ptr Create(const Size size = {256, 256}, diff --git a/platform/default/include/mbgl/map/map_snapshotter.hpp b/platform/default/include/mbgl/map/map_snapshotter.hpp index f41ffb5e646..c17ae38150f 100644 --- a/platform/default/include/mbgl/map/map_snapshotter.hpp +++ b/platform/default/include/mbgl/map/map_snapshotter.hpp @@ -63,10 +63,10 @@ class MapSnapshotter { style::Style& getStyle(); const style::Style& getStyle() const; - using PointForFn = std::function; - using LatLngForFn = std::function; + using PointForFn = std::function; + using LatLngForFn = std::function; using Attributions = std::vector; - using Callback = std::function; + using Callback = std::function; void snapshot(Callback); void cancel(); diff --git a/platform/default/include/mbgl/storage/merge_sideloaded.hpp b/platform/default/include/mbgl/storage/merge_sideloaded.hpp index 494018c9660..ff12ae13e13 100644 --- a/platform/default/include/mbgl/storage/merge_sideloaded.hpp +++ b/platform/default/include/mbgl/storage/merge_sideloaded.hpp @@ -6,48 +6,57 @@ namespace mbgl { static constexpr const char* mergeSideloadedDatabaseSQL = -"INSERT INTO regions\n" -" SELECT DISTINCT NULL, sr.definition, sr.description\n" -" FROM side.regions sr \n" -" LEFT JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description\n" -" WHERE r.definition IS NULL;\n" -"CREATE TEMPORARY TABLE region_mapping AS\n" -" SELECT sr.id AS side_region_id,\n" -" r.id AS main_region_id\n" -" FROM side.regions sr\n" -" JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description;\n" -"REPLACE INTO tiles\n" -" SELECT t.id,\n" -" st.url_template, st.pixel_ratio, st.z, st.x, st.y,\n" -" st.expires, st.modified, st.etag, st.data, st.compressed, st.accessed, st.must_revalidate\n" -" FROM (SELECT DISTINCT sti.* FROM side.region_tiles srt JOIN side.tiles sti ON srt.tile_id = sti.id)\n" -" AS st\n" -" LEFT JOIN tiles t ON st.url_template = t.url_template AND st.pixel_ratio = t.pixel_ratio AND st.z = t.z AND st.x = t.x AND st.y = t.y\n" -" WHERE t.id IS NULL\n" -" OR st.modified > t.modified;\n" -"INSERT OR IGNORE INTO region_tiles\n" -" SELECT rm.main_region_id, sti.id\n" -" FROM side.region_tiles srt\n" -" JOIN region_mapping rm ON srt.region_id = rm.side_region_id\n" -" JOIN (SELECT t.id, st.id AS side_tile_id FROM side.tiles st\n" -" JOIN tiles t ON st.url_template = t.url_template AND st.pixel_ratio = t.pixel_ratio AND st.z = t.z AND st.x = t.x AND st.y = t.y\n" -" ) AS sti ON srt.tile_id = sti.side_tile_id;\n" -"REPLACE INTO resources\n" -" SELECT r.id, \n" -" sr.url, sr.kind, sr.expires, sr.modified, sr.etag,\n" -" sr.data, sr.compressed, sr.accessed, sr.must_revalidate\n" -" FROM side.region_resources srr JOIN side.resources sr ON srr.resource_id = sr.id\n" -" LEFT JOIN resources r ON sr.url = r.url\n" -" WHERE r.id IS NULL\n" -" OR sr.modified > r.modified;\n" -"INSERT OR IGNORE INTO region_resources\n" -" SELECT rm.main_region_id, sri.id\n" -" FROM side.region_resources srr\n" -" JOIN region_mapping rm ON srr.region_id = rm.side_region_id\n" -" JOIN (SELECT r.id, sr.id AS side_resource_id FROM side.resources sr\n" -" JOIN resources r ON sr.url = r.url) AS sri ON srr.resource_id = sri.side_resource_id;\n" -" \n" -"DROP TABLE region_mapping;\n" -; + "INSERT INTO regions\n" + " SELECT DISTINCT NULL, sr.definition, sr.description\n" + " FROM side.regions sr \n" + " LEFT JOIN regions r ON sr.definition = r.definition AND " + "sr.description IS r.description\n" + " WHERE r.definition IS NULL;\n" + "CREATE TEMPORARY TABLE region_mapping AS\n" + " SELECT sr.id AS side_region_id,\n" + " r.id AS main_region_id\n" + " FROM side.regions sr\n" + " JOIN regions r ON sr.definition = r.definition AND sr.description IS " + "r.description;\n" + "REPLACE INTO tiles\n" + " SELECT t.id,\n" + " st.url_template, st.pixel_ratio, st.z, st.x, st.y,\n" + " st.expires, st.modified, st.etag, st.data, st.compressed, " + "st.accessed, st.must_revalidate\n" + " FROM (SELECT DISTINCT sti.* FROM side.region_tiles srt JOIN " + "side.tiles sti ON srt.tile_id = sti.id)\n" + " AS st\n" + " LEFT JOIN tiles t ON st.url_template = t.url_template AND " + "st.pixel_ratio = t.pixel_ratio AND st.z = t.z AND " + "st.x = t.x AND st.y = t.y\n" + " WHERE t.id IS NULL\n" + " OR st.modified > t.modified;\n" + "INSERT OR IGNORE INTO region_tiles\n" + " SELECT rm.main_region_id, sti.id\n" + " FROM side.region_tiles srt\n" + " JOIN region_mapping rm ON srt.region_id = rm.side_region_id\n" + " JOIN (SELECT t.id, st.id AS side_tile_id FROM side.tiles st\n" + " JOIN tiles t ON st.url_template = t.url_template AND " + "st.pixel_ratio = t.pixel_ratio AND st.z = t.z " + "AND st.x = t.x AND st.y = t.y\n" + " ) AS sti ON srt.tile_id = sti.side_tile_id;\n" + "REPLACE INTO resources\n" + " SELECT r.id, \n" + " sr.url, sr.kind, sr.expires, sr.modified, sr.etag,\n" + " sr.data, sr.compressed, sr.accessed, sr.must_revalidate\n" + " FROM side.region_resources srr JOIN side.resources sr ON " + "srr.resource_id = sr.id\n" + " LEFT JOIN resources r ON sr.url = r.url\n" + " WHERE r.id IS NULL\n" + " OR sr.modified > r.modified;\n" + "INSERT OR IGNORE INTO region_resources\n" + " SELECT rm.main_region_id, sri.id\n" + " FROM side.region_resources srr\n" + " JOIN region_mapping rm ON srr.region_id = rm.side_region_id\n" + " JOIN (SELECT r.id, sr.id AS side_resource_id FROM side.resources sr\n" + " JOIN resources r ON sr.url = r.url) AS sri ON srr.resource_id " + "= sri.side_resource_id;\n" + " \n" + "DROP TABLE region_mapping;\n"; } // namespace mbgl diff --git a/platform/default/include/mbgl/storage/offline_database.hpp b/platform/default/include/mbgl/storage/offline_database.hpp index 6a49de10acb..a438508f2a3 100644 --- a/platform/default/include/mbgl/storage/offline_database.hpp +++ b/platform/default/include/mbgl/storage/offline_database.hpp @@ -32,8 +32,9 @@ namespace util { struct IOException; } // namespace util -struct MapboxTileLimitExceededException : util::Exception { - MapboxTileLimitExceededException() : util::Exception("Mapbox tile limit exceeded") {} +struct MapboxTileLimitExceededException : util::Exception { + MapboxTileLimitExceededException() + : util::Exception("Mapbox tile limit exceeded") {} }; class OfflineDatabase { @@ -66,8 +67,7 @@ class OfflineDatabase { expected createRegion(const OfflineRegionDefinition&, const OfflineRegionMetadata&); - expected - mergeDatabase(const std::string& sideDatabasePath); + expected mergeDatabase(const std::string& sideDatabasePath); expected updateMetadata(int64_t regionID, const OfflineRegionMetadata&); @@ -115,17 +115,15 @@ class OfflineDatabase { void vacuum(); void checkFlags(); - mapbox::sqlite::Statement& getStatement(const char *); + mapbox::sqlite::Statement& getStatement(const char*); std::optional> getTile(const Resource::TileData&); std::optional hasTile(const Resource::TileData&); - bool putTile(const Resource::TileData&, const Response&, - const std::string&, bool compressed); + bool putTile(const Resource::TileData&, const Response&, const std::string&, bool compressed); std::optional> getResource(const Resource&); std::optional hasResource(const Resource&); - bool putResource(const Resource&, const Response&, - const std::string&, bool compressed); + bool putResource(const Resource&, const Response&, const std::string&, bool compressed); uint64_t putRegionResourceInternal(int64_t regionID, const Resource&, const Response&); @@ -144,7 +142,7 @@ class OfflineDatabase { std::map> statements; template - T getPragma(const char *); + T getPragma(const char*); uint64_t maximumAmbientCacheSize = util::DEFAULT_MAX_CACHE_SIZE; uint64_t offlineMapboxTileCountLimit = util::mapbox::DEFAULT_OFFLINE_TILE_COUNT_LIMIT; diff --git a/platform/default/include/mbgl/storage/offline_download.hpp b/platform/default/include/mbgl/storage/offline_download.hpp index 973fa826fa9..42bd9d5b822 100644 --- a/platform/default/include/mbgl/storage/offline_download.hpp +++ b/platform/default/include/mbgl/storage/offline_download.hpp @@ -47,7 +47,7 @@ class OfflineDownload { * While the request is in progress, it is recorded in `requests`. If the download * is deactivated, all in progress requests are cancelled. */ - void ensureResource(Resource&&, std::function = {}); + void ensureResource(Resource&&, std::function = {}); void onMapboxTileCountLimitExceeded(); diff --git a/platform/default/include/mbgl/storage/offline_schema.hpp b/platform/default/include/mbgl/storage/offline_schema.hpp index 77c66b7d157..a825435d23c 100644 --- a/platform/default/include/mbgl/storage/offline_schema.hpp +++ b/platform/default/include/mbgl/storage/offline_schema.hpp @@ -6,58 +6,57 @@ namespace mbgl { static constexpr const char* offlineDatabaseSchema = -"CREATE TABLE resources (\n" -" id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" -" url TEXT NOT NULL,\n" -" kind INTEGER NOT NULL,\n" -" expires INTEGER,\n" -" modified INTEGER,\n" -" etag TEXT,\n" -" data BLOB,\n" -" compressed INTEGER NOT NULL DEFAULT 0,\n" -" accessed INTEGER NOT NULL,\n" -" must_revalidate INTEGER NOT NULL DEFAULT 0,\n" -" UNIQUE (url)\n" -");\n" -"CREATE TABLE tiles (\n" -" id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" -" url_template TEXT NOT NULL,\n" -" pixel_ratio INTEGER NOT NULL,\n" -" z INTEGER NOT NULL,\n" -" x INTEGER NOT NULL,\n" -" y INTEGER NOT NULL,\n" -" expires INTEGER,\n" -" modified INTEGER,\n" -" etag TEXT,\n" -" data BLOB,\n" -" compressed INTEGER NOT NULL DEFAULT 0,\n" -" accessed INTEGER NOT NULL,\n" -" must_revalidate INTEGER NOT NULL DEFAULT 0,\n" -" UNIQUE (url_template, pixel_ratio, z, x, y)\n" -");\n" -"CREATE TABLE regions (\n" -" id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" -" definition TEXT NOT NULL,\n" -" description BLOB\n" -");\n" -"CREATE TABLE region_resources (\n" -" region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" -" resource_id INTEGER NOT NULL REFERENCES resources(id),\n" -" UNIQUE (region_id, resource_id)\n" -");\n" -"CREATE TABLE region_tiles (\n" -" region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" -" tile_id INTEGER NOT NULL REFERENCES tiles(id),\n" -" UNIQUE (region_id, tile_id)\n" -");\n" -"CREATE INDEX resources_accessed\n" -"ON resources (accessed);\n" -"CREATE INDEX tiles_accessed\n" -"ON tiles (accessed);\n" -"CREATE INDEX region_resources_resource_id\n" -"ON region_resources (resource_id);\n" -"CREATE INDEX region_tiles_tile_id\n" -"ON region_tiles (tile_id);\n" -; + "CREATE TABLE resources (\n" + " id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " url TEXT NOT NULL,\n" + " kind INTEGER NOT NULL,\n" + " expires INTEGER,\n" + " modified INTEGER,\n" + " etag TEXT,\n" + " data BLOB,\n" + " compressed INTEGER NOT NULL DEFAULT 0,\n" + " accessed INTEGER NOT NULL,\n" + " must_revalidate INTEGER NOT NULL DEFAULT 0,\n" + " UNIQUE (url)\n" + ");\n" + "CREATE TABLE tiles (\n" + " id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " url_template TEXT NOT NULL,\n" + " pixel_ratio INTEGER NOT NULL,\n" + " z INTEGER NOT NULL,\n" + " x INTEGER NOT NULL,\n" + " y INTEGER NOT NULL,\n" + " expires INTEGER,\n" + " modified INTEGER,\n" + " etag TEXT,\n" + " data BLOB,\n" + " compressed INTEGER NOT NULL DEFAULT 0,\n" + " accessed INTEGER NOT NULL,\n" + " must_revalidate INTEGER NOT NULL DEFAULT 0,\n" + " UNIQUE (url_template, pixel_ratio, z, x, y)\n" + ");\n" + "CREATE TABLE regions (\n" + " id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" + " definition TEXT NOT NULL,\n" + " description BLOB\n" + ");\n" + "CREATE TABLE region_resources (\n" + " region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" + " resource_id INTEGER NOT NULL REFERENCES resources(id),\n" + " UNIQUE (region_id, resource_id)\n" + ");\n" + "CREATE TABLE region_tiles (\n" + " region_id INTEGER NOT NULL REFERENCES regions(id) ON DELETE CASCADE,\n" + " tile_id INTEGER NOT NULL REFERENCES tiles(id),\n" + " UNIQUE (region_id, tile_id)\n" + ");\n" + "CREATE INDEX resources_accessed\n" + "ON resources (accessed);\n" + "CREATE INDEX tiles_accessed\n" + "ON tiles (accessed);\n" + "CREATE INDEX region_resources_resource_id\n" + "ON region_resources (resource_id);\n" + "CREATE INDEX region_tiles_tile_id\n" + "ON region_tiles (tile_id);\n"; } // namespace mbgl diff --git a/platform/default/include/mbgl/storage/sqlite3.hpp b/platform/default/include/mbgl/storage/sqlite3.hpp index 9da98daf25f..19898b63ae6 100644 --- a/platform/default/include/mbgl/storage/sqlite3.hpp +++ b/platform/default/include/mbgl/storage/sqlite3.hpp @@ -11,7 +11,7 @@ namespace mapbox { namespace sqlite { enum OpenFlag : int { - ReadOnly = 0b001, + ReadOnly = 0b001, ReadWriteCreate = 0b110, }; @@ -50,13 +50,14 @@ enum class ExtendedResultCode : uint8_t { class Exception : public std::runtime_error { public: - Exception(ResultCode err, const char* msg) : Exception(static_cast(err), msg) {} - Exception(int err, const char* msg) : Exception(err, std::string{ msg }) {} + Exception(ResultCode err, const char* msg) + : Exception(static_cast(err), msg) {} + Exception(int err, const char* msg) + : Exception(err, std::string{msg}) {} Exception(int err, const std::string& msg) : std::runtime_error(msg), code(static_cast(err)), - extendedCode(static_cast(err >> 8)) { - } + extendedCode(static_cast(err >> 8)) {} const ResultCode code = ResultCode::OK; const ExtendedResultCode extendedCode = ExtendedResultCode::Unknown; }; @@ -74,17 +75,17 @@ class Database { Database(std::unique_ptr); public: - Database(const Database &) = delete; - Database &operator=(const Database &) = delete; - static mapbox::util::variant tryOpen(const std::string &filename, int flags = 0); - static Database open(const std::string &filename, int flags = 0); + Database(const Database&) = delete; + Database& operator=(const Database&) = delete; + static mapbox::util::variant tryOpen(const std::string& filename, int flags = 0); + static Database open(const std::string& filename, int flags = 0); Database(Database&&) noexcept; ~Database(); Database& operator=(Database&&) noexcept; void setBusyTimeout(std::chrono::milliseconds); - void exec(const std::string &sql); + void exec(const std::string& sql); private: std::unique_ptr impl; @@ -109,16 +110,18 @@ class Statement { std::unique_ptr impl; #ifndef NDEBUG - // This flag stores whether there exists a Query object that uses this prepared statement. - // There may only be one Query object at a time. Statement objects must outlive Query objects. - // While a Query object exists, a Statement object may not be moved or deleted. + // This flag stores whether there exists a Query object that uses this + // prepared statement. There may only be one Query object at a time. + // Statement objects must outlive Query objects. While a Query object + // exists, a Statement object may not be moved or deleted. bool used = false; #endif }; -// A Query object is used to run a database query with a prepared statement (stored in a Statement -// object). There may only exist one Query object per Statement object. Query objects are designed -// to be constructed and destroyed frequently. +// A Query object is used to run a database query with a prepared statement +// (stored in a Statement object). There may only exist one Query object per +// Statement object. Query objects are designed to be constructed and destroyed +// frequently. class Query { public: Query(Statement&); diff --git a/platform/default/src/mbgl/gfx/headless_backend.cpp b/platform/default/src/mbgl/gfx/headless_backend.cpp index f3eded8dcb2..27428043890 100644 --- a/platform/default/src/mbgl/gfx/headless_backend.cpp +++ b/platform/default/src/mbgl/gfx/headless_backend.cpp @@ -4,8 +4,7 @@ namespace mbgl { namespace gfx { HeadlessBackend::HeadlessBackend(Size size_) - : mbgl::gfx::Renderable(size_, nullptr) { -} + : mbgl::gfx::Renderable(size_, nullptr) {} void HeadlessBackend::setSize(Size size_) { size = size_; diff --git a/platform/default/src/mbgl/gfx/headless_frontend.cpp b/platform/default/src/mbgl/gfx/headless_frontend.cpp index 3c700abdf83..a2a03a5e625 100644 --- a/platform/default/src/mbgl/gfx/headless_frontend.cpp +++ b/platform/default/src/mbgl/gfx/headless_frontend.cpp @@ -32,12 +32,13 @@ HeadlessFrontend::HeadlessFrontend(Size size_, asyncInvalidate([this] { if (renderer && updateParameters) { auto startTime = mbgl::util::MonotonicTimer::now(); - gfx::BackendScope guard {*getBackend()}; + gfx::BackendScope guard{*getBackend()}; - // onStyleImageMissing might be called during a render. The user implemented method - // could trigger a call to MLNRenderFrontend#update which overwrites `updateParameters`. - // Copy the shared pointer here so that the parameters aren't destroyed while `render(...)` is - // still using them. + // onStyleImageMissing might be called during a render. The user + // implemented method could trigger a call to + // MLNRenderFrontend#update which overwrites `updateParameters`. + // Copy the shared pointer here so that the parameters aren't + // destroyed while `render(...)` is still using them. auto updateParameters_ = updateParameters; renderer->render(updateParameters_); @@ -82,8 +83,7 @@ gfx::RendererBackend* HeadlessFrontend::getBackend() { } CameraOptions HeadlessFrontend::getCameraOptions() { - if (updateParameters) - return RendererState::getCameraOptions(*updateParameters); + if (updateParameters) return RendererState::getCameraOptions(*updateParameters); static CameraOptions nullCamera; return nullCamera; @@ -117,7 +117,7 @@ ScreenCoordinate HeadlessFrontend::pixelForLatLng(const LatLng& coordinate) { return RendererState::pixelForLatLng(*updateParameters, coordinate); } - return ScreenCoordinate {}; + return ScreenCoordinate{}; } LatLng HeadlessFrontend::latLngForPixel(const ScreenCoordinate& point) { @@ -125,14 +125,14 @@ LatLng HeadlessFrontend::latLngForPixel(const ScreenCoordinate& point) { return RendererState::latLngForPixel(*updateParameters, point); } - return LatLng {}; + return LatLng{}; } void HeadlessFrontend::setSize(Size size_) { if (size != size_) { size = size_; - backend->setSize({ static_cast(size_.width * pixelRatio), - static_cast(size_.height * pixelRatio) }); + backend->setSize( + {static_cast(size_.width * pixelRatio), static_cast(size_.height * pixelRatio)}); } } @@ -143,7 +143,7 @@ PremultipliedImage HeadlessFrontend::readStillImage() { HeadlessFrontend::RenderResult HeadlessFrontend::render(Map& map) { HeadlessFrontend::RenderResult result; std::exception_ptr error; - gfx::BackendScope guard { *getBackend() }; + gfx::BackendScope guard{*getBackend()}; map.renderStill([&](const std::exception_ptr& e) { if (e) { diff --git a/platform/default/src/mbgl/gl/headless_backend.cpp b/platform/default/src/mbgl/gl/headless_backend.cpp index f8882c47bbc..71178baa1a3 100644 --- a/platform/default/src/mbgl/gl/headless_backend.cpp +++ b/platform/default/src/mbgl/gl/headless_backend.cpp @@ -24,7 +24,7 @@ class HeadlessRenderableResource final : public gl::RenderableResource { void bind() override { context.bindFramebuffer = framebuffer.framebuffer; context.scissorTest = false; - context.viewport = { 0, 0, framebuffer.size }; + context.viewport = {0, 0, framebuffer.size}; } void swap() override { backend.swap(); } @@ -39,13 +39,15 @@ class HeadlessRenderableResource final : public gl::RenderableResource { HeadlessBackend::HeadlessBackend(const Size size_, gfx::HeadlessBackend::SwapBehaviour swapBehaviour_, const gfx::ContextMode contextMode_) - : mbgl::gl::RendererBackend(contextMode_), mbgl::gfx::HeadlessBackend(size_), swapBehaviour(swapBehaviour_) {} + : mbgl::gl::RendererBackend(contextMode_), + mbgl::gfx::HeadlessBackend(size_), + swapBehaviour(swapBehaviour_) {} HeadlessBackend::~HeadlessBackend() { - gfx::BackendScope guard{ *this, gfx::BackendScope::ScopeType::Implicit }; + gfx::BackendScope guard{*this, gfx::BackendScope::ScopeType::Implicit}; resource.reset(); - // Explicitly reset the context so that it is destructed and cleaned up before we destruct - // the impl object. + // Explicitly reset the context so that it is destructed and cleaned up + // before we destruct the impl object. context.reset(); } diff --git a/platform/default/src/mbgl/i18n/collator.cpp b/platform/default/src/mbgl/i18n/collator.cpp index 847d143cd6f..eb63383a346 100644 --- a/platform/default/src/mbgl/i18n/collator.cpp +++ b/platform/default/src/mbgl/i18n/collator.cpp @@ -52,7 +52,8 @@ namespace platform { class Collator::Impl { public: Impl(bool caseSensitive_, bool diacriticSensitive_, const std::optional&) - : caseSensitive(caseSensitive_), diacriticSensitive(diacriticSensitive_) {} + : caseSensitive(caseSensitive_), + diacriticSensitive(diacriticSensitive_) {} bool operator==(const Impl& other) const { return caseSensitive == other.caseSensitive && diacriticSensitive == other.diacriticSensitive; @@ -60,11 +61,9 @@ class Collator::Impl { int compare(const std::string& lhs, const std::string& rhs) const { if (caseSensitive && diacriticSensitive) { - return nu_strcoll(lhs.c_str(), rhs.c_str(), - nu_utf8_read, nu_utf8_read); + return nu_strcoll(lhs.c_str(), rhs.c_str(), nu_utf8_read, nu_utf8_read); } else if (!caseSensitive && diacriticSensitive) { - return nu_strcasecoll(lhs.c_str(), rhs.c_str(), - nu_utf8_read, nu_utf8_read); + return nu_strcasecoll(lhs.c_str(), rhs.c_str(), nu_utf8_read, nu_utf8_read); } else if (caseSensitive && !diacriticSensitive) { return nu_strcoll(unaccent(lhs).c_str(), unaccent(rhs).c_str(), nu_utf8_read, nu_utf8_read); } else { @@ -72,9 +71,7 @@ class Collator::Impl { } } - std::string resolvedLocale() const { - return ""; - } + std::string resolvedLocale() const { return ""; } private: bool caseSensitive; diff --git a/platform/default/src/mbgl/layermanager/layer_manager.cpp b/platform/default/src/mbgl/layermanager/layer_manager.cpp index 3e822a7b4b1..3e5767957c9 100644 --- a/platform/default/src/mbgl/layermanager/layer_manager.cpp +++ b/platform/default/src/mbgl/layermanager/layer_manager.cpp @@ -78,14 +78,16 @@ void LayerManagerDefault::addLayerType(std::unique_ptr factory) { if (!type.empty()) { typeToFactory.emplace(std::make_pair(std::move(type), factory.get())); } else { - Log::Warning(Event::Setup, "Failure adding layer factory. getTypeInfo() returned an empty type string."); + Log::Warning(Event::Setup, + "Failure adding layer factory. getTypeInfo() returned an empty " + "type string."); } factories.emplace_back(std::move(factory)); } LayerFactory* LayerManagerDefault::getFactory(const mbgl::style::LayerTypeInfo* typeInfo) noexcept { assert(typeInfo); - for (const auto& factory: factories) { + for (const auto& factory : factories) { if (factory->getTypeInfo() == typeInfo) { return factory.get(); } @@ -105,7 +107,8 @@ LayerManager* LayerManager::get() noexcept { return &instance; } -#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || defined(MBGL_LAYER_FILL_DISABLE_ALL) +#if defined(MBGL_LAYER_LINE_DISABLE_ALL) || defined(MBGL_LAYER_SYMBOL_DISABLE_ALL) || \ + defined(MBGL_LAYER_FILL_DISABLE_ALL) const bool LayerManager::annotationsEnabled = false; #else const bool LayerManager::annotationsEnabled = true; diff --git a/platform/default/src/mbgl/map/map_snapshotter.cpp b/platform/default/src/mbgl/map/map_snapshotter.cpp index 7ddd4daa2f9..12be320da0a 100644 --- a/platform/default/src/mbgl/map/map_snapshotter.cpp +++ b/platform/default/src/mbgl/map/map_snapshotter.cpp @@ -27,13 +27,12 @@ MapSnapshotterObserver& MapSnapshotterObserver::nullObserver() { class ForwardingRendererObserver final : public RendererObserver { public: explicit ForwardingRendererObserver(RendererObserver& delegate_) - : mailbox(std::make_shared(*Scheduler::GetCurrent())), delegate(delegate_, mailbox) {} + : mailbox(std::make_shared(*Scheduler::GetCurrent())), + delegate(delegate_, mailbox) {} ~ForwardingRendererObserver() override { mailbox->close(); } - void onInvalidate() override { - delegate.invoke(&RendererObserver::onInvalidate); - } + void onInvalidate() override { delegate.invoke(&RendererObserver::onInvalidate); } void onResourceError(std::exception_ptr err) override { delegate.invoke(&RendererObserver::onResourceError, err); } @@ -64,9 +63,7 @@ class SnapshotterRenderer final : public RendererObserver { frontend.reset(); } - void onInvalidate() override { - rendererObserver->onInvalidate(); - } + void onInvalidate() override { rendererObserver->onInvalidate(); } void onResourceError(std::exception_ptr err) override { hasPendingStillImageRequest = false; @@ -209,11 +206,11 @@ class MapSnapshotter::Impl final : public MapObserver { // Create lambda that captures the current transform state // and can be used to translate for geographic to screen // coordinates - LatLngForFn latLngForFn = [transformState = - frontend.getTransformState()](const ScreenCoordinate& screenCoordinate) { - Transform transform{transformState}; - return transform.screenCoordinateToLatLng(screenCoordinate); - }; + LatLngForFn latLngForFn = + [transformState = frontend.getTransformState()](const ScreenCoordinate& screenCoordinate) { + Transform transform{transformState}; + return transform.screenCoordinateToLatLng(screenCoordinate); + }; // Collect all source attributions std::vector attributions; @@ -260,7 +257,10 @@ MapSnapshotter::MapSnapshotter(Size size, : impl(std::make_unique( size, pixelRatio, resourceOptions, clientOptions, observer, std::move(localFontFamily))) {} -MapSnapshotter::MapSnapshotter(Size size, float pixelRatio, const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) +MapSnapshotter::MapSnapshotter(Size size, + float pixelRatio, + const ResourceOptions& resourceOptions, + const ClientOptions& clientOptions) : MapSnapshotter(size, pixelRatio, resourceOptions, clientOptions, MapSnapshotterObserver::nullObserver()) {} MapSnapshotter::~MapSnapshotter() = default; diff --git a/platform/default/src/mbgl/storage/asset_file_source.cpp b/platform/default/src/mbgl/storage/asset_file_source.cpp index 828407b637d..a43c0be9679 100644 --- a/platform/default/src/mbgl/storage/asset_file_source.cpp +++ b/platform/default/src/mbgl/storage/asset_file_source.cpp @@ -21,23 +21,22 @@ namespace mbgl { class AssetFileSource::Impl { public: - Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_): - root (resourceOptions_.assetPath()), - resourceOptions (resourceOptions_.clone()), - clientOptions (clientOptions_.clone()) {} + Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) + : root(resourceOptions_.assetPath()), + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} void request(const std::string& url, const ActorRef& req) { if (!acceptsURL(url)) { Response response; - response.error = std::make_unique(Response::Error::Reason::Other, - "Invalid asset URL"); + response.error = std::make_unique(Response::Error::Reason::Other, "Invalid asset URL"); req.invoke(&FileSourceRequest::setResponse, response); return; } // Cut off the protocol and prefix with path. - const auto path = - root + "/" + mbgl::util::percentDecode(url.substr(std::char_traits::length(util::ASSET_PROTOCOL))); + const auto path = root + "/" + + mbgl::util::percentDecode(url.substr(std::char_traits::length(util::ASSET_PROTOCOL))); requestLocalFile(path, req); } @@ -70,9 +69,11 @@ class AssetFileSource::Impl { }; AssetFileSource::AssetFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), "AssetFileSource", resourceOptions.clone(), clientOptions.clone())) {} - + : impl(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), + "AssetFileSource", + resourceOptions.clone(), + clientOptions.clone())) {} AssetFileSource::~AssetFileSource() = default; @@ -112,5 +113,4 @@ ClientOptions AssetFileSource::getClientOptions() { return impl->actor().ask(&Impl::getClientOptions).get(); } - } // namespace mbgl diff --git a/platform/default/src/mbgl/storage/database_file_source.cpp b/platform/default/src/mbgl/storage/database_file_source.cpp index 3215e161a0e..ba52ea87f8c 100644 --- a/platform/default/src/mbgl/storage/database_file_source.cpp +++ b/platform/default/src/mbgl/storage/database_file_source.cpp @@ -19,22 +19,21 @@ namespace mbgl { class DatabaseFileSourceThread { public: DatabaseFileSourceThread(std::shared_ptr onlineFileSource_, const std::string& cachePath) - : db(std::make_unique( - cachePath, - onlineFileSource_->getResourceOptions().tileServerOptions()) - ), onlineFileSource(std::move(onlineFileSource_)) {} + : db(std::make_unique(cachePath, onlineFileSource_->getResourceOptions().tileServerOptions())), + onlineFileSource(std::move(onlineFileSource_)) {} void request(const Resource& resource, const ActorRef& req) { - std::optional offlineResponse = - (resource.storagePolicy != Resource::StoragePolicy::Volatile) ? db->get(resource) : std::nullopt; + std::optional offlineResponse = (resource.storagePolicy != Resource::StoragePolicy::Volatile) + ? db->get(resource) + : std::nullopt; if (!offlineResponse) { offlineResponse.emplace(); offlineResponse->noContent = true; - offlineResponse->error = - std::make_unique(Response::Error::Reason::NotFound, "Not found in offline database"); + offlineResponse->error = std::make_unique(Response::Error::Reason::NotFound, + "Not found in offline database"); } else if (!offlineResponse->isUsable()) { - offlineResponse->error = - std::make_unique(Response::Error::Reason::NotFound, "Cached resource is unusable"); + offlineResponse->error = std::make_unique(Response::Error::Reason::NotFound, + "Cached resource is unusable"); } req.invoke(&FileSourceRequest::setResponse, *offlineResponse); } @@ -143,8 +142,8 @@ class DatabaseFileSourceThread { if (!definition) { return unexpected(definition.error()); } - auto download = - std::make_unique(regionID, std::move(definition.value()), *db, *onlineFileSource); + auto download = std::make_unique( + regionID, std::move(definition.value()), *db, *onlineFileSource); return downloads.emplace(regionID, std::move(download)).first->second.get(); } @@ -155,14 +154,16 @@ class DatabaseFileSourceThread { class DatabaseFileSource::Impl { public: - Impl(std::shared_ptr onlineFileSource, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) : - thread(std::make_unique>( + Impl(std::shared_ptr onlineFileSource, + const ResourceOptions& resourceOptions_, + const ClientOptions& clientOptions_) + : thread(std::make_unique>( util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_DATABASE), "DatabaseFileSource", std::move(onlineFileSource), resourceOptions_.cachePath())), - resourceOptions(resourceOptions_.clone()), - clientOptions(clientOptions_.clone()) {} + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} ActorRef actor() const { return thread->actor(); } @@ -199,9 +200,9 @@ class DatabaseFileSource::Impl { DatabaseFileSource::DatabaseFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : impl(std::make_unique( - FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), - resourceOptions, - clientOptions)) {} + FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), + resourceOptions, + clientOptions)) {} DatabaseFileSource::~DatabaseFileSource() = default; diff --git a/platform/default/src/mbgl/storage/file_source_manager.cpp b/platform/default/src/mbgl/storage/file_source_manager.cpp index ceddf13f550..d3068404407 100644 --- a/platform/default/src/mbgl/storage/file_source_manager.cpp +++ b/platform/default/src/mbgl/storage/file_source_manager.cpp @@ -12,29 +12,35 @@ namespace mbgl { class DefaultFileSourceManagerImpl final : public FileSourceManager { public: DefaultFileSourceManagerImpl() { - registerFileSourceFactory(FileSourceType::ResourceLoader, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); - - registerFileSourceFactory(FileSourceType::Asset, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); - - registerFileSourceFactory(FileSourceType::Database, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); - - registerFileSourceFactory(FileSourceType::FileSystem, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); - - registerFileSourceFactory(FileSourceType::Mbtiles, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); - - registerFileSourceFactory(FileSourceType::Network, [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { - return std::make_unique(resourceOptions, clientOptions); - }); + registerFileSourceFactory(FileSourceType::ResourceLoader, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + }); + + registerFileSourceFactory(FileSourceType::Asset, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + }); + + registerFileSourceFactory(FileSourceType::Database, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + }); + + registerFileSourceFactory(FileSourceType::FileSystem, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + }); + + registerFileSourceFactory(FileSourceType::Mbtiles, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + }); + + registerFileSourceFactory(FileSourceType::Network, + [](const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) { + return std::make_unique(resourceOptions, clientOptions); + }); } }; diff --git a/platform/default/src/mbgl/storage/file_source_request.cpp b/platform/default/src/mbgl/storage/file_source_request.cpp index 09ea8cc32a9..667cbf345af 100644 --- a/platform/default/src/mbgl/storage/file_source_request.cpp +++ b/platform/default/src/mbgl/storage/file_source_request.cpp @@ -6,9 +6,8 @@ namespace mbgl { FileSourceRequest::FileSourceRequest(FileSource::Callback&& callback) - : responseCallback(callback) - , mailbox(std::make_shared(*Scheduler::GetCurrent())) { -} + : responseCallback(callback), + mailbox(std::make_shared(*Scheduler::GetCurrent())) {} FileSourceRequest::~FileSourceRequest() { if (cancelCallback) { diff --git a/platform/default/src/mbgl/storage/http_file_source.cpp b/platform/default/src/mbgl/storage/http_file_source.cpp index dc002a0d8ec..f6bcca8acb7 100644 --- a/platform/default/src/mbgl/storage/http_file_source.cpp +++ b/platform/default/src/mbgl/storage/http_file_source.cpp @@ -38,7 +38,7 @@ namespace mbgl { class HTTPFileSource::Impl { public: - Impl(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_); + Impl(const ResourceOptions &resourceOptions_, const ClientOptions &clientOptions_); ~Impl(); static int handleSocket(CURL *handle, curl_socket_t s, int action, void *userp, void *socketp); @@ -53,15 +53,15 @@ class HTTPFileSource::Impl { // Used as the CURL timer function to periodically check for socket updates. util::Timer timeout; - // CURL multi handle that we use to request multiple URLs at the same time, without having to - // block and spawn threads. + // CURL multi handle that we use to request multiple URLs at the same time, + // without having to block and spawn threads. CURLM *multi = nullptr; // CURL share handles are used for sharing session state (e.g.) CURLSH *share = nullptr; - // A queue that we use for storing reusable CURL easy handles to avoid creating and destroying - // them all the time. + // A queue that we use for storing reusable CURL easy handles to avoid + // creating and destroying them all the time. std::queue handles; void setResourceOptions(ResourceOptions options); @@ -79,7 +79,7 @@ class HTTPFileSource::Impl { class HTTPRequest : public AsyncRequest { public: - HTTPRequest(HTTPFileSource::Impl*, Resource, FileSource::Callback); + HTTPRequest(HTTPFileSource::Impl *, Resource, FileSource::Callback); ~HTTPRequest() override; void handleResult(CURLcode code); @@ -88,7 +88,7 @@ class HTTPRequest : public AsyncRequest { static size_t headerCallback(char *buffer, size_t size, size_t nmemb, void *userp); static size_t writeCallback(void *contents, size_t size, size_t nmemb, void *userp); - HTTPFileSource::Impl* context = nullptr; + HTTPFileSource::Impl *context = nullptr; Resource resource; FileSource::Callback callback; @@ -102,11 +102,12 @@ class HTTPRequest : public AsyncRequest { CURL *handle = nullptr; curl_slist *headers = nullptr; - char error[CURL_ERROR_SIZE] = { 0 }; + char error[CURL_ERROR_SIZE] = {0}; }; -HTTPFileSource::Impl::Impl(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions (resourceOptions_.clone()), clientOptions (clientOptions_.clone()) { +HTTPFileSource::Impl::Impl(const ResourceOptions &resourceOptions_, const ClientOptions &clientOptions_) + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) { if (curl_global_init(CURL_GLOBAL_ALL)) { throw std::runtime_error("Could not init cURL"); } @@ -156,16 +157,16 @@ void HTTPFileSource::Impl::checkMultiInfo() { while ((message = curl_multi_info_read(multi, &pending))) { switch (message->msg) { - case CURLMSG_DONE: { - HTTPRequest *baton = nullptr; - curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&baton); - assert(baton); - baton->handleResult(message->data.result); - } break; - - default: - // This should never happen, because there are no other message types. - throw std::runtime_error("CURLMsg returned unknown message type"); + case CURLMSG_DONE: { + HTTPRequest *baton = nullptr; + curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&baton); + assert(baton); + baton->handleResult(message->data.result); + } break; + + default: + // This should never happen, because there are no other message types. + throw std::runtime_error("CURLMsg returned unknown message type"); } } } @@ -180,35 +181,34 @@ void HTTPFileSource::Impl::perform(curl_socket_t s, util::RunLoop::Event events) flags |= CURL_CSELECT_OUT; } - int running_handles = 0; curl_multi_socket_action(multi, s, flags, &running_handles); checkMultiInfo(); } -int HTTPFileSource::Impl::handleSocket(CURL * /* handle */, curl_socket_t s, int action, void *userp, - void * /* socketp */) { +int HTTPFileSource::Impl::handleSocket( + CURL * /* handle */, curl_socket_t s, int action, void *userp, void * /* socketp */) { assert(userp); auto context = reinterpret_cast(userp); switch (action) { - case CURL_POLL_IN: { - using namespace std::placeholders; - util::RunLoop::Get()->addWatch(static_cast(s), util::RunLoop::Event::Read, - std::bind(&Impl::perform, context, _1, _2)); - break; - } - case CURL_POLL_OUT: { - using namespace std::placeholders; - util::RunLoop::Get()->addWatch(static_cast(s), util::RunLoop::Event::Write, - std::bind(&Impl::perform, context, _1, _2)); - break; - } - case CURL_POLL_REMOVE: - util::RunLoop::Get()->removeWatch(static_cast(s)); - break; - default: - throw std::runtime_error("Unhandled CURL socket action"); + case CURL_POLL_IN: { + using namespace std::placeholders; + util::RunLoop::Get()->addWatch( + static_cast(s), util::RunLoop::Event::Read, std::bind(&Impl::perform, context, _1, _2)); + break; + } + case CURL_POLL_OUT: { + using namespace std::placeholders; + util::RunLoop::Get()->addWatch( + static_cast(s), util::RunLoop::Event::Write, std::bind(&Impl::perform, context, _1, _2)); + break; + } + case CURL_POLL_REMOVE: + util::RunLoop::Get()->removeWatch(static_cast(s)); + break; + default: + throw std::runtime_error("Unhandled CURL socket action"); } return 0; @@ -233,8 +233,7 @@ int HTTPFileSource::Impl::startTimeout(CURLM * /* multi */, long timeout_ms, voi } context->timeout.stop(); - context->timeout.start(mbgl::Milliseconds(timeout_ms), Duration::zero(), - std::bind(&Impl::onTimeout, context)); + context->timeout.start(mbgl::Milliseconds(timeout_ms), Duration::zero(), std::bind(&Impl::onTimeout, context)); return 0; } @@ -259,20 +258,19 @@ ClientOptions HTTPFileSource::Impl::getClientOptions() { return clientOptions.clone(); } -HTTPRequest::HTTPRequest(HTTPFileSource::Impl* context_, Resource resource_, FileSource::Callback callback_) +HTTPRequest::HTTPRequest(HTTPFileSource::Impl *context_, Resource resource_, FileSource::Callback callback_) : context(context_), resource(std::move(resource_)), callback(std::move(callback_)), handle(context->getHandle()) { - - // If there's already a response, set the correct etags/modified headers to make sure we are - // getting a 304 response if possible. This avoids redownloading unchanged data. + // If there's already a response, set the correct etags/modified headers to + // make sure we are getting a 304 response if possible. This avoids + // redownloading unchanged data. if (resource.priorEtag) { const std::string header = std::string("If-None-Match: ") + *resource.priorEtag; headers = curl_slist_append(headers, header.c_str()); } else if (resource.priorModified) { - const std::string time = - std::string("If-Modified-Since: ") + util::rfc1123(*resource.priorModified); + const std::string time = std::string("If-Modified-Since: ") + util::rfc1123(*resource.priorModified); headers = curl_slist_append(headers, time.c_str()); } @@ -281,8 +279,8 @@ HTTPRequest::HTTPRequest(HTTPFileSource::Impl* context_, Resource resource_, Fil } #ifdef WIN32 - // Windows has issues with TLSv1.3, so we limit to TLSv1.2. Should be resolved in a later cURL release - // https://github.com/curl/curl/issues/9431 + // Windows has issues with TLSv1.3, so we limit to TLSv1.2. Should be + // resolved in a later cURL release https://github.com/curl/curl/issues/9431 handleError(curl_easy_setopt(handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_MAX_TLSv1_2)); #endif handleError(curl_easy_setopt(handle, CURLOPT_PRIVATE, this)); @@ -319,8 +317,8 @@ HTTPRequest::~HTTPRequest() { } } -// This function is called when we have new data for a request. We just append it to the string -// containing the previous data. +// This function is called when we have new data for a request. We just append +// it to the string containing the previous data. size_t HTTPRequest::writeCallback(void *const contents, const size_t size, const size_t nmemb, void *userp) { assert(userp); auto impl = reinterpret_cast(userp); @@ -333,10 +331,11 @@ size_t HTTPRequest::writeCallback(void *const contents, const size_t size, const return size * nmemb; } -// Compares the beginning of the (non-zero-terminated!) data buffer with the (zero-terminated!) -// header string. If the data buffer contains the header string at the beginning, it returns -// the length of the header string == begin of the value, otherwise it returns npos. -// The comparison of the header is ASCII-case-insensitive. +// Compares the beginning of the (non-zero-terminated!) data buffer with the +// (zero-terminated!) header string. If the data buffer contains the header +// string at the beginning, it returns the length of the header string == begin +// of the value, otherwise it returns npos. The comparison of the header is +// ASCII-case-insensitive. size_t headerMatches(const char *const header, const char *const buffer, const size_t length) { const size_t headerLength = strlen(header); if (length < headerLength) { @@ -361,24 +360,27 @@ size_t HTTPRequest::headerCallback(char *const buffer, const size_t size, const const size_t length = size * nmemb; size_t begin = std::string::npos; if ((begin = headerMatches("last-modified: ", buffer, length)) != std::string::npos) { - // Always overwrite the modification date; We might already have a value here from the - // Date header, but this one is more accurate. - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + // Always overwrite the modification date; We might already have a value + // here from the Date header, but this one is more accurate. + const std::string value{buffer + begin, length - begin - 2}; // remove \r\n baton->response->modified = Timestamp{Seconds(curl_getdate(value.c_str(), nullptr))}; } else if ((begin = headerMatches("etag: ", buffer, length)) != std::string::npos) { - baton->response->etag = std::string(buffer + begin, length - begin - 2); // remove \r\n + baton->response->etag = std::string(buffer + begin, + length - begin - 2); // remove \r\n } else if ((begin = headerMatches("cache-control: ", buffer, length)) != std::string::npos) { - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + const std::string value{buffer + begin, length - begin - 2}; // remove \r\n const auto cc = http::CacheControl::parse(value); baton->response->expires = cc.toTimePoint(); baton->response->mustRevalidate = cc.mustRevalidate; } else if ((begin = headerMatches("expires: ", buffer, length)) != std::string::npos) { - const std::string value { buffer + begin, length - begin - 2 }; // remove \r\n + const std::string value{buffer + begin, length - begin - 2}; // remove \r\n baton->response->expires = Timestamp{Seconds(curl_getdate(value.c_str(), nullptr))}; } else if ((begin = headerMatches("retry-after: ", buffer, length)) != std::string::npos) { - baton->retryAfter = std::string(buffer + begin, length - begin - 2); // remove \r\n + baton->retryAfter = std::string(buffer + begin, + length - begin - 2); // remove \r\n } else if ((begin = headerMatches("x-rate-limit-reset: ", buffer, length)) != std::string::npos) { - baton->xRateLimitReset = std::string(buffer + begin, length - begin - 2); // remove \r\n + baton->xRateLimitReset = std::string(buffer + begin, + length - begin - 2); // remove \r\n } // NOLINTEND(bugprone-assignment-in-if-condition) @@ -396,19 +398,19 @@ void HTTPRequest::handleResult(CURLcode code) { // Add human-readable error code if (code != CURLE_OK) { switch (code) { - case CURLE_COULDNT_RESOLVE_PROXY: - case CURLE_COULDNT_RESOLVE_HOST: - case CURLE_COULDNT_CONNECT: - case CURLE_OPERATION_TIMEDOUT: - - response->error = std::make_unique(Error::Reason::Connection, - std::string{curl_easy_strerror(code)} + ": " + error); - break; - - default: - response->error = - std::make_unique(Error::Reason::Other, std::string{curl_easy_strerror(code)} + ": " + error); - break; + case CURLE_COULDNT_RESOLVE_PROXY: + case CURLE_COULDNT_RESOLVE_HOST: + case CURLE_COULDNT_CONNECT: + case CURLE_OPERATION_TIMEDOUT: + + response->error = std::make_unique(Error::Reason::Connection, + std::string{curl_easy_strerror(code)} + ": " + error); + break; + + default: + response->error = std::make_unique(Error::Reason::Other, + std::string{curl_easy_strerror(code)} + ": " + error); + break; } } else { long responseCode = 0; @@ -425,20 +427,16 @@ void HTTPRequest::handleResult(CURLcode code) { } else if (responseCode == 304) { response->notModified = true; } else if (responseCode == 404) { - response->error = - std::make_unique(Error::Reason::NotFound, "HTTP status code 404"); + response->error = std::make_unique(Error::Reason::NotFound, "HTTP status code 404"); } else if (responseCode == 429) { - response->error = - std::make_unique(Error::Reason::RateLimit, "HTTP status code 429", - http::parseRetryHeaders(retryAfter, xRateLimitReset)); + response->error = std::make_unique( + Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset)); } else if (responseCode >= 500 && responseCode < 600) { - response->error = - std::make_unique(Error::Reason::Server, std::string{ "HTTP status code " } + - util::toString(responseCode)); + response->error = std::make_unique(Error::Reason::Server, + std::string{"HTTP status code "} + util::toString(responseCode)); } else { - response->error = - std::make_unique(Error::Reason::Other, std::string{ "HTTP status code " } + - util::toString(responseCode)); + response->error = std::make_unique(Error::Reason::Other, + std::string{"HTTP status code "} + util::toString(responseCode)); } } @@ -448,13 +446,12 @@ void HTTPRequest::handleResult(CURLcode code) { callback_(response_); } -HTTPFileSource::HTTPFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique(resourceOptions, clientOptions)) { -} +HTTPFileSource::HTTPFileSource(const ResourceOptions &resourceOptions, const ClientOptions &clientOptions) + : impl(std::make_unique(resourceOptions, clientOptions)) {} HTTPFileSource::~HTTPFileSource() = default; -std::unique_ptr HTTPFileSource::request(const Resource& resource, Callback callback) { +std::unique_ptr HTTPFileSource::request(const Resource &resource, Callback callback) { return std::make_unique(impl.get(), resource, callback); } diff --git a/platform/default/src/mbgl/storage/local_file_request.cpp b/platform/default/src/mbgl/storage/local_file_request.cpp index 1f00ebdb854..0c71de43723 100644 --- a/platform/default/src/mbgl/storage/local_file_request.cpp +++ b/platform/default/src/mbgl/storage/local_file_request.cpp @@ -6,7 +6,7 @@ #include #if defined(_WIN32) && !defined(S_ISDIR) -#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR) #endif namespace mbgl { @@ -23,9 +23,8 @@ void requestLocalFile(const std::string& path, const ActorRef } else { auto data = util::readFile(path); if (!data) { - response.error = std::make_unique( - Response::Error::Reason::Other, - std::string("Cannot read file ") + path); + response.error = std::make_unique(Response::Error::Reason::Other, + std::string("Cannot read file ") + path); } else { response.data = std::make_shared(std::move(*data)); } diff --git a/platform/default/src/mbgl/storage/local_file_source.cpp b/platform/default/src/mbgl/storage/local_file_source.cpp index 2df1f4e8053..c42ad520c1a 100644 --- a/platform/default/src/mbgl/storage/local_file_source.cpp +++ b/platform/default/src/mbgl/storage/local_file_source.cpp @@ -22,13 +22,13 @@ namespace mbgl { class LocalFileSource::Impl { public: explicit Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions (resourceOptions_.clone()), clientOptions (clientOptions_.clone()) {} + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} void request(const std::string& url, const ActorRef& req) { if (!acceptsURL(url)) { Response response; - response.error = std::make_unique(Response::Error::Reason::Other, - "Invalid file URL"); + response.error = std::make_unique(Response::Error::Reason::Other, "Invalid file URL"); req.invoke(&FileSourceRequest::setResponse, response); return; } @@ -58,7 +58,6 @@ class LocalFileSource::Impl { return clientOptions.clone(); } - private: mutable std::mutex resourceOptionsMutex; mutable std::mutex clientOptionsMutex; @@ -66,9 +65,12 @@ class LocalFileSource::Impl { ClientOptions clientOptions; }; -LocalFileSource::LocalFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions): - impl(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), "LocalFileSource", resourceOptions.clone(), clientOptions.clone())) {} +LocalFileSource::LocalFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) + : impl(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), + "LocalFileSource", + resourceOptions.clone(), + clientOptions.clone())) {} LocalFileSource::~LocalFileSource() = default; @@ -108,5 +110,4 @@ ClientOptions LocalFileSource::getClientOptions() { return impl->actor().ask(&Impl::getClientOptions).get(); } - } // namespace mbgl diff --git a/platform/default/src/mbgl/storage/main_resource_loader.cpp b/platform/default/src/mbgl/storage/main_resource_loader.cpp index 5d051e796f2..a5cbd0616c8 100644 --- a/platform/default/src/mbgl/storage/main_resource_loader.cpp +++ b/platform/default/src/mbgl/storage/main_resource_loader.cpp @@ -29,7 +29,9 @@ class MainResourceLoaderThread { mbtilesFileSource(std::move(mbtilesFileSource_)) {} void request(AsyncRequest* req, const Resource& resource, const ActorRef& ref) { - auto callback = [ref](const Response& res) { ref.invoke(&FileSourceRequest::setResponse, res); }; + auto callback = [ref](const Response& res) { + ref.invoke(&FileSourceRequest::setResponse, res); + }; auto requestFromNetwork = [=](const Resource& res, std::unique_ptr parent) -> std::unique_ptr { @@ -88,9 +90,10 @@ class MainResourceLoaderThread { // Set the priority of existing resource to low if it's expired but usable. res.setPriority(Resource::Priority::Low); } else { - // Set prior data only if it was not returned to the requester. - // Once we get 304 response from the network, we will forward response - // to the requester. + // Set prior data only if it was not returned to + // the requester. Once we get 304 response from + // the network, we will forward response to the + // requester. res.priorData = response.data; } @@ -112,8 +115,8 @@ class MainResourceLoaderThread { if (tasks.size() == tasksSize) { Response response; response.noContent = true; - response.error = - std::make_unique(Response::Error::Reason::Other, "Unsupported resource request."); + response.error = std::make_unique(Response::Error::Reason::Other, + "Unsupported resource request."); callback(response); } } @@ -155,8 +158,8 @@ class MainResourceLoader::Impl { localFileSource, onlineFileSource, mbtilesFileSource)), - resourceOptions (resourceOptions_.clone()), - clientOptions (clientOptions_.clone()) {} + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} std::unique_ptr request(const Resource& resource, Callback callback) { auto req = std::make_unique(std::move(callback)); @@ -226,14 +229,15 @@ class MainResourceLoader::Impl { ClientOptions clientOptions; }; -MainResourceLoader::MainResourceLoader(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions): - impl(std::make_unique(resourceOptions.clone(), - clientOptions.clone(), - FileSourceManager::get()->getFileSource(FileSourceType::Asset, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::Database, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::FileSystem, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), - FileSourceManager::get()->getFileSource(FileSourceType::Mbtiles, resourceOptions, clientOptions))) {} +MainResourceLoader::MainResourceLoader(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) + : impl(std::make_unique( + resourceOptions.clone(), + clientOptions.clone(), + FileSourceManager::get()->getFileSource(FileSourceType::Asset, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::Database, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::FileSystem, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::Network, resourceOptions, clientOptions), + FileSourceManager::get()->getFileSource(FileSourceType::Mbtiles, resourceOptions, clientOptions))) {} MainResourceLoader::~MainResourceLoader() = default; diff --git a/platform/default/src/mbgl/storage/mbtiles_file_source.cpp b/platform/default/src/mbgl/storage/mbtiles_file_source.cpp index f9c6d7dc6c6..6fbcaa2955b 100644 --- a/platform/default/src/mbgl/storage/mbtiles_file_source.cpp +++ b/platform/default/src/mbgl/storage/mbtiles_file_source.cpp @@ -27,7 +27,7 @@ #endif namespace { -bool acceptsURL(const std::string& url) { +bool acceptsURL(const std::string &url) { return 0 == url.rfind(mbgl::util::MBTILES_PROTOCOL, 0); } @@ -39,11 +39,11 @@ std::string url_to_path(const std::string &url) { namespace mbgl { using namespace rapidjson; - class MBTilesFileSource::Impl { public: - explicit Impl(const ActorRef&, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions (resourceOptions_.clone()), clientOptions (clientOptions_.clone()) {} + explicit Impl(const ActorRef &, const ResourceOptions &resourceOptions_, const ClientOptions &clientOptions_) + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} std::vector &split(const std::string &s, char delim, std::vector &elems) { std::stringstream ss(s); @@ -62,7 +62,6 @@ class MBTilesFileSource::Impl { } std::string serialize(Document &doc) { - StringBuffer buffer; Writer writer(buffer); doc.Accept(writer); @@ -70,15 +69,9 @@ class MBTilesFileSource::Impl { return std::string(buffer.GetString(), buffer.GetSize()); } + std::string db_path(const std::string &path) { return path.substr(0, path.find('?')); } - - std::string db_path(const std::string &path) { - return path.substr(0, path.find('?')); - } - - bool is_compressed(const std::string &v) { - return (((uint8_t) v[0]) == 0x1f) && (((uint8_t) v[1]) == 0x8b); - } + bool is_compressed(const std::string &v) { return (((uint8_t)v[0]) == 0x1f) && (((uint8_t)v[1]) == 0x8b); } // Generate a tilejson resource from .mbtiles file void request_tilejson(const Resource &resource, ActorRef req) { @@ -140,8 +133,7 @@ class MBTilesFileSource::Impl { values["minzoom"] = minz; values["maxzoom"] = maxz; - } - else { + } else { minz = minzoom_ptr->second; maxz = maxzoom_ptr->second; } @@ -202,15 +194,14 @@ class MBTilesFileSource::Impl { auto y = std::to_string((int)(pow(2, iz) - 1) - iy); auto z = std::to_string(iz); - std::string sql = "SELECT tile_data FROM tiles where zoom_level = " + z + - " AND tile_column = " + x + " AND tile_row = " + y; + std::string sql = "SELECT tile_data FROM tiles where zoom_level = " + z + " AND tile_column = " + x + + " AND tile_row = " + y; mapbox::sqlite::Statement stmt(db, sql.c_str()); Response response; response.noContent = true; for (mapbox::sqlite::Query q(stmt); q.run();) { - std::optional data = q.get>(0); if (data) { response.data = std::make_shared(*data); @@ -227,8 +218,8 @@ class MBTilesFileSource::Impl { } void setResourceOptions(ResourceOptions options) { - std::lock_guard lock(resourceOptionsMutex); - resourceOptions = options; + std::lock_guard lock(resourceOptionsMutex); + resourceOptions = options; } ResourceOptions getResourceOptions() { @@ -246,7 +237,6 @@ class MBTilesFileSource::Impl { return clientOptions.clone(); } - private: std::map db_cache; @@ -257,9 +247,7 @@ class MBTilesFileSource::Impl { } } - void close_all() { - db_cache.clear(); - } + void close_all() { db_cache.clear(); } // Multiple databases open simultaneoulsy, to effectively support multiple .mbtiles maps mapbox::sqlite::Database &get_db(const std::string &path) { @@ -268,7 +256,8 @@ class MBTilesFileSource::Impl { return ptr->second; }; - auto ptr2 = db_cache.insert(std::pair(path, mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly))); + auto ptr2 = db_cache.insert(std::pair( + path, mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly))); return ptr2.first->second; } @@ -278,10 +267,12 @@ class MBTilesFileSource::Impl { ClientOptions clientOptions; }; - -MBTilesFileSource::MBTilesFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : - thread(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), "MBTilesFileSource", resourceOptions.clone(), clientOptions.clone())) {} +MBTilesFileSource::MBTilesFileSource(const ResourceOptions &resourceOptions, const ClientOptions &clientOptions) + : thread(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_FILE), + "MBTilesFileSource", + resourceOptions.clone(), + clientOptions.clone())) {} std::unique_ptr MBTilesFileSource::request(const Resource &resource, FileSource::Callback callback) { auto req = std::make_unique(std::move(callback)); @@ -295,8 +286,8 @@ std::unique_ptr MBTilesFileSource::request(const Resource &resourc if (resource.url.find(":///") == std::string::npos) { Response response; response.noContent = true; - response.error = std::make_unique( - Response::Error::Reason::Other, "MBTilesFileSource only supports absolute path urls"); + response.error = std::make_unique(Response::Error::Reason::Other, + "MBTilesFileSource only supports absolute path urls"); req->actor().invoke(&FileSourceRequest::setResponse, response); return req; } @@ -308,7 +299,8 @@ std::unique_ptr MBTilesFileSource::request(const Resource &resourc if (result == -1 && errno == ENOENT) { Response response; response.noContent = true; - response.error = std::make_unique(Response::Error::Reason::NotFound, "path not found: "+path); + response.error = std::make_unique(Response::Error::Reason::NotFound, + "path not found: " + path); req->actor().invoke(&FileSourceRequest::setResponse, response); return req; } @@ -318,7 +310,7 @@ std::unique_ptr MBTilesFileSource::request(const Resource &resourc return req; } -bool MBTilesFileSource::canRequest(const Resource& resource) const { +bool MBTilesFileSource::canRequest(const Resource &resource) const { return acceptsURL(resource.url); } @@ -340,4 +332,4 @@ ClientOptions MBTilesFileSource::getClientOptions() { return thread->actor().ask(&Impl::getClientOptions).get(); } -} +} // namespace mbgl diff --git a/platform/default/src/mbgl/storage/offline.cpp b/platform/default/src/mbgl/storage/offline.cpp index a2e42359f03..c700f47edf7 100644 --- a/platform/default/src/mbgl/storage/offline.cpp +++ b/platform/default/src/mbgl/storage/offline.cpp @@ -28,23 +28,28 @@ OfflineTilePyramidRegionDefinition::OfflineTilePyramidRegionDefinition(std::stri maxZoom(maxZoom_), pixelRatio(pixelRatio_), includeIdeographs(includeIdeographs_) { - if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || - !std::isfinite(minZoom) || std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { + if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || !std::isfinite(minZoom) || + std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { throw std::invalid_argument("Invalid offline region definition"); } } // OfflineGeometryRegionDefinition -OfflineGeometryRegionDefinition::OfflineGeometryRegionDefinition(std::string styleURL_, Geometry geometry_, double minZoom_, double maxZoom_, float pixelRatio_, bool includeIdeographs_) - : styleURL(std::move(styleURL_)) - , geometry(std::move(geometry_)) - , minZoom(minZoom_) - , maxZoom(maxZoom_) - , pixelRatio(pixelRatio_) - , includeIdeographs(includeIdeographs_){ - if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || - !std::isfinite(minZoom) || std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { +OfflineGeometryRegionDefinition::OfflineGeometryRegionDefinition(std::string styleURL_, + Geometry geometry_, + double minZoom_, + double maxZoom_, + float pixelRatio_, + bool includeIdeographs_) + : styleURL(std::move(styleURL_)), + geometry(std::move(geometry_)), + minZoom(minZoom_), + maxZoom(maxZoom_), + pixelRatio(pixelRatio_), + includeIdeographs(includeIdeographs_) { + if (minZoom < 0 || maxZoom < 0 || maxZoom < minZoom || pixelRatio < 0 || !std::isfinite(minZoom) || + std::isnan(maxZoom) || !std::isfinite(pixelRatio)) { throw std::invalid_argument("Invalid offline region definition"); } } @@ -56,47 +61,48 @@ OfflineRegionDefinition decodeOfflineRegionDefinition(const std::string& region) // validation auto hasValidBounds = [&] { - return doc.HasMember("bounds") && doc["bounds"].IsArray() && doc["bounds"].Size() == 4 - && doc["bounds"][0].IsDouble() && doc["bounds"][1].IsDouble() - && doc["bounds"][2].IsDouble() && doc["bounds"][3].IsDouble(); + return doc.HasMember("bounds") && doc["bounds"].IsArray() && doc["bounds"].Size() == 4 && + doc["bounds"][0].IsDouble() && doc["bounds"][1].IsDouble() && doc["bounds"][2].IsDouble() && + doc["bounds"][3].IsDouble(); }; auto hasValidGeometry = [&] { return doc.HasMember("geometry") && doc["geometry"].IsObject(); }; - if (doc.HasParseError() - || !doc.HasMember("style_url") || !doc["style_url"].IsString() - || !(hasValidBounds() || hasValidGeometry()) - || !doc.HasMember("min_zoom") || !doc["min_zoom"].IsDouble() - || (doc.HasMember("max_zoom") && !doc["max_zoom"].IsDouble()) - || !doc.HasMember("pixel_ratio") || !doc["pixel_ratio"].IsDouble() - || (doc.HasMember("include_ideographs") && !doc["include_ideographs"].IsBool())) { + if (doc.HasParseError() || !doc.HasMember("style_url") || !doc["style_url"].IsString() || + !(hasValidBounds() || hasValidGeometry()) || !doc.HasMember("min_zoom") || !doc["min_zoom"].IsDouble() || + (doc.HasMember("max_zoom") && !doc["max_zoom"].IsDouble()) || !doc.HasMember("pixel_ratio") || + !doc["pixel_ratio"].IsDouble() || + (doc.HasMember("include_ideographs") && !doc["include_ideographs"].IsBool())) { throw std::runtime_error("Malformed offline region definition"); } // Common properties - std::string styleURL { doc["style_url"].GetString(), doc["style_url"].GetStringLength() }; + std::string styleURL{doc["style_url"].GetString(), doc["style_url"].GetStringLength()}; double minZoom = doc["min_zoom"].GetDouble(); double maxZoom = doc.HasMember("max_zoom") ? doc["max_zoom"].GetDouble() : INFINITY; auto pixelRatio = static_cast(doc["pixel_ratio"].GetDouble()); bool includeIdeographs = doc.HasMember("include_ideographs") ? doc["include_ideographs"].GetBool() : true; - + if (doc.HasMember("bounds")) { return OfflineTilePyramidRegionDefinition{ - styleURL, - LatLngBounds::hull( - LatLng(doc["bounds"][0].GetDouble(), doc["bounds"][1].GetDouble()), - LatLng(doc["bounds"][2].GetDouble(), doc["bounds"][3].GetDouble())), - minZoom, maxZoom, pixelRatio, includeIdeographs }; + styleURL, + LatLngBounds::hull(LatLng(doc["bounds"][0].GetDouble(), doc["bounds"][1].GetDouble()), + LatLng(doc["bounds"][2].GetDouble(), doc["bounds"][3].GetDouble())), + minZoom, + maxZoom, + pixelRatio, + includeIdeographs}; } else { - return OfflineGeometryRegionDefinition{ - styleURL, - mapbox::geojson::convert>(doc["geometry"].GetObject()), - minZoom, maxZoom, pixelRatio, includeIdeographs }; + return OfflineGeometryRegionDefinition{styleURL, + mapbox::geojson::convert>(doc["geometry"].GetObject()), + minZoom, + maxZoom, + pixelRatio, + includeIdeographs}; }; - } std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) { @@ -105,7 +111,8 @@ std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) // Encode common properties region.match([&](auto& _region) { - doc.AddMember("style_url", rapidjson::StringRef(_region.styleURL.data(), _region.styleURL.length()), doc.GetAllocator()); + doc.AddMember( + "style_url", rapidjson::StringRef(_region.styleURL.data(), _region.styleURL.length()), doc.GetAllocator()); doc.AddMember("min_zoom", _region.minZoom, doc.GetAllocator()); if (std::isfinite(_region.maxZoom)) { doc.AddMember("max_zoom", _region.maxZoom, doc.GetAllocator()); @@ -117,20 +124,18 @@ std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) // Encode specific properties region.match( - [&] (const OfflineTilePyramidRegionDefinition& _region) { - rapidjson::GenericValue, rapidjson::CrtAllocator> bounds(rapidjson::kArrayType); - bounds.PushBack(_region.bounds.south(), doc.GetAllocator()); - bounds.PushBack(_region.bounds.west(), doc.GetAllocator()); - bounds.PushBack(_region.bounds.north(), doc.GetAllocator()); - bounds.PushBack(_region.bounds.east(), doc.GetAllocator()); - doc.AddMember("bounds", bounds, doc.GetAllocator()); - - }, - [&] (const OfflineGeometryRegionDefinition& _region) { - doc.AddMember("geometry", mapbox::geojson::convert(_region.geometry, doc.GetAllocator()), doc.GetAllocator()); - - } - ); + [&](const OfflineTilePyramidRegionDefinition& _region) { + rapidjson::GenericValue, rapidjson::CrtAllocator> bounds(rapidjson::kArrayType); + bounds.PushBack(_region.bounds.south(), doc.GetAllocator()); + bounds.PushBack(_region.bounds.west(), doc.GetAllocator()); + bounds.PushBack(_region.bounds.north(), doc.GetAllocator()); + bounds.PushBack(_region.bounds.east(), doc.GetAllocator()); + doc.AddMember("bounds", bounds, doc.GetAllocator()); + }, + [&](const OfflineGeometryRegionDefinition& _region) { + doc.AddMember( + "geometry", mapbox::geojson::convert(_region.geometry, doc.GetAllocator()), doc.GetAllocator()); + }); rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); @@ -139,16 +144,12 @@ std::string encodeOfflineRegionDefinition(const OfflineRegionDefinition& region) return buffer.GetString(); } - // OfflineRegion -OfflineRegion::OfflineRegion(int64_t id_, - OfflineRegionDefinition definition_, - OfflineRegionMetadata metadata_) +OfflineRegion::OfflineRegion(int64_t id_, OfflineRegionDefinition definition_, OfflineRegionMetadata metadata_) : id(id_), definition(std::move(definition_)), - metadata(std::move(metadata_)) { -} + metadata(std::move(metadata_)) {} OfflineRegion::~OfflineRegion() = default; diff --git a/platform/default/src/mbgl/storage/offline_database.cpp b/platform/default/src/mbgl/storage/offline_database.cpp index f11836ad268..79f17bf25cc 100644 --- a/platform/default/src/mbgl/storage/offline_database.cpp +++ b/platform/default/src/mbgl/storage/offline_database.cpp @@ -14,7 +14,8 @@ namespace mbgl { OfflineDatabase::OfflineDatabase(std::string path_, const TileServerOptions& options) - : path(std::move(path_)), tileServerOptions(options) { + : path(std::move(path_)), + tileServerOptions(options) { try { initialize(); } catch (...) { @@ -47,31 +48,31 @@ void OfflineDatabase::initialize() { const auto userVersion = getPragma("PRAGMA user_version"); switch (userVersion) { - case 0: - case 1: - // Newly created database, or old cache-only database; remove old table if it exists. - removeOldCacheTable(); - createSchema(); - return; - case 2: - migrateToVersion3(); - // fall through - case 3: - // Removed migration, see below. - // fall through - case 4: - migrateToVersion5(); - // fall through - case 5: - migrateToVersion6(); - // fall through - case 6: - // Happy path; we're done - return; - default: - // Downgrade: delete the database and try to reinitialize. - removeExisting(); - initialize(); + case 0: + case 1: + // Newly created database, or old cache-only database; remove old table if it exists. + removeOldCacheTable(); + createSchema(); + return; + case 2: + migrateToVersion3(); + // fall through + case 3: + // Removed migration, see below. + // fall through + case 4: + migrateToVersion5(); + // fall through + case 5: + migrateToVersion6(); + // fall through + case 6: + // Happy path; we're done + return; + default: + // Downgrade: delete the database and try to reinitialize. + removeExisting(); + initialize(); } } @@ -102,12 +103,11 @@ bool OfflineDatabase::disabled() { } void OfflineDatabase::handleError(const mapbox::sqlite::Exception& ex, const char* action) { - if (ex.code == mapbox::sqlite::ResultCode::NotADB || - ex.code == mapbox::sqlite::ResultCode::Corrupt || + if (ex.code == mapbox::sqlite::ResultCode::NotADB || ex.code == mapbox::sqlite::ResultCode::Corrupt || (ex.code == mapbox::sqlite::ResultCode::ReadOnly && ex.extendedCode == mapbox::sqlite::ExtendedResultCode::ReadOnlyDBMoved)) { - // The database was corruped, moved away, or deleted. We're going to start fresh with a - // clean slate for the next operation. + // The database was corruped, moved away, or deleted. We're going to + // start fresh with a clean slate for the next operation. Log::Error(Event::Database, static_cast(ex.code), std::string("Can't ") + action + ": " + ex.what()); try { removeExisting(); @@ -205,8 +205,12 @@ void OfflineDatabase::migrateToVersion6() { checkFlags(); mapbox::sqlite::Transaction transaction(*db); - db->exec("ALTER TABLE resources ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0"); - db->exec("ALTER TABLE tiles ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0"); + db->exec( + "ALTER TABLE resources ADD COLUMN must_revalidate INTEGER NOT NULL " + "DEFAULT 0"); + db->exec( + "ALTER TABLE tiles ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT " + "0"); db->exec("PRAGMA user_version = 6"); transaction.commit(); } @@ -246,7 +250,7 @@ std::optional OfflineDatabase::get(const Resource& resource) try { } auto result = getInternal(resource); - return result ? std::optional{ result->first } : std::nullopt; + return result ? std::optional{result->first} : std::nullopt; } catch (...) { handleError("read resource"); return std::nullopt; @@ -278,7 +282,7 @@ std::pair OfflineDatabase::put(const Resource& resource, const R } if (disabled()) { - return { false, 0 }; + return {false, 0}; } mapbox::sqlite::Transaction transaction(*db, mapbox::sqlite::Transaction::Immediate); @@ -290,11 +294,13 @@ std::pair OfflineDatabase::put(const Resource& resource, const R return {false, 0}; } -std::pair OfflineDatabase::putInternal(const Resource& resource, const Response& response, bool evict_) { +std::pair OfflineDatabase::putInternal(const Resource& resource, + const Response& response, + bool evict_) { checkFlags(); if (response.error) { - return { false, 0 }; + return {false, 0}; } std::string compressedData; @@ -320,20 +326,26 @@ std::pair OfflineDatabase::putInternal(const Resource& resource, if (resource.kind == Resource::Kind::Tile) { assert(resource.tileData); - inserted = putTile(*resource.tileData, response, - compressed ? compressedData : response.data ? *response.data : "", - compressed); + inserted = putTile(*resource.tileData, + response, + compressed ? compressedData + : response.data ? *response.data + : "", + compressed); } else { - inserted = putResource(resource, response, - compressed ? compressedData : response.data ? *response.data : "", - compressed); + inserted = putResource(resource, + response, + compressed ? compressedData + : response.data ? *response.data + : "", + compressed); } if (stats) { updateAmbientCacheSize(*stats); } - return { inserted, size }; + return {inserted, size}; } std::optional> OfflineDatabase::getResource(const Resource& resource) { @@ -350,7 +362,8 @@ std::optional> OfflineDatabase::getResource(const } // If we don't have any indication that the database is corrupt, continue as usual. - Log::Warning(Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what()); + Log::Warning( + Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what()); } } @@ -371,10 +384,10 @@ std::optional> OfflineDatabase::getResource(const Response response; uint64_t size = 0; - response.etag = query.get>(0); - response.expires = query.get>(1); + response.etag = query.get>(0); + response.expires = query.get>(1); response.mustRevalidate = query.get(2); - response.modified = query.get>(3); + response.modified = query.get>(3); auto data = query.get>(4); if (!data) { @@ -391,7 +404,7 @@ std::optional> OfflineDatabase::getResource(const } std::optional OfflineDatabase::hasResource(const Resource& resource) { - mapbox::sqlite::Query query{ getStatement("SELECT length(data) FROM resources WHERE url = ?") }; + mapbox::sqlite::Query query{getStatement("SELECT length(data) FROM resources WHERE url = ?")}; query.bind(1, resource.url); if (!query.run()) { return std::nullopt; @@ -515,7 +528,8 @@ std::optional> OfflineDatabase::getTile(const Reso } // If we don't have any indication that the database is corrupt, continue as usual. - Log::Warning(Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what()); + Log::Warning( + Event::Database, static_cast(ex.code), std::string("Can't update timestamp: ") + ex.what()); } } @@ -544,10 +558,10 @@ std::optional> OfflineDatabase::getTile(const Reso Response response; uint64_t size = 0; - response.etag = query.get>(0); - response.expires = query.get>(1); - response.mustRevalidate = query.get(2); - response.modified = query.get>(3); + response.etag = query.get>(0); + response.expires = query.get>(1); + response.mustRevalidate = query.get(2); + response.modified = query.get>(3); std::optional data = query.get>(4); if (!data) { @@ -798,7 +812,7 @@ std::exception_ptr OfflineDatabase::invalidateRegion(int64_t regionID) try { } expected OfflineDatabase::listRegions() try { - mapbox::sqlite::Query query{ getStatement("SELECT id, definition, description FROM regions") }; + mapbox::sqlite::Query query{getStatement("SELECT id, definition, description FROM regions")}; OfflineRegions result; while (query.run()) { const auto id = query.get(0); @@ -815,15 +829,14 @@ expected OfflineDatabase::listRegions() try } } // Explicit move to avoid triggering the copy constructor. - return { std::move(result) }; + return {std::move(result)}; } catch (...) { handleError("list regions"); return unexpected(std::current_exception()); } -expected -OfflineDatabase::createRegion(const OfflineRegionDefinition& definition, - const OfflineRegionMetadata& metadata) try { +expected OfflineDatabase::createRegion(const OfflineRegionDefinition& definition, + const OfflineRegionMetadata& metadata) try { checkFlags(); // clang-format off @@ -841,8 +854,7 @@ OfflineDatabase::createRegion(const OfflineRegionDefinition& definition, return unexpected(std::current_exception()); } -expected -OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { +expected OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { checkFlags(); try { @@ -853,14 +865,16 @@ OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { query.bind(1, sideDatabasePath); query.run(); } catch (const mapbox::sqlite::Exception& ex) { - Log::Error(Event::Database, static_cast(ex.code), std::string("Can't attach database (") + sideDatabasePath + ") for merge: " + ex.what()); + Log::Error(Event::Database, + static_cast(ex.code), + std::string("Can't attach database (") + sideDatabasePath + ") for merge: " + ex.what()); return unexpected(std::current_exception()); } try { - // Support sideloaded databases at user_version = 6. Future schema version - // changes will need to implement migration paths for sideloaded databases at - // version 6. + // Support sideloaded databases at user_version = 6. Future schema + // version changes will need to implement migration paths for sideloaded + // databases at version 6. auto sideUserVersion = static_cast(getPragma("PRAGMA side.user_version")); const auto mainUserVersion = getPragma("PRAGMA user_version"); if (sideUserVersion < 6 || sideUserVersion != mainUserVersion) { @@ -905,13 +919,13 @@ OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { while (queryRegions.run()) { // Construct, then move because this constructor is private. OfflineRegion region(queryRegions.get(0), - decodeOfflineRegionDefinition(queryRegions.get(1)), - queryRegions.get>(2)); + decodeOfflineRegionDefinition(queryRegions.get(1)), + queryRegions.get>(2)); result.emplace_back(std::move(region)); } db->exec("DETACH DATABASE side"); // Explicit move to avoid triggering the copy constructor. - return { std::move(result) }; + return {std::move(result)}; } catch (const std::runtime_error& ex) { db->exec("DETACH DATABASE side"); Log::Error(Event::Database, std::string(ex.what())); @@ -921,8 +935,8 @@ OfflineDatabase::mergeDatabase(const std::string& sideDatabasePath) { return {}; } -expected -OfflineDatabase::updateMetadata(const int64_t regionID, const OfflineRegionMetadata& metadata) try { +expected OfflineDatabase::updateMetadata( + const int64_t regionID, const OfflineRegionMetadata& metadata) try { checkFlags(); // clang-format off @@ -944,7 +958,7 @@ std::exception_ptr OfflineDatabase::deleteRegion(OfflineRegion&& region) try { checkFlags(); { - mapbox::sqlite::Query query{ getStatement("DELETE FROM regions WHERE id = ?") }; + mapbox::sqlite::Query query{getStatement("DELETE FROM regions WHERE id = ?")}; query.bind(1, region.getID()); query.run(); } @@ -977,9 +991,7 @@ std::optional OfflineDatabase::hasRegionResource(const Resource& resour return std::nullopt; } -uint64_t OfflineDatabase::putRegionResource(int64_t regionID, - const Resource& resource, - const Response& response) try { +uint64_t OfflineDatabase::putRegionResource(int64_t regionID, const Resource& resource, const Response& response) try { checkFlags(); if (!db) { @@ -1004,8 +1016,9 @@ void OfflineDatabase::putRegionResources(int64_t regionID, } mapbox::sqlite::Transaction transaction(*db); - // Accumulate all statistics locally first before adding them to the OfflineRegionStatus object - // to ensure correctness when the transaction fails. + // Accumulate all statistics locally first before adding them to the + // OfflineRegionStatus object to ensure correctness when the transaction + // fails. uint64_t completedResourceCount = 0; uint64_t completedResourceSize = 0; uint64_t completedTileCount = 0; @@ -1041,7 +1054,9 @@ void OfflineDatabase::putRegionResources(int64_t regionID, handleError("write region resources"); } -uint64_t OfflineDatabase::putRegionResourceInternal(int64_t regionID, const Resource& resource, const Response& response) { +uint64_t OfflineDatabase::putRegionResourceInternal(int64_t regionID, + const Resource& resource, + const Response& response) { checkFlags(); uint64_t size = putInternal(resource, response, false).second; @@ -1051,10 +1066,8 @@ uint64_t OfflineDatabase::putRegionResourceInternal(int64_t regionID, const Reso throw MapboxTileLimitExceededException(); } - if (offlineMapboxTileCount - && resource.kind == Resource::Kind::Tile - && util::mapbox::isCanonicalURL(tileServerOptions, resource.url) - && previouslyUnused) { + if (offlineMapboxTileCount && resource.kind == Resource::Kind::Tile && + util::mapbox::isCanonicalURL(tileServerOptions, resource.url) && previouslyUnused) { *offlineMapboxTileCount += 1; } @@ -1145,7 +1158,7 @@ bool OfflineDatabase::markUsed(int64_t regionID, const Resource& resource) { } expected OfflineDatabase::getRegionDefinition(int64_t regionID) try { - mapbox::sqlite::Query query{ getStatement("SELECT definition FROM regions WHERE id = ?1") }; + mapbox::sqlite::Query query{getStatement("SELECT definition FROM regions WHERE id = ?1")}; query.bind(1, regionID); query.run(); @@ -1158,10 +1171,8 @@ expected OfflineDatabase::getRegion expected OfflineDatabase::getRegionCompletedStatus(int64_t regionID) try { OfflineRegionStatus result; - std::tie(result.completedResourceCount, result.completedResourceSize) - = getCompletedResourceCountAndSize(regionID); - std::tie(result.completedTileCount, result.completedTileSize) - = getCompletedTileCountAndSize(regionID); + std::tie(result.completedResourceCount, result.completedResourceSize) = getCompletedResourceCountAndSize(regionID); + std::tie(result.completedTileCount, result.completedTileSize) = getCompletedTileCountAndSize(regionID); result.completedResourceCount += result.completedTileCount; result.completedResourceSize += result.completedTileSize; @@ -1182,7 +1193,7 @@ std::pair OfflineDatabase::getCompletedResourceCountAndSize(in // clang-format on query.bind(1, regionID); query.run(); - return { query.get(0), query.get(1) }; + return {query.get(0), query.get(1)}; } std::pair OfflineDatabase::getCompletedTileCountAndSize(int64_t regionID) { @@ -1195,12 +1206,12 @@ std::pair OfflineDatabase::getCompletedTileCountAndSize(int64_ // clang-format on query.bind(1, regionID); query.run(); - return { query.get(0), query.get(1) }; + return {query.get(0), query.get(1)}; } template T OfflineDatabase::getPragma(const char* sql) { - mapbox::sqlite::Query query{ getStatement(sql) }; + mapbox::sqlite::Query query{getStatement(sql)}; query.run(); return query.get(0); } @@ -1213,12 +1224,12 @@ T OfflineDatabase::getPragma(const char* sql) { // SQLite database never shrinks in size unless we call VACUUM. We here // are monitoring the soft limit (i.e. number of free pages in the file) // and as it approaches to the hard limit (i.e. the actual file size) we -// delete an arbitrary number of old cache entries. The free pages approach saves -// us from calling VACUUM or keeping a running total, which can be costly. +// delete an arbitrary number of old cache entries. The free pages approach +// saves us from calling VACUUM or keeping a running total, which can be costly. bool OfflineDatabase::evict(uint64_t neededFreeSize, DatabaseSizeChangeStats& stats) { checkFlags(); - uint64_t ambientCacheSize = - (initAmbientCacheSize() == nullptr) ? *currentAmbientCacheSize : maximumAmbientCacheSize; + uint64_t ambientCacheSize = (initAmbientCacheSize() == nullptr) ? *currentAmbientCacheSize + : maximumAmbientCacheSize; uint64_t newAmbientCacheSize = ambientCacheSize + neededFreeSize + stats.pageSize(); while (newAmbientCacheSize > maximumAmbientCacheSize) { @@ -1410,9 +1421,8 @@ uint64_t OfflineDatabase::getOfflineMapboxTileCount() try { } bool OfflineDatabase::exceedsOfflineMapboxTileCountLimit(const Resource& resource) { - return resource.kind == Resource::Kind::Tile - && util::mapbox::isCanonicalURL(tileServerOptions, resource.url) - && offlineMapboxTileCountLimitExceeded(); + return resource.kind == Resource::Kind::Tile && util::mapbox::isCanonicalURL(tileServerOptions, resource.url) && + offlineMapboxTileCountLimitExceeded(); } void OfflineDatabase::markUsedResources(int64_t regionID, const std::list& resources) try { @@ -1457,7 +1467,8 @@ void OfflineDatabase::reopenDatabaseReadOnly(bool readOnly_) { } } -OfflineDatabase::DatabaseSizeChangeStats::DatabaseSizeChangeStats(OfflineDatabase* db_) : db(db_) { +OfflineDatabase::DatabaseSizeChangeStats::DatabaseSizeChangeStats(OfflineDatabase* db_) + : db(db_) { assert(db); pageSize_ = db->getPragma("PRAGMA page_size"); pageCount_ = db->getPragma("PRAGMA page_count"); diff --git a/platform/default/src/mbgl/storage/offline_download.cpp b/platform/default/src/mbgl/storage/offline_download.cpp index c4933a1090e..d25f7019d8d 100644 --- a/platform/default/src/mbgl/storage/offline_download.cpp +++ b/platform/default/src/mbgl/storage/offline_download.cpp @@ -35,7 +35,9 @@ using namespace style; template Range coveringZoomRange(const RegionDefinition& definition, - style::SourceType type, uint16_t tileSize, const Range& zoomRange) { + style::SourceType type, + uint16_t tileSize, + const Range& zoomRange) { double minZ = std::max(util::coveringZoomLevel(definition.minZoom, type, tileSize), zoomRange.min); double maxZ = std::min(util::coveringZoomLevel(definition.maxZoom, type, tileSize), zoomRange.max); @@ -43,7 +45,7 @@ Range coveringZoomRange(const RegionDefinition& definition, assert(maxZ >= 0); assert(minZ < std::numeric_limits::max()); assert(maxZ < std::numeric_limits::max()); - return { static_cast(minZ), static_cast(maxZ) }; + return {static_cast(minZ), static_cast(maxZ)}; } template @@ -54,33 +56,33 @@ void tileCover(const Geometry& geometry, uint8_t z, Fn&& fn) { } } - template -void tileCover(const OfflineRegionDefinition& definition, style::SourceType type, - uint16_t tileSize, const Range& zoomRange, Fn&& fn) { - const Range clampedZoomRange = - definition.match([&](auto& reg) { return coveringZoomRange(reg, type, tileSize, zoomRange); }); +void tileCover(const OfflineRegionDefinition& definition, + style::SourceType type, + uint16_t tileSize, + const Range& zoomRange, + Fn&& fn) { + const Range clampedZoomRange = definition.match( + [&](auto& reg) { return coveringZoomRange(reg, type, tileSize, zoomRange); }); for (uint8_t z = clampedZoomRange.min; z <= clampedZoomRange.max; z++) { - definition.match( - [&](const OfflineTilePyramidRegionDefinition& reg){ tileCover(reg.bounds, z, fn); }, - [&](const OfflineGeometryRegionDefinition& reg){ tileCover(reg.geometry, z, fn); } - ); + definition.match([&](const OfflineTilePyramidRegionDefinition& reg) { tileCover(reg.bounds, z, fn); }, + [&](const OfflineGeometryRegionDefinition& reg) { tileCover(reg.geometry, z, fn); }); } } -uint64_t tileCount(const OfflineRegionDefinition& definition, style::SourceType type, - uint16_t tileSize, const Range& zoomRange) { - - const Range clampedZoomRange = - definition.match([&](auto& reg) { return coveringZoomRange(reg, type, tileSize, zoomRange); }); +uint64_t tileCount(const OfflineRegionDefinition& definition, + style::SourceType type, + uint16_t tileSize, + const Range& zoomRange) { + const Range clampedZoomRange = definition.match( + [&](auto& reg) { return coveringZoomRange(reg, type, tileSize, zoomRange); }); uint64_t result{}; for (uint8_t z = clampedZoomRange.min; z <= clampedZoomRange.max; z++) { result += definition.match( - [&](const OfflineTilePyramidRegionDefinition& reg){ return util::tileCount(reg.bounds, z); }, - [&](const OfflineGeometryRegionDefinition& reg){ return util::tileCount(reg.geometry, z); } - ); + [&](const OfflineTilePyramidRegionDefinition& reg) { return util::tileCount(reg.bounds, z); }, + [&](const OfflineGeometryRegionDefinition& reg) { return util::tileCount(reg.geometry, z); }); } return result; @@ -128,14 +130,14 @@ OfflineRegionStatus OfflineDownload::getStatus() const { auto result = offlineDatabase.getRegionCompletedStatus(id); if (!result) { - // We can't find this offline region because the database is unavailable, or the download - // does not exist. + // We can't find this offline region because the database is + // unavailable, or the download does not exist. return {}; } result->requiredResourceCount++; - std::optional styleResponse = - offlineDatabase.get(Resource::style(definition.match([](auto& reg){ return reg.styleURL; }))); + std::optional styleResponse = offlineDatabase.get( + Resource::style(definition.match([](auto& reg) { return reg.styleURL; }))); if (!styleResponse) { return *result; } @@ -148,7 +150,7 @@ OfflineRegionStatus OfflineDownload::getStatus() const { for (const auto& source : parser.sources) { SourceType type = source->getType(); - auto handleTiledSource = [&] (const variant& urlOrTileset, const uint16_t tileSize) { + auto handleTiledSource = [&](const variant& urlOrTileset, const uint16_t tileSize) { if (urlOrTileset.is()) { uint64_t tileSourceCount = tileCount(definition, type, tileSize, urlOrTileset.get().zoomRange); result->requiredTileCount += tileSourceCount; @@ -159,7 +161,8 @@ OfflineRegionStatus OfflineDownload::getStatus() const { std::optional sourceResponse = offlineDatabase.get(Resource::source(url)); if (sourceResponse) { style::conversion::Error error; - std::optional tileset = style::conversion::convertJSON(*sourceResponse->data, error); + std::optional tileset = style::conversion::convertJSON(*sourceResponse->data, + error); if (tileset) { uint64_t tileSourceCount = tileCount(definition, type, tileSize, (*tileset).zoomRange); result->requiredTileCount += tileSourceCount; @@ -172,52 +175,52 @@ OfflineRegionStatus OfflineDownload::getStatus() const { }; switch (type) { - case SourceType::Vector: { - const auto& vectorSource = *source->as(); - handleTiledSource(vectorSource.getURLOrTileset(), util::tileSize_I); - break; - } + case SourceType::Vector: { + const auto& vectorSource = *source->as(); + handleTiledSource(vectorSource.getURLOrTileset(), util::tileSize_I); + break; + } - case SourceType::Raster: { - const auto& rasterSource = *source->as(); - handleTiledSource(rasterSource.getURLOrTileset(), rasterSource.getTileSize()); - break; - } + case SourceType::Raster: { + const auto& rasterSource = *source->as(); + handleTiledSource(rasterSource.getURLOrTileset(), rasterSource.getTileSize()); + break; + } - case SourceType::RasterDEM: { - const auto& rasterDEMSource = *source->as(); - handleTiledSource(rasterDEMSource.getURLOrTileset(), rasterDEMSource.getTileSize()); - break; - } + case SourceType::RasterDEM: { + const auto& rasterDEMSource = *source->as(); + handleTiledSource(rasterDEMSource.getURLOrTileset(), rasterDEMSource.getTileSize()); + break; + } - case SourceType::GeoJSON: { - const auto& geojsonSource = *source->as(); - if (geojsonSource.getURL()) { - result->requiredResourceCount += 1; + case SourceType::GeoJSON: { + const auto& geojsonSource = *source->as(); + if (geojsonSource.getURL()) { + result->requiredResourceCount += 1; + } + break; } - break; - } - case SourceType::Image: { - const auto& imageSource = *source->as(); - if (imageSource.getURL()) { - result->requiredResourceCount += 1; + case SourceType::Image: { + const auto& imageSource = *source->as(); + if (imageSource.getURL()) { + result->requiredResourceCount += 1; + } + break; } - break; - } - case SourceType::Video: - case SourceType::Annotations: - case SourceType::CustomVector: - break; + case SourceType::Video: + case SourceType::Annotations: + case SourceType::CustomVector: + break; } } if (!parser.glyphURL.empty()) { result->requiredResourceCount += parser.fontStacks().size() * - (definition.match([](auto& reg){ return reg.includeIdeographs; }) ? - GLYPH_RANGES_PER_FONT_STACK : - NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK); + (definition.match([](auto& reg) { return reg.includeIdeographs; }) + ? GLYPH_RANGES_PER_FONT_STACK + : NON_IDEOGRAPH_GLYPH_RANGES_PER_FONT_STACK); } if (!parser.spriteURL.empty()) { @@ -232,7 +235,7 @@ void OfflineDownload::activateDownload() { status.downloadState = OfflineRegionDownloadState::Active; status.requiredResourceCount++; - auto styleResource = Resource::style(definition.match([](auto& reg){ return reg.styleURL; })); + auto styleResource = Resource::style(definition.match([](auto& reg) { return reg.styleURL; })); styleResource.setPriority(Resource::Priority::Low); styleResource.setUsage(Resource::Usage::Offline); @@ -241,21 +244,21 @@ void OfflineDownload::activateDownload() { style::Parser parser; parser.parse(*styleResponse.data); - + auto tileServerOptions = onlineFileSource.getResourceOptions().tileServerOptions(); parser.spriteURL = util::mapbox::canonicalizeSpriteURL(tileServerOptions, parser.spriteURL); parser.glyphURL = util::mapbox::canonicalizeGlyphURL(tileServerOptions, parser.glyphURL); - + for (const auto& source : parser.sources) { SourceType type = source->getType(); - auto handleTiledSource = [&] (const variant& urlOrTileset, const uint16_t tileSize) { + auto handleTiledSource = [&](const variant& urlOrTileset, const uint16_t tileSize) { if (urlOrTileset.is()) { queueTiles(type, tileSize, urlOrTileset.get()); } else { const auto& rawUrl = urlOrTileset.get(); const auto& url = util::mapbox::canonicalizeSourceURL(tileServerOptions, rawUrl); - + status.requiredResourceCountIsPrecise = false; status.requiredResourceCount++; requiredSourceURLs.insert(url); @@ -266,10 +269,12 @@ void OfflineDownload::activateDownload() { ensureResource(std::move(sourceResource), [=](const Response& sourceResponse) { style::conversion::Error error; - std::optional tileset = style::conversion::convertJSON(*sourceResponse.data, error); + std::optional tileset = style::conversion::convertJSON(*sourceResponse.data, + error); if (tileset) { auto resourceOptions = onlineFileSource.getResourceOptions(); - util::mapbox::canonicalizeTileset(resourceOptions.tileServerOptions(), *tileset, url, type, tileSize); + util::mapbox::canonicalizeTileset( + resourceOptions.tileServerOptions(), *tileset, url, type, tileSize); queueTiles(type, tileSize, *tileset); requiredSourceURLs.erase(url); @@ -325,13 +330,14 @@ void OfflineDownload::activateDownload() { } if (!parser.glyphURL.empty()) { - const bool includeIdeographs = definition.match([](auto& reg){ return reg.includeIdeographs; }); + const bool includeIdeographs = definition.match([](auto& reg) { return reg.includeIdeographs; }); for (const auto& fontStack : parser.fontStacks()) { for (char16_t i = 0; i < GLYPH_RANGES_PER_FONT_STACK; i++) { - // Assumes that if a glyph range starts with fixed width/ideographic characters, the entire - // range will be fixed width. + // Assumes that if a glyph range starts with fixed width/ideographic + // characters, the entire range will be fixed width. if (includeIdeographs || !util::i18n::allowsFixedWidthGlyphGeneration(i * GLYPHS_PER_GLYPH_RANGE)) { - queueResource(Resource::glyphs(parser.glyphURL, fontStack, getGlyphRange(i * GLYPHS_PER_GLYPH_RANGE))); + queueResource( + Resource::glyphs(parser.glyphURL, fontStack, getGlyphRange(i * GLYPHS_PER_GLYPH_RANGE))); } } } @@ -350,21 +356,23 @@ void OfflineDownload::activateDownload() { } /* - Fill up our own request queue by requesting the next few resources. This is called - when activating the download, or when a request completes successfully. - - Note "successfully"; it's not called when a requests receives an error. A request - that errors will be retried after some delay. So in that sense it's still "active" - and consuming resources, notably the request object, its timer, and network resources - when the timer fires. - - We could try to squeeze in subsequent requests while we wait for the errored request - to retry. But that risks overloading the upstream request queue -- defeating our own - metering -- if there are a lot of errored requests that all come up for retry at the - same time. And many times, the cause of a request error will apply to many requests - of the same type. For instance if a server is unreachable, all the requests to that - host are going to error. In that case, continuing to try subsequent resources after - the first few errors is fruitless anyway. + Fill up our own request queue by requesting the next few resources. This is + called when activating the download, or when a request completes + successfully. + + Note "successfully"; it's not called when a requests receives an error. A + request that errors will be retried after some delay. So in that sense it's + still "active" and consuming resources, notably the request object, its + timer, and network resources when the timer fires. + + We could try to squeeze in subsequent requests while we wait for the errored + request to retry. But that risks overloading the upstream request queue -- + defeating our own metering -- if there are a lot of errored requests that all + come up for retry at the same time. And many times, the cause of a request + error will apply to many requests of the same type. For instance if a server + is unreachable, all the requests to that host are going to error. In that + case, continuing to try subsequent resources after the first few errors is + fruitless anyway. */ void OfflineDownload::continueDownload() { if (resourcesRemaining.empty()) { @@ -426,9 +434,12 @@ void OfflineDownload::queueTiles(SourceType type, uint16_t tileSize, const Tiles status.requiredResourceCount++; status.requiredTileCount++; - auto tileResource = Resource::tile( - tileset.tiles[0], definition.match([](auto& def) { return def.pixelRatio; }), - tile.x, tile.y, tile.z, tileset.scheme); + auto tileResource = Resource::tile(tileset.tiles[0], + definition.match([](auto& def) { return def.pixelRatio; }), + tile.x, + tile.y, + tile.z, + tileset.scheme); tileResource.setPriority(Resource::Priority::Low); tileResource.setUsage(Resource::Usage::Offline); @@ -442,8 +453,7 @@ void OfflineDownload::markPendingUsedResources() { resourcesToBeMarkedAsUsed.clear(); } -void OfflineDownload::ensureResource(Resource&& resource, - std::function callback) { +void OfflineDownload::ensureResource(Resource&& resource, std::function callback) { assert(resource.priority == Resource::Priority::Low); assert(resource.usage == Resource::Usage::Offline); @@ -451,7 +461,7 @@ void OfflineDownload::ensureResource(Resource&& resource, *workRequestsIt = util::RunLoop::Get()->invokeCancellable([=]() { requests.erase(workRequestsIt); const auto resourceKind = resource.kind; - auto getResourceSizeInDatabase = [&] () -> std::optional { + auto getResourceSizeInDatabase = [&]() -> std::optional { std::optional result; if (!callback) { result = offlineDatabase.hasRegionResource(resource); @@ -511,7 +521,8 @@ void OfflineDownload::ensureResource(Resource&& resource, buffer.emplace_back(resource, onlineResponse); // Flush buffer periodically. - // Have to keep `resourcesRemaining.empty()` as the following condition would fail otherwise. + // Have to keep `resourcesRemaining.empty()` as the following + // condition would fail otherwise. // TODO: Simplify the tile count limit check code path! if ((buffer.size() == kResourcesBatchSize || resourcesRemaining.empty()) && !flushResourcesBuffer()) return; diff --git a/platform/default/src/mbgl/storage/online_file_source.cpp b/platform/default/src/mbgl/storage/online_file_source.cpp index 1e2b928caf6..3c93075e2bd 100644 --- a/platform/default/src/mbgl/storage/online_file_source.cpp +++ b/platform/default/src/mbgl/storage/online_file_source.cpp @@ -61,13 +61,13 @@ struct OnlineFileRequest { std::function cancelCallback = nullptr; std::shared_ptr mailbox; - // Counts the number of times a response was already expired when received. We're using - // this to add a delay when making a new request so we don't keep retrying immediately - // in case of a server serving expired tiles. + // Counts the number of times a response was already expired when received. + // We're using this to add a delay when making a new request so we don't + // keep retrying immediately in case of a server serving expired tiles. uint32_t expiredRequests = 0; - // Counts the number of subsequent failed requests. We're using this value for exponential - // backoff when retrying requests. + // Counts the number of subsequent failed requests. We're using this value + // for exponential backoff when retrying requests. uint32_t failedRequests = 0; Response::Error::Reason failedRequestReason = Response::Error::Reason::Success; std::optional retryAfter; @@ -76,7 +76,9 @@ struct OnlineFileRequest { class OnlineFileSourceThread { public: OnlineFileSourceThread(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()), httpFileSource(resourceOptions_, clientOptions_) { + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()), + httpFileSource(resourceOptions_, clientOptions_) { NetworkStatus::Subscribe(&reachability); setMaximumConcurrentRequests(util::DEFAULT_MAXIMUM_CONCURRENT_REQUESTS); } @@ -84,7 +86,9 @@ class OnlineFileSourceThread { ~OnlineFileSourceThread() { NetworkStatus::Unsubscribe(&reachability); } void request(AsyncRequest* req, Resource resource, const ActorRef& ref) { - auto callback = [ref](const Response& res) { ref.invoke(&FileSourceRequest::setResponse, res); }; + auto callback = [ref](const Response& res) { + ref.invoke(&FileSourceRequest::setResponse, res); + }; tasks[req] = std::make_unique(std::move(resource), std::move(callback), *this); } @@ -98,8 +102,9 @@ class OnlineFileSourceThread { void add(OnlineFileRequest* req) { allRequests.insert(req); if (resourceTransform) { - // Request the ResourceTransform actor a new url and replace the resource url with the - // transformed one before proceeding to schedule the request. + // Request the ResourceTransform actor a new url and replace the + // resource url with the transformed one before proceeding to + // schedule the request. resourceTransform.transform( req->resource.kind, req->resource.url, [ref = req->actor()](const std::string& url) { ref.invoke(&OnlineFileRequest::setTransformedURL, url); @@ -166,21 +171,13 @@ class OnlineFileSourceThread { void setResourceTransform(ResourceTransform transform) { resourceTransform = std::move(transform); } - void setResourceOptions(ResourceOptions options) { - resourceOptions = options; - } + void setResourceOptions(ResourceOptions options) { resourceOptions = options; } - const ResourceOptions& getResourceOptions() const { - return resourceOptions; - } + const ResourceOptions& getResourceOptions() const { return resourceOptions; } - void setClientOptions(ClientOptions options) { - clientOptions = options; - } + void setClientOptions(ClientOptions options) { clientOptions = options; } - const ClientOptions& getClientOptions() const { - return clientOptions; - } + const ClientOptions& getClientOptions() const { return clientOptions; } void setOnlineStatus(bool status) { online = status; @@ -189,9 +186,7 @@ class OnlineFileSourceThread { } } - uint32_t getMaximumConcurrentRequests() const { - return maximumConcurrentRequests; - } + uint32_t getMaximumConcurrentRequests() const { return maximumConcurrentRequests; } void setMaximumConcurrentRequests(uint32_t maximumConcurrentRequests_) { maximumConcurrentRequests = maximumConcurrentRequests_; @@ -237,7 +232,8 @@ class OnlineFileSourceThread { // firstLowPriorityRequest struct PendingRequests { - PendingRequests() : firstLowPriorityRequest(queue.begin()) {} + PendingRequests() + : firstLowPriorityRequest(queue.begin()) {} std::list queue; std::list::iterator firstLowPriorityRequest; @@ -256,12 +252,10 @@ class OnlineFileSourceThread { if (request->resource.priority == Resource::Priority::Regular) { firstLowPriorityRequest = queue.insert(firstLowPriorityRequest, request); firstLowPriorityRequest++; - } - else { + } else { if (firstLowPriorityRequest == queue.end()) { firstLowPriorityRequest = queue.insert(queue.end(), request); - } - else { + } else { queue.insert(queue.end(), request); } } @@ -284,7 +278,6 @@ class OnlineFileSourceThread { bool contains(OnlineFileRequest* request) const { return (std::find(queue.begin(), queue.end(), request) != queue.end()); } - }; ResourceTransform resourceTransform; @@ -318,11 +311,14 @@ class OnlineFileSourceThread { class OnlineFileSource::Impl { public: - Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : - cachedResourceOptions(resourceOptions.clone()), - cachedClientOptions(clientOptions.clone()), - thread(std::make_unique>( - util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_NETWORK), "OnlineFileSource", resourceOptions.clone(), clientOptions.clone())) {} + Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) + : cachedResourceOptions(resourceOptions.clone()), + cachedClientOptions(clientOptions.clone()), + thread(std::make_unique>( + util::makeThreadPrioritySetter(platform::EXPERIMENTAL_THREAD_PRIORITY_NETWORK), + "OnlineFileSource", + resourceOptions.clone(), + clientOptions.clone())) {} std::unique_ptr request(Callback callback, Resource res) { auto req = std::make_unique(std::move(callback)); @@ -331,7 +327,7 @@ class OnlineFileSource::Impl { thread->actor().invoke(&OnlineFileSourceThread::request, req.get(), std::move(res), req->actor()); return req; } - + void pause() { thread->pause(); } void resume() { thread->resume(); } @@ -409,7 +405,8 @@ class OnlineFileSource::Impl { thread->actor().invoke(&OnlineFileSourceThread::setAPIBaseURL, *baseURL); { std::lock_guard lock(resourceOptionsMutex); - cachedResourceOptions.withTileServerOptions(cachedResourceOptions.tileServerOptions().clone().withBaseURL(*baseURL)); + cachedResourceOptions.withTileServerOptions( + cachedResourceOptions.tileServerOptions().clone().withBaseURL(*baseURL)); } } else { Log::Error(Event::General, "Invalid base-url property value type."); @@ -433,7 +430,9 @@ class OnlineFileSource::Impl { }; OnlineFileRequest::OnlineFileRequest(Resource resource_, Callback callback_, OnlineFileSourceThread& impl_) - : impl(impl_), resource(std::move(resource_)), callback(std::move(callback_)) { + : impl(impl_), + resource(std::move(resource_)), + callback(std::move(callback_)) { impl.add(this); } @@ -504,17 +503,15 @@ void OnlineFileRequest::schedule(Duration timeout) { timeout = Duration::max(); } - timer.start(timeout, Duration::zero(), [&] { - impl.activateOrQueueRequest(this); - }); + timer.start(timeout, Duration::zero(), [&] { impl.activateOrQueueRequest(this); }); } Duration OnlineFileRequest::getUpdateInterval(std::optional expires) const { // Calculate a timeout that depends on how many // consecutive errors we've encountered, and on the expiration time, if present. Duration errorRetryTimeout = http::errorRetryTimeout(failedRequestReason, failedRequests, retryAfter); - Duration expirationTimeout = - std::max(http::expirationTimeout(std::move(expires), expiredRequests), resource.minimumUpdateInterval); + Duration expirationTimeout = std::max(http::expirationTimeout(std::move(expires), expiredRequests), + resource.minimumUpdateInterval); return std::min(errorRetryTimeout, expirationTimeout); } @@ -538,9 +535,10 @@ void OnlineFileRequest::completed(Response response) { } if (response.notModified && resource.priorData) { - // When the priorData field is set, it indicates that we had to revalidate the request and - // that the requestor hasn't gotten data yet. If we get a 304 response, this means that we - // have send the cached data to give the requestor a chance to actually obtain the data. + // When the priorData field is set, it indicates that we had to + // revalidate the request and that the requestor hasn't gotten data yet. + // If we get a 304 response, this means that we have send the cached + // data to give the requestor a chance to actually obtain the data. response.data = std::move(resource.priorData); response.notModified = false; } @@ -579,9 +577,9 @@ void OnlineFileRequest::completed(Response response) { schedule(getUpdateInterval(response.expires)); - // Calling the callback may result in `this` being deleted. It needs to be done last, - // and needs to make a local copy of the callback to ensure that it remains valid for - // the duration of the call. + // Calling the callback may result in `this` being deleted. It needs to be + // done last, and needs to make a local copy of the callback to ensure that + // it remains valid for the duration of the call. auto callback_ = callback; callback_(response); } @@ -628,8 +626,7 @@ std::unique_ptr OnlineFileSource::request(const Resource& resource break; case Resource::Kind::Style: - res.url = - mbgl::util::mapbox::normalizeStyleURL(options, resource.url, impl->getApiKey()); + res.url = mbgl::util::mapbox::normalizeStyleURL(options, resource.url, impl->getApiKey()); break; case Resource::Kind::Source: diff --git a/platform/default/src/mbgl/storage/sqlite3.cpp b/platform/default/src/mbgl/storage/sqlite3.cpp index c6d4c6fc500..28e5351eb12 100644 --- a/platform/default/src/mbgl/storage/sqlite3.cpp +++ b/platform/default/src/mbgl/storage/sqlite3.cpp @@ -11,9 +11,12 @@ #include #include -#define MBGL_CONSTRUCTOR(f) \ - static void f(void); \ - struct f##_t_ { f##_t_(void) { f(); } }; static f##_t_ f##_; \ +#define MBGL_CONSTRUCTOR(f) \ + static void f(void); \ + struct f##_t_ { \ + f##_t_(void) { f(); } \ + }; \ + static f##_t_ f##_; \ static void f(void) namespace mapbox { @@ -51,15 +54,17 @@ void setTempPath(const std::string& path) { class DatabaseImpl { public: - explicit DatabaseImpl(sqlite3* db_) : db(db_) { + explicit DatabaseImpl(sqlite3* db_) + : db(db_) { const int error = sqlite3_extended_result_codes(db, true); if (error != SQLITE_OK) { - mbgl::Log::Warning(mbgl::Event::Database, error, std::string("Failed to enable extended result codes: ") + sqlite3_errmsg(db)); + mbgl::Log::Warning(mbgl::Event::Database, + error, + std::string("Failed to enable extended result codes: ") + sqlite3_errmsg(db)); } } - ~DatabaseImpl() - { + ~DatabaseImpl() { const int error = sqlite3_close(db); if (error != SQLITE_OK) { mbgl::Log::Error(mbgl::Event::Database, error, "Failed to close database: %s", sqlite3_errmsg(db)); @@ -74,17 +79,15 @@ class DatabaseImpl { class StatementImpl { public: - StatementImpl(sqlite3* db, const char* sql) - { + StatementImpl(sqlite3* db, const char* sql) { const int error = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (error != SQLITE_OK) { stmt = nullptr; - throw Exception { error, sqlite3_errmsg(db) }; + throw Exception{error, sqlite3_errmsg(db)}; } } - ~StatementImpl() - { + ~StatementImpl() { if (!stmt) return; sqlite3_finalize(stmt); @@ -92,7 +95,7 @@ class StatementImpl { void check(int err) { if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(sqlite3_db_handle(stmt)) }; + throw Exception{err, sqlite3_errmsg(sqlite3_db_handle(stmt))}; } } @@ -102,7 +105,7 @@ class StatementImpl { }; #ifndef NDEBUG -void logSqlMessage(void *, const int err, const char *msg) { +void logSqlMessage(void*, const int err, const char* msg) { mbgl::Log::Record(mbgl::EventSeverity::Debug, mbgl::Event::Database, err, "%s", msg); } #endif @@ -110,9 +113,12 @@ void logSqlMessage(void *, const int err, const char *msg) { MBGL_CONSTRUCTOR(initialize) { if (sqlite3_libversion_number() / 1000000 != SQLITE_VERSION_NUMBER / 1000000) { char message[96]; - snprintf(message, 96, - "sqlite3 libversion mismatch: headers report %d, but library reports %d", - SQLITE_VERSION_NUMBER, sqlite3_libversion_number()); + snprintf(message, + 96, + "sqlite3 libversion mismatch: headers report %d, but library " + "reports %d", + SQLITE_VERSION_NUMBER, + sqlite3_libversion_number()); throw std::runtime_error(message); } @@ -122,18 +128,18 @@ MBGL_CONSTRUCTOR(initialize) { #endif } -mapbox::util::variant Database::tryOpen(const std::string &filename, int flags) { +mapbox::util::variant Database::tryOpen(const std::string& filename, int flags) { sqlite3* db = nullptr; const int error = sqlite3_open_v2(filename.c_str(), &db, flags | SQLITE_OPEN_URI, nullptr); if (error != SQLITE_OK) { const auto message = sqlite3_errmsg(db); sqlite3_close(db); - return Exception { error, message }; + return Exception{error, message}; } return Database(std::make_unique(db)); } -Database Database::open(const std::string &filename, int flags) { +Database Database::open(const std::string& filename, int flags) { auto result = tryOpen(filename, flags); if (result.is()) { throw std::move(result.get()); @@ -143,10 +149,10 @@ Database Database::open(const std::string &filename, int flags) { } Database::Database(std::unique_ptr impl_) - : impl(std::move(impl_)) -{} + : impl(std::move(impl_)) {} -Database::Database(Database&& other) noexcept : impl(std::move(other.impl)) {} +Database::Database(Database&& other) noexcept + : impl(std::move(other.impl)) {} Database& Database::operator=(Database&& other) noexcept { std::swap(impl, other.impl); @@ -161,33 +167,32 @@ void Database::setBusyTimeout(std::chrono::milliseconds timeout) { } void DatabaseImpl::setBusyTimeout(std::chrono::milliseconds timeout) { - const int err = sqlite3_busy_timeout(db, - int(std::min(timeout.count(), std::numeric_limits::max()))); + const int err = sqlite3_busy_timeout( + db, int(std::min(timeout.count(), std::numeric_limits::max()))); if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(db) }; + throw Exception{err, sqlite3_errmsg(db)}; } } -void Database::exec(const std::string &sql) { +void Database::exec(const std::string& sql) { assert(impl); impl->exec(sql); } void DatabaseImpl::exec(const std::string& sql) { - char *msg = nullptr; + char* msg = nullptr; const int err = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &msg); if (msg) { const std::string message = msg; sqlite3_free(msg); - throw Exception { err, message }; + throw Exception{err, message}; } else if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(db) }; + throw Exception{err, sqlite3_errmsg(db)}; } } Statement::Statement(Database& db, const char* sql) - : impl(std::make_unique(db.impl->db, sql)) { -} + : impl(std::make_unique(db.impl->db, sql)) {} // NOLINTNEXTLINE(modernize-use-equals-default) Statement::~Statement() { @@ -197,7 +202,8 @@ Statement::~Statement() { #endif } -Query::Query(Statement& stmt_) : stmt(stmt_) { +Query::Query(Statement& stmt_) + : stmt(stmt_) { assert(stmt.impl); #ifndef NDEBUG @@ -215,86 +221,98 @@ Query::~Query() { #endif } -template <> void Query::bind(int offset, std::nullptr_t) { +template <> +void Query::bind(int offset, std::nullptr_t) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_null(stmt.impl->stmt, offset)); } -template <> void Query::bind(int offset, int8_t value) { +template <> +void Query::bind(int offset, int8_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, int16_t value) { +template <> +void Query::bind(int offset, int16_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, int32_t value) { +template <> +void Query::bind(int offset, int32_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, int64_t value) { +template <> +void Query::bind(int offset, int64_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, uint8_t value) { +template <> +void Query::bind(int offset, uint8_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, uint16_t value) { +template <> +void Query::bind(int offset, uint16_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, uint32_t value) { +template <> +void Query::bind(int offset, uint32_t value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, float value) { +template <> +void Query::bind(int offset, float value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_double(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, double value) { +template <> +void Query::bind(int offset, double value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_double(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, bool value) { +template <> +void Query::bind(int offset, bool value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int(stmt.impl->stmt, offset, value)); } -template <> void Query::bind(int offset, const char *value) { +template <> +void Query::bind(int offset, const char* value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_text(stmt.impl->stmt, offset, value, -1, SQLITE_STATIC)); } -void Query::bind(int offset, const char * value, std::size_t length, bool retain) { +void Query::bind(int offset, const char* value, std::size_t length, bool retain) { assert(stmt.impl); if (length > std::numeric_limits::max()) { throw std::range_error("value too long for sqlite3_bind_text"); } - stmt.impl->check(sqlite3_bind_text(stmt.impl->stmt, offset, value, int(length), - retain ? SQLITE_TRANSIENT : SQLITE_STATIC)); + stmt.impl->check( + sqlite3_bind_text(stmt.impl->stmt, offset, value, int(length), retain ? SQLITE_TRANSIENT : SQLITE_STATIC)); } void Query::bind(int offset, const std::string& value, bool retain) { bind(offset, value.data(), value.size(), retain); } -void Query::bindBlob(int offset, const void * value, std::size_t length, bool retain) { +void Query::bindBlob(int offset, const void* value, std::size_t length, bool retain) { assert(stmt.impl); if (length > std::numeric_limits::max()) { throw std::range_error("value too long for sqlite3_bind_text"); } - stmt.impl->check(sqlite3_bind_blob(stmt.impl->stmt, offset, value, int(length), - retain ? SQLITE_TRANSIENT : SQLITE_STATIC)); + stmt.impl->check( + sqlite3_bind_blob(stmt.impl->stmt, offset, value, int(length), retain ? SQLITE_TRANSIENT : SQLITE_STATIC)); } void Query::bindBlob(int offset, const std::vector& value, bool retain) { @@ -302,13 +320,13 @@ void Query::bindBlob(int offset, const std::vector& value, bool retain) } template <> -void Query::bind( - int offset, std::chrono::time_point value) { +void Query::bind(int offset, std::chrono::time_point value) { assert(stmt.impl); stmt.impl->check(sqlite3_bind_int64(stmt.impl->stmt, offset, std::chrono::system_clock::to_time_t(value))); } -template <> void Query::bind(int offset, std::optional value) { +template <> +void Query::bind(int offset, std::optional value) { if (!value) { bind(offset, nullptr); } else { @@ -317,9 +335,8 @@ template <> void Query::bind(int offset, std::optional value) { } template <> -void Query::bind( - int offset, - std::optional> value) { +void Query::bind(int offset, + std::optional> value) { if (!value) { bind(offset, nullptr); } else { @@ -337,56 +354,60 @@ bool Query::run() { } else if (err == SQLITE_ROW) { return true; } else if (err != SQLITE_OK) { - throw Exception { err, sqlite3_errmsg(sqlite3_db_handle(stmt.impl->stmt)) }; + throw Exception{err, sqlite3_errmsg(sqlite3_db_handle(stmt.impl->stmt))}; } else { return false; } } -template <> bool Query::get(int offset) { +template <> +bool Query::get(int offset) { assert(stmt.impl); return sqlite3_column_int(stmt.impl->stmt, offset); } -template <> int Query::get(int offset) { +template <> +int Query::get(int offset) { assert(stmt.impl); return sqlite3_column_int(stmt.impl->stmt, offset); } -template <> int64_t Query::get(int offset) { +template <> +int64_t Query::get(int offset) { assert(stmt.impl); return sqlite3_column_int64(stmt.impl->stmt, offset); } -template <> double Query::get(int offset) { +template <> +double Query::get(int offset) { assert(stmt.impl); return sqlite3_column_double(stmt.impl->stmt, offset); } -template <> std::string Query::get(int offset) { +template <> +std::string Query::get(int offset) { assert(stmt.impl); - return { - reinterpret_cast(sqlite3_column_blob(stmt.impl->stmt, offset)), - size_t(sqlite3_column_bytes(stmt.impl->stmt, offset)) - }; + return {reinterpret_cast(sqlite3_column_blob(stmt.impl->stmt, offset)), + size_t(sqlite3_column_bytes(stmt.impl->stmt, offset))}; } -template <> std::vector Query::get(int offset) { +template <> +std::vector Query::get(int offset) { assert(stmt.impl); const auto* begin = reinterpret_cast(sqlite3_column_blob(stmt.impl->stmt, offset)); - const uint8_t* end = begin + sqlite3_column_bytes(stmt.impl->stmt, offset); - return { begin, end }; + const uint8_t* end = begin + sqlite3_column_bytes(stmt.impl->stmt, offset); + return {begin, end}; } template <> -std::chrono::time_point -Query::get(int offset) { +std::chrono::time_point Query::get(int offset) { assert(stmt.impl); return std::chrono::time_point_cast( std::chrono::system_clock::from_time_t(sqlite3_column_int64(stmt.impl->stmt, offset))); } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; @@ -395,7 +416,8 @@ template <> std::optional Query::get(int offset) { } } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; @@ -404,7 +426,8 @@ template <> std::optional Query::get(int offset) { } } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; @@ -414,14 +437,12 @@ template <> std::optional Query::get(int offset) { } template <> -std::optional> -Query::get(int offset) { +std::optional> Query::get(int offset) { assert(stmt.impl); if (sqlite3_column_type(stmt.impl->stmt, offset) == SQLITE_NULL) { return std::nullopt; } else { - return get>( - offset); + return get>(offset); } } @@ -449,15 +470,15 @@ uint64_t Query::changes() const { Transaction::Transaction(Database& db_, Mode mode) : dbImpl(*db_.impl) { switch (mode) { - case Deferred: - dbImpl.exec("BEGIN DEFERRED TRANSACTION"); - break; - case Immediate: - dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); - break; - case Exclusive: - dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); - break; + case Deferred: + dbImpl.exec("BEGIN DEFERRED TRANSACTION"); + break; + case Immediate: + dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); + break; + case Exclusive: + dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); + break; } } diff --git a/platform/default/src/mbgl/text/bidi.cpp b/platform/default/src/mbgl/text/bidi.cpp index 6d6ebd5d4c6..9fecfcd0927 100644 --- a/platform/default/src/mbgl/text/bidi.cpp +++ b/platform/default/src/mbgl/text/bidi.cpp @@ -12,8 +12,9 @@ namespace mbgl { class BiDiImpl { public: - BiDiImpl() : bidiText(ubidi_open()), bidiLine(ubidi_open()) { - } + BiDiImpl() + : bidiText(ubidi_open()), + bidiLine(ubidi_open()) {} ~BiDiImpl() { ubidi_close(bidiText); ubidi_close(bidiLine); @@ -23,33 +24,39 @@ class BiDiImpl { UBiDi* bidiLine = nullptr; }; -BiDi::BiDi() : impl(std::make_unique()) {} +BiDi::BiDi() + : impl(std::make_unique()) {} BiDi::~BiDi() = default; -// Takes UTF16 input in logical order and applies Arabic shaping to the input while maintaining -// logical order. Output won't be intelligible until the bidirectional algorithm is applied +// Takes UTF16 input in logical order and applies Arabic shaping to the input +// while maintaining logical order. Output won't be intelligible until the +// bidirectional algorithm is applied std::u16string applyArabicShaping(const std::u16string& input) { UErrorCode errorCode = U_ZERO_ERROR; - const int32_t outputLength = - u_shapeArabic(mbgl::utf16char_cast(input.c_str()), static_cast(input.size()), nullptr, 0, - (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | - (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), - &errorCode); + const int32_t outputLength = u_shapeArabic( + mbgl::utf16char_cast(input.c_str()), + static_cast(input.size()), + nullptr, + 0, + (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), + &errorCode); // Pre-flighting will always set U_BUFFER_OVERFLOW_ERROR errorCode = U_ZERO_ERROR; std::u16string outputText(outputLength, 0); - u_shapeArabic(mbgl::utf16char_cast(input.c_str()), static_cast(input.size()), mbgl::utf16char_cast(outputText.data()), outputLength, - (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | - (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), - &errorCode); + u_shapeArabic( + mbgl::utf16char_cast(input.c_str()), + static_cast(input.size()), + mbgl::utf16char_cast(outputText.data()), + outputLength, + (U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) | (U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK), + &errorCode); // If the algorithm fails for any reason, fall back to non-transformed text - if (U_FAILURE(errorCode)) - return input; + if (U_FAILURE(errorCode)) return input; return outputText; } @@ -71,9 +78,10 @@ void BiDi::mergeParagraphLineBreaks(std::set& lineBreakPoints) { } std::vector BiDi::applyLineBreaking(std::set lineBreakPoints) { - // BiDi::getLine will error if called across a paragraph boundary, so we need to ensure that all - // paragraph boundaries are included in the set of line break points. The calling code might not - // include the line break because it didn't need to wrap at that point, or because the text was + // BiDi::getLine will error if called across a paragraph boundary, so we + // need to ensure that all paragraph boundaries are included in the set of + // line break points. The calling code might not include the line break + // because it didn't need to wrap at that point, or because the text was // separated with a more exotic code point such as (U+001C) mergeParagraphLineBreaks(lineBreakPoints); @@ -89,12 +97,15 @@ std::vector BiDi::applyLineBreaking(std::set lineBr return transformedLines; } -std::vector BiDi::processText(const std::u16string& input, - std::set lineBreakPoints) { +std::vector BiDi::processText(const std::u16string& input, std::set lineBreakPoints) { UErrorCode errorCode = U_ZERO_ERROR; - ubidi_setPara(impl->bidiText, mbgl::utf16char_cast(input.c_str()), static_cast(input.size()), - UBIDI_DEFAULT_LTR, nullptr, &errorCode); + ubidi_setPara(impl->bidiText, + mbgl::utf16char_cast(input.c_str()), + static_cast(input.size()), + UBIDI_DEFAULT_LTR, + nullptr, + &errorCode); if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processText: ") + u_errorName(errorCode)); @@ -102,47 +113,55 @@ std::vector BiDi::processText(const std::u16string& input, return applyLineBreaking(std::move(lineBreakPoints)); } - + std::vector BiDi::processStyledText(const StyledText& input, std::set lineBreakPoints) { std::vector lines; const auto& inputText = input.first; const auto& styleIndices = input.second; - + UErrorCode errorCode = U_ZERO_ERROR; - - ubidi_setPara(impl->bidiText, mbgl::utf16char_cast(inputText.c_str()), static_cast(inputText.size()), - UBIDI_DEFAULT_LTR, nullptr, &errorCode); - + + ubidi_setPara(impl->bidiText, + mbgl::utf16char_cast(inputText.c_str()), + static_cast(inputText.size()), + UBIDI_DEFAULT_LTR, + nullptr, + &errorCode); + if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processStyledText: ") + u_errorName(errorCode)); } - + mergeParagraphLineBreaks(lineBreakPoints); - + std::size_t lineStartIndex = 0; - + for (std::size_t lineBreakPoint : lineBreakPoints) { StyledText line; line.second.reserve(lineBreakPoint - lineStartIndex); errorCode = U_ZERO_ERROR; - ubidi_setLine(impl->bidiText, static_cast(lineStartIndex), static_cast(lineBreakPoint), impl->bidiLine, &errorCode); + ubidi_setLine(impl->bidiText, + static_cast(lineStartIndex), + static_cast(lineBreakPoint), + impl->bidiLine, + &errorCode); if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processStyledText (setLine): ") + u_errorName(errorCode)); } - + errorCode = U_ZERO_ERROR; uint32_t runCount = ubidi_countRuns(impl->bidiLine, &errorCode); if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::processStyledText (countRuns): ") + u_errorName(errorCode)); } - + for (uint32_t runIndex = 0; runIndex < runCount; runIndex++) { int32_t runLogicalStart; int32_t runLength; UBiDiDirection direction = ubidi_getVisualRun(impl->bidiLine, runIndex, &runLogicalStart, &runLength); const bool isReversed = direction == UBIDI_RTL; - + std::size_t logicalStart = lineStartIndex + runLogicalStart; std::size_t logicalEnd = logicalStart + runLength; if (isReversed) { @@ -166,10 +185,12 @@ std::vector BiDi::processStyledText(const StyledText& input, std::se break; } } - + } else { line.first += input.first.substr(logicalStart, runLength); - line.second.insert(line.second.end(), styleIndices.begin() + logicalStart, styleIndices.begin() + logicalStart + runLength); + line.second.insert(line.second.end(), + styleIndices.begin() + logicalStart, + styleIndices.begin() + logicalStart + runLength); } } @@ -179,27 +200,28 @@ std::vector BiDi::processStyledText(const StyledText& input, std::se return lines; } - + std::u16string BiDi::writeReverse(const std::u16string& input, std::size_t logicalStart, std::size_t logicalEnd) { UErrorCode errorCode = U_ZERO_ERROR; auto logicalLength = static_cast(logicalEnd - logicalStart); std::u16string outputText(logicalLength + 1, 0); - - // UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like parentheses - // UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, remove control characters so that - // they don't show up on screen (some fonts have glyphs representing them) - int32_t outputLength = - ubidi_writeReverse(mbgl::utf16char_cast(&input[logicalStart]), - logicalLength, - mbgl::utf16char_cast(outputText.data()), - logicalLength + 1, // Extra room for null terminator, although we don't really need to have ICU write it for us - UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS, - &errorCode); - + + // UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like + // parentheses UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, + // remove control characters so that they don't show up on screen (some + // fonts have glyphs representing them) + int32_t outputLength = ubidi_writeReverse(mbgl::utf16char_cast(&input[logicalStart]), + logicalLength, + mbgl::utf16char_cast(outputText.data()), + logicalLength + 1, // Extra room for null terminator, although we don't + // really need to have ICU write it for us + UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS, + &errorCode); + if (U_FAILURE(errorCode)) { throw std::runtime_error(std::string("BiDi::writeReverse: ") + u_errorName(errorCode)); } - + outputText.resize(outputLength); // REMOVE_BIDI_CONTROLS may have shrunk the string return outputText; @@ -213,15 +235,17 @@ std::u16string BiDi::getLine(std::size_t start, std::size_t end) { throw std::runtime_error(std::string("BiDi::getLine (setLine): ") + u_errorName(errorCode)); } - // Because we set UBIDI_REMOVE_BIDI_CONTROLS, the output may be smaller than what we reserve + // Because we set UBIDI_REMOVE_BIDI_CONTROLS, the output may be smaller than + // what we reserve // Setting UBIDI_INSERT_LRM_FOR_NUMERIC would require // ubidi_getLength(pBiDi)+2*ubidi_countRuns(pBiDi) const int32_t outputLength = ubidi_getProcessedLength(impl->bidiLine); std::u16string outputText(outputLength, 0); - // UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like parentheses - // UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, remove control characters so that - // they don't show up on screen (some fonts have glyphs representing them) + // UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like + // parentheses UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, + // remove control characters so that they don't show up on screen (some + // fonts have glyphs representing them) int32_t finalLength = ubidi_writeReordered(impl->bidiLine, mbgl::utf16char_cast(outputText.data()), outputLength, @@ -231,8 +255,7 @@ std::u16string BiDi::getLine(std::size_t start, std::size_t end) { outputText.resize(finalLength); // REMOVE_BIDI_CONTROLS may have shrunk the string if (U_FAILURE(errorCode)) { - throw std::runtime_error(std::string("BiDi::getLine (writeReordered): ") + - u_errorName(errorCode)); + throw std::runtime_error(std::string("BiDi::getLine (writeReordered): ") + u_errorName(errorCode)); } return outputText; diff --git a/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp b/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp index ac9b40b297a..caf81fd465a 100644 --- a/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp +++ b/platform/default/src/mbgl/text/local_glyph_rasterizer.cpp @@ -2,8 +2,7 @@ namespace mbgl { -class LocalGlyphRasterizer::Impl { -}; +class LocalGlyphRasterizer::Impl {}; LocalGlyphRasterizer::LocalGlyphRasterizer(const std::optional&) {} diff --git a/platform/default/src/mbgl/util/async_task.cpp b/platform/default/src/mbgl/util/async_task.cpp index d82b8085a1a..b3d1b4fe52a 100644 --- a/platform/default/src/mbgl/util/async_task.cpp +++ b/platform/default/src/mbgl/util/async_task.cpp @@ -12,7 +12,9 @@ namespace util { class AsyncTask::Impl { public: - explicit Impl(std::function fn) : async(new uv_async_t), task(std::move(fn)) { + explicit Impl(std::function fn) + : async(new uv_async_t), + task(std::move(fn)) { auto* loop = reinterpret_cast(RunLoop::getLoopHandle()); if (uv_async_init(loop, async, asyncCallback) != 0) { throw std::runtime_error("Failed to initialize async."); @@ -23,9 +25,7 @@ class AsyncTask::Impl { } ~Impl() { - uv_close(handle(), [](uv_handle_t* h) { - delete reinterpret_cast(h); - }); + uv_close(handle(), [](uv_handle_t* h) { delete reinterpret_cast(h); }); } void maySend() { @@ -36,13 +36,9 @@ class AsyncTask::Impl { } private: - static void asyncCallback(uv_async_t* handle) { - reinterpret_cast(handle->data)->task(); - } + static void asyncCallback(uv_async_t* handle) { reinterpret_cast(handle->data)->task(); } - uv_handle_t* handle() { - return reinterpret_cast(async); - } + uv_handle_t* handle() { return reinterpret_cast(async); } uv_async_t* async; @@ -50,8 +46,7 @@ class AsyncTask::Impl { }; AsyncTask::AsyncTask(std::function&& fn) - : impl(std::make_unique(std::move(fn))) { -} + : impl(std::make_unique(std::move(fn))) {} AsyncTask::~AsyncTask() = default; diff --git a/platform/default/src/mbgl/util/compression.cpp b/platform/default/src/mbgl/util/compression.cpp index 10513e9d1d1..0c8d39eb21f 100644 --- a/platform/default/src/mbgl/util/compression.cpp +++ b/platform/default/src/mbgl/util/compression.cpp @@ -21,8 +21,8 @@ const static bool zlibVersionCheck MBGL_UNUSED = []() { const char *const version = zlibVersion(); if (version[0] != ZLIB_VERSION[0]) { char message[96]; - snprintf(message, 96, "zlib version mismatch: headers report %s, but library reports %s", - ZLIB_VERSION, version); + snprintf( + message, 96, "zlib version mismatch: headers report %s, but library reports %s", ZLIB_VERSION, version); throw std::runtime_error(message); } diff --git a/platform/default/src/mbgl/util/jpeg_reader.cpp b/platform/default/src/mbgl/util/jpeg_reader.cpp index 72db47687f1..79205d6111f 100644 --- a/platform/default/src/mbgl/util/jpeg_reader.cpp +++ b/platform/default/src/mbgl/util/jpeg_reader.cpp @@ -5,8 +5,7 @@ #include #include -extern "C" -{ +extern "C" { #include } @@ -38,13 +37,10 @@ static void skip(j_decompress_ptr cinfo, long count) { if (count <= 0) return; // A zero or negative skip count should be treated as a no-op. auto* wrap = reinterpret_cast(cinfo->src); - if (wrap->manager.bytes_in_buffer > 0 && count < static_cast(wrap->manager.bytes_in_buffer)) - { + if (wrap->manager.bytes_in_buffer > 0 && count < static_cast(wrap->manager.bytes_in_buffer)) { wrap->manager.bytes_in_buffer -= count; wrap->manager.next_input_byte = &wrap->buffer[BUF_SIZE - wrap->manager.bytes_in_buffer]; - } - else - { + } else { wrap->stream->seekg(count - wrap->manager.bytes_in_buffer, std::ios_base::cur); // trigger buffer fill wrap->manager.next_input_byte = nullptr; @@ -59,7 +55,7 @@ static void attach_stream(j_decompress_ptr cinfo, std::istream* in) { cinfo->src = static_cast((*cinfo->mem->alloc_small)( reinterpret_cast(cinfo), JPOOL_PERMANENT, sizeof(jpeg_stream_wrapper))); } - auto * src = reinterpret_cast (cinfo->src); + auto* src = reinterpret_cast(cinfo->src); src->manager.init_source = init_source; src->manager.fill_input_buffer = fill_input_buffer; src->manager.skip_input_data = skip; @@ -79,17 +75,16 @@ static void on_error_message(j_common_ptr cinfo) { } struct jpeg_info_guard { - explicit jpeg_info_guard(jpeg_decompress_struct* cinfo) : i_(cinfo) {} + explicit jpeg_info_guard(jpeg_decompress_struct* cinfo) + : i_(cinfo) {} - ~jpeg_info_guard() { - jpeg_destroy_decompress(i_); - } + ~jpeg_info_guard() { jpeg_destroy_decompress(i_); } jpeg_decompress_struct* i_; }; PremultipliedImage decodeJPEG(const uint8_t* data, size_t size) { - util::CharArrayBuffer dataBuffer { reinterpret_cast(data), size }; + util::CharArrayBuffer dataBuffer{reinterpret_cast(data), size}; std::istream stream(&dataBuffer); jpeg_decompress_struct cinfo; @@ -102,8 +97,7 @@ PremultipliedImage decodeJPEG(const uint8_t* data, size_t size) { attach_stream(&cinfo, &stream); int ret = jpeg_read_header(&cinfo, TRUE); - if (ret != JPEG_HEADER_OK) - throw std::runtime_error("JPEG Reader: failed to read header"); + if (ret != JPEG_HEADER_OK) throw std::runtime_error("JPEG Reader: failed to read header"); jpeg_start_decompress(&cinfo); @@ -118,10 +112,11 @@ PremultipliedImage decodeJPEG(const uint8_t* data, size_t size) { size_t components = cinfo.output_components; size_t rowStride = components * width; - PremultipliedImage image({ static_cast(width), static_cast(height) }); + PremultipliedImage image({static_cast(width), static_cast(height)}); uint8_t* dst = image.data.get(); - JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)(reinterpret_cast(&cinfo), JPOOL_IMAGE, static_cast(rowStride), 1); + JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)( + reinterpret_cast(&cinfo), JPOOL_IMAGE, static_cast(rowStride), 1); while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, buffer, 1); diff --git a/platform/default/src/mbgl/util/png_reader.cpp b/platform/default/src/mbgl/util/png_reader.cpp index 40448cf2795..d66373b9699 100644 --- a/platform/default/src/mbgl/util/png_reader.cpp +++ b/platform/default/src/mbgl/util/png_reader.cpp @@ -6,13 +6,12 @@ #include #include -extern "C" -{ +extern "C" { #include } -template -static std::string sprintf(const char *msg, Args... args) { +template +static std::string sprintf(const char* msg, Args... args) { char res[max]; int len = snprintf(res, sizeof(res), msg, args...); return std::string(res, len); @@ -21,10 +20,15 @@ static std::string sprintf(const char *msg, Args... args) { const static bool png_version_check [[maybe_unused]] = []() { const png_uint_32 version = png_access_version_number(); if (version != PNG_LIBPNG_VER) { - throw std::runtime_error(sprintf<96>( - "libpng version mismatch: headers report %d.%d.%d, but library reports %d.%d.%d", - PNG_LIBPNG_VER / 10000, (PNG_LIBPNG_VER / 100) % 100, PNG_LIBPNG_VER % 100, - version / 10000, (version / 100) % 100, version % 100)); + throw std::runtime_error( + sprintf<96>("libpng version mismatch: headers report %d.%d.%d, but library " + "reports %d.%d.%d", + PNG_LIBPNG_VER / 10000, + (PNG_LIBPNG_VER / 100) % 100, + PNG_LIBPNG_VER % 100, + version / 10000, + (version / 100) % 100, + version % 100)); } return true; }(); @@ -43,8 +47,7 @@ static void png_read_data(png_structp png_ptr, png_bytep data, png_size_t length auto* fin = reinterpret_cast(png_get_io_ptr(png_ptr)); fin->read(reinterpret_cast(data), length); std::streamsize read_count = fin->gcount(); - if (read_count < 0 || static_cast(read_count) != length) - { + if (read_count < 0 || static_cast(read_count) != length) { png_error(png_ptr, "Read Error"); } } @@ -54,30 +57,25 @@ struct png_struct_guard { : p_(png_ptr_ptr), i_(info_ptr_ptr) {} - ~png_struct_guard() { - png_destroy_read_struct(p_,i_,nullptr); - } + ~png_struct_guard() { png_destroy_read_struct(p_, i_, nullptr); } png_structpp p_; png_infopp i_; }; PremultipliedImage decodePNG(const uint8_t* data, size_t size) { - util::CharArrayBuffer dataBuffer { reinterpret_cast(data), size }; + util::CharArrayBuffer dataBuffer{reinterpret_cast(data), size}; std::istream stream(&dataBuffer); - png_byte header[8] = { 0 }; + png_byte header[8] = {0}; stream.read(reinterpret_cast(header), 8); - if (stream.gcount() != 8) - throw std::runtime_error("PNG reader: Could not read image"); + if (stream.gcount() != 8) throw std::runtime_error("PNG reader: Could not read image"); int is_png = !png_sig_cmp(header, 0, 8); - if (!is_png) - throw std::runtime_error("File or stream is not a png"); + if (!is_png) throw std::runtime_error("File or stream is not a png"); png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); - if (!png_ptr) - throw std::runtime_error("failed to allocate png_ptr"); + if (!png_ptr) throw std::runtime_error("failed to allocate png_ptr"); // catch errors in a custom way to avoid the need for setjmp png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn); @@ -85,8 +83,7 @@ PremultipliedImage decodePNG(const uint8_t* data, size_t size) { png_infop info_ptr; png_struct_guard sguard(&png_ptr, &info_ptr); info_ptr = png_create_info_struct(png_ptr); - if (!info_ptr) - throw std::runtime_error("failed to create info_ptr"); + if (!info_ptr) throw std::runtime_error("failed to create info_ptr"); png_set_read_fn(png_ptr, &stream, png_read_data); png_set_sig_bytes(png_ptr, 8); @@ -98,27 +95,21 @@ PremultipliedImage decodePNG(const uint8_t* data, size_t size) { int color_type = 0; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, nullptr, nullptr, nullptr); - UnassociatedImage image({ static_cast(width), static_cast(height) }); + UnassociatedImage image({static_cast(width), static_cast(height)}); - if (color_type == PNG_COLOR_TYPE_PALETTE) - png_set_expand(png_ptr); + if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); - if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) - png_set_expand(png_ptr); + if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand(png_ptr); - if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) - png_set_expand(png_ptr); + if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); - if (bit_depth == 16) - png_set_strip_16(png_ptr); + if (bit_depth == 16) png_set_strip_16(png_ptr); - if (color_type == PNG_COLOR_TYPE_GRAY || - color_type == PNG_COLOR_TYPE_GRAY_ALPHA) - png_set_gray_to_rgb(png_ptr); + if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); - if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7) { + if (png_get_interlace_type(png_ptr, info_ptr) == PNG_INTERLACE_ADAM7) { png_set_interlace_handling(png_ptr); // FIXME: libpng bug? // according to docs png_read_image // "..automatically handles interlacing, @@ -130,8 +121,7 @@ PremultipliedImage decodePNG(const uint8_t* data, size_t size) { // we can read whole image at once // alloc row pointers const std::unique_ptr rows(new png_bytep[height]); - for (unsigned row = 0; row < height; ++row) - rows[row] = image.data.get() + row * width * 4; + for (unsigned row = 0; row < height; ++row) rows[row] = image.data.get() + row * width * 4; png_read_image(png_ptr, rows.get()); png_read_end(png_ptr, nullptr); diff --git a/platform/default/src/mbgl/util/png_writer.cpp b/platform/default/src/mbgl/util/png_writer.cpp index 4a7ef43052c..19290cc9952 100644 --- a/platform/default/src/mbgl/util/png_writer.cpp +++ b/platform/default/src/mbgl/util/png_writer.cpp @@ -19,8 +19,8 @@ void addChunk(std::string& png, const char* type, const char* data = "", const u checksum.process_bytes(type, 4); checksum.process_bytes(data, size); - const char length[4] = { NETWORK_BYTE_UINT32(size) }; - const char crc[4] = { NETWORK_BYTE_UINT32(checksum.checksum()) }; + const char length[4] = {NETWORK_BYTE_UINT32(size)}; + const char crc[4] = {NETWORK_BYTE_UINT32(checksum.checksum())}; png.reserve(png.size() + 4 /* length */ + 4 /* type */ + size + 4 /* CRC */); png.append(length, 4); @@ -39,7 +39,7 @@ std::string encodePNG(const PremultipliedImage& pre) { const auto src = util::unpremultiply(pre.clone()); // PNG magic bytes - const char preamble[8] = { char(0x89), 'P', 'N', 'G', '\r', '\n', 0x1a, '\n' }; + const char preamble[8] = {char(0x89), 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}; // IHDR chunk for our RGBA image. const char ihdr[13] = { @@ -64,8 +64,7 @@ std::string encodePNG(const PremultipliedImage& pre) { // Assemble the PNG. std::string png; - png.reserve((8 /* preamble */) + (12 + 13 /* IHDR */) + - (12 + idat.size() /* IDAT */) + (12 /* IEND */)); + png.reserve((8 /* preamble */) + (12 + 13 /* IHDR */) + (12 + idat.size() /* IDAT */) + (12 /* IEND */)); png.append(preamble, 8); addChunk(png, "IHDR", ihdr, 13); addChunk(png, "IDAT", idat.data(), static_cast(idat.size())); diff --git a/platform/default/src/mbgl/util/run_loop.cpp b/platform/default/src/mbgl/util/run_loop.cpp index 8e8eb35052a..3d4ac14b685 100644 --- a/platform/default/src/mbgl/util/run_loop.cpp +++ b/platform/default/src/mbgl/util/run_loop.cpp @@ -24,21 +24,21 @@ struct Watch { RunLoop::Event watchEvent = RunLoop::Event::None; switch (event) { - case UV_READABLE: - watchEvent = RunLoop::Event::Read; - break; - case UV_WRITABLE: - watchEvent = RunLoop::Event::Write; - break; - case UV_READABLE | UV_WRITABLE: - watchEvent = RunLoop::Event::ReadWrite; - break; + case UV_READABLE: + watchEvent = RunLoop::Event::Read; + break; + case UV_WRITABLE: + watchEvent = RunLoop::Event::Write; + break; + case UV_READABLE | UV_WRITABLE: + watchEvent = RunLoop::Event::ReadWrite; + break; } watch->eventCallback(watch->fd, watchEvent); }; - static void onClose(uv_handle_t *poll) { + static void onClose(uv_handle_t* poll) { auto watch = reinterpret_cast(poll->data); watch->closeCallback(); }; @@ -58,16 +58,12 @@ RunLoop* RunLoop::Get() { class RunLoop::Impl { public: void closeHolder() { - uv_close(holderHandle(), [](uv_handle_t* h) { - delete reinterpret_cast(h); - }); + uv_close(holderHandle(), [](uv_handle_t* h) { delete reinterpret_cast(h); }); } - uv_handle_t* holderHandle() { - return reinterpret_cast(holder); - } + uv_handle_t* holderHandle() { return reinterpret_cast(holder); } - uv_loop_t *loop = nullptr; + uv_loop_t* loop = nullptr; uv_async_t* holder = new uv_async_t; RunLoop::Type type; @@ -76,17 +72,18 @@ class RunLoop::Impl { std::unordered_map> watchPoll; }; -RunLoop::RunLoop(Type type) : impl(std::make_unique()) { +RunLoop::RunLoop(Type type) + : impl(std::make_unique()) { switch (type) { - case Type::New: - impl->loop = new uv_loop_t; - if (uv_loop_init(impl->loop) != 0) { - throw std::runtime_error("Failed to initialize loop."); - } - break; - case Type::Default: - impl->loop = uv_default_loop(); - break; + case Type::New: + impl->loop = new uv_loop_t; + if (uv_loop_init(impl->loop) != 0) { + throw std::runtime_error("Failed to initialize loop."); + } + break; + case Type::Default: + impl->loop = uv_default_loop(); + break; } // Just for holding a ref to the main loop and keep @@ -153,7 +150,7 @@ void RunLoop::stop() { void RunLoop::addWatch(int fd, Event event, std::function&& callback) { MBGL_VERIFY_THREAD(tid); - Watch *watch = nullptr; + Watch* watch = nullptr; auto watchPollIter = impl->watchPoll.find(fd); if (watchPollIter == impl->watchPoll.end()) { @@ -179,17 +176,17 @@ void RunLoop::addWatch(int fd, Event event, std::function&& ca int pollEvent = 0; switch (event) { - case Event::Read: - pollEvent = UV_READABLE; - break; - case Event::Write: - pollEvent = UV_WRITABLE; - break; - case Event::ReadWrite: - pollEvent = UV_READABLE | UV_WRITABLE; - break; - default: - throw std::runtime_error("Unhandled event."); + case Event::Read: + pollEvent = UV_READABLE; + break; + case Event::Write: + pollEvent = UV_WRITABLE; + break; + case Event::ReadWrite: + pollEvent = UV_READABLE | UV_WRITABLE; + break; + default: + throw std::runtime_error("Unhandled event."); } if (uv_poll_start(&watch->poll, pollEvent, &Watch::onEvent)) { diff --git a/platform/default/src/mbgl/util/string_stdlib.cpp b/platform/default/src/mbgl/util/string_stdlib.cpp index f2c554a3e9f..8eef7b373f2 100644 --- a/platform/default/src/mbgl/util/string_stdlib.cpp +++ b/platform/default/src/mbgl/util/string_stdlib.cpp @@ -3,68 +3,54 @@ #include #include -namespace mbgl { namespace platform { +namespace mbgl { +namespace platform { -std::string uppercase(const std::string& str) -{ +std::string uppercase(const std::string &str) { std::stringstream output; char const *itr = str.c_str(); char const *nitr; char const *end = itr + str.length(); - char lo[5] = { 0 }; + char lo[5] = {0}; - for (; itr < end; itr = nitr) - { + for (; itr < end; itr = nitr) { uint32_t code_point = 0; - char const* buf = nullptr; + char const *buf = nullptr; nitr = _nu_toupper(itr, end, nu_utf8_read, &code_point, &buf, nullptr); - if (buf != nullptr) - { - do - { + if (buf != nullptr) { + do { buf = NU_CASEMAP_DECODING_FUNCTION(buf, &code_point); if (code_point == 0) break; output.write(lo, nu_utf8_write(code_point, lo) - lo); - } - while (code_point != 0); - } - else - { + } while (code_point != 0); + } else { output.write(itr, nitr - itr); } } return output.str(); - } -std::string lowercase(const std::string& str) -{ +std::string lowercase(const std::string &str) { std::stringstream output; char const *itr = str.c_str(); char const *nitr; char const *end = itr + str.length(); - char lo[5] = { 0 }; + char lo[5] = {0}; - for (; itr < end; itr = nitr) - { + for (; itr < end; itr = nitr) { uint32_t code_point = 0; - char const* buf = nullptr; + char const *buf = nullptr; nitr = _nu_tolower(itr, end, nu_utf8_read, &code_point, &buf, nullptr); - if (buf != nullptr) - { - do - { + if (buf != nullptr) { + do { buf = NU_CASEMAP_DECODING_FUNCTION(buf, &code_point); if (code_point == 0) break; output.write(lo, nu_utf8_write(code_point, lo) - lo); - } - while (code_point != 0); - } - else - { + } while (code_point != 0); + } else { output.write(itr, nitr - itr); } } diff --git a/platform/default/src/mbgl/util/thread_local.cpp b/platform/default/src/mbgl/util/thread_local.cpp index 5fb66c34404..e8d9d93715a 100644 --- a/platform/default/src/mbgl/util/thread_local.cpp +++ b/platform/default/src/mbgl/util/thread_local.cpp @@ -20,8 +20,8 @@ ThreadLocalBase::ThreadLocalBase() { } ThreadLocalBase::~ThreadLocalBase() { - // ThreadLocal will not take ownership of the pointer it is managing. The pointer - // needs to be explicitly cleared before we destroy this object. + // ThreadLocal will not take ownership of the pointer it is managing. The + // pointer needs to be explicitly cleared before we destroy this object. assert(!get()); if (pthread_key_delete(reinterpret_cast(storage)) != 0) { diff --git a/platform/default/src/mbgl/util/timer.cpp b/platform/default/src/mbgl/util/timer.cpp index f59b3528428..c870ff16f5b 100644 --- a/platform/default/src/mbgl/util/timer.cpp +++ b/platform/default/src/mbgl/util/timer.cpp @@ -9,7 +9,8 @@ namespace util { class Timer::Impl { public: - Impl() : timer(new uv_timer_t) { + Impl() + : timer(new uv_timer_t) { auto* loop = reinterpret_cast(RunLoop::getLoopHandle()); if (uv_timer_init(loop, timer) != 0) { throw std::runtime_error("Failed to initialize timer."); @@ -20,12 +21,10 @@ class Timer::Impl { } ~Impl() { - uv_close(handle(), [](uv_handle_t* h) { - delete reinterpret_cast(h); - }); + uv_close(handle(), [](uv_handle_t* h) { delete reinterpret_cast(h); }); } - void start(uint64_t timeout, uint64_t repeat, std::function&& cb_) { + void start(uint64_t timeout, uint64_t repeat, std::function&& cb_) { cb = std::move(cb_); if (uv_timer_start(timer, timerCallback, timeout, repeat) != 0) { throw std::runtime_error("Failed to start timer."); @@ -40,13 +39,9 @@ class Timer::Impl { } private: - static void timerCallback(uv_timer_t* handle) { - reinterpret_cast(handle->data)->cb(); - } + static void timerCallback(uv_timer_t* handle) { reinterpret_cast(handle->data)->cb(); } - uv_handle_t* handle() { - return reinterpret_cast(timer); - } + uv_handle_t* handle() { return reinterpret_cast(timer); } uv_timer_t* timer; @@ -54,8 +49,7 @@ class Timer::Impl { }; Timer::Timer() - : impl(std::make_unique()) { -} + : impl(std::make_unique()) {} Timer::~Timer() = default; diff --git a/platform/glfw/glfw_gl_backend.cpp b/platform/glfw/glfw_gl_backend.cpp index 6af68d83d66..5a264e1ac71 100644 --- a/platform/glfw/glfw_gl_backend.cpp +++ b/platform/glfw/glfw_gl_backend.cpp @@ -7,16 +7,15 @@ class GLFWGLRenderableResource final : public mbgl::gl::RenderableResource { public: - explicit GLFWGLRenderableResource(GLFWGLBackend& backend_) : backend(backend_) {} + explicit GLFWGLRenderableResource(GLFWGLBackend& backend_) + : backend(backend_) {} void bind() override { backend.setFramebufferBinding(0); backend.setViewport(0, 0, backend.getSize()); } - void swap() override { - backend.swap(); - } + void swap() override { backend.swap(); } private: GLFWGLBackend& backend; @@ -29,7 +28,7 @@ GLFWGLBackend::GLFWGLBackend(GLFWwindow* window_, const bool capFrameRate) int fbWidth; int fbHeight; glfwGetFramebufferSize(window_, &fbWidth, &fbHeight); - return mbgl::Size{ static_cast(fbWidth), static_cast(fbHeight) }; + return mbgl::Size{static_cast(fbWidth), static_cast(fbHeight)}; }(), std::make_unique(*this)), window(window_) { @@ -77,8 +76,7 @@ namespace mbgl { namespace gfx { template <> -std::unique_ptr -Backend::Create(GLFWwindow* window, bool capFrameRate) { +std::unique_ptr Backend::Create(GLFWwindow* window, bool capFrameRate) { return std::make_unique(window, capFrameRate); } diff --git a/platform/glfw/glfw_gl_backend.hpp b/platform/glfw/glfw_gl_backend.hpp index 5971bbd0c50..cd7a2ab0180 100644 --- a/platform/glfw/glfw_gl_backend.hpp +++ b/platform/glfw/glfw_gl_backend.hpp @@ -7,9 +7,7 @@ struct GLFWwindow; -class GLFWGLBackend final : public GLFWBackend, - public mbgl::gl::RendererBackend, - public mbgl::gfx::Renderable { +class GLFWGLBackend final : public GLFWBackend, public mbgl::gl::RendererBackend, public mbgl::gfx::Renderable { public: GLFWGLBackend(GLFWwindow*, bool capFrameRate); ~GLFWGLBackend() override; @@ -18,17 +16,13 @@ class GLFWGLBackend final : public GLFWBackend, // GLFWRendererBackend implementation public: - mbgl::gfx::RendererBackend& getRendererBackend() override { - return *this; - } + mbgl::gfx::RendererBackend& getRendererBackend() override { return *this; } mbgl::Size getSize() const override; void setSize(mbgl::Size) override; // mbgl::gfx::RendererBackend implementation public: - mbgl::gfx::Renderable& getDefaultRenderable() override { - return *this; - } + mbgl::gfx::Renderable& getDefaultRenderable() override { return *this; } protected: void activate() override; diff --git a/platform/glfw/glfw_renderer_frontend.cpp b/platform/glfw/glfw_renderer_frontend.cpp index 6c7335d6a1d..0daa481e4ad 100644 --- a/platform/glfw/glfw_renderer_frontend.cpp +++ b/platform/glfw/glfw_renderer_frontend.cpp @@ -4,9 +4,9 @@ #include GLFWRendererFrontend::GLFWRendererFrontend(std::unique_ptr renderer_, GLFWView& glfwView_) - : glfwView(glfwView_) - , renderer(std::move(renderer_)) { - glfwView.setRenderFrontend(this); + : glfwView(glfwView_), + renderer(std::move(renderer_)) { + glfwView.setRenderFrontend(this); } GLFWRendererFrontend::~GLFWRendererFrontend() = default; @@ -28,15 +28,15 @@ void GLFWRendererFrontend::update(std::shared_ptr params void GLFWRendererFrontend::render() { assert(renderer); - + if (!updateParameters) return; - - mbgl::gfx::BackendScope guard { glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit }; - // onStyleImageMissing might be called during a render. The user implemented method - // could trigger a call to MLNRenderFrontend#update which overwrites `updateParameters`. - // Copy the shared pointer here so that the parameters aren't destroyed while `render(...)` is - // still using them. + mbgl::gfx::BackendScope guard{glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit}; + + // onStyleImageMissing might be called during a render. The user implemented + // method could trigger a call to MLNRenderFrontend#update which overwrites + // `updateParameters`. Copy the shared pointer here so that the parameters + // aren't destroyed while `render(...)` is still using them. auto updateParameters_ = updateParameters; renderer->render(updateParameters_); } diff --git a/platform/glfw/glfw_renderer_frontend.hpp b/platform/glfw/glfw_renderer_frontend.hpp index c992fe20fe9..08e649f6e84 100644 --- a/platform/glfw/glfw_renderer_frontend.hpp +++ b/platform/glfw/glfw_renderer_frontend.hpp @@ -13,13 +13,13 @@ class GLFWRendererFrontend : public mbgl::RendererFrontend { public: GLFWRendererFrontend(std::unique_ptr, GLFWView&); ~GLFWRendererFrontend() override; - + void reset() override; void setObserver(mbgl::RendererObserver&) override; void update(std::shared_ptr) override; void render(); - + mbgl::Renderer* getRenderer(); private: diff --git a/platform/glfw/glfw_view.cpp b/platform/glfw/glfw_view.cpp index afd5a4c5f44..7f41e9a9a3c 100644 --- a/platform/glfw/glfw_view.cpp +++ b/platform/glfw/glfw_view.cpp @@ -121,10 +121,12 @@ void addFillExtrusionLayer(mbgl::style::Style &style, bool visible) { void glfwError(int error, const char *description) { mbgl::Log::Error(mbgl::Event::OpenGL, std::string("GLFW error (") + std::to_string(error) + "): " + description); - } -GLFWView::GLFWView(bool fullscreen_, bool benchmark_, const mbgl::ResourceOptions &resourceOptions, const mbgl::ClientOptions &clientOptions) +GLFWView::GLFWView(bool fullscreen_, + bool benchmark_, + const mbgl::ResourceOptions &resourceOptions, + const mbgl::ClientOptions &clientOptions) : fullscreen(fullscreen_), benchmark(benchmark_), snapshotterObserver(std::make_unique()), @@ -199,7 +201,9 @@ GLFWView::GLFWView(bool fullscreen_, bool benchmark_, const mbgl::ResourceOption glfwMakeContextCurrent(nullptr); printf("\n"); - printf("================================================================================\n"); + printf( + "======================================================================" + "==========\n"); printf("\n"); printf("- Press `S` to cycle through bundled styles\n"); printf("- Press `X` to reset the transform\n"); @@ -210,18 +214,29 @@ GLFWView::GLFWView(bool fullscreen_, bool benchmark_, const mbgl::ResourceOption printf("- Press `Z` to cycle through north orientations\n"); printf("- Press `X` to cycle through the viewport modes\n"); printf("- Press `I` to delete existing database and re-initialize\n"); - printf("- Press `A` to cycle through Mapbox offices in the world + dateline monument\n"); + printf( + "- Press `A` to cycle through Mapbox offices in the world + dateline " + "monument\n"); printf("- Press `B` to cycle through the color, stencil, and depth buffer\n"); - printf("- Press `D` to cycle through camera bounds: inside, crossing IDL at left, crossing IDL at right, and disabled\n"); + printf( + "- Press `D` to cycle through camera bounds: inside, crossing IDL at " + "left, crossing IDL at right, and " + "disabled\n"); printf("- Press `T` to add custom geometry source\n"); printf("- Press `F` to enable feature-state demo\n"); printf("- Press `U` to toggle pitch bounds\n"); printf("- Press `H` to take a snapshot of a current map.\n"); - printf("- Press `J` to take a snapshot of a current map with an extrusions overlay.\n"); + printf( + "- Press `J` to take a snapshot of a current map with an extrusions " + "overlay.\n"); printf("- Press `Y` to start a camera fly-by demo\n"); printf("\n"); - printf("- Press `1` through `6` to add increasing numbers of point annotations for testing\n"); - printf("- Press `7` through `0` to add increasing numbers of shape annotations for testing\n"); + printf( + "- Press `1` through `6` to add increasing numbers of point " + "annotations for testing\n"); + printf( + "- Press `7` through `0` to add increasing numbers of shape " + "annotations for testing\n"); printf("\n"); printf("- Press `Q` to query annotations\n"); printf("- Press `C` to remove annotations\n"); @@ -238,7 +253,9 @@ GLFWView::GLFWView(bool fullscreen_, bool benchmark_, const mbgl::ResourceOption printf("- Press `Tab` to cycle through the map debug options\n"); printf("- Press `Esc` to quit\n"); printf("\n"); - printf("================================================================================\n"); + printf( + "======================================================================" + "==========\n"); printf("\n"); } @@ -252,7 +269,7 @@ void GLFWView::setMap(mbgl::Map *map_) { map->addAnnotationImage(makeImage("default_marker", 22, 22, 1)); } -void GLFWView::setRenderFrontend(GLFWRendererFrontend* rendererFrontend_) { +void GLFWView::setRenderFrontend(GLFWRendererFrontend *rendererFrontend_) { rendererFrontend = rendererFrontend_; } @@ -284,231 +301,262 @@ void GLFWView::onKey(GLFWwindow *window, int key, int /*scancode*/, int action, case GLFW_KEY_S: if (view->changeStyleCallback) view->changeStyleCallback(); break; - case GLFW_KEY_N: - if (!mods) - view->map->easeTo(mbgl::CameraOptions().withBearing(0.0), mbgl::AnimationOptions {{mbgl::Milliseconds(500)}}); - break; - case GLFW_KEY_Z: - view->nextOrientation(); - break; - case GLFW_KEY_Q: { - auto result = view->rendererFrontend->getRenderer()->queryPointAnnotations({ {}, { static_cast(view->getSize().width), static_cast(view->getSize().height) } }); - printf("visible point annotations: %zu\n", result.size()); - auto features = view->rendererFrontend->getRenderer()->queryRenderedFeatures( - mbgl::ScreenBox{{view->getSize().width * 0.5, view->getSize().height * 0.5}, - {view->getSize().width * 0.5 + 1.0, view->getSize().height * 0.5 + 1}}, - {}); - printf("Rendered features at the center of the screen: %zu\n", features.size()); - } break; - case GLFW_KEY_P: - view->pauseResumeCallback(); - break; - case GLFW_KEY_C: - view->clearAnnotations(); - break; - case GLFW_KEY_I: - view->resetDatabaseCallback(); - break; - case GLFW_KEY_K: - view->addRandomCustomPointAnnotations(1); - break; - case GLFW_KEY_L: - view->addRandomLineAnnotations(1); - break; - case GLFW_KEY_A: { - // XXX Fix precision loss in flyTo: - // https://github.com/mapbox/mapbox-gl-native/issues/4298 - static const std::vector places = { - mbgl::LatLng { -16.796665, -179.999983 }, // Dateline monument - mbgl::LatLng { 12.9810542, 77.6345551 }, // Mapbox Bengaluru, India - mbgl::LatLng { -13.15607,-74.21773 }, // Mapbox Peru - mbgl::LatLng { 37.77572, -122.4158818 }, // Mapbox SF, USA - mbgl::LatLng { 38.91318,-77.03255 }, // Mapbox DC, USA - }; - static size_t nextPlace = 0; - mbgl::CameraOptions cameraOptions; - cameraOptions.center = places[nextPlace++]; - cameraOptions.zoom = 20; - cameraOptions.pitch = 30; - - mbgl::AnimationOptions animationOptions(mbgl::Seconds(10)); - view->map->flyTo(cameraOptions, animationOptions); - nextPlace = nextPlace % places.size(); - } break; - case GLFW_KEY_R: { - view->show3DExtrusions = true; - view->toggle3DExtrusions(view->show3DExtrusions); - if (view->animateRouteCallback) break; - view->animateRouteCallback = [](mbgl::Map* routeMap) { - static mapbox::cheap_ruler::CheapRuler ruler { 40.7 }; // New York - static mapbox::geojson::geojson route { mapbox::geojson::parse(mbgl::platform::glfw::route) }; - const auto& geometry = route.get>(); - const auto& lineString = geometry.get>(); - - static double routeDistance = ruler.lineDistance(lineString); - static double routeProgress = 0; - routeProgress += 0.0005; - if (routeProgress > 1.0) { - routeProgress = 0.0; + case GLFW_KEY_N: + if (!mods) + view->map->easeTo(mbgl::CameraOptions().withBearing(0.0), + mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); + break; + case GLFW_KEY_Z: + view->nextOrientation(); + break; + case GLFW_KEY_Q: { + auto result = view->rendererFrontend->getRenderer()->queryPointAnnotations( + {{}, {static_cast(view->getSize().width), static_cast(view->getSize().height)}}); + printf("visible point annotations: %zu\n", result.size()); + auto features = view->rendererFrontend->getRenderer()->queryRenderedFeatures( + mbgl::ScreenBox{{view->getSize().width * 0.5, view->getSize().height * 0.5}, + {view->getSize().width * 0.5 + 1.0, view->getSize().height * 0.5 + 1}}, + {}); + printf("Rendered features at the center of the screen: %zu\n", features.size()); + } break; + case GLFW_KEY_P: + view->pauseResumeCallback(); + break; + case GLFW_KEY_C: + view->clearAnnotations(); + break; + case GLFW_KEY_I: + view->resetDatabaseCallback(); + break; + case GLFW_KEY_K: + view->addRandomCustomPointAnnotations(1); + break; + case GLFW_KEY_L: + view->addRandomLineAnnotations(1); + break; + case GLFW_KEY_A: { + // XXX Fix precision loss in flyTo: + // https://github.com/mapbox/mapbox-gl-native/issues/4298 + static const std::vector places = { + mbgl::LatLng{-16.796665, -179.999983}, // Dateline monument + mbgl::LatLng{12.9810542, 77.6345551}, // Mapbox Bengaluru, India + mbgl::LatLng{-13.15607, -74.21773}, // Mapbox Peru + mbgl::LatLng{37.77572, -122.4158818}, // Mapbox SF, USA + mbgl::LatLng{38.91318, -77.03255}, // Mapbox DC, USA + }; + static size_t nextPlace = 0; + mbgl::CameraOptions cameraOptions; + cameraOptions.center = places[nextPlace++]; + cameraOptions.zoom = 20; + cameraOptions.pitch = 30; + + mbgl::AnimationOptions animationOptions(mbgl::Seconds(10)); + view->map->flyTo(cameraOptions, animationOptions); + nextPlace = nextPlace % places.size(); + } break; + case GLFW_KEY_R: { + view->show3DExtrusions = true; + view->toggle3DExtrusions(view->show3DExtrusions); + if (view->animateRouteCallback) break; + view->animateRouteCallback = [](mbgl::Map *routeMap) { + static mapbox::cheap_ruler::CheapRuler ruler{40.7}; // New York + static mapbox::geojson::geojson route{mapbox::geojson::parse(mbgl::platform::glfw::route)}; + const auto &geometry = route.get>(); + const auto &lineString = geometry.get>(); + + static double routeDistance = ruler.lineDistance(lineString); + static double routeProgress = 0; + routeProgress += 0.0005; + if (routeProgress > 1.0) { + routeProgress = 0.0; + } + + auto camera = routeMap->getCameraOptions(); + + auto point = ruler.along(lineString, routeProgress * routeDistance); + const mbgl::LatLng center{point.y, point.x}; + auto latLng = *camera.center; + double bearing = ruler.bearing({latLng.longitude(), latLng.latitude()}, point); + double easing = bearing - *camera.bearing; + easing += easing > 180.0 ? -360.0 : easing < -180 ? 360.0 : 0; + bearing = *camera.bearing + (easing / 20); + routeMap->jumpTo( + mbgl::CameraOptions().withCenter(center).withZoom(18.0).withBearing(bearing).withPitch(60.0)); + }; + view->animateRouteCallback(view->map); + } break; + case GLFW_KEY_E: + view->toggle3DExtrusions(!view->show3DExtrusions); + break; + case GLFW_KEY_D: { + static const std::vector bounds = { + mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -170.0}, mbgl::LatLng{45.0, 170.0}), // inside + mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -200.0}, mbgl::LatLng{45.0, -160.0}), // left IDL + mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, 160.0}, mbgl::LatLng{45.0, 200.0}), // right IDL + mbgl::LatLngBounds()}; + static size_t nextBound = 0u; + static mbgl::AnnotationID boundAnnotationID = std::numeric_limits::max(); + + mbgl::LatLngBounds bound = bounds[nextBound++]; + nextBound = nextBound % bounds.size(); + + view->map->setBounds(mbgl::BoundOptions().withLatLngBounds(bound)); + + if (bound == mbgl::LatLngBounds()) { + view->map->removeAnnotation(boundAnnotationID); + boundAnnotationID = std::numeric_limits::max(); + } else { + mbgl::Polygon rect; + rect.push_back({ + mbgl::Point{bound.west(), bound.north()}, + mbgl::Point{bound.east(), bound.north()}, + mbgl::Point{bound.east(), bound.south()}, + mbgl::Point{bound.west(), bound.south()}, + }); + + auto boundAnnotation = mbgl::FillAnnotation{ + rect, 0.5f, {view->makeRandomColor()}, {view->makeRandomColor()}}; + + if (boundAnnotationID == std::numeric_limits::max()) { + boundAnnotationID = view->map->addAnnotation(boundAnnotation); + } else { + view->map->updateAnnotation(boundAnnotationID, boundAnnotation); + } + } + } break; + case GLFW_KEY_T: + view->toggleCustomSource(); + break; + case GLFW_KEY_F: { + using namespace mbgl; + using namespace mbgl::style; + using namespace mbgl::style::expression::dsl; + + auto &style = view->map->getStyle(); + if (!style.getSource("states")) { + std::string url = + "https://maplibre.org/maplibre-gl-js-docs/assets/" + "us_states.geojson"; + auto source = std::make_unique("states"); + source->setURL(url); + style.addSource(std::move(source)); + + mbgl::CameraOptions cameraOptions; + cameraOptions.center = mbgl::LatLng{42.619626, -103.523181}; + cameraOptions.zoom = 3; + cameraOptions.pitch = 0; + cameraOptions.bearing = 0; + view->map->jumpTo(cameraOptions); } - auto camera = routeMap->getCameraOptions(); - - auto point = ruler.along(lineString, routeProgress * routeDistance); - const mbgl::LatLng center { point.y, point.x }; - auto latLng = *camera.center; - double bearing = ruler.bearing({ latLng.longitude(), latLng.latitude() }, point); - double easing = bearing - *camera.bearing; - easing += easing > 180.0 ? -360.0 : easing < -180 ? 360.0 : 0; - bearing = *camera.bearing + (easing / 20); - routeMap->jumpTo(mbgl::CameraOptions().withCenter(center).withZoom(18.0).withBearing(bearing).withPitch(60.0)); - }; - view->animateRouteCallback(view->map); - } break; - case GLFW_KEY_E: - view->toggle3DExtrusions(!view->show3DExtrusions); - break; - case GLFW_KEY_D: { - static const std::vector bounds = { - mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -170.0}, mbgl::LatLng{45.0, 170.0}), // inside - mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -200.0}, mbgl::LatLng{45.0, -160.0}), // left IDL - mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, 160.0}, mbgl::LatLng{45.0, 200.0}), // right IDL - mbgl::LatLngBounds()}; - static size_t nextBound = 0u; - static mbgl::AnnotationID boundAnnotationID = std::numeric_limits::max(); - - mbgl::LatLngBounds bound = bounds[nextBound++]; - nextBound = nextBound % bounds.size(); - - view->map->setBounds(mbgl::BoundOptions().withLatLngBounds(bound)); - - if (bound == mbgl::LatLngBounds()) { - view->map->removeAnnotation(boundAnnotationID); - boundAnnotationID = std::numeric_limits::max(); - } else { - mbgl::Polygon rect; - rect.push_back({ - mbgl::Point{ bound.west(), bound.north() }, - mbgl::Point{ bound.east(), bound.north() }, - mbgl::Point{ bound.east(), bound.south() }, - mbgl::Point{ bound.west(), bound.south() }, - }); - - auto boundAnnotation = mbgl::FillAnnotation { rect, 0.5f, { view->makeRandomColor() }, { view->makeRandomColor() } }; - - if (boundAnnotationID == std::numeric_limits::max()) { - boundAnnotationID = view->map->addAnnotation(boundAnnotation); + auto layer = style.getLayer("state-fills"); + if (!layer) { + auto fillLayer = std::make_unique("state-fills", "states"); + fillLayer->setFillColor(mbgl::Color{0.0, 0.0, 1.0, 0.5}); + fillLayer->setFillOpacity(PropertyExpression( + createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 1, 0.5])"))); + style.addLayer(std::move(fillLayer)); } else { - view->map->updateAnnotation(boundAnnotationID, boundAnnotation); + layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible + ? mbgl::style::VisibilityType::None + : mbgl::style::VisibilityType::Visible); } - } - } break; - case GLFW_KEY_T: - view->toggleCustomSource(); - break; - case GLFW_KEY_F: { - using namespace mbgl; - using namespace mbgl::style; - using namespace mbgl::style::expression::dsl; - - auto &style = view->map->getStyle(); - if (!style.getSource("states")) { - std::string url = "https://maplibre.org/maplibre-gl-js-docs/assets/us_states.geojson"; - auto source = std::make_unique("states"); - source->setURL(url); - style.addSource(std::move(source)); - - mbgl::CameraOptions cameraOptions; - cameraOptions.center = mbgl::LatLng{42.619626, -103.523181}; - cameraOptions.zoom = 3; - cameraOptions.pitch = 0; - cameraOptions.bearing = 0; - view->map->jumpTo(cameraOptions); - } - - auto layer = style.getLayer("state-fills"); - if (!layer) { - auto fillLayer = std::make_unique("state-fills", "states"); - fillLayer->setFillColor(mbgl::Color{0.0, 0.0, 1.0, 0.5}); - fillLayer->setFillOpacity(PropertyExpression( - createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 1, 0.5])"))); - style.addLayer(std::move(fillLayer)); - } else { - layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible - ? mbgl::style::VisibilityType::None - : mbgl::style::VisibilityType::Visible); - } - layer = style.getLayer("state-borders"); - if (!layer) { - auto borderLayer = std::make_unique("state-borders", "states"); - borderLayer->setLineColor(mbgl::Color{0.0, 0.0, 1.0, 1.0}); - borderLayer->setLineWidth(PropertyExpression( - createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 2, 1])"))); - style.addLayer(std::move(borderLayer)); - } else { - layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible - ? mbgl::style::VisibilityType::None - : mbgl::style::VisibilityType::Visible); - } - } break; - case GLFW_KEY_F1: { - bool success = TestWriter() - .withInitialSize(mbgl::Size(view->width, view->height)) - .withStyle(view->map->getStyle()) - .withCameraOptions(view->map->getCameraOptions()) - .write(view->testDirectory); - - if (success) { - mbgl::Log::Info(mbgl::Event::General, "Render test created!"); - } else { - mbgl::Log::Error(mbgl::Event::General, - "Fail to create render test! Base directory does not exist or permission denied."); - } - } break; - case GLFW_KEY_U: { - auto bounds = view->map->getBounds(); - if (bounds.minPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MIN) && - bounds.maxPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MAX)) { - mbgl::Log::Info(mbgl::Event::General, "Limiting pitch bounds to [30, 40] degrees"); - view->map->setBounds(mbgl::BoundOptions().withMinPitch(30).withMaxPitch(40)); - } else { - mbgl::Log::Info(mbgl::Event::General, "Resetting pitch bounds to [0, 60] degrees"); - view->map->setBounds(mbgl::BoundOptions().withMinPitch(0).withMaxPitch(60)); - } - } break; - case GLFW_KEY_H: { - view->makeSnapshot(); - } break; - case GLFW_KEY_J: { - // Snapshot with overlay - view->makeSnapshot(true); - } break; - case GLFW_KEY_G: { - view->toggleLocationIndicatorLayer(); - } break; - case GLFW_KEY_Y: { - view->freeCameraDemoPhase = 0; - view->freeCameraDemoStartTime = mbgl::Clock::now(); - view->invalidate(); - } break; + layer = style.getLayer("state-borders"); + if (!layer) { + auto borderLayer = std::make_unique("state-borders", "states"); + borderLayer->setLineColor(mbgl::Color{0.0, 0.0, 1.0, 1.0}); + borderLayer->setLineWidth(PropertyExpression( + createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 2, 1])"))); + style.addLayer(std::move(borderLayer)); + } else { + layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible + ? mbgl::style::VisibilityType::None + : mbgl::style::VisibilityType::Visible); + } + } break; + case GLFW_KEY_F1: { + bool success = TestWriter() + .withInitialSize(mbgl::Size(view->width, view->height)) + .withStyle(view->map->getStyle()) + .withCameraOptions(view->map->getCameraOptions()) + .write(view->testDirectory); + + if (success) { + mbgl::Log::Info(mbgl::Event::General, "Render test created!"); + } else { + mbgl::Log::Error(mbgl::Event::General, + "Fail to create render test! Base directory does not " + "exist or permission denied."); + } + } break; + case GLFW_KEY_U: { + auto bounds = view->map->getBounds(); + if (bounds.minPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MIN) && + bounds.maxPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MAX)) { + mbgl::Log::Info(mbgl::Event::General, "Limiting pitch bounds to [30, 40] degrees"); + view->map->setBounds(mbgl::BoundOptions().withMinPitch(30).withMaxPitch(40)); + } else { + mbgl::Log::Info(mbgl::Event::General, "Resetting pitch bounds to [0, 60] degrees"); + view->map->setBounds(mbgl::BoundOptions().withMinPitch(0).withMaxPitch(60)); + } + } break; + case GLFW_KEY_H: { + view->makeSnapshot(); + } break; + case GLFW_KEY_J: { + // Snapshot with overlay + view->makeSnapshot(true); + } break; + case GLFW_KEY_G: { + view->toggleLocationIndicatorLayer(); + } break; + case GLFW_KEY_Y: { + view->freeCameraDemoPhase = 0; + view->freeCameraDemoStartTime = mbgl::Clock::now(); + view->invalidate(); + } break; } } if (action == GLFW_RELEASE || action == GLFW_REPEAT) { switch (key) { - case GLFW_KEY_W: view->popAnnotation(); break; - case GLFW_KEY_1: view->addRandomPointAnnotations(1); break; - case GLFW_KEY_2: view->addRandomPointAnnotations(10); break; - case GLFW_KEY_3: view->addRandomPointAnnotations(100); break; - case GLFW_KEY_4: view->addRandomPointAnnotations(1000); break; - case GLFW_KEY_5: view->addRandomPointAnnotations(10000); break; - case GLFW_KEY_6: view->addRandomPointAnnotations(100000); break; - case GLFW_KEY_7: view->addRandomShapeAnnotations(1); break; - case GLFW_KEY_8: view->addRandomShapeAnnotations(10); break; - case GLFW_KEY_9: view->addRandomShapeAnnotations(100); break; - case GLFW_KEY_0: view->addRandomShapeAnnotations(1000); break; - case GLFW_KEY_M: view->addAnimatedAnnotation(); break; + case GLFW_KEY_W: + view->popAnnotation(); + break; + case GLFW_KEY_1: + view->addRandomPointAnnotations(1); + break; + case GLFW_KEY_2: + view->addRandomPointAnnotations(10); + break; + case GLFW_KEY_3: + view->addRandomPointAnnotations(100); + break; + case GLFW_KEY_4: + view->addRandomPointAnnotations(1000); + break; + case GLFW_KEY_5: + view->addRandomPointAnnotations(10000); + break; + case GLFW_KEY_6: + view->addRandomPointAnnotations(100000); + break; + case GLFW_KEY_7: + view->addRandomShapeAnnotations(1); + break; + case GLFW_KEY_8: + view->addRandomShapeAnnotations(10); + break; + case GLFW_KEY_9: + view->addRandomShapeAnnotations(100); + break; + case GLFW_KEY_0: + view->addRandomShapeAnnotations(1000); + break; + case GLFW_KEY_M: + view->addAnimatedAnnotation(); + break; } } } @@ -563,18 +611,20 @@ mbgl::Color GLFWView::makeRandomColor() const { const auto r = static_cast(std::rand()) / static_cast(RAND_MAX); const auto g = static_cast(std::rand()) / static_cast(RAND_MAX); const auto b = static_cast(std::rand()) / static_cast(RAND_MAX); - return { r, g, b, 1.0f }; + return {r, g, b, 1.0f}; } mbgl::Point GLFWView::makeRandomPoint() const { const double x = width * static_cast(std::rand()) / RAND_MAX; const double y = height * static_cast(std::rand()) / RAND_MAX; - mbgl::LatLng latLng = map->latLngForPixel({ x, y }); - return { latLng.longitude(), latLng.latitude() }; + mbgl::LatLng latLng = map->latLngForPixel({x, y}); + return {latLng.longitude(), latLng.latitude()}; } -std::unique_ptr -GLFWView::makeImage(const std::string& id, int width, int height, float pixelRatio) { +std::unique_ptr GLFWView::makeImage(const std::string &id, + int width, + int height, + float pixelRatio) { const int r = static_cast(255 * (static_cast(std::rand()) / RAND_MAX)); const int g = static_cast(255 * (static_cast(std::rand()) / RAND_MAX)); const int b = static_cast(255 * (static_cast(std::rand()) / RAND_MAX)); @@ -582,8 +632,8 @@ GLFWView::makeImage(const std::string& id, int width, int height, float pixelRat const int w = static_cast(std::ceil(pixelRatio * width)); const int h = static_cast(std::ceil(pixelRatio * height)); - mbgl::PremultipliedImage image({ static_cast(w), static_cast(h) }); - auto data = reinterpret_cast(image.data.get()); + mbgl::PremultipliedImage image({static_cast(w), static_cast(h)}); + auto data = reinterpret_cast(image.data.get()); const int dist = (w / 2) * (w / 2); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { @@ -593,8 +643,7 @@ GLFWView::makeImage(const std::string& id, int width, int height, float pixelRat if (diff > 0) { const int a = std::min(0xFF, diff) * 0xFF / dist; // Premultiply the rgb values with alpha - data[w * y + x] = - (a << 24) | ((a * r / 0xFF) << 16) | ((a * g / 0xFF) << 8) | (a * b / 0xFF); + data[w * y + x] = (a << 24) | ((a * r / 0xFF) << 16) | ((a * g / 0xFF) << 8) | (a * b / 0xFF); } } } @@ -605,26 +654,34 @@ GLFWView::makeImage(const std::string& id, int width, int height, float pixelRat void GLFWView::nextOrientation() { using NO = mbgl::NorthOrientation; switch (map->getMapOptions().northOrientation()) { - case NO::Upwards: map->setNorthOrientation(NO::Rightwards); break; - case NO::Rightwards: map->setNorthOrientation(NO::Downwards); break; - case NO::Downwards: map->setNorthOrientation(NO::Leftwards); break; - default: map->setNorthOrientation(NO::Upwards); break; + case NO::Upwards: + map->setNorthOrientation(NO::Rightwards); + break; + case NO::Rightwards: + map->setNorthOrientation(NO::Downwards); + break; + case NO::Downwards: + map->setNorthOrientation(NO::Leftwards); + break; + default: + map->setNorthOrientation(NO::Upwards); + break; } } void GLFWView::addRandomCustomPointAnnotations(int count) { for (int i = 0; i < count; i++) { static int spriteID = 1; - const auto name = std::string{ "marker-" } + mbgl::util::toString(spriteID++); + const auto name = std::string{"marker-"} + mbgl::util::toString(spriteID++); map->addAnnotationImage(makeImage(name, 22, 22, 1)); spriteIDs.push_back(name); - annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation { makeRandomPoint(), name })); + annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{makeRandomPoint(), name})); } } void GLFWView::addRandomPointAnnotations(int count) { for (int i = 0; i < count; ++i) { - annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation { makeRandomPoint(), "default_marker" })); + annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{makeRandomPoint(), "default_marker"})); } } @@ -634,21 +691,22 @@ void GLFWView::addRandomLineAnnotations(int count) { for (int j = 0; j < 3; ++j) { lineString.push_back(makeRandomPoint()); } - annotationIDs.push_back(map->addAnnotation(mbgl::LineAnnotation { lineString, 1.0f, 2.0f, { makeRandomColor() } })); + annotationIDs.push_back(map->addAnnotation(mbgl::LineAnnotation{lineString, 1.0f, 2.0f, {makeRandomColor()}})); } } void GLFWView::addRandomShapeAnnotations(int count) { for (int i = 0; i < count; ++i) { mbgl::Polygon triangle; - triangle.push_back({ makeRandomPoint(), makeRandomPoint(), makeRandomPoint() }); - annotationIDs.push_back(map->addAnnotation(mbgl::FillAnnotation { triangle, 0.5f, { makeRandomColor() }, { makeRandomColor() } })); + triangle.push_back({makeRandomPoint(), makeRandomPoint(), makeRandomPoint()}); + annotationIDs.push_back( + map->addAnnotation(mbgl::FillAnnotation{triangle, 0.5f, {makeRandomColor()}, {makeRandomColor()}})); } } void GLFWView::addAnimatedAnnotation() { const double started = glfwGetTime(); - animatedAnnotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation { { 0, 0 } , "default_marker" })); + animatedAnnotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{{0, 0}, "default_marker"})); animatedAnnotationAddedTimes.push_back(started); } @@ -659,8 +717,8 @@ void GLFWView::updateAnimatedAnnotations() { const double period = 10; const double x = dt / period * 360 - 180; - const double y = std::sin(dt/ period * M_PI * 2.0) * 80; - map->updateAnnotation(animatedAnnotationIDs[i], mbgl::SymbolAnnotation { {x, y }, "default_marker" }); + const double y = std::sin(dt / period * M_PI * 2.0) * 80; + map->updateAnnotation(animatedAnnotationIDs[i], mbgl::SymbolAnnotation{{x, y}, "default_marker"}); } } @@ -684,13 +742,13 @@ void GLFWView::cycleDebugOptions() { } void GLFWView::clearAnnotations() { - for (const auto& id : annotationIDs) { + for (const auto &id : annotationIDs) { map->removeAnnotation(id); } annotationIDs.clear(); - for (const auto& id : animatedAnnotationIDs) { + for (const auto &id : animatedAnnotationIDs) { map->removeAnnotation(id); } @@ -708,8 +766,11 @@ void GLFWView::popAnnotation() { void GLFWView::makeSnapshot(bool withOverlay) { if (!snapshotter || snapshotter->getStyleURL() != map->getStyle().getURL()) { - snapshotter = std::make_unique( - map->getMapOptions().size(), map->getMapOptions().pixelRatio(), mapResourceOptions, mapClientOptions, *snapshotterObserver); + snapshotter = std::make_unique(map->getMapOptions().size(), + map->getMapOptions().pixelRatio(), + mapResourceOptions, + mapClientOptions, + *snapshotterObserver); snapshotter->setStyleURL(map->getStyle().getURL()); } @@ -722,7 +783,8 @@ void GLFWView::makeSnapshot(bool withOverlay) { const mbgl::MapSnapshotter::LatLngForFn &) { if (!ptr) { std::ostringstream oss; - oss << "Made snapshot './snapshot.png' with size w:" << image.size.width << "px h:" << image.size.height << "px"; + oss << "Made snapshot './snapshot.png' with size w:" << image.size.width << "px h:" << image.size.height + << "px"; mbgl::Log::Info(mbgl::Event::General, oss.str()); std::ofstream file("./snapshot.png"); file << mbgl::encodePNG(image); @@ -761,7 +823,7 @@ void GLFWView::onScroll(GLFWwindow *window, double /*xOffset*/, double yOffset) scale = 1.0 / scale; } - view->map->scaleBy(scale, mbgl::ScreenCoordinate { view->lastX, view->lastY }); + view->map->scaleBy(scale, mbgl::ScreenCoordinate{view->lastX, view->lastY}); #if defined(MBGL_RENDER_BACKEND_OPENGL) && !defined(MBGL_LAYER_CUSTOM_DISABLE_ALL) if (view->puck && view->puckFollowsCameraCenter) { mbgl::LatLng mapCenter = view->map->getCameraOptions().center.value(); @@ -774,25 +836,24 @@ void GLFWView::onWindowResize(GLFWwindow *window, int width, int height) { auto *view = reinterpret_cast(glfwGetWindowUserPointer(window)); view->width = width; view->height = height; - view->map->setSize({ static_cast(view->width), static_cast(view->height) }); + view->map->setSize({static_cast(view->width), static_cast(view->height)}); } void GLFWView::onFramebufferResize(GLFWwindow *window, int width, int height) { auto *view = reinterpret_cast(glfwGetWindowUserPointer(window)); - view->backend->setSize({ static_cast(width), static_cast(height) }); + view->backend->setSize({static_cast(width), static_cast(height)}); - // This is only triggered when the framebuffer is resized, but not the window. It can - // happen when you move the window between screens with a different pixel ratio. - // We are forcing a repaint my invalidating the view, which triggers a rerender with the - // new framebuffer dimensions. + // This is only triggered when the framebuffer is resized, but not the + // window. It can happen when you move the window between screens with a + // different pixel ratio. We are forcing a repaint my invalidating the view, + // which triggers a rerender with the new framebuffer dimensions. view->invalidate(); } void GLFWView::onMouseClick(GLFWwindow *window, int button, int action, int modifiers) { auto *view = reinterpret_cast(glfwGetWindowUserPointer(window)); - if (button == GLFW_MOUSE_BUTTON_RIGHT || - (button == GLFW_MOUSE_BUTTON_LEFT && modifiers & GLFW_MOD_CONTROL)) { + if (button == GLFW_MOUSE_BUTTON_RIGHT || (button == GLFW_MOUSE_BUTTON_LEFT && modifiers & GLFW_MOD_CONTROL)) { view->rotating = action == GLFW_PRESS; view->map->setGestureInProgress(view->rotating); } else if (button == GLFW_MOUSE_BUTTON_LEFT && (modifiers & GLFW_MOD_SHIFT)) { @@ -806,9 +867,13 @@ void GLFWView::onMouseClick(GLFWwindow *window, int button, int action, int modi double now = glfwGetTime(); if (now - view->lastClick < 0.4 /* ms */) { if (modifiers & GLFW_MOD_SHIFT) { - view->map->scaleBy(0.5, mbgl::ScreenCoordinate { view->lastX, view->lastY }, mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); + view->map->scaleBy(0.5, + mbgl::ScreenCoordinate{view->lastX, view->lastY}, + mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); } else { - view->map->scaleBy(2.0, mbgl::ScreenCoordinate { view->lastX, view->lastY }, mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); + view->map->scaleBy(2.0, + mbgl::ScreenCoordinate{view->lastX, view->lastY}, + mbgl::AnimationOptions{{mbgl::Milliseconds(500)}}); } } view->lastClick = now; @@ -822,10 +887,10 @@ void GLFWView::onMouseMove(GLFWwindow *window, double x, double y) { const double dx = x - view->lastX; const double dy = y - view->lastY; if (dx || dy) { - view->map->moveBy(mbgl::ScreenCoordinate { dx, dy }); + view->map->moveBy(mbgl::ScreenCoordinate{dx, dy}); } } else if (view->rotating) { - view->map->rotateBy({ view->lastX, view->lastY }, { x, y }); + view->map->rotateBy({view->lastX, view->lastY}, {x, y}); } else if (view->pitching) { const double dy = y - view->lastY; if (dy) { @@ -896,12 +961,11 @@ void GLFWView::run() { dirty = false; const double started = glfwGetTime(); - if (animateRouteCallback) - animateRouteCallback(map); + if (animateRouteCallback) animateRouteCallback(map); updateAnimatedAnnotations(); - mbgl::gfx::BackendScope scope { backend->getRendererBackend() }; + mbgl::gfx::BackendScope scope{backend->getRendererBackend()}; rendererFrontend->render(); @@ -929,7 +993,7 @@ float GLFWView::getPixelRatio() const { } mbgl::Size GLFWView::getSize() const { - return { static_cast(width), static_cast(height) }; + return {static_cast(width), static_cast(height)}; } void GLFWView::invalidate() { @@ -965,8 +1029,8 @@ void GLFWView::setShouldClose() { glfwPostEmptyEvent(); } -void GLFWView::setWindowTitle(const std::string& title) { - glfwSetWindowTitle(window, (std::string { "Mapbox GL: " } + title).c_str()); +void GLFWView::setWindowTitle(const std::string &title) { + glfwSetWindowTitle(window, (std::string{"Mapbox GL: "} + title).c_str()); } void GLFWView::onDidFinishLoadingStyle() { @@ -987,13 +1051,15 @@ void GLFWView::toggle3DExtrusions(bool visible) { void GLFWView::toggleCustomSource() { if (!map->getStyle().getSource("custom")) { mbgl::style::CustomGeometrySource::Options options; - options.cancelTileFunction = [](const mbgl::CanonicalTileID&) {}; - options.fetchTileFunction = [&](const mbgl::CanonicalTileID& tileID) { + options.cancelTileFunction = [](const mbgl::CanonicalTileID &) { + }; + options.fetchTileFunction = [&](const mbgl::CanonicalTileID &tileID) { double gridSpacing = 0.1; mbgl::FeatureCollection features; const mbgl::LatLngBounds bounds(tileID); - for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; y >= floor(bounds.south() / gridSpacing) * gridSpacing; y -= gridSpacing) { - + for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; + y >= floor(bounds.south() / gridSpacing) * gridSpacing; + y -= gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(bounds.west(), y); gridLine.emplace_back(bounds.east(), y); @@ -1001,7 +1067,9 @@ void GLFWView::toggleCustomSource() { features.emplace_back(gridLine); } - for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; x <= ceil(bounds.east() / gridSpacing) * gridSpacing; x += gridSpacing) { + for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; + x <= ceil(bounds.east() / gridSpacing) * gridSpacing; + x += gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(x, bounds.south()); gridLine.emplace_back(x, bounds.north()); @@ -1017,15 +1085,16 @@ void GLFWView::toggleCustomSource() { map->getStyle().addSource(std::make_unique("custom", options)); } - auto* layer = map->getStyle().getLayer("grid"); + auto *layer = map->getStyle().getLayer("grid"); if (!layer) { auto lineLayer = std::make_unique("grid", "custom"); - lineLayer->setLineColor(mbgl::Color{ 1.0, 0.0, 0.0, 1.0 }); + lineLayer->setLineColor(mbgl::Color{1.0, 0.0, 0.0, 1.0}); map->getStyle().addLayer(std::move(lineLayer)); } else { - layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible ? - mbgl::style::VisibilityType::None : mbgl::style::VisibilityType::Visible); + layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible + ? mbgl::style::VisibilityType::None + : mbgl::style::VisibilityType::Visible); } } @@ -1036,10 +1105,11 @@ void GLFWView::toggleLocationIndicatorLayer() { if (puck == nullptr) { auto puckLayer = std::make_unique("puck"); - puckLayer->setLocationTransition(mbgl::style::TransitionOptions( - mbgl::Duration::zero(), mbgl::Duration::zero())); // Note: This is used here for demo purpose. - // SDKs should not use this, or else the location - // will "jump" to positions. + puckLayer->setLocationTransition( + mbgl::style::TransitionOptions(mbgl::Duration::zero(), + mbgl::Duration::zero())); // Note: This is used here for demo purpose. + // SDKs should not use this, or else the location + // will "jump" to positions. puckLayer->setLocation(toArray(puckLocation)); puckLayer->setAccuracyRadius(50); puckLayer->setAccuracyRadiusColor( diff --git a/platform/glfw/glfw_view.hpp b/platform/glfw/glfw_view.hpp index c430fad6d94..40f7119409c 100644 --- a/platform/glfw/glfw_view.hpp +++ b/platform/glfw/glfw_view.hpp @@ -25,16 +25,19 @@ class RendererBackend; class GLFWView : public mbgl::MapObserver { public: - GLFWView(bool fullscreen, bool benchmark, const mbgl::ResourceOptions &resourceOptions, const mbgl::ClientOptions &clientOptions); + GLFWView(bool fullscreen, + bool benchmark, + const mbgl::ResourceOptions &resourceOptions, + const mbgl::ClientOptions &clientOptions); ~GLFWView() override; float getPixelRatio() const; - void setMap(mbgl::Map*); - - void setRenderFrontend(GLFWRendererFrontend*); + void setMap(mbgl::Map *); - mbgl::gfx::RendererBackend& getRendererBackend(); + void setRenderFrontend(GLFWRendererFrontend *); + + mbgl::gfx::RendererBackend &getRendererBackend(); void setTestDirectory(std::string dir) { testDirectory = std::move(dir); }; @@ -50,10 +53,10 @@ class GLFWView : public mbgl::MapObserver { void setShouldClose(); - void setWindowTitle(const std::string&); + void setWindowTitle(const std::string &); void run(); - + void invalidate(); mbgl::Size getSize() const; @@ -80,7 +83,10 @@ class GLFWView : public mbgl::MapObserver { mbgl::Color makeRandomColor() const; mbgl::Point makeRandomPoint() const; - static std::unique_ptr makeImage(const std::string& id, int width, int height, float pixelRatio); + static std::unique_ptr makeImage(const std::string &id, + int width, + int height, + float pixelRatio); void nextOrientation(); @@ -109,8 +115,8 @@ class GLFWView : public mbgl::MapObserver { private: void toggle3DExtrusions(bool visible); - mbgl::Map* map = nullptr; - GLFWRendererFrontend* rendererFrontend = nullptr; + mbgl::Map *map = nullptr; + GLFWRendererFrontend *rendererFrontend = nullptr; std::unique_ptr backend; std::string testDirectory = "."; @@ -141,7 +147,7 @@ class GLFWView : public mbgl::MapObserver { std::function pauseResumeCallback; std::function onlineStatusCallback; std::function resetDatabaseCallback; - std::function animateRouteCallback; + std::function animateRouteCallback; mbgl::util::RunLoop runLoop; mbgl::util::Timer frameTick; diff --git a/platform/glfw/main.cpp b/platform/glfw/main.cpp index 876486bf6c4..c5e496df97f 100644 --- a/platform/glfw/main.cpp +++ b/platform/glfw/main.cpp @@ -35,7 +35,7 @@ void quit_handler(int) { } } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { args::ArgumentParser argumentParser("Mapbox GL GLFW example"); args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {'h', "help"}); @@ -112,22 +112,27 @@ int main(int argc, char *argv[]) { GLFWView backend(fullscreen, benchmark, resourceOptions, clientOptions); view = &backend; - std::shared_ptr onlineFileSource = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Network, resourceOptions, clientOptions); + std::shared_ptr onlineFileSource = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::Network, resourceOptions, clientOptions); if (!settings.online) { if (onlineFileSource) { onlineFileSource->setProperty("online-status", false); mbgl::Log::Warning(mbgl::Event::Setup, "Application is offline. Press `O` to toggle online status."); } else { mbgl::Log::Warning(mbgl::Event::Setup, - "Network resource provider is not available, only local requests are supported."); + "Network resource provider is not available, only local " + "requests are supported."); } } - GLFWRendererFrontend rendererFrontend { std::make_unique(view->getRendererBackend(), view->getPixelRatio()), *view }; + GLFWRendererFrontend rendererFrontend{ + std::make_unique(view->getRendererBackend(), view->getPixelRatio()), *view}; - mbgl::Map map(rendererFrontend, *view, - mbgl::MapOptions().withSize(view->getSize()).withPixelRatio(view->getPixelRatio()), resourceOptions, clientOptions); + mbgl::Map map(rendererFrontend, + *view, + mbgl::MapOptions().withSize(view->getSize()).withPixelRatio(view->getPixelRatio()), + resourceOptions, + clientOptions); backend.setMap(&map); @@ -136,7 +141,7 @@ int main(int argc, char *argv[]) { } map.jumpTo(mbgl::CameraOptions() - .withCenter(mbgl::LatLng {settings.latitude, settings.longitude}) + .withCenter(mbgl::LatLng{settings.latitude, settings.longitude}) .withZoom(settings.zoom) .withBearing(settings.bearing) .withPitch(settings.pitch)); @@ -147,15 +152,18 @@ int main(int argc, char *argv[]) { view->setOnlineStatusCallback([&settings, onlineFileSource]() { if (!onlineFileSource) { mbgl::Log::Warning(mbgl::Event::Setup, - "Cannot change online status. Network resource provider is not available."); + "Cannot change online status. Network resource provider is not " + "available."); return; } settings.online = !settings.online; onlineFileSource->setProperty("online-status", settings.online); - mbgl::Log::Info(mbgl::Event::Setup, std::string("Application is ") + (settings.online ? "online" : "offline") + ". Press `O` to toggle online status."); + mbgl::Log::Info(mbgl::Event::Setup, + std::string("Application is ") + (settings.online ? "online" : "offline") + + ". Press `O` to toggle online status."); }); - view->setChangeStyleCallback([&map,&orderedStyles] () { + view->setChangeStyleCallback([&map, &orderedStyles]() { static uint8_t currentStyleIndex; if (++currentStyleIndex == orderedStyles.size()) { @@ -169,9 +177,10 @@ int main(int argc, char *argv[]) { mbgl::Log::Info(mbgl::Event::Setup, "Changed style to: " + newStyle.getName()); }); - // Resource loader controls top-level request processing and can resume / pause all managed sources simultaneously. - std::shared_ptr resourceLoader = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions); + // Resource loader controls top-level request processing and can resume / + // pause all managed sources simultaneously. + std::shared_ptr resourceLoader = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions); view->setPauseResumeCallback([resourceLoader]() { static bool isPaused = false; @@ -197,7 +206,7 @@ int main(int argc, char *argv[]) { // Load style if (style.empty()) { - const char *url = getenv("MAPBOX_STYLE_URL"); + const char* url = getenv("MAPBOX_STYLE_URL"); if (url == nullptr) { mbgl::util::DefaultStyle newStyle = orderedStyles[0]; style = newStyle.getUrl(); @@ -222,10 +231,9 @@ int main(int argc, char *argv[]) { settings.debug = mbgl::EnumType(map.getDebug()); settings.save(); mbgl::Log::Info(mbgl::Event::General, - "Exit location: --lat=\"" + std::to_string(settings.latitude) + - "\" --lon=\"" + std::to_string(settings.longitude) + - "\" --zoom=\"" + std::to_string(settings.zoom) + - "\" --bearing=\"" + std::to_string(settings.bearing) + "\""); + "Exit location: --lat=\"" + std::to_string(settings.latitude) + "\" --lon=\"" + + std::to_string(settings.longitude) + "\" --zoom=\"" + std::to_string(settings.zoom) + + "\" --bearing=\"" + std::to_string(settings.bearing) + "\""); view = nullptr; diff --git a/platform/glfw/settings_json.cpp b/platform/glfw/settings_json.cpp index 5b6aa4e0da1..1355e16f2c2 100644 --- a/platform/glfw/settings_json.cpp +++ b/platform/glfw/settings_json.cpp @@ -3,7 +3,9 @@ namespace mbgl { -Settings_JSON::Settings_JSON() { load(); } +Settings_JSON::Settings_JSON() { + load(); +} void Settings_JSON::load() { std::ifstream file("/tmp/mbgl-native.cfg"); diff --git a/platform/glfw/test_writer.cpp b/platform/glfw/test_writer.cpp index 4fcb79a8121..82dc8d0164d 100644 --- a/platform/glfw/test_writer.cpp +++ b/platform/glfw/test_writer.cpp @@ -20,7 +20,8 @@ class TestOperationSerializer { class SetCamera final : public TestOperationSerializer { public: - explicit SetCamera(mbgl::CameraOptions camera_) : camera(std::move(camera_)) {} + explicit SetCamera(mbgl::CameraOptions camera_) + : camera(std::move(camera_)) {} void serialize(Writer& writer) const override { if (camera.zoom) { @@ -59,7 +60,8 @@ class SetCamera final : public TestOperationSerializer { class SetStyle final : public TestOperationSerializer { public: - explicit SetStyle(const mbgl::style::Style& style) : url(style.getURL()) {} + explicit SetStyle(const mbgl::style::Style& style) + : url(style.getURL()) {} void serialize(Writer& writer) const override { writer.StartArray(); @@ -74,7 +76,9 @@ class SetStyle final : public TestOperationSerializer { class SetInitialSize final : public TestOperationSerializer { public: - explicit SetInitialSize(const mbgl::Size& size) : width(size.width), height(size.height) {} + explicit SetInitialSize(const mbgl::Size& size) + : width(size.width), + height(size.height) {} void serialize(Writer& writer) const override { writer.Key("width"); diff --git a/platform/linux/src/gl_functions.cpp b/platform/linux/src/gl_functions.cpp index f13626f3db7..3fcc0ae47b5 100644 --- a/platform/linux/src/gl_functions.cpp +++ b/platform/linux/src/gl_functions.cpp @@ -10,255 +10,274 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = ::glActiveTexture; -void (* const glAttachShader)(GLuint, GLuint) = ::glAttachShader; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = ::glBindAttribLocation; -void (* const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; -void (* const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; -void (* const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; -void (* const glBindTexture)(GLenum, GLuint) = ::glBindTexture; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; -void (* const glBlendEquation)(GLenum) = ::glBlendEquation; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; -void (* const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = ::glBufferData; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = ::glBufferSubData; -GLenum (* const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; -void (* const glClear)(GLbitfield) = ::glClear; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; -void (* const glClearDepthf)(GLfloat) = ::glClearDepthf; -void (* const glClearStencil)(GLint) = ::glClearStencil; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; -void (* const glCompileShader)(GLuint) = ::glCompileShader; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = ::glCompressedTexImage2D; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = ::glCompressedTexSubImage2D; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; -GLuint (* const glCreateProgram)() = ::glCreateProgram; -GLuint (* const glCreateShader)(GLenum) = ::glCreateShader; -void (* const glCullFace)(GLenum) = ::glCullFace; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = ::glDeleteBuffers; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = ::glDeleteFramebuffers; -void (* const glDeleteProgram)(GLuint) = ::glDeleteProgram; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = ::glDeleteRenderbuffers; -void (* const glDeleteShader)(GLuint) = ::glDeleteShader; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = ::glDeleteTextures; -void (* const glDepthFunc)(GLenum) = ::glDepthFunc; -void (* const glDepthMask)(GLboolean) = ::glDepthMask; -void (* const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; -void (* const glDetachShader)(GLuint, GLuint) = ::glDetachShader; -void (* const glDisable)(GLenum) = ::glDisable; -void (* const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = ::glDrawElements; -void (* const glEnable)(GLenum) = ::glEnable; -void (* const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; -void (* const glFinish)() = ::glFinish; -void (* const glFlush)() = ::glFlush; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; -void (* const glFrontFace)(GLenum) = ::glFrontFace; -void (* const glGenBuffers)(GLsizei, GLuint *) = ::glGenBuffers; -void (* const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = ::glGenFramebuffers; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = ::glGenRenderbuffers; -void (* const glGenTextures)(GLsizei, GLuint *) = ::glGenTextures; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveAttrib; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveUniform; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = ::glGetAttachedShaders; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = ::glGetAttribLocation; -void (* const glGetBooleanv)(GLenum, GLboolean *) = ::glGetBooleanv; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetBufferParameteriv; -GLenum (* const glGetError)() = ::glGetError; -void (* const glGetFloatv)(GLenum, GLfloat *) = ::glGetFloatv; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = ::glGetFramebufferAttachmentParameteriv; -void (* const glGetIntegerv)(GLenum, GLint *) = ::glGetIntegerv; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetProgramInfoLog; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = ::glGetProgramiv; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetRenderbufferParameteriv; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderInfoLog; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = ::glGetShaderiv; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = ::glGetShaderPrecisionFormat; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderSource; -const GLubyte *(* const glGetString)(GLenum) = ::glGetString; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = ::glGetTexParameterfv; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = ::glGetTexParameteriv; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = ::glGetUniformfv; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = ::glGetUniformiv; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = ::glGetUniformLocation; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = ::glGetVertexAttribfv; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribiv; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = ::glGetVertexAttribPointerv; -void (* const glHint)(GLenum, GLenum) = ::glHint; -GLboolean (* const glIsBuffer)(GLuint) = ::glIsBuffer; -GLboolean (* const glIsEnabled)(GLenum) = ::glIsEnabled; -GLboolean (* const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; -GLboolean (* const glIsProgram)(GLuint) = ::glIsProgram; -GLboolean (* const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; -GLboolean (* const glIsShader)(GLuint) = ::glIsShader; -GLboolean (* const glIsTexture)(GLuint) = ::glIsTexture; -void (* const glLineWidth)(GLfloat) = ::glLineWidth; -void (* const glLinkProgram)(GLuint) = ::glLinkProgram; -void (* const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; -void (* const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = ::glReadPixels; -void (* const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; -void (* const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = ::glShaderBinary; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = ::glShaderSource; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; -void (* const glStencilMask)(GLuint) = ::glStencilMask; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = ::glTexImage2D; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = ::glTexParameterfv; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = ::glTexParameteriv; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = ::glTexSubImage2D; -void (* const glUniform1f)(GLint, GLfloat) = ::glUniform1f; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = ::glUniform1fv; -void (* const glUniform1i)(GLint, GLint) = ::glUniform1i; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = ::glUniform1iv; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = ::glUniform2fv; -void (* const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = ::glUniform2iv; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = ::glUniform3fv; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = ::glUniform3iv; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = ::glUniform4fv; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = ::glUniform4iv; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2fv; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3fv; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4fv; -void (* const glUseProgram)(GLuint) = ::glUseProgram; -void (* const glValidateProgram)(GLuint) = ::glValidateProgram; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = ::glVertexAttrib1fv; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = ::glVertexAttrib2fv; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = ::glVertexAttrib3fv; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = ::glVertexAttrib4fv; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = ::glVertexAttribPointer; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; +void (*const glActiveTexture)(GLenum) = ::glActiveTexture; +void (*const glAttachShader)(GLuint, GLuint) = ::glAttachShader; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = ::glBindAttribLocation; +void (*const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; +void (*const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; +void (*const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; +void (*const glBindTexture)(GLenum, GLuint) = ::glBindTexture; +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; +void (*const glBlendEquation)(GLenum) = ::glBlendEquation; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; +void (*const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = ::glBufferData; +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = ::glBufferSubData; +GLenum (*const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; +void (*const glClear)(GLbitfield) = ::glClear; +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; +void (*const glClearDepthf)(GLfloat) = ::glClearDepthf; +void (*const glClearStencil)(GLint) = ::glClearStencil; +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; +void (*const glCompileShader)(GLuint) = ::glCompileShader; +void (*const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = + ::glCompressedTexImage2D; +void (*const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = + ::glCompressedTexSubImage2D; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; +GLuint (*const glCreateProgram)() = ::glCreateProgram; +GLuint (*const glCreateShader)(GLenum) = ::glCreateShader; +void (*const glCullFace)(GLenum) = ::glCullFace; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = ::glDeleteBuffers; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = ::glDeleteFramebuffers; +void (*const glDeleteProgram)(GLuint) = ::glDeleteProgram; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = ::glDeleteRenderbuffers; +void (*const glDeleteShader)(GLuint) = ::glDeleteShader; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = ::glDeleteTextures; +void (*const glDepthFunc)(GLenum) = ::glDepthFunc; +void (*const glDepthMask)(GLboolean) = ::glDepthMask; +void (*const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; +void (*const glDetachShader)(GLuint, GLuint) = ::glDetachShader; +void (*const glDisable)(GLenum) = ::glDisable; +void (*const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = ::glDrawElements; +void (*const glEnable)(GLenum) = ::glEnable; +void (*const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; +void (*const glFinish)() = ::glFinish; +void (*const glFlush)() = ::glFlush; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; +void (*const glFrontFace)(GLenum) = ::glFrontFace; +void (*const glGenBuffers)(GLsizei, GLuint*) = ::glGenBuffers; +void (*const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = ::glGenFramebuffers; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = ::glGenRenderbuffers; +void (*const glGenTextures)(GLsizei, GLuint*) = ::glGenTextures; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveAttrib; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveUniform; +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = ::glGetAttachedShaders; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = ::glGetAttribLocation; +void (*const glGetBooleanv)(GLenum, GLboolean*) = ::glGetBooleanv; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetBufferParameteriv; +GLenum (*const glGetError)() = ::glGetError; +void (*const glGetFloatv)(GLenum, GLfloat*) = ::glGetFloatv; +void (*const glGetFramebufferAttachmentParameteriv)(GLenum, + GLenum, + GLenum, + GLint*) = ::glGetFramebufferAttachmentParameteriv; +void (*const glGetIntegerv)(GLenum, GLint*) = ::glGetIntegerv; +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetProgramInfoLog; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = ::glGetProgramiv; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetRenderbufferParameteriv; +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderInfoLog; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = ::glGetShaderiv; +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = ::glGetShaderPrecisionFormat; +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderSource; +const GLubyte* (*const glGetString)(GLenum) = ::glGetString; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = ::glGetTexParameterfv; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = ::glGetTexParameteriv; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = ::glGetUniformfv; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = ::glGetUniformiv; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = ::glGetUniformLocation; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = ::glGetVertexAttribfv; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribiv; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = ::glGetVertexAttribPointerv; +void (*const glHint)(GLenum, GLenum) = ::glHint; +GLboolean (*const glIsBuffer)(GLuint) = ::glIsBuffer; +GLboolean (*const glIsEnabled)(GLenum) = ::glIsEnabled; +GLboolean (*const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; +GLboolean (*const glIsProgram)(GLuint) = ::glIsProgram; +GLboolean (*const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; +GLboolean (*const glIsShader)(GLuint) = ::glIsShader; +GLboolean (*const glIsTexture)(GLuint) = ::glIsTexture; +void (*const glLineWidth)(GLfloat) = ::glLineWidth; +void (*const glLinkProgram)(GLuint) = ::glLinkProgram; +void (*const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; +void (*const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = ::glReadPixels; +void (*const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; +void (*const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = ::glShaderBinary; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = ::glShaderSource; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; +void (*const glStencilMask)(GLuint) = ::glStencilMask; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = ::glTexImage2D; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = ::glTexParameterfv; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = ::glTexParameteriv; +void (*const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = + ::glTexSubImage2D; +void (*const glUniform1f)(GLint, GLfloat) = ::glUniform1f; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = ::glUniform1fv; +void (*const glUniform1i)(GLint, GLint) = ::glUniform1i; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = ::glUniform1iv; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = ::glUniform2fv; +void (*const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = ::glUniform2iv; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = ::glUniform3fv; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = ::glUniform3iv; +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = ::glUniform4fv; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = ::glUniform4iv; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2fv; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3fv; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4fv; +void (*const glUseProgram)(GLuint) = ::glUseProgram; +void (*const glValidateProgram)(GLuint) = ::glValidateProgram; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = ::glVertexAttrib1fv; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = ::glVertexAttrib2fv; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = ::glVertexAttrib3fv; +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = ::glVertexAttrib4fv; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = ::glVertexAttribPointer; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = ::glReadBuffer; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *) = ::glDrawRangeElements; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *) = ::glTexImage3D; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *) = ::glTexSubImage3D; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *) = ::glCompressedTexImage3D; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *) = ::glCompressedTexSubImage3D; -void (* const glGenQueries)(GLsizei, GLuint *) = ::glGenQueries; -void (* const glDeleteQueries)(GLsizei, const GLuint *) = ::glDeleteQueries; -GLboolean (* const glIsQuery)(GLuint) = ::glIsQuery; -void (* const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; -void (* const glEndQuery)(GLenum) = ::glEndQuery; -void (* const glGetQueryiv)(GLenum, GLenum, GLint *) = ::glGetQueryiv; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *) = ::glGetQueryObjectuiv; -GLboolean (* const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **) = ::glGetBufferPointerv; -void (* const glDrawBuffers)(GLsizei, const GLenum *) = ::glDrawBuffers; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x3fv; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x2fv; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x4fv; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x2fv; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x4fv; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x3fv; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; -void (* const glBindVertexArray)(GLuint) = ::glBindVertexArray; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint *) = ::glDeleteVertexArrays; -void (* const glGenVertexArrays)(GLsizei, GLuint *) = ::glGenVertexArrays; -GLboolean (* const glIsVertexArray)(GLuint) = ::glIsVertexArray; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *) = ::glGetIntegeri_v; -void (* const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; -void (* const glEndTransformFeedback)() = ::glEndTransformFeedback; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum) = ::glTransformFeedbackVaryings; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *) = ::glGetTransformFeedbackVarying; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *) = ::glVertexAttribIPointer; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribIiv; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *) = ::glGetVertexAttribIuiv; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; -void (* const glVertexAttribI4iv)(GLuint, const GLint *) = ::glVertexAttribI4iv; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint *) = ::glVertexAttribI4uiv; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint *) = ::glGetUniformuiv; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar *) = ::glGetFragDataLocation; -void (* const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *) = ::glUniform1uiv; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *) = ::glUniform2uiv; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *) = ::glUniform3uiv; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *) = ::glUniform4uiv; -void (* const glClearBufferiv)(GLenum, GLint, const GLint *) = ::glClearBufferiv; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *) = ::glClearBufferuiv; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *) = ::glClearBufferfv; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = ::glGetStringi; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *) = ::glGetUniformIndices; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *) = ::glGetActiveUniformsiv; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *) = ::glGetUniformBlockIndex; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *) = ::glGetActiveUniformBlockiv; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetActiveUniformBlockName; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei) = ::glDrawElementsInstanced; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; -GLboolean (* const glIsSync)(GLsync) = ::glIsSync; -void (* const glDeleteSync)(GLsync) = ::glDeleteSync; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; -void (* const glGetInteger64v)(GLenum, GLint64 *) = ::glGetInteger64v; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *) = ::glGetSynciv; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *) = ::glGetInteger64i_v; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *) = ::glGetBufferParameteri64v; -void (* const glGenSamplers)(GLsizei, GLuint *) = ::glGenSamplers; -void (* const glDeleteSamplers)(GLsizei, const GLuint *) = ::glDeleteSamplers; -GLboolean (* const glIsSampler)(GLuint) = ::glIsSampler; -void (* const glBindSampler)(GLuint, GLuint) = ::glBindSampler; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *) = ::glSamplerParameteriv; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *) = ::glSamplerParameterfv; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *) = ::glGetSamplerParameteriv; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *) = ::glGetSamplerParameterfv; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; -void (* const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *) = ::glDeleteTransformFeedbacks; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint *) = ::glGenTransformFeedbacks; -GLboolean (* const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; -void (* const glPauseTransformFeedback)() = ::glPauseTransformFeedback; -void (* const glResumeTransformFeedback)() = ::glResumeTransformFeedback; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *) = ::glGetProgramBinary; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei) = ::glProgramBinary; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *) = ::glInvalidateFramebuffer; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *) = ::glGetInternalformativ; +void (*const glReadBuffer)(GLenum) = ::glReadBuffer; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = ::glDrawRangeElements; +void (*const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = + ::glTexImage3D; +void (*const glTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = ::glTexSubImage3D; +void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = + ::glCopyTexSubImage3D; +void (*const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = + ::glCompressedTexImage3D; +void (*const glCompressedTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = + ::glCompressedTexSubImage3D; +void (*const glGenQueries)(GLsizei, GLuint*) = ::glGenQueries; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = ::glDeleteQueries; +GLboolean (*const glIsQuery)(GLuint) = ::glIsQuery; +void (*const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; +void (*const glEndQuery)(GLenum) = ::glEndQuery; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = ::glGetQueryiv; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = ::glGetQueryObjectuiv; +GLboolean (*const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = ::glGetBufferPointerv; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = ::glDrawBuffers; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x3fv; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x2fv; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x4fv; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x2fv; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x4fv; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x3fv; +void (*const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = + ::glBlitFramebuffer; +void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = + ::glRenderbufferStorageMultisample; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; +void (*const glBindVertexArray)(GLuint) = ::glBindVertexArray; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = ::glDeleteVertexArrays; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = ::glGenVertexArrays; +GLboolean (*const glIsVertexArray)(GLuint) = ::glIsVertexArray; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = ::glGetIntegeri_v; +void (*const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; +void (*const glEndTransformFeedback)() = ::glEndTransformFeedback; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; +void (*const glTransformFeedbackVaryings)(GLuint, + GLsizei, + const GLchar* const*, + GLenum) = ::glTransformFeedbackVaryings; +void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = + ::glGetTransformFeedbackVarying; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = ::glVertexAttribIPointer; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribIiv; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = ::glGetVertexAttribIuiv; +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = ::glVertexAttribI4iv; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = ::glVertexAttribI4uiv; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = ::glGetUniformuiv; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = ::glGetFragDataLocation; +void (*const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = ::glUniform1uiv; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = ::glUniform2uiv; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = ::glUniform3uiv; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = ::glUniform4uiv; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = ::glClearBufferiv; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = ::glClearBufferuiv; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = ::glClearBufferfv; +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = ::glGetStringi; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = ::glGetUniformIndices; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = ::glGetActiveUniformsiv; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = ::glGetUniformBlockIndex; +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = ::glGetActiveUniformBlockiv; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetActiveUniformBlockName; +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = ::glDrawElementsInstanced; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; +GLboolean (*const glIsSync)(GLsync) = ::glIsSync; +void (*const glDeleteSync)(GLsync) = ::glDeleteSync; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; +void (*const glGetInteger64v)(GLenum, GLint64*) = ::glGetInteger64v; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = ::glGetSynciv; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = ::glGetInteger64i_v; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = ::glGetBufferParameteri64v; +void (*const glGenSamplers)(GLsizei, GLuint*) = ::glGenSamplers; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = ::glDeleteSamplers; +GLboolean (*const glIsSampler)(GLuint) = ::glIsSampler; +void (*const glBindSampler)(GLuint, GLuint) = ::glBindSampler; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = ::glSamplerParameteriv; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = ::glSamplerParameterfv; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = ::glGetSamplerParameteriv; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = ::glGetSamplerParameterfv; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; +void (*const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = ::glDeleteTransformFeedbacks; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = ::glGenTransformFeedbacks; +GLboolean (*const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; +void (*const glPauseTransformFeedback)() = ::glPauseTransformFeedback; +void (*const glResumeTransformFeedback)() = ::glResumeTransformFeedback; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = ::glGetProgramBinary; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = ::glProgramBinary; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = ::glInvalidateFramebuffer; +void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = + ::glInvalidateSubFramebuffer; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = ::glGetInternalformativ; -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl diff --git a/platform/linux/src/headless_backend_egl.cpp b/platform/linux/src/headless_backend_egl.cpp index 31c64b415ea..5d412b08bcf 100644 --- a/platform/linux/src/headless_backend_egl.cpp +++ b/platform/linux/src/headless_backend_egl.cpp @@ -11,12 +11,14 @@ namespace mbgl { namespace gl { -// This class provides a singleton that contains information about the configuration used for -// instantiating new headless rendering contexts. +// This class provides a singleton that contains information about the +// configuration used for instantiating new headless rendering contexts. class EGLDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; public: EGLDisplayConfig(Key) { @@ -31,27 +33,22 @@ class EGLDisplayConfig { } if (!eglBindAPI(EGL_OPENGL_ES_API)) { - mbgl::Log::Error(mbgl::Event::OpenGL, "eglBindAPI(EGL_OPENGL_ES_API) returned error " + - std::to_string(eglGetError())); + mbgl::Log::Error(mbgl::Event::OpenGL, + "eglBindAPI(EGL_OPENGL_ES_API) returned error " + std::to_string(eglGetError())); throw std::runtime_error("eglBindAPI() failed"); } - const EGLint attribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_NONE - }; + const EGLint attribs[] = {EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE}; - // Note: we're choosing an arbitrary pixel format, since we're not using the default surface - // anyway; all rendering will be directed to framebuffers which have their own configuration. + // Note: we're choosing an arbitrary pixel format, since we're not using + // the default surface anyway; all rendering will be directed to + // framebuffers which have their own configuration. if (!eglChooseConfig(display, attribs, &config, 1, &numConfigs) || numConfigs != 1) { throw std::runtime_error("Failed to choose ARGB config.\n"); } } - ~EGLDisplayConfig() { - eglTerminate(display); - } + ~EGLDisplayConfig() { eglTerminate(display); } static std::shared_ptr create() { static std::weak_ptr instance; @@ -70,14 +67,11 @@ class EGLDisplayConfig { class EGLBackendImpl final : public HeadlessBackend::Impl { public: EGLBackendImpl() { - // EGL initializes the context client version to 1 by default. We want to - // use OpenGL ES 2.0 which has the ability to create shader and program - // objects and also to write vertex and fragment shaders in the OpenGL ES - // Shading Language. - const EGLint attribs[] = { - EGL_CONTEXT_CLIENT_VERSION, 3, - EGL_NONE - }; + // EGL initializes the context client version to 1 by default. We want + // to use OpenGL ES 2.0 which has the ability to create shader and + // program objects and also to write vertex and fragment shaders in the + // OpenGL ES Shading Language. + const EGLint attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE}; eglContext = eglCreateContext(eglDisplay->display, eglDisplay->config, EGL_NO_CONTEXT, attribs); if (eglContext == EGL_NO_CONTEXT) { @@ -88,16 +82,11 @@ class EGLBackendImpl final : public HeadlessBackend::Impl { throw std::runtime_error("Error creating the EGL context object.\n"); } - // Create a dummy pbuffer. We will render to framebuffers anyway, but we need a pbuffer to - // activate the context. - // Note that to be able to create pbuffer surfaces, we need to choose a config that - // includes EGL_SURFACE_TYPE, EGL_PBUFFER_BIT in HeadlessDisplay. - const EGLint surfAttribs[] = { - EGL_WIDTH, 8, - EGL_HEIGHT, 8, - EGL_LARGEST_PBUFFER, EGL_TRUE, - EGL_NONE - }; + // Create a dummy pbuffer. We will render to framebuffers anyway, but we + // need a pbuffer to activate the context. Note that to be able to + // create pbuffer surfaces, we need to choose a config that includes + // EGL_SURFACE_TYPE, EGL_PBUFFER_BIT in HeadlessDisplay. + const EGLint surfAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_LARGEST_PBUFFER, EGL_TRUE, EGL_NONE}; eglSurface = eglCreatePbufferSurface(eglDisplay->display, eglDisplay->config, surfAttribs); if (eglSurface == EGL_NO_SURFACE) { @@ -117,9 +106,7 @@ class EGLBackendImpl final : public HeadlessBackend::Impl { } } - gl::ProcAddress getExtensionFunctionPointer(const char* name) final { - return eglGetProcAddress(name); - } + gl::ProcAddress getExtensionFunctionPointer(const char* name) final { return eglGetProcAddress(name); } void activateContext() final { if (!eglMakeCurrent(eglDisplay->display, eglSurface, eglSurface, eglContext)) { diff --git a/platform/linux/src/headless_backend_glx.cpp b/platform/linux/src/headless_backend_glx.cpp index 4bb503a8a71..8e6e0f8cbb8 100644 --- a/platform/linux/src/headless_backend_glx.cpp +++ b/platform/linux/src/headless_backend_glx.cpp @@ -9,12 +9,14 @@ namespace mbgl { namespace gl { -// This class provides a singleton that contains information about the configuration used for -// instantiating new headless rendering contexts. +// This class provides a singleton that contains information about the +// configuration used for instantiating new headless rendering contexts. class GLXDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; public: explicit GLXDisplayConfig(Key) { @@ -40,7 +42,7 @@ class GLXDisplayConfig { } // We're creating a dummy pbuffer anyway that we're not using. - static int pixelFormat[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, None }; + static int pixelFormat[] = {GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, None}; int configs = 0; fbConfigs = glXChooseFBConfig(xDisplay, DefaultScreen(xDisplay), pixelFormat, &configs); @@ -75,8 +77,7 @@ class GLXBackendImpl final : public HeadlessBackend::Impl { public: GLXBackendImpl() { // Try to create a legacy context. - glContext = glXCreateNewContext(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], - GLX_RGBA_TYPE, None, True); + glContext = glXCreateNewContext(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], GLX_RGBA_TYPE, None, True); if (glContext && !glXIsDirect(glxDisplay->xDisplay, glContext)) { Log::Error(Event::OpenGL, "failed to create direct OpenGL Legacy context"); glXDestroyContext(glxDisplay->xDisplay, glContext); @@ -86,11 +87,10 @@ class GLXBackendImpl final : public HeadlessBackend::Impl { throw std::runtime_error("Error creating GL context object."); } - // Create a dummy pbuffer. We will render to framebuffers anyway, but we need a pbuffer to - // activate the context. - int pbufferAttributes[] = { GLX_PBUFFER_WIDTH, 8, GLX_PBUFFER_HEIGHT, 8, None }; - glxPbuffer = - glXCreatePbuffer(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], pbufferAttributes); + // Create a dummy pbuffer. We will render to framebuffers anyway, but we + // need a pbuffer to activate the context. + int pbufferAttributes[] = {GLX_PBUFFER_WIDTH, 8, GLX_PBUFFER_HEIGHT, 8, None}; + glxPbuffer = glXCreatePbuffer(glxDisplay->xDisplay, glxDisplay->fbConfigs[0], pbufferAttributes); } ~GLXBackendImpl() final { diff --git a/platform/node/src/node_conversion.hpp b/platform/node/src/node_conversion.hpp index 64da82d203f..267b5baec00 100644 --- a/platform/node/src/node_conversion.hpp +++ b/platform/node/src/node_conversion.hpp @@ -46,12 +46,13 @@ class ConversionTraits> { return value->IsObject() && !value->IsArray(); } - static std::optional> objectMember(const v8::Local& value, const char * name) { + static std::optional> objectMember(const v8::Local& value, const char* name) { Nan::EscapableHandleScope scope; if (!Nan::Has(Nan::To(value).ToLocalChecked(), Nan::New(name).ToLocalChecked()).FromJust()) { return {}; } - Nan::MaybeLocal result = Nan::Get(Nan::To(value).ToLocalChecked(), Nan::New(name).ToLocalChecked()); + Nan::MaybeLocal result = Nan::Get(Nan::To(value).ToLocalChecked(), + Nan::New(name).ToLocalChecked()); if (result.IsEmpty()) { return {}; } @@ -61,11 +62,13 @@ class ConversionTraits> { template static std::optional eachMember(const v8::Local& value, Fn&& fn) { Nan::HandleScope scope; - v8::Local names = Nan::GetOwnPropertyNames(Nan::To(value).ToLocalChecked()).ToLocalChecked(); + v8::Local names = + Nan::GetOwnPropertyNames(Nan::To(value).ToLocalChecked()).ToLocalChecked(); for (uint32_t i = 0; i < names->Length(); ++i) { v8::Local k = Nan::Get(names, i).ToLocalChecked(); v8::Local v = Nan::Get(Nan::To(value).ToLocalChecked(), k).ToLocalChecked(); - std::optional result = fn(*Nan::Utf8String(k), std::move(v)); // NOLINT(performance-move-const-arg) + std::optional result = fn(*Nan::Utf8String(k), + std::move(v)); // NOLINT(performance-move-const-arg) if (result) { return result; } @@ -107,17 +110,17 @@ class ConversionTraits> { static std::optional toValue(const v8::Local& value) { if (value->IsFalse()) { - return { false }; + return {false}; } else if (value->IsTrue()) { - return { true }; + return {true}; } else if (value->IsString()) { - return { std::string(*Nan::Utf8String(value)) }; + return {std::string(*Nan::Utf8String(value))}; } else if (value->IsUint32()) { - return { Nan::To(value).ToChecked() }; + return {Nan::To(value).ToChecked()}; } else if (value->IsInt32()) { - return { Nan::To(value).ToChecked() }; + return {Nan::To(value).ToChecked()}; } else if (value->IsNumber()) { - return { Nan::To(value).ToChecked() }; + return {Nan::To(value).ToChecked()}; } else { return {}; } @@ -131,14 +134,14 @@ class ConversionTraits> { std::string string = *Nan::Utf8String(stringified); return parseGeoJSON(string, error); } catch (const std::exception& ex) { - error = { ex.what() }; + error = {ex.what()}; return {}; } } }; -template -std::optional convert(const v8::Local& value, Error& error, Args&&...args) { +template +std::optional convert(const v8::Local& value, Error& error, Args&&... args) { return convert(Convertible(value), error, std::forward(args)...); } diff --git a/platform/node/src/node_expression.cpp b/platform/node/src/node_expression.cpp index 7da4f12c355..efd03370cf2 100644 --- a/platform/node/src/node_expression.cpp +++ b/platform/node/src/node_expression.cpp @@ -59,7 +59,8 @@ type::Type parseType(v8::Local type) { #else v8::Local context = type->GetCreationContext().ToLocalChecked(); #endif - type::Type itemType = parseType(Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject(context).ToLocalChecked()); + type::Type itemType = parseType( + Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject(context).ToLocalChecked()); std::optional N; v8::Local Nkey = Nan::New("N").ToLocalChecked(); @@ -97,12 +98,8 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo& info) { for (std::size_t i = 0; i < errors.size(); ++i) { const auto& error = errors[i]; v8::Local err = Nan::New(); - Nan::Set(err, - Nan::New("key").ToLocalChecked(), - Nan::New(error.key.c_str()).ToLocalChecked()); - Nan::Set(err, - Nan::New("error").ToLocalChecked(), - Nan::New(error.message.c_str()).ToLocalChecked()); + Nan::Set(err, Nan::New("key").ToLocalChecked(), Nan::New(error.key.c_str()).ToLocalChecked()); + Nan::Set(err, Nan::New("error").ToLocalChecked(), Nan::New(error.message.c_str()).ToLocalChecked()); Nan::Set(result, Nan::New(static_cast(i)), err); } info.GetReturnValue().Set(result); @@ -119,7 +116,7 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo& info) { if (func) { return success(std::move(*func)); } - return fail({ { error.message, "" } }); + return fail({{error.message, ""}}); } ParsingContext ctx = expected ? ParsingContext(*expected) : ParsingContext(); @@ -129,7 +126,7 @@ void NodeExpression::Parse(const Nan::FunctionCallbackInfo& info) { return success(std::move(*parsed)); } return fail(ctx.getErrors()); - } catch(std::exception &ex) { + } catch (std::exception& ex) { return Nan::ThrowError(ex.what()); } } @@ -213,12 +210,10 @@ struct ToValue { } v8::Local operator()(const mbgl::Color& color) { - return operator()(std::vector { - static_cast(color.r), - static_cast(color.g), - static_cast(color.b), - static_cast(color.a) - }); + return operator()(std::vector{static_cast(color.r), + static_cast(color.g), + static_cast(color.b), + static_cast(color.a)}); } v8::Local operator()(const std::unordered_map& map) { @@ -248,11 +243,14 @@ void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo& info) } std::optional zoom; - v8::Local v8zoom = Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked(); + v8::Local v8zoom = + Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked(); if (v8zoom->IsNumber()) zoom = static_cast(Nan::To(v8zoom).FromJust()); std::optional heatmapDensity; - v8::Local v8heatmapDensity = Nan::Get(info[0]->ToObject(context).ToLocalChecked(), Nan::New("heatmapDensity").ToLocalChecked()).ToLocalChecked(); + v8::Local v8heatmapDensity = Nan::Get(info[0]->ToObject(context).ToLocalChecked(), + Nan::New("heatmapDensity").ToLocalChecked()) + .ToLocalChecked(); if (v8heatmapDensity->IsNumber()) heatmapDensity = Nan::To(v8heatmapDensity).FromJust(); Nan::JSON NanJSON; @@ -270,12 +268,11 @@ void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo& info) info.GetReturnValue().Set(toJS(*result)); } else { v8::Local res = Nan::New(); - Nan::Set(res, - Nan::New("error").ToLocalChecked(), - Nan::New(result.error().message.c_str()).ToLocalChecked()); + Nan::Set( + res, Nan::New("error").ToLocalChecked(), Nan::New(result.error().message.c_str()).ToLocalChecked()); info.GetReturnValue().Set(res); } - } catch(std::exception &ex) { + } catch (std::exception& ex) { return Nan::ThrowTypeError(ex.what()); } } @@ -285,7 +282,7 @@ void NodeExpression::GetType(const Nan::FunctionCallbackInfo& info) { const std::unique_ptr& expression = nodeExpr->expression; const type::Type type = expression->getType(); - const std::string name = type.match([&] (const auto& t) { return t.getName(); }); + const std::string name = type.match([&](const auto& t) { return t.getName(); }); info.GetReturnValue().Set(Nan::New(name.c_str()).ToLocalChecked()); } diff --git a/platform/node/src/node_feature.cpp b/platform/node/src/node_feature.cpp index 7f2c5f35fe8..fa88a1d1f70 100644 --- a/platform/node/src/node_feature.cpp +++ b/platform/node/src/node_feature.cpp @@ -14,37 +14,21 @@ using Properties = mbgl::PropertyMap; template struct ToType { public: - v8::Local operator()(const empty&) { - return type("Empty"); - } + v8::Local operator()(const empty&) { return type("Empty"); } - v8::Local operator()(const point&) { - return type("Point"); - } + v8::Local operator()(const point&) { return type("Point"); } - v8::Local operator()(const line_string&) { - return type("LineString"); - } + v8::Local operator()(const line_string&) { return type("LineString"); } - v8::Local operator()(const polygon&) { - return type("Polygon"); - } + v8::Local operator()(const polygon&) { return type("Polygon"); } - v8::Local operator()(const multi_point&) { - return type("MultiPoint"); - } + v8::Local operator()(const multi_point&) { return type("MultiPoint"); } - v8::Local operator()(const multi_line_string&) { - return type("MultiLineString"); - } + v8::Local operator()(const multi_line_string&) { return type("MultiLineString"); } - v8::Local operator()(const multi_polygon&) { - return type("MultiPolygon"); - } + v8::Local operator()(const multi_polygon&) { return type("MultiPolygon"); } - v8::Local operator()(const geometry_collection&) { - return type("GeometryCollection"); - } + v8::Local operator()(const geometry_collection&) { return type("GeometryCollection"); } private: v8::Local type(const char* type_) { @@ -56,7 +40,8 @@ struct ToType { template struct ToCoordinatesOrGeometries { public: - // Handles line_string, polygon, multi_point, multi_line_string, multi_polygon, and geometry_collection. + // Handles line_string, polygon, multi_point, multi_line_string, + // multi_polygon, and geometry_collection. template v8::Local operator()(const std::vector& vector) { Nan::EscapableHandleScope scope; @@ -75,9 +60,7 @@ struct ToCoordinatesOrGeometries { return scope.Escape(result); } - v8::Local operator()(const geometry& geometry) { - return toJS(geometry); - } + v8::Local operator()(const geometry& geometry) { return toJS(geometry); } }; struct ToValue { @@ -91,13 +74,9 @@ struct ToValue { return scope.Escape(Nan::New(t)); } - v8::Local operator()(int64_t t) { - return operator()(static_cast(t)); - } + v8::Local operator()(int64_t t) { return operator()(static_cast(t)); } - v8::Local operator()(uint64_t t) { - return operator()(static_cast(t)); - } + v8::Local operator()(uint64_t t) { return operator()(static_cast(t)); } v8::Local operator()(double t) { Nan::EscapableHandleScope scope; @@ -118,9 +97,7 @@ struct ToValue { return scope.Escape(result); } - v8::Local operator()(const std::unordered_map& map) { - return toJS(map); - } + v8::Local operator()(const std::unordered_map& map) { return toJS(map); } }; v8::Local toJS(const Geometry& geometry) { @@ -128,13 +105,11 @@ v8::Local toJS(const Geometry& geometry) { v8::Local result = Nan::New(); - Nan::Set(result, - Nan::New("type").ToLocalChecked(), - Geometry::visit(geometry, ToType())); + Nan::Set(result, Nan::New("type").ToLocalChecked(), Geometry::visit(geometry, ToType())); Nan::Set(result, - Nan::New(geometry.is() ? "geometries" : "coordinates").ToLocalChecked(), - Geometry::visit(geometry, ToCoordinatesOrGeometries())); + Nan::New(geometry.is() ? "geometries" : "coordinates").ToLocalChecked(), + Geometry::visit(geometry, ToCoordinatesOrGeometries())); return scope.Escape(result); } diff --git a/platform/node/src/node_feature.hpp b/platform/node/src/node_feature.hpp index 8d1eceba38f..4a7e6be23da 100644 --- a/platform/node/src/node_feature.hpp +++ b/platform/node/src/node_feature.hpp @@ -15,4 +15,4 @@ v8::Local toJS(const mbgl::Feature&); v8::Local toJS(const mbgl::Feature::geometry_type&); v8::Local toJS(const mbgl::PropertyMap&); -} +} // namespace node_mbgl diff --git a/platform/node/src/node_logging.cpp b/platform/node/src/node_logging.cpp index 5e7326e90a9..e29f6e4e5fd 100644 --- a/platform/node/src/node_logging.cpp +++ b/platform/node/src/node_logging.cpp @@ -12,9 +12,9 @@ struct NodeLogObserver::LogMessage { LogMessage(mbgl::EventSeverity severity_, mbgl::Event event_, int64_t code_, std::string text_) : severity(severity_), - event(event_), - code(code_), - text(std::move(text_)) {} + event(event_), + code(code_), + text(std::move(text_)) {} }; NodeLogObserver::NodeLogObserver(v8::Local target) @@ -23,25 +23,26 @@ NodeLogObserver::NodeLogObserver(v8::Local target) auto msg = Nan::New(); - Nan::Set(msg, Nan::New("class").ToLocalChecked(), - Nan::New(mbgl::Enum::toString(message.event)).ToLocalChecked()); + Nan::Set(msg, + Nan::New("class").ToLocalChecked(), + Nan::New(mbgl::Enum::toString(message.event)).ToLocalChecked()); - Nan::Set(msg, Nan::New("severity").ToLocalChecked(), - Nan::New(mbgl::Enum::toString(message.severity)).ToLocalChecked()); + Nan::Set(msg, + Nan::New("severity").ToLocalChecked(), + Nan::New(mbgl::Enum::toString(message.severity)).ToLocalChecked()); if (message.code != -1) { - Nan::Set(msg, Nan::New("code").ToLocalChecked(), - Nan::New(message.code)); + Nan::Set(msg, Nan::New("code").ToLocalChecked(), Nan::New(message.code)); } if (!message.text.empty()) { - Nan::Set(msg, Nan::New("text").ToLocalChecked(), - Nan::New(message.text).ToLocalChecked()); + Nan::Set(msg, Nan::New("text").ToLocalChecked(), Nan::New(message.text).ToLocalChecked()); } - v8::Local argv[] = { Nan::New("message").ToLocalChecked(), msg }; + v8::Local argv[] = {Nan::New("message").ToLocalChecked(), msg}; auto handle = Nan::New(module); - auto emit = Nan::To(Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); + auto emit = Nan::To(Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked()) + .ToLocalChecked(); Nan::CallAsFunction(emit, handle, 2, argv); })) { Nan::HandleScope scope; @@ -56,7 +57,7 @@ NodeLogObserver::~NodeLogObserver() { } bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) { - queue->send({ severity, event, code, text }); + queue->send({severity, event, code, text}); return true; } diff --git a/platform/node/src/node_logging.hpp b/platform/node/src/node_logging.hpp index 67f4ace079d..c03c7a00e29 100644 --- a/platform/node/src/node_logging.hpp +++ b/platform/node/src/node_logging.hpp @@ -12,7 +12,10 @@ namespace node_mbgl { -namespace util { template class AsyncQueue; } +namespace util { +template +class AsyncQueue; +} class NodeLogObserver : public mbgl::Log::Observer { public: diff --git a/platform/node/src/node_map.cpp b/platform/node/src/node_map.cpp index bb5536ef0dd..b67ed90a19d 100644 --- a/platform/node/src/node_map.cpp +++ b/platform/node/src/node_map.cpp @@ -41,7 +41,7 @@ struct NodeMap::RenderOptions { double pitch = 0; double latitude = 0; double longitude = 0; - mbgl::Size size = { 512, 512 }; + mbgl::Size size = {512, 512}; bool axonometric = false; double xSkew = 0; double ySkew = 1; @@ -77,7 +77,9 @@ class ParseError extends Error { } } } -ParseError)JS").ToLocalChecked()).ToLocalChecked(); +ParseError)JS") + .ToLocalChecked()) + .ToLocalChecked(); parseError.Reset(Nan::To(Nan::RunScript(script).ToLocalChecked()).ToLocalChecked()); Nan::Set(target, Nan::New("ParseError").ToLocalChecked(), Nan::New(parseError)); @@ -177,35 +179,36 @@ void NodeMap::New(const Nan::FunctionCallbackInfo& info) { v8::Local options; - if(info.Length() > 0) { + if (info.Length() > 0) { options = Nan::To(info[0]).ToLocalChecked(); } else { options = Nan::New(); } - // Check that if 'request' is set it must be a function, if 'cancel' is set it must be a - // function and if 'ratio' is set it must be a number. - if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() - && !Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { + // Check that if 'request' is set it must be a function, if 'cancel' is set + // it must be a function and if 'ratio' is set it must be a number. + if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() && + !Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { return Nan::ThrowError("Options object 'request' property must be a function"); } - if (Nan::Has(options, Nan::New("cancel").ToLocalChecked()).FromJust() - && !Nan::Get(options, Nan::New("cancel").ToLocalChecked()).ToLocalChecked()->IsFunction()) { + 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()) { + if (Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust() && + !Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->IsNumber()) { return Nan::ThrowError("Options object 'ratio' property must be a number"); } info.This()->SetInternalField(1, options); - if(Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() - && Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { + if (Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust() && + Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) { mbgl::FileSourceManager::get()->registerFileSourceFactory( - mbgl::FileSourceType::ResourceLoader, [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions&) { + mbgl::FileSourceType::ResourceLoader, + [](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions&) { return std::make_unique( reinterpret_cast(resourceOptions.platformContext())); }); @@ -214,7 +217,7 @@ void NodeMap::New(const Nan::FunctionCallbackInfo& info) { try { auto nodeMap = new NodeMap(options); nodeMap->Wrap(info.This()); - } catch(std::exception &ex) { + } catch (std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -267,7 +270,7 @@ void NodeMap::Load(const Nan::FunctionCallbackInfo& info) { nodeMap->map->getStyle().loadJSON(style); } catch (const mbgl::util::StyleParseException& ex) { return Nan::ThrowError(ParseError(ex.what())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -278,9 +281,12 @@ void NodeMap::Load(const Nan::FunctionCallbackInfo& info) { auto options = Nan::To(info[1]).ToLocalChecked(); if (Nan::Has(options, Nan::New("defaultStyleCamera").ToLocalChecked()).FromJust()) { if (!Nan::Get(options, Nan::New("defaultStyleCamera").ToLocalChecked()).ToLocalChecked()->IsBoolean()) { - return Nan::ThrowError("Options object 'defaultStyleCamera' property must be a boolean"); + return Nan::ThrowError( + "Options object 'defaultStyleCamera' property must be a " + "boolean"); } - if (Nan::To(Nan::Get(options, Nan::New("cameraMutated").ToLocalChecked()).ToLocalChecked()).ToChecked()) { + if (Nan::To(Nan::Get(options, Nan::New("cameraMutated").ToLocalChecked()).ToLocalChecked()) + .ToChecked()) { nodeMap->map->jumpTo(nodeMap->map->getStyle().getDefaultCamera()); } } @@ -299,7 +305,7 @@ void NodeMap::Loaded(const Nan::FunctionCallbackInfo& info) { try { loaded = nodeMap->map->isFullyLoaded(); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -316,7 +322,8 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { } if (Nan::Has(obj, Nan::New("bearing").ToLocalChecked()).FromJust()) { - options.bearing = Nan::To(Nan::Get(obj, Nan::New("bearing").ToLocalChecked()).ToLocalChecked()).ToChecked(); + options.bearing = + Nan::To(Nan::Get(obj, Nan::New("bearing").ToLocalChecked()).ToLocalChecked()).ToChecked(); } if (Nan::Has(obj, Nan::New("pitch").ToLocalChecked()).FromJust()) { @@ -334,15 +341,20 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { } if (Nan::Has(obj, Nan::New("axonometric").ToLocalChecked()).FromJust()) { - options.axonometric = Nan::To(Nan::Get(obj, Nan::New("axonometric").ToLocalChecked()).ToLocalChecked()).ToChecked(); + options.axonometric = + Nan::To(Nan::Get(obj, Nan::New("axonometric").ToLocalChecked()).ToLocalChecked()).ToChecked(); } if (Nan::Has(obj, Nan::New("skew").ToLocalChecked()).FromJust()) { auto skewObj = Nan::Get(obj, Nan::New("skew").ToLocalChecked()).ToLocalChecked(); if (skewObj->IsArray()) { auto skew = skewObj.As(); - if (skew->Length() > 0) { options.xSkew = Nan::To(Nan::Get(skew, 0).ToLocalChecked()).ToChecked(); } - if (skew->Length() > 1) { options.ySkew = Nan::To(Nan::Get(skew, 1).ToLocalChecked()).ToChecked(); } + if (skew->Length() > 0) { + options.xSkew = Nan::To(Nan::Get(skew, 0).ToLocalChecked()).ToChecked(); + } + if (skew->Length() > 1) { + options.ySkew = Nan::To(Nan::Get(skew, 1).ToLocalChecked()).ToChecked(); + } } } @@ -350,30 +362,40 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { auto centerObj = Nan::Get(obj, Nan::New("center").ToLocalChecked()).ToLocalChecked(); if (centerObj->IsArray()) { auto center = centerObj.As(); - if (center->Length() > 0) { options.longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); } - if (center->Length() > 1) { options.latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); } + if (center->Length() > 0) { + options.longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); + } + if (center->Length() > 1) { + options.latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); + } } } if (Nan::Has(obj, Nan::New("width").ToLocalChecked()).FromJust()) { - options.size.width = static_cast(Nan::To(Nan::Get(obj, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked()); + options.size.width = static_cast( + Nan::To(Nan::Get(obj, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked()); } if (Nan::Has(obj, Nan::New("height").ToLocalChecked()).FromJust()) { - options.size.height = static_cast(Nan::To(Nan::Get(obj, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked()); + options.size.height = static_cast( + Nan::To(Nan::Get(obj, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked()); } if (Nan::Has(obj, Nan::New("classes").ToLocalChecked()).FromJust()) { - auto classes = Nan::To(Nan::Get(obj, Nan::New("classes").ToLocalChecked()).ToLocalChecked()).ToLocalChecked().As(); + auto classes = Nan::To(Nan::Get(obj, Nan::New("classes").ToLocalChecked()).ToLocalChecked()) + .ToLocalChecked() + .As(); const int length = classes->Length(); options.classes.reserve(length); for (int i = 0; i < length; i++) { - options.classes.emplace_back(std::string { *Nan::Utf8String(Nan::To(Nan::Get(classes, i).ToLocalChecked()).ToLocalChecked()) }); + options.classes.emplace_back(std::string{ + *Nan::Utf8String(Nan::To(Nan::Get(classes, i).ToLocalChecked()).ToLocalChecked())}); } } if (Nan::Has(obj, Nan::New("debug").ToLocalChecked()).FromJust()) { - auto debug = Nan::To(Nan::Get(obj, Nan::New("debug").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); + auto debug = + Nan::To(Nan::Get(obj, Nan::New("debug").ToLocalChecked()).ToLocalChecked()).ToLocalChecked(); if (Nan::Has(debug, Nan::New("tileBorders").ToLocalChecked()).FromJust()) { if (Nan::To(Nan::Get(debug, Nan::New("tileBorders").ToLocalChecked()).ToLocalChecked()).ToChecked()) { options.debugOptions = options.debugOptions | mbgl::MapDebugOptions::TileBorders; @@ -406,12 +428,11 @@ NodeMap::RenderOptions NodeMap::ParseOptions(v8::Local obj) { class RenderRequest : public Nan::AsyncResource { public: - explicit RenderRequest(v8::Local callback_) : AsyncResource("mbgl:RenderRequest") { + explicit RenderRequest(v8::Local callback_) + : AsyncResource("mbgl:RenderRequest") { callback.Reset(callback_); } - ~RenderRequest() { - callback.Reset(); - } + ~RenderRequest() { callback.Reset(); } Nan::Persistent callback; }; @@ -471,7 +492,7 @@ void NodeMap::Render(const Nan::FunctionCallbackInfo& info) { return Nan::ThrowTypeError(err.message.c_str()); } catch (const mbgl::util::StyleParseException& ex) { return Nan::ThrowError(ParseError(ex.what())); - } catch (const mbgl::util::Exception &ex) { + } catch (const mbgl::util::Exception& ex) { return Nan::ThrowError(ex.what()); } @@ -490,12 +511,12 @@ void NodeMap::startRender() { } }); - // Retain this object, otherwise it might get destructed before we are finished rendering the - // still image. + // Retain this object, otherwise it might get destructed before we are + // finished rendering the still image. Ref(); - // Similarly, we're now waiting for the async to be called, so we need to make sure that it - // keeps the loop alive. + // Similarly, we're now waiting for the async to be called, so we need to + // make sure that it keeps the loop alive. uv_ref(reinterpret_cast(async)); } @@ -504,15 +525,13 @@ void NodeMap::startRender(const NodeMap::RenderOptions& options) { map->setSize(options.size); mbgl::CameraOptions camera; - camera.center = mbgl::LatLng { options.latitude, options.longitude }; + camera.center = mbgl::LatLng{options.latitude, options.longitude}; camera.zoom = options.zoom; camera.bearing = options.bearing; camera.pitch = options.pitch; - auto projectionOptions = mbgl::ProjectionMode() - .withAxonometric(options.axonometric) - .withXSkew(options.xSkew) - .withYSkew(options.ySkew); + auto projectionOptions = + mbgl::ProjectionMode().withAxonometric(options.axonometric).withXSkew(options.xSkew).withYSkew(options.ySkew); map->setProjectionMode(projectionOptions); @@ -527,17 +546,17 @@ void NodeMap::startRender(const NodeMap::RenderOptions& options) { } }); - // Retain this object, otherwise it might get destructed before we are finished rendering the - // still image. + // Retain this object, otherwise it might get destructed before we are + // finished rendering the still image. Ref(); - // Similarly, we're now waiting for the async to be called, so we need to make sure that it - // keeps the loop alive. - uv_ref(reinterpret_cast(async)); + // Similarly, we're now waiting for the async to be called, so we need to + // make sure that it keeps the loop alive. + uv_ref(reinterpret_cast(async)); } v8::Local NodeMap::ParseError(const char* msg) { - v8::Local argv[] = { Nan::New(msg).ToLocalChecked() }; + v8::Local argv[] = {Nan::New(msg).ToLocalChecked()}; return Nan::CallAsConstructor(Nan::New(parseError), 1, argv).ToLocalChecked(); } @@ -547,7 +566,7 @@ void NodeMap::renderFinished() { 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)); + uv_unref(reinterpret_cast(async)); // Move the callback and image out of the way so that the callback can start a new render call. auto request = std::move(req); @@ -573,9 +592,7 @@ void NodeMap::renderFinished() { err = Nan::Error(ex.what()); } - v8::Local argv[] = { - err - }; + v8::Local argv[] = {err}; // This must be empty to be prepared for the next render call. error = nullptr; @@ -584,31 +601,25 @@ void NodeMap::renderFinished() { request->runInAsyncScope(target, callback, 1, argv); } else if (img.data) { v8::Local pixels = Nan::NewBuffer( - reinterpret_cast(img.data.get()), img.bytes(), - // Retain the data until the buffer is deleted. - [](char *, void * hint) { - delete [] reinterpret_cast(hint); - }, - img.data.get() - ).ToLocalChecked(); + reinterpret_cast(img.data.get()), + img.bytes(), + // Retain the data until the buffer is deleted. + [](char*, void* hint) { delete[] reinterpret_cast(hint); }, + img.data.get()) + .ToLocalChecked(); if (!pixels.IsEmpty()) { img.data.release(); } - v8::Local argv[] = { - Nan::Null(), - pixels - }; + v8::Local argv[] = {Nan::Null(), pixels}; request->runInAsyncScope(target, callback, 2, argv); } else { - v8::Local argv[] = { - Nan::Error("Didn't get an image") - }; + v8::Local argv[] = {Nan::Error("Didn't get an image")}; request->runInAsyncScope(target, callback, 1, argv); } - // There is no render pending anymore, we the GC could now delete this object if it went out - // of scope. + // There is no render pending anymore, we the GC could now delete this + // object if it went out of scope. Unref(); } @@ -623,7 +634,7 @@ void NodeMap::Release(const Nan::FunctionCallbackInfo& info) { try { nodeMap->release(); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -633,9 +644,7 @@ void NodeMap::Release(const Nan::FunctionCallbackInfo& info) { void NodeMap::release() { if (!map) throw mbgl::util::Exception(releasedMessage()); - uv_close(reinterpret_cast(async), [] (uv_handle_t *h) { - delete reinterpret_cast(h); - }); + uv_close(reinterpret_cast(async), [](uv_handle_t* h) { delete reinterpret_cast(h); }); map.reset(); frontend.reset(); @@ -655,7 +664,7 @@ void NodeMap::Cancel(const Nan::FunctionCallbackInfo& info) { try { nodeMap->cancel(); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -669,22 +678,21 @@ void NodeMap::cancel() { map.reset(); // Remove the existing async handle to flush any scheduled calls to renderFinished. - uv_unref(reinterpret_cast(async)); - uv_close(reinterpret_cast(async), [] (uv_handle_t *h) { - delete reinterpret_cast(h); - }); + uv_unref(reinterpret_cast(async)); + uv_close(reinterpret_cast(async), [](uv_handle_t* h) { delete reinterpret_cast(h); }); async = new uv_async_t; async->data = this; - uv_async_init(uv_default_loop(), async, [](uv_async_t* h) { - reinterpret_cast(h->data)->renderFinished(); - }); - - frontend = std::make_unique(mbgl::Size{ 512, 512 }, pixelRatio); - map = std::make_unique(*frontend, mapObserver, - mbgl::MapOptions().withSize(frontend->getSize()) - .withPixelRatio(pixelRatio) - .withMapMode(mode) - .withCrossSourceCollisions(crossSourceCollisions), + uv_async_init( + uv_default_loop(), async, [](uv_async_t* h) { reinterpret_cast(h->data)->renderFinished(); }); + + frontend = std::make_unique(mbgl::Size{512, 512}, pixelRatio); + map = std::make_unique(*frontend, + mapObserver, + mbgl::MapOptions() + .withSize(frontend->getSize()) + .withPixelRatio(pixelRatio) + .withMapMode(mode) + .withCrossSourceCollisions(crossSourceCollisions), mbgl::ResourceOptions().withPlatformContext(reinterpret_cast(this)), mbgl::ClientOptions()); @@ -717,7 +725,8 @@ void NodeMap::AddSource(const Nan::FunctionCallbackInfo& info) { } Error error; - std::optional> source = convert>(info[1], error, *Nan::Utf8String(info[0])); + std::optional> source = convert>( + info[1], error, *Nan::Utf8String(info[0])); if (!source) { Nan::ThrowTypeError(error.message.c_str()); return; @@ -822,8 +831,10 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo& info) { return Nan::ThrowTypeError("pixelRatio parameter required"); } - uint32_t imageHeight = Nan::To(Nan::Get(optionObject, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked(); - uint32_t imageWidth = Nan::To(Nan::Get(optionObject, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked(); + uint32_t imageHeight = + Nan::To(Nan::Get(optionObject, Nan::New("height").ToLocalChecked()).ToLocalChecked()).ToChecked(); + uint32_t imageWidth = + Nan::To(Nan::Get(optionObject, Nan::New("width").ToLocalChecked()).ToLocalChecked()).ToChecked(); if (imageWidth > 1024 || imageHeight > 1024) { return Nan::ThrowTypeError("Max height and width is 1024"); @@ -834,10 +845,12 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo& info) { sdf = Nan::To(Nan::Get(optionObject, Nan::New("sdf").ToLocalChecked()).ToLocalChecked()).ToChecked(); } - float pixelRatio = (float)Nan::To(Nan::Get(optionObject, Nan::New("pixelRatio").ToLocalChecked()).ToLocalChecked()).ToChecked(); + float pixelRatio = (float)Nan::To( + Nan::Get(optionObject, Nan::New("pixelRatio").ToLocalChecked()).ToLocalChecked()) + .ToChecked(); auto imageBuffer = Nan::To(info[1]).ToLocalChecked()->ToObject(context).ToLocalChecked(); - char * imageDataBuffer = node::Buffer::Data(imageBuffer); + char* imageDataBuffer = node::Buffer::Data(imageBuffer); size_t imageLength = node::Buffer::Length(imageBuffer); if (imageLength != imageHeight * imageWidth * 4) { @@ -847,9 +860,10 @@ void NodeMap::AddImage(const Nan::FunctionCallbackInfo& info) { std::unique_ptr data = std::make_unique(imageLength); std::copy(imageDataBuffer, imageDataBuffer + imageLength, data.get()); - mbgl::UnassociatedImage cImage({ imageWidth, imageHeight}, std::move(data)); + mbgl::UnassociatedImage cImage({imageWidth, imageHeight}, std::move(data)); mbgl::PremultipliedImage cPremultipliedImage = mbgl::util::premultiply(std::move(cImage)); - nodeMap->map->getStyle().addImage(std::make_unique(*Nan::Utf8String(info[0]), std::move(cPremultipliedImage), pixelRatio, sdf)); + nodeMap->map->getStyle().addImage(std::make_unique( + *Nan::Utf8String(info[0]), std::move(cPremultipliedImage), pixelRatio, sdf)); } void NodeMap::RemoveImage(const Nan::FunctionCallbackInfo& info) { @@ -973,15 +987,19 @@ void NodeMap::SetSize(const Nan::FunctionCallbackInfo& info) { } auto size = info[0].As(); - uint32_t width= 0; + uint32_t width = 0; uint32_t height = 0; - if (size->Length() > 0) { width = Nan::To(Nan::Get(size, 0).ToLocalChecked()).ToChecked(); } - if (size->Length() > 1) { height = Nan::To(Nan::Get(size, 1).ToLocalChecked()).ToChecked(); } + if (size->Length() > 0) { + width = Nan::To(Nan::Get(size, 0).ToLocalChecked()).ToChecked(); + } + if (size->Length() > 1) { + height = Nan::To(Nan::Get(size, 1).ToLocalChecked()).ToChecked(); + } try { - nodeMap->frontend->setSize({ width, height }); - nodeMap->map->setSize({ width, height }); - } catch (const std::exception &ex) { + nodeMap->frontend->setSize({width, height}); + nodeMap->map->setSize({width, height}); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -999,12 +1017,16 @@ void NodeMap::SetCenter(const Nan::FunctionCallbackInfo& info) { auto center = info[0].As(); double latitude = 0; double longitude = 0; - if (center->Length() > 0) { longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); } - if (center->Length() > 1) { latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); } + if (center->Length() > 0) { + longitude = Nan::To(Nan::Get(center, 0).ToLocalChecked()).ToChecked(); + } + if (center->Length() > 1) { + latitude = Nan::To(Nan::Get(center, 1).ToLocalChecked()).ToChecked(); + } try { - nodeMap->map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng { latitude, longitude })); - } catch (const std::exception &ex) { + nodeMap->map->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng{latitude, longitude})); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1021,7 +1043,7 @@ void NodeMap::SetZoom(const Nan::FunctionCallbackInfo& info) { try { nodeMap->map->jumpTo(mbgl::CameraOptions().withZoom(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1038,7 +1060,7 @@ void NodeMap::SetBearing(const Nan::FunctionCallbackInfo& info) { try { nodeMap->map->jumpTo(mbgl::CameraOptions().withBearing(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1055,7 +1077,7 @@ void NodeMap::SetPitch(const Nan::FunctionCallbackInfo& info) { try { nodeMap->map->jumpTo(mbgl::CameraOptions().withPitch(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1080,7 +1102,7 @@ void NodeMap::SetLight(const Nan::FunctionCallbackInfo& info) { } else { return Nan::ThrowTypeError(conversionError.message.c_str()); } - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1096,9 +1118,8 @@ void NodeMap::SetAxonometric(const Nan::FunctionCallbackInfo& info) { } try { - nodeMap->map->setProjectionMode(mbgl::ProjectionMode() - .withAxonometric(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withAxonometric(Nan::To(info[0]).ToChecked())); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1114,9 +1135,8 @@ void NodeMap::SetXSkew(const Nan::FunctionCallbackInfo& info) { } try { - nodeMap->map->setProjectionMode(mbgl::ProjectionMode() - .withXSkew(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withXSkew(Nan::To(info[0]).ToChecked())); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1132,9 +1152,8 @@ void NodeMap::SetYSkew(const Nan::FunctionCallbackInfo& info) { } try { - nodeMap->map->setProjectionMode(mbgl::ProjectionMode() - .withYSkew(Nan::To(info[0]).ToChecked())); - } catch (const std::exception &ex) { + nodeMap->map->setProjectionMode(mbgl::ProjectionMode().withYSkew(Nan::To(info[0]).ToChecked())); + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } @@ -1173,7 +1192,9 @@ void NodeMap::SetFeatureState(const Nan::FunctionCallbackInfo& info) if (Nan::Has(feature, Nan::New("sourceLayer").ToLocalChecked()).FromJust()) { auto sourceLayerOption = Nan::Get(feature, Nan::New("sourceLayer").ToLocalChecked()).ToLocalChecked(); if (!sourceLayerOption->IsString()) { - return Nan::ThrowTypeError("SetFeatureState: Requires feature.sourceLayer property to be a string"); + return Nan::ThrowTypeError( + "SetFeatureState: Requires feature.sourceLayer property to be " + "a string"); } sourceLayerID = {*Nan::Utf8String(sourceLayerOption)}; } @@ -1274,7 +1295,9 @@ void NodeMap::GetFeatureState(const Nan::FunctionCallbackInfo& info) if (Nan::Has(feature, Nan::New("sourceLayer").ToLocalChecked()).FromJust()) { auto sourceLayerOption = Nan::Get(feature, Nan::New("sourceLayer").ToLocalChecked()).ToLocalChecked(); if (!sourceLayerOption->IsString()) { - return Nan::ThrowTypeError("GetFeatureState: Requires feature.sourceLayer property to be a string"); + return Nan::ThrowTypeError( + "GetFeatureState: Requires feature.sourceLayer property to be " + "a string"); } sourceLayerID = {*Nan::Utf8String(sourceLayerOption)}; } @@ -1333,7 +1356,9 @@ void NodeMap::RemoveFeatureState(const Nan::FunctionCallbackInfo& inf if (Nan::Has(feature, Nan::New("sourceLayer").ToLocalChecked()).FromJust()) { auto sourceLayerOption = Nan::Get(feature, Nan::New("sourceLayer").ToLocalChecked()).ToLocalChecked(); if (!sourceLayerOption->IsString()) { - return Nan::ThrowTypeError("RemoveFeatureState: Requires feature.sourceLayer property to be a string"); + return Nan::ThrowTypeError( + "RemoveFeatureState: Requires feature.sourceLayer property to " + "be a string"); } sourceLayerID = {*Nan::Utf8String(sourceLayerOption)}; } @@ -1349,7 +1374,9 @@ void NodeMap::RemoveFeatureState(const Nan::FunctionCallbackInfo& inf if (info.Length() == 2) { auto keyParam = Nan::To(info[1]).ToLocalChecked(); if (!keyParam->IsString()) { - return Nan::ThrowTypeError("RemoveFeatureState: Requires feature key property to be a string"); + return Nan::ThrowTypeError( + "RemoveFeatureState: Requires feature key property to be a " + "string"); } stateKey = {*Nan::Utf8String(keyParam)}; } @@ -1397,7 +1424,7 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& auto options = Nan::To(info[1]).ToLocalChecked(); - //Check if layers is set. If provided, it must be an array of strings + // Check if layers is set. If provided, it must be an array of strings if (Nan::Has(options, Nan::New("layers").ToLocalChecked()).FromJust()) { auto layersOption = Nan::Get(options, Nan::New("layers").ToLocalChecked()).ToLocalChecked(); if (!layersOption->IsArray()) { @@ -1405,13 +1432,13 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& } auto layers = layersOption.As(); std::vector layersVec; - for (uint32_t i=0; i < layers->Length(); i++) { - layersVec.emplace_back(*Nan::Utf8String(Nan::Get(layers,i).ToLocalChecked())); + for (uint32_t i = 0; i < layers->Length(); i++) { + layersVec.emplace_back(*Nan::Utf8String(Nan::Get(layers, i).ToLocalChecked())); } queryOptions.layerIDs = layersVec; } - //Check if filter is provided. If set it must be a valid Filter object + // Check if filter is provided. If set it must be a valid Filter object if (Nan::Has(options, Nan::New("filter").ToLocalChecked()).FromJust()) { auto filterOption = Nan::Get(options, Nan::New("filter").ToLocalChecked()).ToLocalChecked(); Error error; @@ -1427,25 +1454,21 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& std::vector optional; if (Nan::Get(posOrBox, 0).ToLocalChecked()->IsArray()) { - auto pos0 = Nan::Get(posOrBox, 0).ToLocalChecked().As(); auto pos1 = Nan::Get(posOrBox, 1).ToLocalChecked().As(); - optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(mbgl::ScreenBox { - { - Nan::To(Nan::Get(pos0, 0).ToLocalChecked()).ToChecked(), - Nan::To(Nan::Get(pos0, 1).ToLocalChecked()).ToChecked() - }, { - Nan::To(Nan::Get(pos1, 0).ToLocalChecked()).ToChecked(), - Nan::To(Nan::Get(pos1, 1).ToLocalChecked()).ToChecked() - } - }, queryOptions); + optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures( + mbgl::ScreenBox{{Nan::To(Nan::Get(pos0, 0).ToLocalChecked()).ToChecked(), + Nan::To(Nan::Get(pos0, 1).ToLocalChecked()).ToChecked()}, + {Nan::To(Nan::Get(pos1, 0).ToLocalChecked()).ToChecked(), + Nan::To(Nan::Get(pos1, 1).ToLocalChecked()).ToChecked()}}, + queryOptions); } else { - optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures(mbgl::ScreenCoordinate { - Nan::To(Nan::Get(posOrBox, 0).ToLocalChecked()).ToChecked(), - Nan::To(Nan::Get(posOrBox, 1).ToLocalChecked()).ToChecked() - }, queryOptions); + optional = nodeMap->frontend->getRenderer()->queryRenderedFeatures( + mbgl::ScreenCoordinate{Nan::To(Nan::Get(posOrBox, 0).ToLocalChecked()).ToChecked(), + Nan::To(Nan::Get(posOrBox, 1).ToLocalChecked()).ToChecked()}, + queryOptions); } auto array = Nan::New(); @@ -1453,7 +1476,7 @@ void NodeMap::QueryRenderedFeatures(const Nan::FunctionCallbackInfo& Nan::Set(array, static_cast(i), toJS(optional[i])); } info.GetReturnValue().Set(array); - } catch (const std::exception &ex) { + } catch (const std::exception& ex) { return Nan::ThrowError(ex.what()); } } @@ -1462,42 +1485,47 @@ NodeMap::NodeMap(v8::Local options) : pixelRatio([&] { Nan::HandleScope scope; return Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust() - ? static_cast(Nan::To(Nan::Get(options, Nan::New("ratio").ToLocalChecked()) - .ToLocalChecked()).ToChecked()) + ? static_cast( + Nan::To(Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()) + .ToChecked()) : 1.0f; - }()) - , mode([&] { - Nan::HandleScope scope; - if (std::string(*v8::String::Utf8Value(v8::Isolate::GetCurrent(), Nan::Get(options, Nan::New("mode").ToLocalChecked()).ToLocalChecked())) == "tile") { - return mbgl::MapMode::Tile; - } else { - return mbgl::MapMode::Static; - } - }()) - , crossSourceCollisions([&] { - Nan::HandleScope scope; - return Nan::Has(options, Nan::New("crossSourceCollisions").ToLocalChecked()).FromJust() - ? Nan::To(Nan::Get(options, Nan::New("crossSourceCollisions").ToLocalChecked()) - .ToLocalChecked()).ToChecked() - : true; - }()) - , mapObserver(NodeMapObserver()) - , frontend(std::make_unique(mbgl::Size { 512, 512 }, pixelRatio)) - , map(std::make_unique(*frontend, mapObserver, - mbgl::MapOptions().withSize(frontend->getSize()) - .withPixelRatio(pixelRatio) - .withMapMode(mode) - .withCrossSourceCollisions(crossSourceCollisions), + }()), + mode([&] { + Nan::HandleScope scope; + if (std::string(*v8::String::Utf8Value( + v8::Isolate::GetCurrent(), Nan::Get(options, Nan::New("mode").ToLocalChecked()).ToLocalChecked())) == + "tile") { + return mbgl::MapMode::Tile; + } else { + return mbgl::MapMode::Static; + } + }()), + crossSourceCollisions([&] { + Nan::HandleScope scope; + return Nan::Has(options, Nan::New("crossSourceCollisions").ToLocalChecked()).FromJust() + ? Nan::To( + Nan::Get(options, Nan::New("crossSourceCollisions").ToLocalChecked()).ToLocalChecked()) + .ToChecked() + : true; + }()), + mapObserver(NodeMapObserver()), + frontend(std::make_unique(mbgl::Size{512, 512}, pixelRatio)), + map(std::make_unique(*frontend, + mapObserver, + mbgl::MapOptions() + .withSize(frontend->getSize()) + .withPixelRatio(pixelRatio) + .withMapMode(mode) + .withCrossSourceCollisions(crossSourceCollisions), mbgl::ResourceOptions().withPlatformContext(reinterpret_cast(this)), - mbgl::ClientOptions())) - , async(new uv_async_t) { + mbgl::ClientOptions())), + async(new uv_async_t) { async->data = this; - uv_async_init(uv_default_loop(), async, [](uv_async_t* h) { - reinterpret_cast(h->data)->renderFinished(); - }); + uv_async_init( + uv_default_loop(), async, [](uv_async_t* h) { reinterpret_cast(h->data)->renderFinished(); }); // Make sure the async handle doesn't keep the loop alive. - uv_unref(reinterpret_cast(async)); + uv_unref(reinterpret_cast(async)); } NodeMap::~NodeMap() { @@ -1508,24 +1536,24 @@ NodeMap::~NodeMap() { } } -std::unique_ptr NodeFileSource::request(const mbgl::Resource& resource, mbgl::FileSource::Callback callback_) { +std::unique_ptr NodeFileSource::request(const mbgl::Resource& resource, + mbgl::FileSource::Callback callback_) { assert(nodeMap); Nan::HandleScope scope; - // Because this method may be called while this NodeMap is already eligible for garbage collection, - // we need to explicitly hold onto our own handle here so that GC during a v8 call doesn't destroy - // *this while we're still executing code. + // Because this method may be called while this NodeMap is already eligible + // for garbage collection, we need to explicitly hold onto our own handle + // here so that GC during a v8 call doesn't destroy *this while we're still + // executing code. nodeMap->handle(); auto asyncRequest = std::make_unique(); - v8::Local argv[] = { - Nan::New(nodeMap), - Nan::New(&callback_), - Nan::New(asyncRequest.get()), - Nan::New(resource.url).ToLocalChecked(), - Nan::New(resource.kind) - }; + v8::Local argv[] = {Nan::New(nodeMap), + Nan::New(&callback_), + Nan::New(asyncRequest.get()), + Nan::New(resource.url).ToLocalChecked(), + Nan::New(resource.kind)}; Nan::NewInstance(Nan::New(node_mbgl::NodeRequest::constructor), 5, argv).ToLocalChecked(); @@ -1537,7 +1565,7 @@ bool NodeFileSource::canRequest(const mbgl::Resource&) const { } void NodeFileSource::setResourceOptions(mbgl::ResourceOptions options) { - this->_resourceOptions = std::move(options); + this->_resourceOptions = std::move(options); } mbgl::ResourceOptions NodeFileSource::getResourceOptions() { diff --git a/platform/node/src/node_map.hpp b/platform/node/src/node_map.hpp index 179ab4121be..9f170d32750 100644 --- a/platform/node/src/node_map.hpp +++ b/platform/node/src/node_map.hpp @@ -94,13 +94,14 @@ class NodeMap : public Nan::ObjectWrap { std::unique_ptr req; // Async for delivering the notifications of render completion. - uv_async_t *async; + uv_async_t* async; bool loaded = false; }; struct NodeFileSource : public mbgl::FileSource { - NodeFileSource(NodeMap* nodeMap_) : nodeMap(nodeMap_) {} + NodeFileSource(NodeMap* nodeMap_) + : nodeMap(nodeMap_) {} ~NodeFileSource() override = default; std::unique_ptr request(const mbgl::Resource&, mbgl::FileSource::Callback) final; bool canRequest(const mbgl::Resource&) const override; diff --git a/platform/node/src/node_mapbox_gl_native.cpp b/platform/node/src/node_mapbox_gl_native.cpp index 425dd2b8aa5..1400fd01ed0 100644 --- a/platform/node/src/node_mapbox_gl_native.cpp +++ b/platform/node/src/node_mapbox_gl_native.cpp @@ -14,20 +14,20 @@ #include "node_request.hpp" #include "node_expression.hpp" - void SetBackendType(const Nan::FunctionCallbackInfo& info) { if (info.Length() < 1 || info[0]->IsUndefined()) { return Nan::ThrowTypeError("Requires a render backend name"); } - const std::string backendName { *Nan::Utf8String(info[0]) }; + const std::string backendName{*Nan::Utf8String(info[0])}; (void)backendName; } void RegisterModule(v8::Local target, v8::Local module) { // This has the effect of: - // a) Ensuring that the static local variable is initialized before any thread contention. - // b) unreffing an async handle, which otherwise would keep the default loop running. + // a) Ensuring that the static local variable is initialized before any + // thread contention. b) unreffing an async handle, which otherwise would + // keep the default loop running. static mbgl::util::RunLoop nodeRunLoop; nodeRunLoop.stop(); @@ -40,54 +40,35 @@ void RegisterModule(v8::Local target, v8::Local module) // Exports Resource constants. v8::Local resource = Nan::New(); - Nan::Set(resource, - Nan::New("Unknown").ToLocalChecked(), - Nan::New(mbgl::Resource::Unknown)); + Nan::Set(resource, Nan::New("Unknown").ToLocalChecked(), Nan::New(mbgl::Resource::Unknown)); - Nan::Set(resource, - Nan::New("Style").ToLocalChecked(), - Nan::New(mbgl::Resource::Style)); + 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("Source").ToLocalChecked(), Nan::New(mbgl::Resource::Source)); - Nan::Set(resource, - Nan::New("Tile").ToLocalChecked(), - Nan::New(mbgl::Resource::Tile)); + 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("Glyphs").ToLocalChecked(), Nan::New(mbgl::Resource::Glyphs)); - Nan::Set(resource, - Nan::New("SpriteImage").ToLocalChecked(), - Nan::New(mbgl::Resource::SpriteImage)); + 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(resource, Nan::New("SpriteJSON").ToLocalChecked(), Nan::New(mbgl::Resource::SpriteJSON)); - Nan::Set(target, - Nan::New("Resource").ToLocalChecked(), - resource); + Nan::Set(target, Nan::New("Resource").ToLocalChecked(), resource); // Make the exported object inherit from EventEmitter - v8::Local require = Nan::Get(module, - Nan::New("require").ToLocalChecked()).ToLocalChecked().As(); + v8::Local require = + Nan::Get(module, Nan::New("require").ToLocalChecked()).ToLocalChecked().As(); v8::Local eventsString = Nan::New("events").ToLocalChecked(); - v8::Local events = Nan::To(Nan::Call(require, module, 1, &eventsString).ToLocalChecked()).ToLocalChecked(); + v8::Local events = + Nan::To(Nan::Call(require, module, 1, &eventsString).ToLocalChecked()).ToLocalChecked(); - v8::Local EventEmitter = Nan::To( - Nan::Get( - events, - Nan::New("EventEmitter").ToLocalChecked() - ).ToLocalChecked() - ).ToLocalChecked(); + v8::Local EventEmitter = + Nan::To(Nan::Get(events, Nan::New("EventEmitter").ToLocalChecked()).ToLocalChecked()) + .ToLocalChecked(); - Nan::SetPrototype(target, - Nan::Get(EventEmitter, Nan::New("prototype").ToLocalChecked()).ToLocalChecked()); + Nan::SetPrototype(target, Nan::Get(EventEmitter, Nan::New("prototype").ToLocalChecked()).ToLocalChecked()); Nan::CallAsFunction(EventEmitter, target, 0, nullptr); mbgl::Log::setObserver(std::make_unique(target)); diff --git a/platform/node/src/node_request.cpp b/platform/node/src/node_request.cpp index c8901f07a19..4e5615ebea7 100644 --- a/platform/node/src/node_request.cpp +++ b/platform/node/src/node_request.cpp @@ -7,12 +7,10 @@ namespace node_mbgl { -NodeRequest::NodeRequest( - mbgl::FileSource::Callback callback_, - NodeAsyncRequest* asyncRequest_) +NodeRequest::NodeRequest(mbgl::FileSource::Callback callback_, NodeAsyncRequest* asyncRequest_) : callback(std::move(callback_)), - asyncRequest(asyncRequest_) { - asyncRequest->request = this; + asyncRequest(asyncRequest_) { + asyncRequest->request = this; } NodeRequest::~NodeRequest() { @@ -53,13 +51,9 @@ void NodeRequest::New(const Nan::FunctionCallbackInfo& info) { request->Ref(); Nan::Set(info.This(), Nan::New("url").ToLocalChecked(), info[3]); Nan::Set(info.This(), Nan::New("kind").ToLocalChecked(), info[4]); - v8::Local argv[] = { info.This() }; + v8::Local argv[] = {info.This()}; request->asyncResource->runInAsyncScope( - Nan::To(target->handle()->GetInternalField(1)).ToLocalChecked(), - "request", - 1, - argv - ); + Nan::To(target->handle()->GetInternalField(1)).ToLocalChecked(), "request", 1, argv); info.GetReturnValue().Set(info.This()); } @@ -84,15 +78,11 @@ void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo& inf if (Nan::Has(err, msg).FromJust()) { response.error = std::make_unique( - mbgl::Response::Error::Reason::Other, - *Nan::Utf8String(Nan::Get(err, msg).ToLocalChecked()) - ); + mbgl::Response::Error::Reason::Other, *Nan::Utf8String(Nan::Get(err, msg).ToLocalChecked())); } } else if (info[0]->IsString()) { - response.error = std::make_unique( - mbgl::Response::Error::Reason::Other, - *Nan::Utf8String(info[0]) - ); + response.error = std::make_unique(mbgl::Response::Error::Reason::Other, + *Nan::Utf8String(info[0])); } else if (info.Length() < 2 || !info[1]->IsObject()) { request->unrefRequest(); return Nan::ThrowTypeError("Second argument must be a response object"); @@ -100,33 +90,30 @@ void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo& inf auto res = Nan::To(info[1]).ToLocalChecked(); if (Nan::Has(res, Nan::New("modified").ToLocalChecked()).FromJust()) { - const double modified = Nan::To(Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()).FromJust(); + const double modified = + Nan::To(Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()).FromJust(); if (!std::isnan(modified)) { - response.modified = mbgl::Timestamp{ mbgl::Seconds( - static_cast(modified / 1000)) }; + response.modified = mbgl::Timestamp{mbgl::Seconds(static_cast(modified / 1000))}; } } if (Nan::Has(res, Nan::New("expires").ToLocalChecked()).FromJust()) { - const double expires = Nan::To(Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()).FromJust(); + const double expires = + Nan::To(Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()).FromJust(); if (!std::isnan(expires)) { - response.expires = mbgl::Timestamp{ mbgl::Seconds( - static_cast(expires / 1000)) }; + response.expires = mbgl::Timestamp{mbgl::Seconds(static_cast(expires / 1000))}; } } if (Nan::Has(res, Nan::New("etag").ToLocalChecked()).FromJust()) { const Nan::Utf8String etag(Nan::Get(res, Nan::New("etag").ToLocalChecked()).ToLocalChecked()); - response.etag = std::string { *etag, size_t(etag.length()) }; + response.etag = std::string{*etag, size_t(etag.length())}; } if (Nan::Has(res, Nan::New("data").ToLocalChecked()).FromJust()) { auto data = Nan::Get(res, Nan::New("data").ToLocalChecked()).ToLocalChecked(); if (node::Buffer::HasInstance(data)) { - response.data = std::make_shared( - node::Buffer::Data(data), - node::Buffer::Length(data) - ); + response.data = std::make_shared(node::Buffer::Data(data), node::Buffer::Length(data)); } else { request->unrefRequest(); return Nan::ThrowTypeError("Response data must be a Buffer"); diff --git a/platform/node/src/node_request.hpp b/platform/node/src/node_request.hpp index 71cccfe9ddb..fa8f8752e0d 100644 --- a/platform/node/src/node_request.hpp +++ b/platform/node/src/node_request.hpp @@ -21,9 +21,7 @@ struct NodeAsyncRequest : public mbgl::AsyncRequest { }; class NodeRequest : public Nan::ObjectWrap { - public: - NodeRequest(mbgl::FileSource::Callback, NodeAsyncRequest*); ~NodeRequest() override; diff --git a/platform/node/src/util/async_queue.hpp b/platform/node/src/util/async_queue.hpp index adf40e3ff5d..79d3d641849 100644 --- a/platform/node/src/util/async_queue.hpp +++ b/platform/node/src/util/async_queue.hpp @@ -15,9 +15,10 @@ namespace util { template class AsyncQueue { public: - AsyncQueue(uv_loop_t *loop, std::function fn) : callback(std::move(fn)) { + AsyncQueue(uv_loop_t *loop, std::function fn) + : callback(std::move(fn)) { async.data = this; - uv_async_init(loop, &async, [](uv_async_t* handle) { + uv_async_init(loop, &async, [](uv_async_t *handle) { auto q = reinterpret_cast(handle->data); q->process(); }); diff --git a/platform/qt/app/main.cpp b/platform/qt/app/main.cpp index 134ccddba95..ce19aeb0f1c 100644 --- a/platform/qt/app/main.cpp +++ b/platform/qt/app/main.cpp @@ -2,8 +2,7 @@ #include -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { QApplication app(argc, argv); QMapLibreGL::Settings settings; diff --git a/platform/qt/app/mapwindow.cpp b/platform/qt/app/mapwindow.cpp index 54c457fb577..96a1d1a24f5 100644 --- a/platform/qt/app/mapwindow.cpp +++ b/platform/qt/app/mapwindow.cpp @@ -12,20 +12,17 @@ int kAnimationDuration = 10000; MapWindow::MapWindow(const QMapLibreGL::Settings &settings) - : m_settings(settings) -{ + : m_settings(settings) { setWindowIcon(QIcon(":icon.png")); } -MapWindow::~MapWindow() -{ +MapWindow::~MapWindow() { // Make sure we have a valid context so we // can delete the QMapLibreGL::Map. makeCurrent(); } -void MapWindow::selfTest() -{ +void MapWindow::selfTest() { if (m_bearingAnimation) { m_bearingAnimation->setDuration(kAnimationDuration); m_bearingAnimation->setEndValue(m_map->bearing() + 360 * 4); @@ -43,25 +40,21 @@ qreal MapWindow::pixelRatio() { return devicePixelRatioF(); } - -void MapWindow::animationFinished() -{ - qDebug() << "Animation ticks/s: " << m_animationTicks / static_cast(kAnimationDuration) * 1000.; - qDebug() << "Frame draws/s: " << m_frameDraws / static_cast(kAnimationDuration) * 1000.; +void MapWindow::animationFinished() { + qDebug() << "Animation ticks/s: " << m_animationTicks / static_cast(kAnimationDuration) * 1000.; + qDebug() << "Frame draws/s: " << m_frameDraws / static_cast(kAnimationDuration) * 1000.; qApp->quit(); } -void MapWindow::animationValueChanged() -{ +void MapWindow::animationValueChanged() { m_animationTicks++; } -void MapWindow::changeStyle() -{ +void MapWindow::changeStyle() { static uint8_t currentStyleIndex; - auto& styles = m_map->defaultStyles(); + auto &styles = m_map->defaultStyles(); m_map->setStyleUrl(styles[currentStyleIndex].first); setWindowTitle(QString("MapLibre GL: ") + styles[currentStyleIndex].second); @@ -73,13 +66,12 @@ void MapWindow::changeStyle() m_sourceAdded = false; } -void MapWindow::keyPressEvent(QKeyEvent *ev) -{ +void MapWindow::keyPressEvent(QKeyEvent *ev) { switch (ev->key()) { - case Qt::Key_S: - changeStyle(); - break; - case Qt::Key_L: { + case Qt::Key_S: + changeStyle(); + break; + case Qt::Key_L: { if (m_sourceAdded) { return; } @@ -246,25 +238,23 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) extrusionBase["property"] = "min_height"; m_map->setPaintProperty("3d-buildings", "fill-extrusion-base", extrusionBase); - } - break; - case Qt::Key_1: { + } break; + case Qt::Key_1: { if (m_symbolAnnotationId.isNull()) { QMapLibreGL::Coordinate coordinate = m_map->coordinate(); - QMapLibreGL::SymbolAnnotation symbol { coordinate, "default_marker" }; + QMapLibreGL::SymbolAnnotation symbol{coordinate, "default_marker"}; m_map->addAnnotationIcon("default_marker", QImage(":default_marker.svg")); m_symbolAnnotationId = m_map->addAnnotation(QVariant::fromValue(symbol)); } else { m_map->removeAnnotation(m_symbolAnnotationId.toUInt()); m_symbolAnnotationId.clear(); } - } - break; - case Qt::Key_2: { + } break; + case Qt::Key_2: { if (m_lineAnnotationId.isNull()) { QMapLibreGL::Coordinates coordinates; - coordinates.push_back(m_map->coordinateForPixel({ 0, 0 })); - coordinates.push_back(m_map->coordinateForPixel({ qreal(size().width()), qreal(size().height()) })); + coordinates.push_back(m_map->coordinateForPixel({0, 0})); + coordinates.push_back(m_map->coordinateForPixel({qreal(size().width()), qreal(size().height())})); QMapLibreGL::CoordinatesCollection collection; collection.push_back(coordinates); @@ -272,7 +262,8 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) QMapLibreGL::CoordinatesCollections lineGeometry; lineGeometry.push_back(collection); - QMapLibreGL::ShapeAnnotationGeometry annotationGeometry(QMapLibreGL::ShapeAnnotationGeometry::LineStringType, lineGeometry); + QMapLibreGL::ShapeAnnotationGeometry annotationGeometry( + QMapLibreGL::ShapeAnnotationGeometry::LineStringType, lineGeometry); QMapLibreGL::LineAnnotation line; line.geometry = annotationGeometry; @@ -284,15 +275,14 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->removeAnnotation(m_lineAnnotationId.toUInt()); m_lineAnnotationId.clear(); } - } - break; - case Qt::Key_3: { + } break; + case Qt::Key_3: { if (m_fillAnnotationId.isNull()) { QMapLibreGL::Coordinates coordinates; - coordinates.push_back(m_map->coordinateForPixel({ qreal(size().width()), 0 })); - coordinates.push_back(m_map->coordinateForPixel({ qreal(size().width()), qreal(size().height()) })); - coordinates.push_back(m_map->coordinateForPixel({ 0, qreal(size().height()) })); - coordinates.push_back(m_map->coordinateForPixel({ 0, 0 })); + coordinates.push_back(m_map->coordinateForPixel({qreal(size().width()), 0})); + coordinates.push_back(m_map->coordinateForPixel({qreal(size().width()), qreal(size().height())})); + coordinates.push_back(m_map->coordinateForPixel({0, qreal(size().height())})); + coordinates.push_back(m_map->coordinateForPixel({0, 0})); QMapLibreGL::CoordinatesCollection collection; collection.push_back(coordinates); @@ -300,7 +290,8 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) QMapLibreGL::CoordinatesCollections fillGeometry; fillGeometry.push_back(collection); - QMapLibreGL::ShapeAnnotationGeometry annotationGeometry(QMapLibreGL::ShapeAnnotationGeometry::PolygonType, fillGeometry); + QMapLibreGL::ShapeAnnotationGeometry annotationGeometry( + QMapLibreGL::ShapeAnnotationGeometry::PolygonType, fillGeometry); QMapLibreGL::FillAnnotation fill; fill.geometry = annotationGeometry; @@ -312,9 +303,8 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->removeAnnotation(m_fillAnnotationId.toUInt()); m_fillAnnotationId.clear(); } - } - break; - case Qt::Key_5: { + } break; + case Qt::Key_5: { if (m_map->layerExists("circleLayer")) { m_map->removeLayer("circleLayer"); m_map->removeSource("circleSource"); @@ -344,53 +334,37 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->setPaintProperty("circleLayer", "circle-radius", 10.0); m_map->setPaintProperty("circleLayer", "circle-color", QColor("black")); } - } - break; - case Qt::Key_6: { + } break; + case Qt::Key_6: { if (m_map->layerExists("innerCirclesLayer") || m_map->layerExists("outerCirclesLayer")) { m_map->removeLayer("innerCirclesLayer"); m_map->removeLayer("outerCirclesLayer"); m_map->removeSource("innerCirclesSource"); m_map->removeSource("outerCirclesSource"); } else { - auto makePoint = [&] (double dx, double dy, const QString &color) { + auto makePoint = [&](double dx, double dy, const QString &color) { auto coordinate = m_map->coordinate(); coordinate.first += dx; coordinate.second += dy; - return QMapLibreGL::Feature{QMapLibreGL::Feature::PointType, - {{{coordinate}}}, {{"color", color}}, {}}; + return QMapLibreGL::Feature{ + QMapLibreGL::Feature::PointType, {{{coordinate}}}, {{"color", color}}, {}}; }; // multiple features by QVector QVector inner{ - makePoint(0.001, 0, "red"), - makePoint(0, 0.001, "green"), - makePoint(0, -0.001, "blue") - }; + makePoint(0.001, 0, "red"), makePoint(0, 0.001, "green"), makePoint(0, -0.001, "blue")}; - m_map->addSource("innerCirclesSource", - {{"type", "geojson"}, {"data", QVariant::fromValue(inner)}}); - m_map->addLayer({ - {"id", "innerCirclesLayer"}, - {"type", "circle"}, - {"source", "innerCirclesSource"} - }); + m_map->addSource("innerCirclesSource", {{"type", "geojson"}, {"data", QVariant::fromValue(inner)}}); + m_map->addLayer({{"id", "innerCirclesLayer"}, {"type", "circle"}, {"source", "innerCirclesSource"}}); // multiple features by QList - QList outer{ - makePoint( 0.002, 0.002, "cyan"), - makePoint(-0.002, 0.002, "magenta"), - makePoint( 0.002, -0.002, "yellow"), - makePoint(-0.002, -0.002, "black") - }; + QList outer{makePoint(0.002, 0.002, "cyan"), + makePoint(-0.002, 0.002, "magenta"), + makePoint(0.002, -0.002, "yellow"), + makePoint(-0.002, -0.002, "black")}; - m_map->addSource("outerCirclesSource", - {{"type", "geojson"}, {"data", QVariant::fromValue(outer)}}); - m_map->addLayer({ - {"id", "outerCirclesLayer"}, - {"type", "circle"}, - {"source", "outerCirclesSource"} - }); + m_map->addSource("outerCirclesSource", {{"type", "geojson"}, {"data", QVariant::fromValue(outer)}}); + m_map->addLayer({{"id", "outerCirclesLayer"}, {"type", "circle"}, {"source", "outerCirclesSource"}}); QVariantList getColor{"get", "color"}; m_map->setPaintProperty("innerCirclesLayer", "circle-radius", 10.0); @@ -398,17 +372,15 @@ void MapWindow::keyPressEvent(QKeyEvent *ev) m_map->setPaintProperty("outerCirclesLayer", "circle-radius", 15.0); m_map->setPaintProperty("outerCirclesLayer", "circle-color", getColor); } - } - break; - default: - break; + } break; + default: + break; } ev->accept(); } -void MapWindow::mousePressEvent(QMouseEvent *ev) -{ +void MapWindow::mousePressEvent(QMouseEvent *ev) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) m_lastPos = ev->position(); #else @@ -432,8 +404,7 @@ void MapWindow::mousePressEvent(QMouseEvent *ev) ev->accept(); } -void MapWindow::mouseMoveEvent(QMouseEvent *ev) -{ +void MapWindow::mouseMoveEvent(QMouseEvent *ev) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) const QPointF &position = ev->position(); #else @@ -455,8 +426,7 @@ void MapWindow::mouseMoveEvent(QMouseEvent *ev) ev->accept(); } -void MapWindow::wheelEvent(QWheelEvent *ev) -{ +void MapWindow::wheelEvent(QWheelEvent *ev) { if (ev->angleDelta().y() == 0) { return; } @@ -474,8 +444,7 @@ void MapWindow::wheelEvent(QWheelEvent *ev) ev->accept(); } -void MapWindow::initializeGL() -{ +void MapWindow::initializeGL() { m_map.reset(new QMapLibreGL::Map(nullptr, m_settings, size(), pixelRatio())); connect(m_map.get(), SIGNAL(needsRendering()), this, SLOT(update())); @@ -497,8 +466,7 @@ void MapWindow::initializeGL() connect(m_zoomAnimation, &QPropertyAnimation::valueChanged, this, &MapWindow::animationValueChanged); } -void MapWindow::paintGL() -{ +void MapWindow::paintGL() { m_frameDraws++; m_map->resize(size()); m_map->setFramebufferObject(defaultFramebufferObject(), size() * pixelRatio()); diff --git a/platform/qt/app/mapwindow.hpp b/platform/qt/app/mapwindow.hpp index 06b6fb02337..d03483356dd 100644 --- a/platform/qt/app/mapwindow.hpp +++ b/platform/qt/app/mapwindow.hpp @@ -18,8 +18,7 @@ class QWheelEvent; QT_END_NAMESPACE -class MapWindow : public QOpenGLWidget -{ +class MapWindow : public QOpenGLWidget { Q_OBJECT public: diff --git a/platform/qt/include/QMapLibreGL/export.hpp b/platform/qt/include/QMapLibreGL/export.hpp index 9d4b14d3675..4017e5dc442 100644 --- a/platform/qt/include/QMapLibreGL/export.hpp +++ b/platform/qt/include/QMapLibreGL/export.hpp @@ -4,13 +4,13 @@ // This header follows the Qt coding style: https://wiki.qt.io/Qt_Coding_Style #if !defined(QT_MAPLIBREGL_STATIC) -# if defined(QT_BUILD_MAPLIBREGL_LIB) -# define Q_MAPLIBREGL_EXPORT Q_DECL_EXPORT -# else -# define Q_MAPLIBREGL_EXPORT Q_DECL_IMPORT -# endif +#if defined(QT_BUILD_MAPLIBREGL_LIB) +#define Q_MAPLIBREGL_EXPORT Q_DECL_EXPORT #else -# define Q_MAPLIBREGL_EXPORT +#define Q_MAPLIBREGL_EXPORT Q_DECL_IMPORT +#endif +#else +#define Q_MAPLIBREGL_EXPORT #endif #endif // QMAPLIBRE_EXPORT_H diff --git a/platform/qt/include/QMapLibreGL/map.hpp b/platform/qt/include/QMapLibreGL/map.hpp index 4b6450ca60d..a8f560e57c6 100644 --- a/platform/qt/include/QMapLibreGL/map.hpp +++ b/platform/qt/include/QMapLibreGL/map.hpp @@ -21,8 +21,7 @@ class MapPrivate; // This header follows the Qt coding style: https://wiki.qt.io/Qt_Coding_Style -class Q_MAPLIBREGL_EXPORT Map : public QObject -{ +class Q_MAPLIBREGL_EXPORT Map : public QObject { Q_OBJECT Q_PROPERTY(double latitude READ latitude WRITE setLatitude) Q_PROPERTY(double longitude READ longitude WRITE setLongitude) @@ -70,10 +69,7 @@ class Q_MAPLIBREGL_EXPORT Map : public QObject NorthLeftwards, }; - Map(QObject* parent = 0, - const Settings& = Settings(), - const QSize& size = QSize(), - qreal pixelRatio = 1); + Map(QObject *parent = 0, const Settings & = Settings(), const QSize &size = QSize(), qreal pixelRatio = 1); virtual ~Map(); QString styleJson() const; @@ -112,7 +108,7 @@ class Q_MAPLIBREGL_EXPORT Map : public QObject void setCoordinate(const Coordinate &); void setCoordinateZoom(const Coordinate &, double zoom); - void jumpTo(const CameraOptions&); + void jumpTo(const CameraOptions &); void setGestureInProgress(bool inProgress); @@ -139,26 +135,23 @@ class Q_MAPLIBREGL_EXPORT Map : public QObject Coordinate coordinateForPixel(const QPointF &) const; CoordinateZoom coordinateZoomForBounds(const Coordinate &sw, const Coordinate &ne) const; - CoordinateZoom coordinateZoomForBounds(const Coordinate &sw, - const Coordinate &ne, - double bearing, - double pitch); + CoordinateZoom coordinateZoomForBounds(const Coordinate &sw, const Coordinate &ne, double bearing, double pitch); void setMargins(const QMargins &margins); QMargins margins() const; - void addSource(const QString &sourceID, const QVariantMap& params); + void addSource(const QString &sourceID, const QVariantMap ¶ms); bool sourceExists(const QString &sourceID); - void updateSource(const QString &sourceID, const QVariantMap& params); + void updateSource(const QString &sourceID, const QVariantMap ¶ms); void removeSource(const QString &sourceID); void addImage(const QString &name, const QImage &sprite); void removeImage(const QString &name); void addCustomLayer(const QString &id, - std::unique_ptr host, - const QString &before = QString()); - void addLayer(const QVariantMap ¶ms, const QString& before = QString()); + std::unique_ptr host, + const QString &before = QString()); + void addLayer(const QVariantMap ¶ms, const QString &before = QString()); bool layerExists(const QString &id); void removeLayer(const QString &id); diff --git a/platform/qt/include/QMapLibreGL/settings.hpp b/platform/qt/include/QMapLibreGL/settings.hpp index d814dfc8b70..6ffdde8239f 100644 --- a/platform/qt/include/QMapLibreGL/settings.hpp +++ b/platform/qt/include/QMapLibreGL/settings.hpp @@ -11,16 +11,13 @@ // This header follows the Qt coding style: https://wiki.qt.io/Qt_Coding_Style // TODO: this will be wrapped at some point -namespace mbgl -{ - class TileServerOptions; +namespace mbgl { +class TileServerOptions; } - namespace QMapLibreGL { -class Q_MAPLIBREGL_EXPORT Settings -{ +class Q_MAPLIBREGL_EXPORT Settings { public: Settings(); diff --git a/platform/qt/include/QMapLibreGL/types.hpp b/platform/qt/include/QMapLibreGL/types.hpp index ce601d3182a..486326993fd 100644 --- a/platform/qt/include/QMapLibreGL/types.hpp +++ b/platform/qt/include/QMapLibreGL/types.hpp @@ -28,9 +28,14 @@ struct Q_MAPLIBREGL_EXPORT Feature { }; /*! Class constructor. */ - Feature(Type type_ = PointType, const CoordinatesCollections& geometry_ = CoordinatesCollections(), - const QVariantMap& properties_ = QVariantMap(), const QVariant& id_ = QVariant()) - : type(type_), geometry(geometry_), properties(properties_), id(id_) {} + Feature(Type type_ = PointType, + const CoordinatesCollections& geometry_ = CoordinatesCollections(), + const QVariantMap& properties_ = QVariantMap(), + const QVariant& id_ = QVariant()) + : type(type_), + geometry(geometry_), + properties(properties_), + id(id_) {} Type type; CoordinatesCollections geometry; @@ -47,8 +52,10 @@ struct Q_MAPLIBREGL_EXPORT ShapeAnnotationGeometry { }; /*! Class constructor. */ - ShapeAnnotationGeometry(Type type_ = LineStringType, const CoordinatesCollections& geometry_ = CoordinatesCollections()) - : type(type_), geometry(geometry_) {} + ShapeAnnotationGeometry(Type type_ = LineStringType, + const CoordinatesCollections& geometry_ = CoordinatesCollections()) + : type(type_), + geometry(geometry_) {} Type type; CoordinatesCollections geometry; @@ -61,9 +68,14 @@ struct Q_MAPLIBREGL_EXPORT SymbolAnnotation { struct Q_MAPLIBREGL_EXPORT LineAnnotation { /*! Class constructor. */ - LineAnnotation(const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), float opacity_ = 1.0f, - float width_ = 1.0f, const QColor& color_ = Qt::black) - : geometry(geometry_), opacity(opacity_), width(width_), color(color_) {} + LineAnnotation(const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), + float opacity_ = 1.0f, + float width_ = 1.0f, + const QColor& color_ = Qt::black) + : geometry(geometry_), + opacity(opacity_), + width(width_), + color(color_) {} ShapeAnnotationGeometry geometry; float opacity; @@ -73,9 +85,14 @@ struct Q_MAPLIBREGL_EXPORT LineAnnotation { struct Q_MAPLIBREGL_EXPORT FillAnnotation { /*! Class constructor. */ - FillAnnotation(const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), float opacity_ = 1.0f, - const QColor& color_ = Qt::black, const QVariant& outlineColor_ = QVariant()) - : geometry(geometry_), opacity(opacity_), color(color_), outlineColor(outlineColor_) {} + FillAnnotation(const ShapeAnnotationGeometry& geometry_ = ShapeAnnotationGeometry(), + float opacity_ = 1.0f, + const QColor& color_ = Qt::black, + const QVariant& outlineColor_ = QVariant()) + : geometry(geometry_), + opacity(opacity_), + color(color_), + outlineColor(outlineColor_) {} ShapeAnnotationGeometry geometry; float opacity; diff --git a/platform/qt/src/map.cpp b/platform/qt/src/map.cpp index b0ababa80b1..00952648b6f 100644 --- a/platform/qt/src/map.cpp +++ b/platform/qt/src/map.cpp @@ -63,37 +63,42 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4805) +#pragma warning(disable : 4805) #endif // mbgl::NorthOrientation -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthUpwards) == mbgl::underlying_type(mbgl::NorthOrientation::Upwards), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthRightwards) == mbgl::underlying_type(mbgl::NorthOrientation::Rightwards), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthDownwards) == mbgl::underlying_type(mbgl::NorthOrientation::Downwards), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthLeftwards) == mbgl::underlying_type(mbgl::NorthOrientation::Leftwards), "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthUpwards) == + mbgl::underlying_type(mbgl::NorthOrientation::Upwards), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthRightwards) == + mbgl::underlying_type(mbgl::NorthOrientation::Rightwards), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthDownwards) == + mbgl::underlying_type(mbgl::NorthOrientation::Downwards), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Map::NorthLeftwards) == + mbgl::underlying_type(mbgl::NorthOrientation::Leftwards), + "error"); #ifdef _MSC_VER #pragma warning(pop) #endif - namespace { QThreadStorage> loop; // Conversion helper functions. -mbgl::Size sanitizedSize(const QSize& size) { - return mbgl::Size { +mbgl::Size sanitizedSize(const QSize &size) { + return mbgl::Size{ mbgl::util::max(0u, static_cast(size.width())), mbgl::util::max(0u, static_cast(size.height())), }; }; std::unique_ptr toStyleImage(const QString &id, const QImage &sprite) { - const QImage swapped = sprite - .rgbSwapped() - .convertToFormat(QImage::Format_ARGB32_Premultiplied); + const QImage swapped = sprite.rgbSwapped().convertToFormat(QImage::Format_ARGB32_Premultiplied); #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) auto img = std::make_unique(swapped.sizeInBytes()); @@ -105,73 +110,75 @@ std::unique_ptr toStyleImage(const QString &id, const QImage return std::make_unique( id.toStdString(), - mbgl::PremultipliedImage( - { static_cast(swapped.width()), static_cast(swapped.height()) }, - std::move(img)), + mbgl::PremultipliedImage({static_cast(swapped.width()), static_cast(swapped.height())}, + std::move(img)), 1.0); } mbgl::MapOptions mapOptionsFromSettings(const QMapLibreGL::Settings &settings, const QSize &size, qreal pixelRatio) { return std::move(mbgl::MapOptions() - .withSize(sanitizedSize(size)) - .withPixelRatio(pixelRatio) - .withMapMode(static_cast(settings.mapMode())) - .withConstrainMode(static_cast(settings.constrainMode())) - .withViewportMode(static_cast(settings.viewportMode()))); + .withSize(sanitizedSize(size)) + .withPixelRatio(pixelRatio) + .withMapMode(static_cast(settings.mapMode())) + .withConstrainMode(static_cast(settings.constrainMode())) + .withViewportMode(static_cast(settings.viewportMode()))); } mbgl::ResourceOptions resourceOptionsFromSettings(const QMapLibreGL::Settings &settings) { return std::move(mbgl::ResourceOptions() - .withApiKey(settings.apiKey().toStdString()) - .withAssetPath(settings.assetPath().toStdString()) - .withTileServerOptions(*settings.tileServerOptionsInternal()) - .withCachePath(settings.cacheDatabasePath().toStdString()) - .withMaximumCacheSize(settings.cacheDatabaseMaximumSize())); + .withApiKey(settings.apiKey().toStdString()) + .withAssetPath(settings.assetPath().toStdString()) + .withTileServerOptions(*settings.tileServerOptionsInternal()) + .withCachePath(settings.cacheDatabasePath().toStdString()) + .withMaximumCacheSize(settings.cacheDatabaseMaximumSize())); } mbgl::ClientOptions clientOptionsFromSettings(const QMapLibreGL::Settings &settings) { return std::move(mbgl::ClientOptions() - .withName(settings.clientName().toStdString()) - .withVersion(settings.clientVersion().toStdString())); + .withName(settings.clientName().toStdString()) + .withVersion(settings.clientVersion().toStdString())); } - -std::optional asAnnotation(const QMapLibreGL::Annotation & annotation) { +std::optional asAnnotation(const QMapLibreGL::Annotation &annotation) { auto asGeometry = [](const QMapLibreGL::ShapeAnnotationGeometry &geometry) { mbgl::ShapeAnnotationGeometry result; switch (geometry.type) { - case QMapLibreGL::ShapeAnnotationGeometry::LineStringType: - result = QMapLibreGL::GeoJSON::asLineString(geometry.geometry.first().first()); - break; - case QMapLibreGL::ShapeAnnotationGeometry::PolygonType: - result = QMapLibreGL::GeoJSON::asPolygon(geometry.geometry.first()); - break; - case QMapLibreGL::ShapeAnnotationGeometry::MultiLineStringType: - result = QMapLibreGL::GeoJSON::asMultiLineString(geometry.geometry.first()); - break; - case QMapLibreGL::ShapeAnnotationGeometry::MultiPolygonType: - result = QMapLibreGL::GeoJSON::asMultiPolygon(geometry.geometry); - break; + case QMapLibreGL::ShapeAnnotationGeometry::LineStringType: + result = QMapLibreGL::GeoJSON::asLineString(geometry.geometry.first().first()); + break; + case QMapLibreGL::ShapeAnnotationGeometry::PolygonType: + result = QMapLibreGL::GeoJSON::asPolygon(geometry.geometry.first()); + break; + case QMapLibreGL::ShapeAnnotationGeometry::MultiLineStringType: + result = QMapLibreGL::GeoJSON::asMultiLineString(geometry.geometry.first()); + break; + case QMapLibreGL::ShapeAnnotationGeometry::MultiPolygonType: + result = QMapLibreGL::GeoJSON::asMultiPolygon(geometry.geometry); + break; } return result; }; if (annotation.canConvert()) { QMapLibreGL::SymbolAnnotation symbolAnnotation = annotation.value(); - QMapLibreGL::Coordinate& pair = symbolAnnotation.geometry; - return { mbgl::SymbolAnnotation(mbgl::Point { pair.second, pair.first }, symbolAnnotation.icon.toStdString()) }; + QMapLibreGL::Coordinate &pair = symbolAnnotation.geometry; + return { + mbgl::SymbolAnnotation(mbgl::Point{pair.second, pair.first}, symbolAnnotation.icon.toStdString())}; } else if (annotation.canConvert()) { QMapLibreGL::LineAnnotation lineAnnotation = annotation.value(); auto color = mbgl::Color::parse(mbgl::style::conversion::convertColor(lineAnnotation.color)); - return { mbgl::LineAnnotation(asGeometry(lineAnnotation.geometry), lineAnnotation.opacity, lineAnnotation.width, { *color }) }; + return {mbgl::LineAnnotation( + asGeometry(lineAnnotation.geometry), lineAnnotation.opacity, lineAnnotation.width, {*color})}; } else if (annotation.canConvert()) { QMapLibreGL::FillAnnotation fillAnnotation = annotation.value(); auto color = mbgl::Color::parse(mbgl::style::conversion::convertColor(fillAnnotation.color)); if (fillAnnotation.outlineColor.canConvert()) { - auto outlineColor = mbgl::Color::parse(mbgl::style::conversion::convertColor(fillAnnotation.outlineColor.value())); - return { mbgl::FillAnnotation(asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, { *color }, { *outlineColor }) }; + auto outlineColor = mbgl::Color::parse( + mbgl::style::conversion::convertColor(fillAnnotation.outlineColor.value())); + return {mbgl::FillAnnotation( + asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, {*color}, {*outlineColor})}; } else { - return { mbgl::FillAnnotation(asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, { *color }, {}) }; + return {mbgl::FillAnnotation(asGeometry(fillAnnotation.geometry), fillAnnotation.opacity, {*color}, {})}; } } @@ -181,7 +188,6 @@ std::optional asAnnotation(const QMapLibreGL::Annotation & ann } // namespace - namespace QMapLibreGL { /*! @@ -204,43 +210,53 @@ namespace QMapLibreGL { This enum represents the last changed occurred to the map state. - \value MapChangeRegionWillChange A region of the map will change, like - when resizing the map. + \value MapChangeRegionWillChange A region of the map + will change, like when resizing the map. - \value MapChangeRegionWillChangeAnimated Not in use by QMapLibreGL::Map. + \value MapChangeRegionWillChangeAnimated Not in use by + QMapLibreGL::Map. - \value MapChangeRegionIsChanging A region of the map is changing. + \value MapChangeRegionIsChanging A region of the map is + changing. - \value MapChangeRegionDidChange A region of the map finished changing. + \value MapChangeRegionDidChange A region of the map + finished changing. - \value MapChangeRegionDidChangeAnimated Not in use by QMapLibreGL::Map. + \value MapChangeRegionDidChangeAnimated Not in use by + QMapLibreGL::Map. - \value MapChangeWillStartLoadingMap The map is getting loaded. This state - is set only once right after QMapLibreGL::Map is created and a style is set. + \value MapChangeWillStartLoadingMap The map is getting + loaded. This state is set only once right after QMapLibreGL::Map is created + and a style is set. - \value MapChangeDidFinishLoadingMap All the resources were loaded and parsed - and the map is fully rendered. After this state the mapChanged() signal won't fire again unless - the is some client side interaction with the map or a tile expires, causing a new resource - to be requested from the network. + \value MapChangeDidFinishLoadingMap All the resources were + loaded and parsed and the map is fully rendered. After this state the + mapChanged() signal won't fire again unless the is some client side + interaction with the map or a tile expires, causing a new resource to be + requested from the network. - \value MapChangeDidFailLoadingMap An error occurred when loading the map. + \value MapChangeDidFailLoadingMap An error occurred when + loading the map. - \value MapChangeWillStartRenderingFrame Just before rendering the frame. This - is the state of the map just after calling render() and might happened many times before - the map is fully loaded. + \value MapChangeWillStartRenderingFrame Just before rendering + the frame. This is the state of the map just after calling render() and might + happened many times before the map is fully loaded. - \value MapChangeDidFinishRenderingFrame The current frame was rendered but was - left in a partial state. Some parts of the map might be missing because have not arrived - from the network or are being parsed. + \value MapChangeDidFinishRenderingFrame The current frame was + rendered but was left in a partial state. Some parts of the map might be + missing because have not arrived from the network or are being parsed. - \value MapChangeDidFinishRenderingFrameFullyRendered The current frame was fully rendered. + \value MapChangeDidFinishRenderingFrameFullyRendered The current frame was + fully rendered. - \value MapChangeWillStartRenderingMap Set once when the map is about to get - rendered for the first time. + \value MapChangeWillStartRenderingMap Set once when the map + is about to get rendered for the first time. - \value MapChangeDidFinishRenderingMap Not in use by QMapLibreGL::Map. + \value MapChangeDidFinishRenderingMap Not in use by + QMapLibreGL::Map. - \value MapChangeDidFinishRenderingMapFullyRendered Map is fully loaded and rendered. + \value MapChangeDidFinishRenderingMapFullyRendered Map is fully loaded + and rendered. \value MapChangeDidFinishLoadingStyle The style was loaded. @@ -254,10 +270,11 @@ namespace QMapLibreGL { This enum represents map loading failure type. - \value StyleParseFailure Failure to parse the style. - \value StyleLoadFailure Failure to load the style data. - \value NotFoundFailure Failure to obtain style resource file. - \value UnknownFailure Unknown map loading failure. + \value StyleParseFailure Failure to parse the + style. \value StyleLoadFailure Failure to load + the style data. \value NotFoundFailure Failure + to obtain style resource file. \value UnknownFailure Unknown map loading + failure. \sa mapLoadingFailed() */ @@ -265,10 +282,11 @@ namespace QMapLibreGL { /*! \enum QMapLibreGL::Map::NorthOrientation - This enum sets the orientation of the north bearing. It will directly affect bearing when - resetting the north (i.e. setting bearing to 0). + This enum sets the orientation of the north bearing. It will directly affect + bearing when resetting the north (i.e. setting bearing to 0). - \value NorthUpwards The north is pointing up in the map. This is usually how maps are oriented. + \value NorthUpwards The north is pointing up in the map. This is usually + how maps are oriented. \value NorthRightwards The north is pointing right. @@ -281,14 +299,13 @@ namespace QMapLibreGL { */ /*! - Constructs a QMapLibreGL::Map object with \a settings and sets \a parent_ as the parent - object. The \a settings cannot be changed after the object is constructed. The - \a size represents the size of the viewport and the \a pixelRatio the initial pixel - density of the screen. + Constructs a QMapLibreGL::Map object with \a settings and sets \a parent_ as + the parent object. The \a settings cannot be changed after the object is + constructed. The \a size represents the size of the viewport and the \a + pixelRatio the initial pixel density of the screen. */ -Map::Map(QObject *parent_, const Settings &settings, const QSize& size, qreal pixelRatio) - : QObject(parent_) -{ +Map::Map(QObject *parent_, const Settings &settings, const QSize &size, qreal pixelRatio) + : QObject(parent_) { assert(!size.isEmpty()); // Multiple QMapLibreGL::Map running on the same thread @@ -303,8 +320,7 @@ Map::Map(QObject *parent_, const Settings &settings, const QSize& size, qreal pi /*! Destroys this QMapLibreGL::Map. */ -Map::~Map() -{ +Map::~Map() { delete d_ptr; } @@ -319,13 +335,11 @@ Map::~Map() \note In case of a invalid style it will trigger a mapChanged signal with QMapLibreGL::Map::MapChangeDidFailLoadingMap as argument. */ -QString Map::styleJson() const -{ +QString Map::styleJson() const { return QString::fromStdString(d_ptr->mapObj->getStyle().getJSON()); } -void Map::setStyleJson(const QString &style) -{ +void Map::setStyleJson(const QString &style) { d_ptr->mapObj->getStyle().loadJSON(style.toStdString()); } @@ -344,13 +358,11 @@ void Map::setStyleJson(const QString &style) \note In case of a invalid style it will trigger a mapChanged signal with QMapLibreGL::Map::MapChangeDidFailLoadingMap as argument. */ -QString Map::styleUrl() const -{ +QString Map::styleUrl() const { return QString::fromStdString(d_ptr->mapObj->getStyle().getURL()); } -void Map::setStyleUrl(const QString &url) -{ +void Map::setStyleUrl(const QString &url) { d_ptr->mapObj->getStyle().loadURL(url.toStdString()); } @@ -361,32 +373,30 @@ void Map::setStyleUrl(const QString &url) Setting a latitude doesn't necessarily mean it will be accepted since QMapLibreGL::Map might constrain it within the limits of the Web Mercator projection. */ -double Map::latitude() const -{ +double Map::latitude() const { return d_ptr->mapObj->getCameraOptions(d_ptr->margins).center->latitude(); } -void Map::setLatitude(double latitude_) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng { latitude_, longitude() }).withPadding(d_ptr->margins)); +void Map::setLatitude(double latitude_) { + d_ptr->mapObj->jumpTo( + mbgl::CameraOptions().withCenter(mbgl::LatLng{latitude_, longitude()}).withPadding(d_ptr->margins)); } /*! \property QMapLibreGL::Map::longitude \brief the map current longitude in degrees. - Setting a longitude beyond the limits of the Web Mercator projection will make - the map wrap. As an example, setting the longitude to 360 is effectively the same - as setting it to 0. + Setting a longitude beyond the limits of the Web Mercator projection will + make the map wrap. As an example, setting the longitude to 360 is effectively + the same as setting it to 0. */ -double Map::longitude() const -{ +double Map::longitude() const { return d_ptr->mapObj->getCameraOptions(d_ptr->margins).center->longitude(); } -void Map::setLongitude(double longitude_) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withCenter(mbgl::LatLng { latitude(), longitude_ }).withPadding(d_ptr->margins)); +void Map::setLongitude(double longitude_) { + d_ptr->mapObj->jumpTo( + mbgl::CameraOptions().withCenter(mbgl::LatLng{latitude(), longitude_}).withPadding(d_ptr->margins)); } /*! @@ -402,33 +412,30 @@ void Map::setLongitude(double longitude_) \sa zoom() */ -double Map::scale() const -{ +double Map::scale() const { return std::pow(2.0, zoom()); } -void Map::setScale(double scale_, const QPointF ¢er) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withZoom(::log2(scale_)).withAnchor(mbgl::ScreenCoordinate { center.x(), center.y() })); +void Map::setScale(double scale_, const QPointF ¢er) { + d_ptr->mapObj->jumpTo( + mbgl::CameraOptions().withZoom(::log2(scale_)).withAnchor(mbgl::ScreenCoordinate{center.x(), center.y()})); } /*! \property QMapLibreGL::Map::zoom \brief the map zoom factor. - This property is used to zoom the map. When \a center is defined, the map will - zoom in the direction of the center. This function could be used for implementing - a pinch gesture or zooming by using the mouse scroll wheel. + This property is used to zoom the map. When \a center is defined, the map + will zoom in the direction of the center. This function could be used for + implementing a pinch gesture or zooming by using the mouse scroll wheel. \sa scale() */ -double Map::zoom() const -{ +double Map::zoom() const { return *d_ptr->mapObj->getCameraOptions().zoom; } -void Map::setZoom(double zoom_) -{ +void Map::setZoom(double zoom_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withZoom(zoom_).withPadding(d_ptr->margins)); } @@ -437,8 +444,7 @@ void Map::setZoom(double zoom_) \sa maximumZoom() */ -double Map::minimumZoom() const -{ +double Map::minimumZoom() const { return *d_ptr->mapObj->getBounds().minZoom; } @@ -447,8 +453,7 @@ double Map::minimumZoom() const \sa minimumZoom() */ -double Map::maximumZoom() const -{ +double Map::maximumZoom() const { return *d_ptr->mapObj->getBounds().maxZoom; } @@ -460,16 +465,14 @@ double Map::maximumZoom() const \sa margins() */ -Coordinate Map::coordinate() const -{ +Coordinate Map::coordinate() const { const mbgl::LatLng latLng = *d_ptr->mapObj->getCameraOptions(d_ptr->margins).center; return Coordinate(latLng.latitude(), latLng.longitude()); } -void Map::setCoordinate(const Coordinate &coordinate_) -{ +void Map::setCoordinate(const Coordinate &coordinate_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withCenter(mbgl::LatLng { coordinate_.first, coordinate_.second }) + .withCenter(mbgl::LatLng{coordinate_.first, coordinate_.second}) .withPadding(d_ptr->margins)); } @@ -484,10 +487,9 @@ void Map::setCoordinate(const Coordinate &coordinate_) \sa zoom() \sa coordinate() */ -void Map::setCoordinateZoom(const Coordinate &coordinate_, double zoom_) -{ +void Map::setCoordinateZoom(const Coordinate &coordinate_, double zoom_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withCenter(mbgl::LatLng { coordinate_.first, coordinate_.second }) + .withCenter(mbgl::LatLng{coordinate_.first, coordinate_.second}) .withZoom(zoom_) .withPadding(d_ptr->margins)); } @@ -495,16 +497,15 @@ void Map::setCoordinateZoom(const Coordinate &coordinate_, double zoom_) /*! Atomically jumps to the \a camera options. */ -void Map::jumpTo(const CameraOptions& camera) -{ +void Map::jumpTo(const CameraOptions &camera) { mbgl::CameraOptions mbglCamera; if (camera.center.isValid()) { const Coordinate center = camera.center.value(); - mbglCamera.center = mbgl::LatLng { center.first, center.second }; + mbglCamera.center = mbgl::LatLng{center.first, center.second}; } if (camera.anchor.isValid()) { const QPointF anchor = camera.anchor.value(); - mbglCamera.anchor = mbgl::ScreenCoordinate { anchor.x(), anchor.y() }; + mbglCamera.anchor = mbgl::ScreenCoordinate{anchor.x(), anchor.y()}; } if (camera.zoom.isValid()) { mbglCamera.zoom = camera.zoom.value(); @@ -528,28 +529,22 @@ void Map::jumpTo(const CameraOptions& camera) Set the angle in degrees. Negative values and values over 360 are valid and will wrap. The direction of the rotation is counterclockwise. - When \a center is defined, the map will rotate around the center pixel coordinate - respecting the margins if defined. + When \a center is defined, the map will rotate around the center pixel + coordinate respecting the margins if defined. \sa margins() */ -double Map::bearing() const -{ +double Map::bearing() const { return *d_ptr->mapObj->getCameraOptions().bearing; } -void Map::setBearing(double degrees) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withBearing(degrees) - .withPadding(d_ptr->margins)); +void Map::setBearing(double degrees) { + d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withBearing(degrees).withPadding(d_ptr->margins)); } -void Map::setBearing(double degrees, const QPointF ¢er) -{ - d_ptr->mapObj->jumpTo(mbgl::CameraOptions() - .withBearing(degrees) - .withAnchor(mbgl::ScreenCoordinate { center.x(), center.y() })); +void Map::setBearing(double degrees, const QPointF ¢er) { + d_ptr->mapObj->jumpTo( + mbgl::CameraOptions().withBearing(degrees).withAnchor(mbgl::ScreenCoordinate{center.x(), center.y()})); } /*! @@ -561,44 +556,38 @@ void Map::setBearing(double degrees, const QPointF ¢er) \sa margins() */ -double Map::pitch() const -{ +double Map::pitch() const { return *d_ptr->mapObj->getCameraOptions().pitch; } -void Map::setPitch(double pitch_) -{ +void Map::setPitch(double pitch_) { d_ptr->mapObj->jumpTo(mbgl::CameraOptions().withPitch(pitch_)); } -void Map::pitchBy(double pitch_) -{ +void Map::pitchBy(double pitch_) { d_ptr->mapObj->pitchBy(pitch_); } /*! Returns the north orientation mode. */ -Map::NorthOrientation Map::northOrientation() const -{ +Map::NorthOrientation Map::northOrientation() const { return static_cast(d_ptr->mapObj->getMapOptions().northOrientation()); } /*! Sets the north orientation mode to \a orientation. */ -void Map::setNorthOrientation(NorthOrientation orientation) -{ +void Map::setNorthOrientation(NorthOrientation orientation) { d_ptr->mapObj->setNorthOrientation(static_cast(orientation)); } /*! - Tells the map rendering engine that there is currently a gesture in \a progress. This - affects how the map renders labels, as it will use different texture filters if a gesture - is ongoing. + Tells the map rendering engine that there is currently a gesture in \a + progress. This affects how the map renders labels, as it will use different + texture filters if a gesture is ongoing. */ -void Map::setGestureInProgress(bool progress) -{ +void Map::setGestureInProgress(bool progress) { d_ptr->mapObj->setGestureInProgress(progress); } @@ -611,7 +600,7 @@ void Map::setTransitionOptions(qint64 duration, qint64 delay) { return std::chrono::duration_cast(mbgl::Milliseconds(value)); }; - d_ptr->mapObj->getStyle().setTransitionOptions(mbgl::style::TransitionOptions{ convert(duration), convert(delay) }); + d_ptr->mapObj->getStyle().setTransitionOptions(mbgl::style::TransitionOptions{convert(duration), convert(delay)}); } /*! @@ -621,8 +610,7 @@ void Map::setTransitionOptions(qint64 duration, qint64 delay) { \sa addAnnotationIcon() */ -AnnotationID Map::addAnnotation(const Annotation &annotation) -{ +AnnotationID Map::addAnnotation(const Annotation &annotation) { return static_cast(d_ptr->mapObj->addAnnotation(*asAnnotation(annotation))); } @@ -631,23 +619,23 @@ AnnotationID Map::addAnnotation(const Annotation &annotation) \sa addAnnotationIcon() */ -void Map::updateAnnotation(AnnotationID id, const Annotation &annotation) -{ +void Map::updateAnnotation(AnnotationID id, const Annotation &annotation) { d_ptr->mapObj->updateAnnotation(id, *asAnnotation(annotation)); } /*! Removes an existing annotation referred by \a id. */ -void Map::removeAnnotation(AnnotationID id) -{ +void Map::removeAnnotation(AnnotationID id) { d_ptr->mapObj->removeAnnotation(id); } /*! - Sets a layout \a property_ \a value to an existing \a layer. The \a property_ string can be any - as defined by the \l {https://www.mapbox.com/mapbox-gl-style-spec/} {Mapbox style specification} - for layout properties. Returns true if the operation succeeds, and false otherwise. + Sets a layout \a property_ \a value to an existing \a layer. The \a + property_ string can be any as defined by the \l + {https://www.mapbox.com/mapbox-gl-style-spec/} {Mapbox style specification} + for layout properties. Returns true if the operation succeeds, and false + otherwise. The implementation attempts to treat \a value as a JSON string, if the QVariant inner type is a string. If not a valid JSON string, then it'll @@ -659,8 +647,9 @@ void Map::removeAnnotation(AnnotationID id) map->setLayoutProperty("route", "visibility", "none"); \endcode - This table describes the mapping between \l {https://www.mapbox.com/mapbox-gl-style-spec/#types} - {style types} and Qt types accepted by setLayoutProperty(): + This table describes the mapping between \l + {https://www.mapbox.com/mapbox-gl-style-spec/#types} {style types} and Qt + types accepted by setLayoutProperty(): \table \header @@ -683,29 +672,31 @@ void Map::removeAnnotation(AnnotationID id) \li QVariantList \endtable */ -bool Map::setLayoutProperty(const QString& layer, const QString& propertyName, const QVariant& value) -{ +bool Map::setLayoutProperty(const QString &layer, const QString &propertyName, const QVariant &value) { return d_ptr->setProperty(&mbgl::style::Layer::setProperty, layer, propertyName, value); } /*! - Sets a paint \a property_ \a value to an existing \a layer. The \a property_ string can be any - as defined by the \l {https://www.mapbox.com/mapbox-gl-style-spec/} {Mapbox style specification} - for paint properties. Returns true if the operation succeeds, and false otherwise. + Sets a paint \a property_ \a value to an existing \a layer. The \a property_ + string can be any as defined by the \l + {https://www.mapbox.com/mapbox-gl-style-spec/} {Mapbox style specification} + for paint properties. Returns true if the operation succeeds, and false + otherwise. The implementation attempts to treat \a value as a JSON string, if the QVariant inner type is a string. If not a valid JSON string, then it'll proceed with the mapping described below. - For paint properties that take a color as \a value, such as \c fill-color, a string such as - \c blue can be passed or a QColor. + For paint properties that take a color as \a value, such as \c fill-color, a + string such as \c blue can be passed or a QColor. \code map->setPaintProperty("route", "line-color", QColor("blue")); \endcode - This table describes the mapping between \l {https://www.mapbox.com/mapbox-gl-style-spec/#types} - {style types} and Qt types accepted by setPaintProperty(): + This table describes the mapping between \l + {https://www.mapbox.com/mapbox-gl-style-spec/#types} {style types} and Qt + types accepted by setPaintProperty(): \table \header @@ -731,8 +722,9 @@ bool Map::setLayoutProperty(const QString& layer, const QString& propertyName, c \li QVariantList \endtable - If the style specification defines the property's type as \b Array, use a QVariantList. For - example, the following code sets a \c route layer's \c line-dasharray property: + If the style specification defines the property's type as \b Array, use a + QVariantList. For example, the following code sets a \c route layer's \c + line-dasharray property: \code QVariantList lineDashArray; @@ -743,8 +735,7 @@ bool Map::setLayoutProperty(const QString& layer, const QString& propertyName, c \endcode */ -bool Map::setPaintProperty(const QString& layer, const QString& propertyName, const QVariant& value) -{ +bool Map::setPaintProperty(const QString &layer, const QString &propertyName, const QVariant &value) { return d_ptr->setProperty(&mbgl::style::Layer::setProperty, layer, propertyName, value); } @@ -752,8 +743,7 @@ bool Map::setPaintProperty(const QString& layer, const QString& propertyName, co Returns true when the map is completely rendered, false otherwise. A partially rendered map ranges from nothing rendered at all to only labels missing. */ -bool Map::isFullyLoaded() const -{ +bool Map::isFullyLoaded() const { return d_ptr->mapObj->isFullyLoaded(); } @@ -762,9 +752,8 @@ bool Map::isFullyLoaded() const The pixel coordinate origin is located at the upper left corner of the map. */ -void Map::moveBy(const QPointF &offset) -{ - d_ptr->mapObj->moveBy(mbgl::ScreenCoordinate { offset.x(), offset.y() }); +void Map::moveBy(const QPointF &offset) { + d_ptr->mapObj->moveBy(mbgl::ScreenCoordinate{offset.x(), offset.y()}); } /*! @@ -774,47 +763,43 @@ void Map::moveBy(const QPointF &offset) can be used for implementing a pinch gesture. */ void Map::scaleBy(double scale_, const QPointF ¢er) { - d_ptr->mapObj->scaleBy(scale_, mbgl::ScreenCoordinate { center.x(), center.y() }); + d_ptr->mapObj->scaleBy(scale_, mbgl::ScreenCoordinate{center.x(), center.y()}); } /*! - Rotate the map from the \a first screen coordinate to the \a second screen coordinate. - This method can be used for implementing rotating the map by clicking and dragging, - being \a first the cursor coordinate at the last frame and \a second the cursor coordinate - at the current frame. + Rotate the map from the \a first screen coordinate to the \a second screen + coordinate. This method can be used for implementing rotating the map by + clicking and dragging, being \a first the cursor coordinate at the last frame + and \a second the cursor coordinate at the current frame. */ -void Map::rotateBy(const QPointF &first, const QPointF &second) -{ - d_ptr->mapObj->rotateBy( - mbgl::ScreenCoordinate { first.x(), first.y() }, - mbgl::ScreenCoordinate { second.x(), second.y() }); +void Map::rotateBy(const QPointF &first, const QPointF &second) { + d_ptr->mapObj->rotateBy(mbgl::ScreenCoordinate{first.x(), first.y()}, + mbgl::ScreenCoordinate{second.x(), second.y()}); } /*! Resize the map to \a size_ and scale to fit at the framebuffer. For high DPI screens, the size will be smaller than the framebuffer. */ -void Map::resize(const QSize& size_) -{ +void Map::resize(const QSize &size_) { auto size = sanitizedSize(size_); - if (d_ptr->mapObj->getMapOptions().size() == size) - return; + if (d_ptr->mapObj->getMapOptions().size() == size) return; d_ptr->mapObj->setSize(size); } /*! - Adds an \a icon to the annotation icon pool. This can be later used by the annotation - functions to shown any drawing on the map by referencing its \a name. + Adds an \a icon to the annotation icon pool. This can be later used by the + annotation functions to shown any drawing on the map by referencing its \a + name. - Unlike using addIcon() for runtime styling, annotations added with addAnnotation() - will survive style changes. + Unlike using addIcon() for runtime styling, annotations added with + addAnnotation() will survive style changes. \sa addAnnotation() */ -void Map::addAnnotationIcon(const QString &name, const QImage &icon) -{ +void Map::addAnnotationIcon(const QString &name, const QImage &icon) { if (icon.isNull()) return; d_ptr->mapObj->addAnnotationImage(toStyleImage(name, icon)); @@ -831,10 +816,9 @@ void Map::addAnnotationIcon(const QString &name, const QImage &icon) /note The return value is affected by the current zoom level, bearing and pitch. */ -QPointF Map::pixelForCoordinate(const Coordinate &coordinate_) const -{ - const mbgl::ScreenCoordinate pixel = - d_ptr->mapObj->pixelForLatLng(mbgl::LatLng { coordinate_.first, coordinate_.second }); +QPointF Map::pixelForCoordinate(const Coordinate &coordinate_) const { + const mbgl::ScreenCoordinate pixel = d_ptr->mapObj->pixelForLatLng( + mbgl::LatLng{coordinate_.first, coordinate_.second}); return QPointF(pixel.x, pixel.y); } @@ -842,39 +826,37 @@ QPointF Map::pixelForCoordinate(const Coordinate &coordinate_) const /*! Returns the geographic coordinate for the \a pixel coordinate. */ -Coordinate Map::coordinateForPixel(const QPointF &pixel) const -{ - const mbgl::LatLng latLng = - d_ptr->mapObj->latLngForPixel(mbgl::ScreenCoordinate { pixel.x(), pixel.y() }); +Coordinate Map::coordinateForPixel(const QPointF &pixel) const { + const mbgl::LatLng latLng = d_ptr->mapObj->latLngForPixel(mbgl::ScreenCoordinate{pixel.x(), pixel.y()}); return Coordinate(latLng.latitude(), latLng.longitude()); } /*! - Returns the coordinate and zoom combination needed in order to make the coordinate - bounding box \a sw and \a ne visible. + Returns the coordinate and zoom combination needed in order to make the + coordinate bounding box \a sw and \a ne visible. */ -CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, - const Coordinate &ne) const { - auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng { sw.first, sw.second }, mbgl::LatLng { ne.first, ne.second }); +CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, const Coordinate &ne) const { + auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng{sw.first, sw.second}, mbgl::LatLng{ne.first, ne.second}); mbgl::CameraOptions camera = d_ptr->mapObj->cameraForLatLngBounds(bounds, d_ptr->margins); - return {{ (*camera.center).latitude(), (*camera.center).longitude() }, *camera.zoom }; + return {{(*camera.center).latitude(), (*camera.center).longitude()}, *camera.zoom}; } /*! - Returns the coordinate and zoom combination needed in order to make the coordinate - bounding box \a sw and \a ne visible taking into account \a newBearing and \a newPitch. + Returns the coordinate and zoom combination needed in order to make the + coordinate bounding box \a sw and \a ne visible taking into account \a + newBearing and \a newPitch. */ CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, - const Coordinate &ne, - double newBearing, - double newPitch) + const Coordinate &ne, + double newBearing, + double newPitch) { - auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng { sw.first, sw.second }, mbgl::LatLng { ne.first, ne.second }); + auto bounds = mbgl::LatLngBounds::hull(mbgl::LatLng{sw.first, sw.second}, mbgl::LatLng{ne.first, ne.second}); mbgl::CameraOptions camera = d_ptr->mapObj->cameraForLatLngBounds(bounds, d_ptr->margins, newBearing, newPitch); - return {{ (*camera.center).latitude(), (*camera.center).longitude() }, *camera.zoom }; + return {{(*camera.center).latitude(), (*camera.center).longitude()}, *camera.zoom}; } /*! @@ -883,32 +865,24 @@ CoordinateZoom Map::coordinateZoomForBounds(const Coordinate &sw, This property sets a new reference center for the map. */ -void Map::setMargins(const QMargins &margins_) -{ - d_ptr->margins = { - static_cast(margins_.top()), - static_cast(margins_.left()), - static_cast(margins_.bottom()), - static_cast(margins_.right()) - }; +void Map::setMargins(const QMargins &margins_) { + d_ptr->margins = {static_cast(margins_.top()), + static_cast(margins_.left()), + static_cast(margins_.bottom()), + static_cast(margins_.right())}; } -QMargins Map::margins() const -{ - return QMargins( - d_ptr->margins.left(), - d_ptr->margins.top(), - d_ptr->margins.right(), - d_ptr->margins.bottom() - ); +QMargins Map::margins() const { + return QMargins(d_ptr->margins.left(), d_ptr->margins.top(), d_ptr->margins.right(), d_ptr->margins.bottom()); } /*! Adds a source \a id to the map as specified by the \l - {https://www.mapbox.com/mapbox-gl-style-spec/#root-sources}{Mapbox style specification} with - \a params. + {https://www.mapbox.com/mapbox-gl-style-spec/#root-sources}{Mapbox style + specification} with \a params. - This example reads a GeoJSON from the Qt resource system and adds it as source: + This example reads a GeoJSON from the Qt resource system and adds it as + source: \code QFile geojson(":source1.geojson"); @@ -921,13 +895,13 @@ QMargins Map::margins() const map->addSource("routeSource", routeSource); \endcode */ -void Map::addSource(const QString &id, const QVariantMap ¶ms) -{ +void Map::addSource(const QString &id, const QVariantMap ¶ms) { using namespace mbgl::style; using namespace mbgl::style::conversion; Error error; - std::optional> source = convert>(QVariant(params), error, id.toStdString()); + std::optional> source = convert>( + QVariant(params), error, id.toStdString()); if (!source) { qWarning() << "Unable to add source:" << error.message.c_str(); return; @@ -939,8 +913,7 @@ void Map::addSource(const QString &id, const QVariantMap ¶ms) /*! Returns true if the layer with given \a sourceID exists, false otherwise. */ -bool Map::sourceExists(const QString& sourceID) -{ +bool Map::sourceExists(const QString &sourceID) { return !!d_ptr->mapObj->getStyle().getSource(sourceID.toStdString()); } @@ -950,8 +923,7 @@ bool Map::sourceExists(const QString& sourceID) If the source does not exist, it will be added like in addSource(). Only image and GeoJSON sources can be updated. */ -void Map::updateSource(const QString &id, const QVariantMap ¶ms) -{ +void Map::updateSource(const QString &id, const QVariantMap ¶ms) { using namespace mbgl::style; using namespace mbgl::style::conversion; @@ -964,7 +936,8 @@ void Map::updateSource(const QString &id, const QVariantMap ¶ms) auto sourceGeoJSON = source->as(); auto sourceImage = source->as(); if (!sourceGeoJSON && !sourceImage) { - qWarning() << "Unable to update source: only GeoJSON and Image sources are mutable."; + qWarning() << "Unable to update source: only GeoJSON and Image sources " + "are mutable."; return; } @@ -984,8 +957,7 @@ void Map::updateSource(const QString &id, const QVariantMap ¶ms) This method has no effect if the source does not exist. */ -void Map::removeSource(const QString& id) -{ +void Map::removeSource(const QString &id) { auto sourceIDStdString = id.toStdString(); if (d_ptr->mapObj->getStyle().getSource(sourceIDStdString)) { @@ -995,28 +967,22 @@ void Map::removeSource(const QString& id) /*! Adds a custom layer \a id with the initialization function \a initFn, the - render function \a renderFn and the deinitialization function \a deinitFn with - the user data \a context before the existing layer \a before. + render function \a renderFn and the deinitialization function \a deinitFn + with the user data \a context before the existing layer \a before. \warning This is used for delegating the rendering of a layer to the user of this API and is not officially supported. Use at your own risk. */ -void Map::addCustomLayer(const QString &id, - std::unique_ptr host, - const QString &before) -{ +void Map::addCustomLayer(const QString &id, std::unique_ptr host, const QString &before) { class HostWrapper : public mbgl::style::CustomLayerHost { - public: + public: std::unique_ptr ptr{}; HostWrapper(std::unique_ptr p) - : ptr(std::move(p)) { - } + : ptr(std::move(p)) {} - void initialize() { - ptr->initialize(); - } + void initialize() { ptr->initialize(); } - void render(const mbgl::style::CustomLayerRenderParameters& params) { + void render(const mbgl::style::CustomLayerRenderParameters ¶ms) { CustomLayerRenderParameters renderParams; renderParams.width = params.width; renderParams.height = params.height; @@ -1029,27 +995,26 @@ void Map::addCustomLayer(const QString &id, ptr->render(renderParams); } - void contextLost() { } + void contextLost() {} - void deinitialize() { - ptr->deinitialize(); - } + void deinitialize() { ptr->deinitialize(); } }; - d_ptr->mapObj->getStyle().addLayer(std::make_unique( - id.toStdString(), - std::make_unique(std::move(host))), - before.isEmpty() ? std::optional() : std::optional(before.toStdString())); + d_ptr->mapObj->getStyle().addLayer( + std::make_unique(id.toStdString(), std::make_unique(std::move(host))), + before.isEmpty() ? std::optional() : std::optional(before.toStdString())); } /*! Adds a style layer to the map as specified by the \l - {https://www.mapbox.com/mapbox-gl-style-spec/#root-layers}{Mapbox style specification} with - \a params. The layer will be added under the layer specified by \a before, if specified. - Otherwise it will be added as the topmost layer. + {https://www.mapbox.com/mapbox-gl-style-spec/#root-layers}{Mapbox style + specification} with \a params. The layer will be added under the layer + specified by \a before, if specified. Otherwise it will be added as the + topmost layer. - This example shows how to add a layer that will be used to show a route line on the map. Note - that nothing will be drawn until we set paint properties using setPaintProperty(). + This example shows how to add a layer that will be used to show a route line + on the map. Note that nothing will be drawn until we set paint properties + using setPaintProperty(). \code QVariantMap route; @@ -1062,8 +1027,7 @@ void Map::addCustomLayer(const QString &id, /note The source must exist prior to adding a layer. */ -void Map::addLayer(const QVariantMap ¶ms, const QString& before) -{ +void Map::addLayer(const QVariantMap ¶ms, const QString &before) { using namespace mbgl::style; using namespace mbgl::style::conversion; @@ -1074,31 +1038,29 @@ void Map::addLayer(const QVariantMap ¶ms, const QString& before) return; } - d_ptr->mapObj->getStyle().addLayer(std::move(*layer), + d_ptr->mapObj->getStyle().addLayer( + std::move(*layer), before.isEmpty() ? std::optional() : std::optional(before.toStdString())); } /*! Returns true if the layer with given \a id exists, false otherwise. */ -bool Map::layerExists(const QString& id) -{ +bool Map::layerExists(const QString &id) { return !!d_ptr->mapObj->getStyle().getLayer(id.toStdString()); } /*! Removes the layer with given \a id. */ -void Map::removeLayer(const QString& id) -{ +void Map::removeLayer(const QString &id) { d_ptr->mapObj->getStyle().removeLayer(id.toStdString()); } /*! List of all existing layer ids from the current style. */ -QVector Map::layerIds() const -{ +QVector Map::layerIds() const { const auto &layers = d_ptr->mapObj->getStyle().getLayers(); QVector layerIds; @@ -1121,8 +1083,7 @@ QVector Map::layerIds() const \sa addLayer() */ -void Map::addImage(const QString &id, const QImage &image) -{ +void Map::addImage(const QString &id, const QImage &image) { if (image.isNull()) return; d_ptr->mapObj->getStyle().addImage(toStyleImage(id, image)); @@ -1131,18 +1092,18 @@ void Map::addImage(const QString &id, const QImage &image) /*! Removes the image \a id. */ -void Map::removeImage(const QString &id) -{ +void Map::removeImage(const QString &id) { d_ptr->mapObj->getStyle().removeImage(id.toStdString()); } /*! Adds a \a filter to a style \a layer using the format described in the \l - {https://maplibre.org/maplibre-gl-js-docs/style-spec/#other-filter}{Mapbox style specification}. + {https://maplibre.org/maplibre-gl-js-docs/style-spec/#other-filter}{Mapbox + style specification}. - Given a layer \c marker from an arbitrary GeoJSON source containing features of type \b - "Point" and \b "LineString", this example shows how to make sure the layer will only tag - features of type \b "Point". + Given a layer \c marker from an arbitrary GeoJSON source containing features + of type \b "Point" and \b "LineString", this example shows how to make sure + the layer will only tag features of type \b "Point". \code QVariantList filterExpression; @@ -1156,12 +1117,11 @@ void Map::removeImage(const QString &id) map->setFilter(QLatin1String("marker"), filter); \endcode */ -void Map::setFilter(const QString& layer, const QVariant& filter) -{ +void Map::setFilter(const QString &layer, const QVariant &filter) { using namespace mbgl::style; using namespace mbgl::style::conversion; - Layer* layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); + Layer *layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); if (!layer_) { qWarning() << "Layer not found:" << layer; return; @@ -1178,50 +1138,44 @@ void Map::setFilter(const QString& layer, const QVariant& filter) } QVariant QVariantFromValue(const mbgl::Value &value) { - return value.match( - [](const mbgl::NullValue) { - return QVariant(); - }, [](const bool value_) { - return QVariant(value_); - }, [](const float value_) { - return QVariant(value_); - }, [](const int64_t value_) { - return QVariant(static_cast(value_)); - }, [](const double value_) { - return QVariant(value_); - }, [](const std::string &value_) { - return QVariant(value_.c_str()); - }, [](const mbgl::Color &value_) { - return QColor(value_.r, value_.g, value_.b, value_.a); - }, [&](const std::vector &vector) { - QVariantList list; - list.reserve(static_cast(vector.size())); - for (const auto &value_ : vector) { - list.push_back(QVariantFromValue(value_)); - } - return list; - }, [&](const std::unordered_map &map) { - QVariantMap varMap; - for (auto &item : map) { - varMap.insert(item.first.c_str(), QVariantFromValue(item.second)); - } - return varMap; - }, [](const auto &) { - return QVariant(); - }); + return value.match([](const mbgl::NullValue) { return QVariant(); }, + [](const bool value_) { return QVariant(value_); }, + [](const float value_) { return QVariant(value_); }, + [](const int64_t value_) { return QVariant(static_cast(value_)); }, + [](const double value_) { return QVariant(value_); }, + [](const std::string &value_) { return QVariant(value_.c_str()); }, + [](const mbgl::Color &value_) { return QColor(value_.r, value_.g, value_.b, value_.a); }, + [&](const std::vector &vector) { + QVariantList list; + list.reserve(static_cast(vector.size())); + for (const auto &value_ : vector) { + list.push_back(QVariantFromValue(value_)); + } + return list; + }, + [&](const std::unordered_map &map) { + QVariantMap varMap; + for (auto &item : map) { + varMap.insert(item.first.c_str(), QVariantFromValue(item.second)); + } + return varMap; + }, + [](const auto &) { return QVariant(); }); } /*! Returns the current \a expression-based filter value applied to a style \layer, if any. - Filter value types are described in the {https://maplibre.org/maplibre-gl-js-docs/style-spec/#types}{Mapbox style specification}. + Filter value types are described in the + {https://maplibre.org/maplibre-gl-js-docs/style-spec/#types}{Mapbox style + specification}. */ -QVariant Map::getFilter(const QString &layer) const { +QVariant Map::getFilter(const QString &layer) const { using namespace mbgl::style; using namespace mbgl::style::conversion; - Layer* layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); + Layer *layer_ = d_ptr->mapObj->getStyle().getLayer(layer.toStdString()); if (!layer_) { qWarning() << "Layer not found:" << layer; return QVariant(); @@ -1237,8 +1191,7 @@ QVariant Map::getFilter(const QString &layer) const { Must be called on the render thread. */ -void Map::createRenderer() -{ +void Map::createRenderer() { d_ptr->createRenderer(); } @@ -1248,8 +1201,7 @@ void Map::createRenderer() Must be called on the render thread. */ -void Map::destroyRenderer() -{ +void Map::destroyRenderer() { d_ptr->destroyRenderer(); } @@ -1259,8 +1211,7 @@ void Map::destroyRenderer() \sa QMapLibreGL::Settings::MapMode */ -void Map::startStaticRender() -{ +void Map::startStaticRender() { d_ptr->mapObj->renderStill([this](std::exception_ptr err) { QString what; @@ -1268,7 +1219,7 @@ void Map::startStaticRender() if (err) { std::rethrow_exception(err); } - } catch(const std::exception& e) { + } catch (const std::exception &e) { what = e.what(); } @@ -1287,8 +1238,7 @@ void Map::startStaticRender() Must be called on the render thread. */ -void Map::render() -{ +void Map::render() { d_ptr->render(); } @@ -1299,8 +1249,7 @@ void Map::render() Must be called on the render thread. */ -void Map::setFramebufferObject(quint32 fbo, const QSize& size) -{ +void Map::setFramebufferObject(quint32 fbo, const QSize &size) { d_ptr->setFramebufferObject(fbo, size); } @@ -1308,8 +1257,7 @@ void Map::setFramebufferObject(quint32 fbo, const QSize& size) Informs the map that the network connection has been established, causing all network requests that previously timed out to be retried immediately. */ -void Map::connectionEstablished() -{ +void Map::connectionEstablished() { mbgl::NetworkStatus::Reachable(); } @@ -1317,8 +1265,7 @@ void Map::connectionEstablished() Returns a list containing a pair of string objects, representing the style URL and name, respectively. */ -const QVector> &Map::defaultStyles() const -{ +const QVector> &Map::defaultStyles() const { return d_ptr->defaultStyles; } @@ -1351,7 +1298,8 @@ const QVector> &Map::defaultStyles() const */ /*! - \fn void QMapLibreGL::Map::mapLoadingFailed(QMapLibreGL::Map::MapLoadingFailure type, const QString &description) + \fn void QMapLibreGL::Map::mapLoadingFailed(QMapLibreGL::Map::MapLoadingFailure + type, const QString &description) This signal is emitted when a map loading failure happens. Details of the failures are provided, including its \a type and textual \a description. @@ -1367,11 +1315,10 @@ const QVector> &Map::defaultStyles() const */ MapPrivate::MapPrivate(Map *q, const Settings &settings, const QSize &size, qreal pixelRatio_) - : QObject(q) - , m_mode(settings.contextMode()) - , m_pixelRatio(pixelRatio_) - , m_localFontFamily(settings.localFontFamily()) -{ + : QObject(q), + m_mode(settings.contextMode()), + m_pixelRatio(pixelRatio_), + m_localFontFamily(settings.localFontFamily()) { // Setup MapObserver m_mapObserver = std::make_unique(this); @@ -1383,47 +1330,45 @@ MapPrivate::MapPrivate(Map *q, const Settings &settings, const QSize &size, qrea auto resourceOptions = resourceOptionsFromSettings(settings); for (auto style : resourceOptions.tileServerOptions().defaultStyles()) { - defaultStyles.append(QPair( - QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName()))); + defaultStyles.append( + QPair(QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName()))); } - + auto clientOptions = clientOptionsFromSettings(settings); // Setup the Map object. - mapObj = std::make_unique(*this, *m_mapObserver, + mapObj = std::make_unique(*this, + *m_mapObserver, mapOptionsFromSettings(settings, size, m_pixelRatio), resourceOptions, clientOptionsFromSettings(settings)); - if (settings.resourceTransform()) { - m_resourceTransform = std::make_unique>( - *mbgl::Scheduler::GetCurrent(), - [callback = settings.resourceTransform()]( - mbgl::Resource::Kind, const std::string &url_, mbgl::ResourceTransform::FinishedCallback onFinished) { - onFinished(callback(std::move(url_))); - }); - - mbgl::ResourceTransform transform{[actorRef = m_resourceTransform->self()]( - mbgl::Resource::Kind kind, - const std::string &url, - mbgl::ResourceTransform::FinishedCallback onFinished) { - actorRef.invoke(&mbgl::ResourceTransform::TransformCallback::operator(), kind, url, std::move(onFinished)); - }}; - std::shared_ptr fs = - mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::Network, resourceOptions, clientOptions); - fs->setResourceTransform(std::move(transform)); - } + if (settings.resourceTransform()) { + m_resourceTransform = std::make_unique>( + *mbgl::Scheduler::GetCurrent(), + [callback = settings.resourceTransform()]( + mbgl::Resource::Kind, const std::string &url_, mbgl::ResourceTransform::FinishedCallback onFinished) { + onFinished(callback(std::move(url_))); + }); + + mbgl::ResourceTransform transform{[actorRef = m_resourceTransform->self()]( + mbgl::Resource::Kind kind, + const std::string &url, + mbgl::ResourceTransform::FinishedCallback onFinished) { + actorRef.invoke(&mbgl::ResourceTransform::TransformCallback::operator(), kind, url, std::move(onFinished)); + }}; + std::shared_ptr fs = mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::Network, resourceOptions, clientOptions); + fs->setResourceTransform(std::move(transform)); + } // Needs to be Queued to give time to discard redundant draw calls via the `renderQueued` flag. connect(this, &MapPrivate::needsRendering, q, &Map::needsRendering, Qt::QueuedConnection); } -MapPrivate::~MapPrivate() -{ -} +MapPrivate::~MapPrivate() {} -void MapPrivate::update(std::shared_ptr parameters) -{ +void MapPrivate::update(std::shared_ptr parameters) { std::lock_guard lock(m_mapRendererMutex); m_updateParameters = std::move(parameters); @@ -1437,10 +1382,8 @@ void MapPrivate::update(std::shared_ptr parameters) requestRendering(); } -void MapPrivate::setObserver(mbgl::RendererObserver &observer) -{ - m_rendererObserver = std::make_shared( - *mbgl::util::RunLoop::Get(), observer); +void MapPrivate::setObserver(mbgl::RendererObserver &observer) { + m_rendererObserver = std::make_shared(*mbgl::util::RunLoop::Get(), observer); std::lock_guard lock(m_mapRendererMutex); @@ -1449,19 +1392,14 @@ void MapPrivate::setObserver(mbgl::RendererObserver &observer) } } -void MapPrivate::createRenderer() -{ +void MapPrivate::createRenderer() { std::lock_guard lock(m_mapRendererMutex); if (m_mapRenderer) { return; } - m_mapRenderer = std::make_unique( - m_pixelRatio, - m_mode, - m_localFontFamily - ); + m_mapRenderer = std::make_unique(m_pixelRatio, m_mode, m_localFontFamily); connect(m_mapRenderer.get(), &MapRenderer::needsRendering, this, &MapPrivate::requestRendering); @@ -1473,15 +1411,13 @@ void MapPrivate::createRenderer() } } -void MapPrivate::destroyRenderer() -{ +void MapPrivate::destroyRenderer() { std::lock_guard lock(m_mapRendererMutex); m_mapRenderer.reset(); } -void MapPrivate::render() -{ +void MapPrivate::render() { std::lock_guard lock(m_mapRendererMutex); if (!m_mapRenderer) { @@ -1492,8 +1428,7 @@ void MapPrivate::render() m_mapRenderer->render(); } -void MapPrivate::setFramebufferObject(quint32 fbo, const QSize& size) -{ +void MapPrivate::setFramebufferObject(quint32 fbo, const QSize &size) { std::lock_guard lock(m_mapRendererMutex); if (!m_mapRenderer) { @@ -1503,23 +1438,25 @@ void MapPrivate::setFramebufferObject(quint32 fbo, const QSize& size) m_mapRenderer->updateFramebuffer(fbo, sanitizedSize(size)); } -void MapPrivate::requestRendering() -{ +void MapPrivate::requestRendering() { if (!m_renderQueued.test_and_set()) { emit needsRendering(); } } -bool MapPrivate::setProperty(const PropertySetter& setter, const QString& layer, const QString& name, const QVariant& value) { +bool MapPrivate::setProperty(const PropertySetter &setter, + const QString &layer, + const QString &name, + const QVariant &value) { using namespace mbgl::style; - Layer* layerObject = mapObj->getStyle().getLayer(layer.toStdString()); + Layer *layerObject = mapObj->getStyle().getLayer(layer.toStdString()); if (!layerObject) { qWarning() << "Layer not found:" << layer; return false; } - const std::string& propertyString = name.toStdString(); + const std::string &propertyString = name.toStdString(); std::optional result; @@ -1532,7 +1469,7 @@ bool MapPrivate::setProperty(const PropertySetter& setter, const QString& layer, document.Parse<0>(value.toString().toStdString()); if (!document.HasParseError()) { // Treat value as a valid JSON. - const mbgl::JSValue* jsonValue = &document; + const mbgl::JSValue *jsonValue = &document; result = (layerObject->*setter)(propertyString, jsonValue); } else { result = (layerObject->*setter)(propertyString, value); @@ -1542,7 +1479,8 @@ bool MapPrivate::setProperty(const PropertySetter& setter, const QString& layer, } if (result) { - qWarning() << "Error setting property" << name << "on layer" << layer << ":" << QString::fromStdString(result->message); + qWarning() << "Error setting property" << name << "on layer" << layer << ":" + << QString::fromStdString(result->message); return false; } diff --git a/platform/qt/src/map_p.hpp b/platform/qt/src/map_p.hpp index b93492d4a11..ae44fcf64b4 100644 --- a/platform/qt/src/map_p.hpp +++ b/platform/qt/src/map_p.hpp @@ -19,17 +19,16 @@ namespace QMapLibreGL { -class MapPrivate : public QObject, public mbgl::RendererFrontend -{ +class MapPrivate : public QObject, public mbgl::RendererFrontend { Q_OBJECT public: - explicit MapPrivate(Map *, const Settings &, const QSize &size, qreal pixelRatio); + explicit MapPrivate(Map*, const Settings&, const QSize& size, qreal pixelRatio); virtual ~MapPrivate(); // mbgl::RendererFrontend implementation. void reset() final {} - void setObserver(mbgl::RendererObserver &) final; + void setObserver(mbgl::RendererObserver&) final; void update(std::shared_ptr) final; // These need to be called on the same thread. @@ -38,7 +37,8 @@ class MapPrivate : public QObject, public mbgl::RendererFrontend void render(); void setFramebufferObject(quint32 fbo, const QSize& size); - using PropertySetter = std::optional (mbgl::style::Layer::*)(const std::string&, const mbgl::style::conversion::Convertible&); + using PropertySetter = std::optional (mbgl::style::Layer::*)( + const std::string&, const mbgl::style::conversion::Convertible&); bool setProperty(const PropertySetter& setter, const QString& layer, const QString& name, const QVariant& value); mbgl::EdgeInsets margins; diff --git a/platform/qt/src/mbgl/async_task.cpp b/platform/qt/src/mbgl/async_task.cpp index 2422e547e85..3ae29254f07 100644 --- a/platform/qt/src/mbgl/async_task.cpp +++ b/platform/qt/src/mbgl/async_task.cpp @@ -28,15 +28,13 @@ void AsyncTask::Impl::runTask() { } AsyncTask::AsyncTask(std::function&& fn) - : impl(std::make_unique(std::move(fn))) { -} + : impl(std::make_unique(std::move(fn))) {} -AsyncTask::~AsyncTask() { -} +AsyncTask::~AsyncTask() {} void AsyncTask::send() { impl->maySend(); } -} -} +} // namespace util +} // namespace mbgl diff --git a/platform/qt/src/mbgl/async_task_impl.hpp b/platform/qt/src/mbgl/async_task_impl.hpp index ea86079a90f..c608306968b 100644 --- a/platform/qt/src/mbgl/async_task_impl.hpp +++ b/platform/qt/src/mbgl/async_task_impl.hpp @@ -16,7 +16,7 @@ class AsyncTask::Impl : public QObject { Q_OBJECT public: - Impl(std::function &&); + Impl(std::function&&); void maySend(); @@ -33,6 +33,5 @@ public slots: std::atomic_flag queued = ATOMIC_FLAG_INIT; }; - } // namespace util } // namespace mbgl diff --git a/platform/qt/src/mbgl/bidi.cpp b/platform/qt/src/mbgl/bidi.cpp index 57e61d33427..f6d7673aa8d 100644 --- a/platform/qt/src/mbgl/bidi.cpp +++ b/platform/qt/src/mbgl/bidi.cpp @@ -14,9 +14,8 @@ std::u16string applyArabicShaping(const std::u16string& input) { return input; } -BiDi::BiDi() : impl(std::make_unique()) -{ -} +BiDi::BiDi() + : impl(std::make_unique()) {} BiDi::~BiDi() = default; diff --git a/platform/qt/src/mbgl/gl_functions.cpp b/platform/qt/src/mbgl/gl_functions.cpp index 2009646905f..e04151ac086 100644 --- a/platform/qt/src/mbgl/gl_functions.cpp +++ b/platform/qt/src/mbgl/gl_functions.cpp @@ -9,888 +9,902 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = [](auto... args) { +void (*const glActiveTexture)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glActiveTexture(args...); }; -void (* const glAttachShader)(GLuint, GLuint) = [](auto... args) { +void (*const glAttachShader)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glAttachShader(args...); }; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = [](auto... args) { +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindAttribLocation(args...); }; -void (* const glBindBuffer)(GLenum, GLuint) = [](auto... args) { +void (*const glBindBuffer)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindBuffer(args...); }; -void (* const glBindFramebuffer)(GLenum, GLuint) = [](auto... args) { +void (*const glBindFramebuffer)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindFramebuffer(args...); }; -void (* const glBindRenderbuffer)(GLenum, GLuint) = [](auto... args) { +void (*const glBindRenderbuffer)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindRenderbuffer(args...); }; -void (* const glBindTexture)(GLenum, GLuint) = [](auto... args) { +void (*const glBindTexture)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBindTexture(args...); }; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendColor(args...); }; -void (* const glBlendEquation)(GLenum) = [](auto... args) { +void (*const glBlendEquation)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendEquation(args...); }; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = [](auto... args) { +void (*const glBlendEquationSeparate)(GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendEquationSeparate(args...); }; -void (* const glBlendFunc)(GLenum, GLenum) = [](auto... args) { +void (*const glBlendFunc)(GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendFunc(args...); }; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBlendFuncSeparate(args...); }; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = [](auto... args) { +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBufferData(args...); }; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = [](auto... args) { +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glBufferSubData(args...); }; -GLenum (* const glCheckFramebufferStatus)(GLenum) = [](auto... args) { +GLenum (*const glCheckFramebufferStatus)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCheckFramebufferStatus(args...); }; -void (* const glClear)(GLbitfield) = [](auto... args) { +void (*const glClear)(GLbitfield) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClear(args...); }; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClearColor(args...); }; -void (* const glClearDepthf)(GLfloat) = [](auto... args) { +void (*const glClearDepthf)(GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClearDepthf(args...); }; -void (* const glClearStencil)(GLint) = [](auto... args) { +void (*const glClearStencil)(GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glClearStencil(args...); }; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = [](auto... args) { +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glColorMask(args...); }; -void (* const glCompileShader)(GLuint) = [](auto... args) { +void (*const glCompileShader)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCompileShader(args...); }; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = [](auto... args) { - return QOpenGLContext::currentContext()->functions()->glCompressedTexImage2D(args...); -}; +void (*const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = + [](auto... args) { + return QOpenGLContext::currentContext()->functions()->glCompressedTexImage2D(args...); + }; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = [](auto... args) { - return QOpenGLContext::currentContext()->functions()->glCompressedTexSubImage2D(args...); -}; +void (*const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = + [](auto... args) { + return QOpenGLContext::currentContext()->functions()->glCompressedTexSubImage2D(args...); + }; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = [](auto... args) { +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCopyTexImage2D(args...); }; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCopyTexSubImage2D(args...); }; -GLuint (* const glCreateProgram)() = [](auto... args) { +GLuint (*const glCreateProgram)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCreateProgram(args...); }; -GLuint (* const glCreateShader)(GLenum) = [](auto... args) { +GLuint (*const glCreateShader)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCreateShader(args...); }; -void (* const glCullFace)(GLenum) = [](auto... args) { +void (*const glCullFace)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glCullFace(args...); }; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteBuffers(args...); }; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteFramebuffers(args...); }; -void (* const glDeleteProgram)(GLuint) = [](auto... args) { +void (*const glDeleteProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteProgram(args...); }; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteRenderbuffers(args...); }; -void (* const glDeleteShader)(GLuint) = [](auto... args) { +void (*const glDeleteShader)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteShader(args...); }; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = [](auto... args) { +void (*const glDeleteTextures)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDeleteTextures(args...); }; -void (* const glDepthFunc)(GLenum) = [](auto... args) { +void (*const glDepthFunc)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDepthFunc(args...); }; -void (* const glDepthMask)(GLboolean) = [](auto... args) { +void (*const glDepthMask)(GLboolean) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDepthMask(args...); }; -void (* const glDepthRangef)(GLfloat, GLfloat) = [](auto... args) { +void (*const glDepthRangef)(GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDepthRangef(args...); }; -void (* const glDetachShader)(GLuint, GLuint) = [](auto... args) { +void (*const glDetachShader)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDetachShader(args...); }; -void (* const glDisable)(GLenum) = [](auto... args) { +void (*const glDisable)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDisable(args...); }; -void (* const glDisableVertexAttribArray)(GLuint) = [](auto... args) { +void (*const glDisableVertexAttribArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDisableVertexAttribArray(args...); }; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = [](auto... args) { +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDrawArrays(args...); }; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = [](auto... args) { +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glDrawElements(args...); }; -void (* const glEnable)(GLenum) = [](auto... args) { +void (*const glEnable)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glEnable(args...); }; -void (* const glEnableVertexAttribArray)(GLuint) = [](auto... args) { +void (*const glEnableVertexAttribArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glEnableVertexAttribArray(args...); }; -void (* const glFinish)() = [](auto... args) { +void (*const glFinish)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFinish(args...); }; -void (* const glFlush)() = [](auto... args) { +void (*const glFlush)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFlush(args...); }; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = [](auto... args) { +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFramebufferRenderbuffer(args...); }; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = [](auto... args) { +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFramebufferTexture2D(args...); }; -void (* const glFrontFace)(GLenum) = [](auto... args) { +void (*const glFrontFace)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glFrontFace(args...); }; -void (* const glGenBuffers)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenBuffers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenBuffers(args...); }; -void (* const glGenerateMipmap)(GLenum) = [](auto... args) { +void (*const glGenerateMipmap)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenerateMipmap(args...); }; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenFramebuffers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenFramebuffers(args...); }; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenRenderbuffers(args...); }; -void (* const glGenTextures)(GLsizei, GLuint *) = [](auto... args) { +void (*const glGenTextures)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGenTextures(args...); }; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = [](auto... args) { +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetActiveAttrib(args...); }; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = [](auto... args) { +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetActiveUniform(args...); }; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = [](auto... args) { +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetAttachedShaders(args...); }; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = [](auto... args) { +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetAttribLocation(args...); }; -void (* const glGetBooleanv)(GLenum, GLboolean *) = [](auto... args) { +void (*const glGetBooleanv)(GLenum, GLboolean*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetBooleanv(args...); }; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetBufferParameteriv(args...); }; -GLenum (* const glGetError)() = [](auto... args) { +GLenum (*const glGetError)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetError(args...); }; -void (* const glGetFloatv)(GLenum, GLfloat *) = [](auto... args) { +void (*const glGetFloatv)(GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetFloatv(args...); }; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetFramebufferAttachmentParameteriv(args...); }; -void (* const glGetIntegerv)(GLenum, GLint *) = [](auto... args) { +void (*const glGetIntegerv)(GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetIntegerv(args...); }; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = [](auto... args) { +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetProgramInfoLog(args...); }; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = [](auto... args) { +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetProgramiv(args...); }; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetRenderbufferParameteriv(args...); }; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = [](auto... args) { +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderInfoLog(args...); }; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = [](auto... args) { +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderiv(args...); }; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = [](auto... args) { +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderPrecisionFormat(args...); }; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = [](auto... args) { +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetShaderSource(args...); }; -const GLubyte *(* const glGetString)(GLenum) = [](auto... args) { +const GLubyte* (*const glGetString)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetString(args...); }; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = [](auto... args) { +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetTexParameterfv(args...); }; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = [](auto... args) { +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetTexParameteriv(args...); }; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = [](auto... args) { +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetUniformfv(args...); }; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = [](auto... args) { +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetUniformiv(args...); }; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = [](auto... args) { +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetUniformLocation(args...); }; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = [](auto... args) { +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetVertexAttribfv(args...); }; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = [](auto... args) { +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetVertexAttribiv(args...); }; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = [](auto... args) { +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glGetVertexAttribPointerv(args...); }; -void (* const glHint)(GLenum, GLenum) = [](auto... args) { +void (*const glHint)(GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glHint(args...); }; -GLboolean (* const glIsBuffer)(GLuint) = [](auto... args) { +GLboolean (*const glIsBuffer)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsBuffer(args...); }; -GLboolean (* const glIsEnabled)(GLenum) = [](auto... args) { +GLboolean (*const glIsEnabled)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsEnabled(args...); }; -GLboolean (* const glIsFramebuffer)(GLuint) = [](auto... args) { +GLboolean (*const glIsFramebuffer)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsFramebuffer(args...); }; -GLboolean (* const glIsProgram)(GLuint) = [](auto... args) { +GLboolean (*const glIsProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsProgram(args...); }; -GLboolean (* const glIsRenderbuffer)(GLuint) = [](auto... args) { +GLboolean (*const glIsRenderbuffer)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsRenderbuffer(args...); }; -GLboolean (* const glIsShader)(GLuint) = [](auto... args) { +GLboolean (*const glIsShader)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsShader(args...); }; -GLboolean (* const glIsTexture)(GLuint) = [](auto... args) { +GLboolean (*const glIsTexture)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glIsTexture(args...); }; -void (* const glLineWidth)(GLfloat) = [](auto... args) { +void (*const glLineWidth)(GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glLineWidth(args...); }; -void (* const glLinkProgram)(GLuint) = [](auto... args) { +void (*const glLinkProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glLinkProgram(args...); }; -void (* const glPixelStorei)(GLenum, GLint) = [](auto... args) { +void (*const glPixelStorei)(GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glPixelStorei(args...); }; -void (* const glPolygonOffset)(GLfloat, GLfloat) = [](auto... args) { +void (*const glPolygonOffset)(GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glPolygonOffset(args...); }; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = [](auto... args) { +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glReadPixels(args...); }; -void (* const glReleaseShaderCompiler)() = [](auto... args) { +void (*const glReleaseShaderCompiler)() = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glReleaseShaderCompiler(args...); }; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = [](auto... args) { +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glRenderbufferStorage(args...); }; -void (* const glSampleCoverage)(GLfloat, GLboolean) = [](auto... args) { +void (*const glSampleCoverage)(GLfloat, GLboolean) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glSampleCoverage(args...); }; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glScissor(args...); }; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = [](auto... args) { +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glShaderBinary(args...); }; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = [](GLuint shader, GLsizei count, const GLchar * const * string, const GLint *length) { - return QOpenGLContext::currentContext()->functions()->glShaderSource(shader, count, const_cast(string), length); -}; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = + [](GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length) { + return QOpenGLContext::currentContext()->functions()->glShaderSource( + shader, count, const_cast(string), length); + }; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = [](auto... args) { +void (*const glStencilFunc)(GLenum, GLint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilFunc(args...); }; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = [](auto... args) { +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilFuncSeparate(args...); }; -void (* const glStencilMask)(GLuint) = [](auto... args) { +void (*const glStencilMask)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilMask(args...); }; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = [](auto... args) { +void (*const glStencilMaskSeparate)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilMaskSeparate(args...); }; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = [](auto... args) { +void (*const glStencilOp)(GLenum, GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilOp(args...); }; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glStencilOpSeparate(args...); }; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = [](auto... args) { - return QOpenGLContext::currentContext()->functions()->glTexImage2D(args...); -}; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = + [](auto... args) { + return QOpenGLContext::currentContext()->functions()->glTexImage2D(args...); + }; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = [](auto... args) { +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameterf(args...); }; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = [](auto... args) { +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameterfv(args...); }; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = [](auto... args) { +void (*const glTexParameteri)(GLenum, GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameteri(args...); }; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = [](auto... args) { +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glTexParameteriv(args...); }; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = [](auto... args) { - return QOpenGLContext::currentContext()->functions()->glTexSubImage2D(args...); -}; +void (*const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = + [](auto... args) { + return QOpenGLContext::currentContext()->functions()->glTexSubImage2D(args...); + }; -void (* const glUniform1f)(GLint, GLfloat) = [](auto... args) { +void (*const glUniform1f)(GLint, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1f(args...); }; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1fv(args...); }; -void (* const glUniform1i)(GLint, GLint) = [](auto... args) { +void (*const glUniform1i)(GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1i(args...); }; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform1iv(args...); }; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = [](auto... args) { +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2f(args...); }; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2fv(args...); }; -void (* const glUniform2i)(GLint, GLint, GLint) = [](auto... args) { +void (*const glUniform2i)(GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2i(args...); }; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform2iv(args...); }; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3f(args...); }; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3fv(args...); }; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = [](auto... args) { +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3i(args...); }; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform3iv(args...); }; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4f(args...); }; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = [](auto... args) { +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4fv(args...); }; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = [](auto... args) { +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4i(args...); }; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = [](auto... args) { +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniform4iv(args...); }; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = [](auto... args) { +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniformMatrix2fv(args...); }; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = [](auto... args) { +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniformMatrix3fv(args...); }; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = [](auto... args) { +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUniformMatrix4fv(args...); }; -void (* const glUseProgram)(GLuint) = [](auto... args) { +void (*const glUseProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glUseProgram(args...); }; -void (* const glValidateProgram)(GLuint) = [](auto... args) { +void (*const glValidateProgram)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glValidateProgram(args...); }; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = [](auto... args) { +void (*const glVertexAttrib1f)(GLuint, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib1f(args...); }; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib1fv(args...); }; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](auto... args) { +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib2f(args...); }; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib2fv(args...); }; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib3f(args...); }; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib3fv(args...); }; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib4f(args...); }; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = [](auto... args) { +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttrib4fv(args...); }; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = [](auto... args) { +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glVertexAttribPointer(args...); }; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->functions()->glViewport(args...); }; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = [](auto... args) { +void (*const glReadBuffer)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glReadBuffer(args...); }; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = [](auto... args) { +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawRangeElements(args...); }; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = [](auto... args) { - return QOpenGLContext::currentContext()->extraFunctions()->glTexImage3D(args...); -}; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = [](auto... args) { +void (*const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = + [](auto... args) { + return QOpenGLContext::currentContext()->extraFunctions()->glTexImage3D(args...); + }; +void (*const glTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTexSubImage3D(args...); }; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { - return QOpenGLContext::currentContext()->extraFunctions()->glCopyTexSubImage3D(args...); -}; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = [](auto... args) { - return QOpenGLContext::currentContext()->extraFunctions()->glCompressedTexImage3D(args...); -}; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = [](auto... args) { +void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = + [](auto... args) { + return QOpenGLContext::currentContext()->extraFunctions()->glCopyTexSubImage3D(args...); + }; +void (*const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = + [](auto... args) { + return QOpenGLContext::currentContext()->extraFunctions()->glCompressedTexImage3D(args...); + }; +void (*const glCompressedTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glCompressedTexSubImage3D(args...); }; -void (* const glGenQueries)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenQueries)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenQueries(args...); }; -void (* const glDeleteQueries)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteQueries)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteQueries(args...); }; -GLboolean (* const glIsQuery)(GLuint) = [](auto... args) { +GLboolean (*const glIsQuery)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsQuery(args...); }; -void (* const glBeginQuery)(GLenum, GLuint) = [](auto... args) { +void (*const glBeginQuery)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBeginQuery(args...); }; -void (* const glEndQuery)(GLenum) = [](auto... args) { +void (*const glEndQuery)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glEndQuery(args...); }; -void (* const glGetQueryiv)(GLenum, GLenum, GLint*) = [](auto... args) { +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetQueryiv(args...); }; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetQueryObjectuiv(args...); }; -GLboolean (* const glUnmapBuffer)(GLenum) = [](auto... args) { +GLboolean (*const glUnmapBuffer)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUnmapBuffer(args...); }; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](auto... args) { +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetBufferPointerv(args...); }; -void (* const glDrawBuffers)(GLsizei, const GLenum*) = [](auto... args) { +void (*const glDrawBuffers)(GLsizei, const GLenum*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawBuffers(args...); }; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix2x3fv(args...); }; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix3x2fv(args...); }; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix2x4fv(args...); }; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix4x2fv(args...); }; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix3x4fv(args...); }; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformMatrix4x3fv(args...); }; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = [](auto... args) { - return QOpenGLContext::currentContext()->extraFunctions()->glBlitFramebuffer(args...); -}; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { +void (*const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = + [](auto... args) { + return QOpenGLContext::currentContext()->extraFunctions()->glBlitFramebuffer(args...); + }; +void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glRenderbufferStorageMultisample(args...); }; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = [](auto... args) { +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glFramebufferTextureLayer(args...); }; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = [](auto... args) { +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glMapBufferRange(args...); }; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = [](auto... args) { +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glFlushMappedBufferRange(args...); }; -void (* const glBindVertexArray)(GLuint) = [](auto... args) { +void (*const glBindVertexArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindVertexArray(args...); }; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteVertexArrays(args...); }; -void (* const glGenVertexArrays)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenVertexArrays)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenVertexArrays(args...); }; -GLboolean (* const glIsVertexArray)(GLuint) = [](auto... args) { +GLboolean (*const glIsVertexArray)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsVertexArray(args...); }; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](auto... args) { +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetIntegeri_v(args...); }; -void (* const glBeginTransformFeedback)(GLenum) = [](auto... args) { +void (*const glBeginTransformFeedback)(GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBeginTransformFeedback(args...); }; -void (* const glEndTransformFeedback)() = [](auto... args) { +void (*const glEndTransformFeedback)() = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glEndTransformFeedback(args...); }; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = [](auto... args) { +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindBufferRange(args...); }; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = [](auto... args) { +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindBufferBase(args...); }; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = [](auto... args) { +void (*const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTransformFeedbackVaryings(args...); }; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = [](auto... args) { - return QOpenGLContext::currentContext()->extraFunctions()->glGetTransformFeedbackVarying(args...); -}; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = [](auto... args) { +void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = + [](auto... args) { + return QOpenGLContext::currentContext()->extraFunctions()->glGetTransformFeedbackVarying(args...); + }; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribIPointer(args...); }; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](auto... args) { +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetVertexAttribIiv(args...); }; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetVertexAttribIuiv(args...); }; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = [](auto... args) { +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4i(args...); }; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4ui(args...); }; -void (* const glVertexAttribI4iv)(GLuint, const GLint*) = [](auto... args) { +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4iv(args...); }; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](auto... args) { +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribI4uiv(args...); }; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](auto... args) { +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetUniformuiv(args...); }; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar*) = [](auto... args) { +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetFragDataLocation(args...); }; -void (* const glUniform1ui)(GLint, GLuint) = [](auto... args) { +void (*const glUniform1ui)(GLint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform1ui(args...); }; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = [](auto... args) { +void (*const glUniform2ui)(GLint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform2ui(args...); }; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform3ui(args...); }; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform4ui(args...); }; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform1uiv(args...); }; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform2uiv(args...); }; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform3uiv(args...); }; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniform4uiv(args...); }; -void (* const glClearBufferiv)(GLenum, GLint, const GLint*) = [](auto... args) { +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferiv(args...); }; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint*) = [](auto... args) { +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferuiv(args...); }; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat*) = [](auto... args) { +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferfv(args...); }; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = [](auto... args) { +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClearBufferfi(args...); }; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = [](auto... args) { +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetStringi(args...); }; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = [](auto... args) { +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glCopyBufferSubData(args...); }; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = [](auto... args) { +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetUniformIndices(args...); }; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = [](auto... args) { +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetActiveUniformsiv(args...); }; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](auto... args) { +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetUniformBlockIndex(args...); }; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = [](auto... args) { +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetActiveUniformBlockiv(args...); }; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetActiveUniformBlockName(args...); }; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = [](auto... args) { +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glUniformBlockBinding(args...); }; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = [](auto... args) { +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawArraysInstanced(args...); }; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = [](auto... args) { +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDrawElementsInstanced(args...); }; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = [](auto... args) { +GLsync (*const glFenceSync)(GLenum, GLbitfield) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glFenceSync(args...); }; -GLboolean (* const glIsSync)(GLsync) = [](auto... args) { +GLboolean (*const glIsSync)(GLsync) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsSync(args...); }; -void (* const glDeleteSync)(GLsync) = [](auto... args) { +void (*const glDeleteSync)(GLsync) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteSync(args...); }; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glClientWaitSync(args...); }; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glWaitSync(args...); }; -void (* const glGetInteger64v)(GLenum, GLint64*) = [](auto... args) { +void (*const glGetInteger64v)(GLenum, GLint64*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetInteger64v(args...); }; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = [](auto... args) { +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetSynciv(args...); }; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](auto... args) { +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetInteger64i_v(args...); }; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](auto... args) { +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetBufferParameteri64v(args...); }; -void (* const glGenSamplers)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenSamplers)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenSamplers(args...); }; -void (* const glDeleteSamplers)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteSamplers(args...); }; -GLboolean (* const glIsSampler)(GLuint) = [](auto... args) { +GLboolean (*const glIsSampler)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsSampler(args...); }; -void (* const glBindSampler)(GLuint, GLuint) = [](auto... args) { +void (*const glBindSampler)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindSampler(args...); }; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = [](auto... args) { +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameteri(args...); }; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = [](auto... args) { +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameteriv(args...); }; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](auto... args) { +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameterf(args...); }; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = [](auto... args) { +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glSamplerParameterfv(args...); }; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](auto... args) { +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetSamplerParameteriv(args...); }; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](auto... args) { +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetSamplerParameterfv(args...); }; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = [](auto... args) { +void (*const glVertexAttribDivisor)(GLuint, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glVertexAttribDivisor(args...); }; -void (* const glBindTransformFeedback)(GLenum, GLuint) = [](auto... args) { +void (*const glBindTransformFeedback)(GLenum, GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glBindTransformFeedback(args...); }; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](auto... args) { +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glDeleteTransformFeedbacks(args...); }; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](auto... args) { +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGenTransformFeedbacks(args...); }; -GLboolean (* const glIsTransformFeedback)(GLuint) = [](auto... args) { +GLboolean (*const glIsTransformFeedback)(GLuint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glIsTransformFeedback(args...); }; -void (* const glPauseTransformFeedback)() = [](auto... args) { +void (*const glPauseTransformFeedback)() = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glPauseTransformFeedback(args...); }; -void (* const glResumeTransformFeedback)() = [](auto... args) { +void (*const glResumeTransformFeedback)() = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glResumeTransformFeedback(args...); }; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = [](auto... args) { +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetProgramBinary(args...); }; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = [](auto... args) { +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glProgramBinary(args...); }; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = [](auto... args) { +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glProgramParameteri(args...); }; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = [](auto... args) { +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glInvalidateFramebuffer(args...); }; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = [](auto... args) { - return QOpenGLContext::currentContext()->extraFunctions()->glInvalidateSubFramebuffer(args...); -}; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { +void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = + [](auto... args) { + return QOpenGLContext::currentContext()->extraFunctions()->glInvalidateSubFramebuffer(args...); + }; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTexStorage2D(args...); }; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = [](auto... args) { +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glTexStorage3D(args...); }; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = [](auto... args) { +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = [](auto... args) { return QOpenGLContext::currentContext()->extraFunctions()->glGetInternalformativ(args...); }; -} // namespace platform -} // namespace mbgl \ No newline at end of file +} // namespace platform +} // namespace mbgl \ No newline at end of file diff --git a/platform/qt/src/mbgl/headless_backend_qt.cpp b/platform/qt/src/mbgl/headless_backend_qt.cpp index 03bf3bfb16b..bce5ae0cf5d 100644 --- a/platform/qt/src/mbgl/headless_backend_qt.cpp +++ b/platform/qt/src/mbgl/headless_backend_qt.cpp @@ -23,13 +23,9 @@ class QtBackendImpl final : public HeadlessBackend::Impl { return thisContext->getProcAddress(name); } - void activateContext() { - context.makeCurrent(&surface); - } + void activateContext() { context.makeCurrent(&surface); } - void deactivateContext() { - context.doneCurrent(); - } + void deactivateContext() { context.doneCurrent(); } private: QOpenGLContext context; diff --git a/platform/qt/src/mbgl/http_file_source.cpp b/platform/qt/src/mbgl/http_file_source.cpp index 1819aa8bcb3..43df2470715 100644 --- a/platform/qt/src/mbgl/http_file_source.cpp +++ b/platform/qt/src/mbgl/http_file_source.cpp @@ -14,13 +14,11 @@ namespace mbgl { HTTPFileSource::Impl::Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) : m_manager(new QNetworkAccessManager(this)), m_resourceOptions(resourceOptions.clone()), - m_clientOptions(clientOptions.clone()) -{ + m_clientOptions(clientOptions.clone()) { QNetworkProxyFactory::setUseSystemConfiguration(true); } -void HTTPFileSource::Impl::request(HTTPRequest* req) -{ +void HTTPFileSource::Impl::request(HTTPRequest* req) { QUrl url = req->requestUrl(); QPair, QVector>& data = m_pending[url]; @@ -33,12 +31,11 @@ void HTTPFileSource::Impl::request(HTTPRequest* req) QNetworkRequest networkRequest = req->networkRequest(); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) -# if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) - networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, - QNetworkRequest::NoLessSafeRedirectPolicy); -# elif QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) + networkRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); +#elif QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); -# endif +#endif #endif data.first = m_manager->get(networkRequest); @@ -50,8 +47,7 @@ void HTTPFileSource::Impl::request(HTTPRequest* req) #endif } -void HTTPFileSource::Impl::cancel(HTTPRequest* req) -{ +void HTTPFileSource::Impl::cancel(HTTPRequest* req) { QUrl url = req->requestUrl(); auto it = m_pending.find(url); @@ -76,9 +72,8 @@ void HTTPFileSource::Impl::cancel(HTTPRequest* req) } } -void HTTPFileSource::Impl::onReplyFinished() -{ - QNetworkReply* reply = qobject_cast(sender()); +void HTTPFileSource::Impl::onReplyFinished() { + QNetworkReply* reply = qobject_cast(sender()); const QUrl& url = reply->request().url(); auto it = m_pending.find(url); @@ -101,34 +96,28 @@ void HTTPFileSource::Impl::onReplyFinished() reply->deleteLater(); } -void HTTPFileSource::Impl::setResourceOptions(ResourceOptions options) -{ +void HTTPFileSource::Impl::setResourceOptions(ResourceOptions options) { m_resourceOptions = options; } -ResourceOptions HTTPFileSource::Impl::getResourceOptions() -{ +ResourceOptions HTTPFileSource::Impl::getResourceOptions() { return m_resourceOptions.clone(); } -void HTTPFileSource::Impl::setClientOptions(ClientOptions options) -{ +void HTTPFileSource::Impl::setClientOptions(ClientOptions options) { m_clientOptions = options; } -ClientOptions HTTPFileSource::Impl::getClientOptions() -{ +ClientOptions HTTPFileSource::Impl::getClientOptions() { return m_clientOptions.clone(); } HTTPFileSource::HTTPFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique(resourceOptions, clientOptions)) { -} + : impl(std::make_unique(resourceOptions, clientOptions)) {} HTTPFileSource::~HTTPFileSource() = default; -std::unique_ptr HTTPFileSource::request(const Resource& resource, Callback callback) -{ +std::unique_ptr HTTPFileSource::request(const Resource& resource, Callback callback) { return std::make_unique(impl.get(), resource, callback); } @@ -148,5 +137,4 @@ ClientOptions HTTPFileSource::getClientOptions() { return impl->getClientOptions(); } - } // namespace mbgl diff --git a/platform/qt/src/mbgl/http_file_source.hpp b/platform/qt/src/mbgl/http_file_source.hpp index 156c7e7f162..7ed59526f08 100644 --- a/platform/qt/src/mbgl/http_file_source.hpp +++ b/platform/qt/src/mbgl/http_file_source.hpp @@ -18,12 +18,11 @@ namespace mbgl { class HTTPRequest; -class HTTPFileSource::Impl : public QObject -{ +class HTTPFileSource::Impl : public QObject { Q_OBJECT public: - Impl(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions); + Impl(const ResourceOptions &resourceOptions, const ClientOptions &clientOptions); virtual ~Impl() = default; void request(HTTPRequest *); diff --git a/platform/qt/src/mbgl/http_request.cpp b/platform/qt/src/mbgl/http_request.cpp index ed33403a8cb..1a7e052b0fb 100644 --- a/platform/qt/src/mbgl/http_request.cpp +++ b/platform/qt/src/mbgl/http_request.cpp @@ -14,42 +14,36 @@ namespace mbgl { HTTPRequest::HTTPRequest(HTTPFileSource::Impl* context, const Resource& resource, FileSource::Callback callback) - : m_context(context) - , m_resource(resource) - , m_callback(callback) -{ + : m_context(context), + m_resource(resource), + m_callback(callback) { m_context->request(this); } -HTTPRequest::~HTTPRequest() -{ +HTTPRequest::~HTTPRequest() { if (!m_handled) { m_context->cancel(this); } } -QUrl HTTPRequest::requestUrl() const -{ +QUrl HTTPRequest::requestUrl() const { return QUrl::fromPercentEncoding(QByteArray(m_resource.url.data(), static_cast(m_resource.url.size()))); } -QNetworkRequest HTTPRequest::networkRequest() const -{ +QNetworkRequest HTTPRequest::networkRequest() const { QNetworkRequest req = QNetworkRequest(requestUrl()); req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); - static const QByteArray agent = !m_context->getClientOptions().name().empty() - ? QString("%1/%2 (%3) MapLibreGL/%4 (Qt %5)") - .arg(QString::fromStdString(m_context->getClientOptions().name())) - .arg(QString::fromStdString(m_context->getClientOptions().version())) - .arg(QSysInfo::prettyProductName()) - .arg(version::revision) - .arg(QT_VERSION_STR) - .toLatin1() - : QString("MapLibreGL/%1 (Qt %2)") - .arg(version::revision) - .arg(QT_VERSION_STR) - .toLatin1(); + static const QByteArray agent = + !m_context->getClientOptions().name().empty() + ? QString("%1/%2 (%3) MapLibreGL/%4 (Qt %5)") + .arg(QString::fromStdString(m_context->getClientOptions().name())) + .arg(QString::fromStdString(m_context->getClientOptions().version())) + .arg(QSysInfo::prettyProductName()) + .arg(version::revision) + .arg(QT_VERSION_STR) + .toLatin1() + : QString("MapLibreGL/%1 (Qt %2)").arg(version::revision).arg(QT_VERSION_STR).toLatin1(); req.setRawHeader("User-Agent", agent); if (m_resource.priorEtag) { @@ -62,8 +56,7 @@ QNetworkRequest HTTPRequest::networkRequest() const return req; } -void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& data) -{ +void HTTPRequest::handleNetworkReply(QNetworkReply* reply, const QByteArray& data) { m_handled = true; // Calling `callback` may result in deleting `this`. @@ -75,8 +68,7 @@ void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& dat // Handle non-HTTP errors (i.e. like connection). if (reply->error() && reply->error() < 100) { - response.error = std::make_unique( - Error::Reason::Connection, reply->errorString().toStdString()); + response.error = std::make_unique(Error::Reason::Connection, reply->errorString().toStdString()); callback(response); return; } @@ -84,7 +76,7 @@ void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& dat QPair line; std::optional retryAfter; std::optional xRateLimitReset; - foreach(line, reply->rawHeaderPairs()) { + foreach (line, reply->rawHeaderPairs()) { QString header = QString(line.first).toLower(); if (header == "last-modified") { @@ -116,41 +108,38 @@ void HTTPRequest::handleNetworkReply(QNetworkReply *reply, const QByteArray& dat int responseCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - switch(responseCode) { - case 200: { - if (data.isEmpty()) { - response.data = std::make_shared(); - } else { - response.data = std::make_shared(data.constData(), data.size()); + switch (responseCode) { + case 200: { + if (data.isEmpty()) { + response.data = std::make_shared(); + } else { + response.data = std::make_shared(data.constData(), data.size()); + } + break; } - break; - } - case 204: - response.noContent = true; - break; - case 304: - response.notModified = true; - break; - case 404: { - if (m_resource.kind == Resource::Kind::Tile) { + case 204: response.noContent = true; - } else { - response.error = std::make_unique( - Error::Reason::NotFound, "HTTP status code 404"); + break; + case 304: + response.notModified = true; + break; + case 404: { + if (m_resource.kind == Resource::Kind::Tile) { + response.noContent = true; + } else { + response.error = std::make_unique(Error::Reason::NotFound, "HTTP status code 404"); + } + break; } - break; - } - case 429: - response.error = std::make_unique( - Error::Reason::RateLimit, "HTTP status code 429", - http::parseRetryHeaders(retryAfter, xRateLimitReset)); - break; - default: - Response::Error::Reason reason = (responseCode >= 500 && responseCode < 600) ? - Error::Reason::Server : Error::Reason::Other; - - response.error = std::make_unique( - reason, "HTTP status code " + util::toString(responseCode)); + case 429: + response.error = std::make_unique( + Error::Reason::RateLimit, "HTTP status code 429", http::parseRetryHeaders(retryAfter, xRateLimitReset)); + break; + default: + Response::Error::Reason reason = (responseCode >= 500 && responseCode < 600) ? Error::Reason::Server + : Error::Reason::Other; + + response.error = std::make_unique(reason, "HTTP status code " + util::toString(responseCode)); } callback(response); diff --git a/platform/qt/src/mbgl/http_request.hpp b/platform/qt/src/mbgl/http_request.hpp index 2e760fc8d56..5486b686caf 100644 --- a/platform/qt/src/mbgl/http_request.hpp +++ b/platform/qt/src/mbgl/http_request.hpp @@ -12,16 +12,15 @@ namespace mbgl { class Response; -class HTTPRequest : public AsyncRequest -{ +class HTTPRequest : public AsyncRequest { public: - HTTPRequest(HTTPFileSource::Impl *, const Resource&, FileSource::Callback); + HTTPRequest(HTTPFileSource::Impl*, const Resource&, FileSource::Callback); virtual ~HTTPRequest(); QUrl requestUrl() const; QNetworkRequest networkRequest() const; - void handleNetworkReply(QNetworkReply *, const QByteArray& data); + void handleNetworkReply(QNetworkReply*, const QByteArray& data); private: HTTPFileSource::Impl* m_context; diff --git a/platform/qt/src/mbgl/image.cpp b/platform/qt/src/mbgl/image.cpp index 59816a65585..a4a69a494f8 100644 --- a/platform/qt/src/mbgl/image.cpp +++ b/platform/qt/src/mbgl/image.cpp @@ -7,8 +7,7 @@ namespace mbgl { std::string encodePNG(const PremultipliedImage& pre) { - QImage image(pre.data.get(), pre.size.width, pre.size.height, - QImage::Format_ARGB32_Premultiplied); + QImage image(pre.data.get(), pre.size.width, pre.size.height, QImage::Format_ARGB32_Premultiplied); QByteArray array; QBuffer buffer(&array); @@ -36,10 +35,9 @@ PremultipliedImage decodeImage(const std::string& string) { } #endif - QImage image = - QImage::fromData(data, static_cast(size)) - .rgbSwapped() - .convertToFormat(QImage::Format_ARGB32_Premultiplied); + QImage image = QImage::fromData(data, static_cast(size)) + .rgbSwapped() + .convertToFormat(QImage::Format_ARGB32_Premultiplied); if (image.isNull()) { throw std::runtime_error("Unsupported image type"); @@ -53,7 +51,6 @@ PremultipliedImage decodeImage(const std::string& string) { memcpy(img.get(), image.constBits(), image.byteCount()); #endif - return { { static_cast(image.width()), static_cast(image.height()) }, - std::move(img) }; -} + return {{static_cast(image.width()), static_cast(image.height())}, std::move(img)}; } +} // namespace mbgl diff --git a/platform/qt/src/mbgl/local_glyph_rasterizer.cpp b/platform/qt/src/mbgl/local_glyph_rasterizer.cpp index 8cadb54b09b..3a3e7c278c0 100644 --- a/platform/qt/src/mbgl/local_glyph_rasterizer.cpp +++ b/platform/qt/src/mbgl/local_glyph_rasterizer.cpp @@ -21,7 +21,8 @@ class LocalGlyphRasterizer::Impl { std::optional metrics; }; -LocalGlyphRasterizer::Impl::Impl(const std::optional& fontFamily_) : fontFamily(fontFamily_) { +LocalGlyphRasterizer::Impl::Impl(const std::optional& fontFamily_) + : fontFamily(fontFamily_) { if (isConfigured()) { font.setFamily(QString::fromStdString(*fontFamily)); font.setPixelSize(util::ONE_EM); @@ -36,11 +37,11 @@ bool LocalGlyphRasterizer::Impl::isConfigured() const { LocalGlyphRasterizer::LocalGlyphRasterizer(const std::optional& fontFamily) : impl(std::make_unique(fontFamily)) {} -LocalGlyphRasterizer::~LocalGlyphRasterizer() { -} +LocalGlyphRasterizer::~LocalGlyphRasterizer() {} bool LocalGlyphRasterizer::canRasterizeGlyph(const FontStack&, GlyphID glyphID) { - return impl->isConfigured() && impl->metrics->inFont(glyphID) && util::i18n::allowsFixedWidthGlyphGeneration(glyphID); + return impl->isConfigured() && impl->metrics->inFont(glyphID) && + util::i18n::allowsFixedWidthGlyphGeneration(glyphID); } Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack&, GlyphID glyphID) { @@ -80,7 +81,7 @@ Glyph LocalGlyphRasterizer::rasterizeGlyph(const FontStack&, GlyphID glyphID) { memcpy(img.get(), image.constBits(), image.byteCount()); #endif - glyph.bitmap = AlphaImage { size, std::move(img) }; + glyph.bitmap = AlphaImage{size, std::move(img)}; return glyph; } diff --git a/platform/qt/src/mbgl/number_format.cpp b/platform/qt/src/mbgl/number_format.cpp index b6fe3558e6f..f792439c98c 100644 --- a/platform/qt/src/mbgl/number_format.cpp +++ b/platform/qt/src/mbgl/number_format.cpp @@ -6,9 +6,11 @@ namespace mbgl { namespace platform { -std::string formatNumber(double number, const std::string& localeId, const std::string& currency, - uint8_t minFractionDigits, uint8_t maxFractionDigits) { - +std::string formatNumber(double number, + const std::string& localeId, + const std::string& currency, + uint8_t minFractionDigits, + uint8_t maxFractionDigits) { QString formatted; // Qt Locale::toString() API takes only one precision argument (void)minFractionDigits; diff --git a/platform/qt/src/mbgl/run_loop.cpp b/platform/qt/src/mbgl/run_loop.cpp index 7394fc7bc28..6bd9cb035c5 100644 --- a/platform/qt/src/mbgl/run_loop.cpp +++ b/platform/qt/src/mbgl/run_loop.cpp @@ -24,14 +24,15 @@ RunLoop* RunLoop::Get() { return static_cast(Scheduler::GetCurrent()); } -RunLoop::RunLoop(Type type) : impl(std::make_unique()) { +RunLoop::RunLoop(Type type) + : impl(std::make_unique()) { switch (type) { - case Type::New: - impl->loop = std::make_unique(); - break; - case Type::Default: - // Use QCoreApplication::instance(). - break; + case Type::New: + impl->loop = std::make_unique(); + break; + case Type::Default: + // Use QCoreApplication::instance(). + break; } impl->type = type; @@ -119,5 +120,5 @@ void RunLoop::removeWatch(int fd) { } } -} -} +} // namespace util +} // namespace mbgl diff --git a/platform/qt/src/mbgl/sqlite3.cpp b/platform/qt/src/mbgl/sqlite3.cpp index b3f5abdb394..9afd08707a3 100644 --- a/platform/qt/src/mbgl/sqlite3.cpp +++ b/platform/qt/src/mbgl/sqlite3.cpp @@ -26,30 +26,28 @@ namespace sqlite { void checkQueryError(const QSqlQuery& query) { QSqlError lastError = query.lastError(); if (lastError.type() != QSqlError::NoError) { - throw Exception { lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString() }; + throw Exception{lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString()}; } } -void checkDatabaseError(const QSqlDatabase &db) { +void checkDatabaseError(const QSqlDatabase& db) { QSqlError lastError = db.lastError(); if (lastError.type() != QSqlError::NoError) { - throw Exception { lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString() }; + throw Exception{lastError.nativeErrorCode().toInt(), lastError.databaseText().toStdString()}; } } namespace { - QString incrementCounter() { - static QAtomicInt count = 0; - return QString::number(count.fetchAndAddAcquire(1)); - } +QString incrementCounter() { + static QAtomicInt count = 0; + return QString::number(count.fetchAndAddAcquire(1)); } +} // namespace class DatabaseImpl { public: DatabaseImpl(QString connectionName_) - : connectionName(std::move(connectionName_)) - { - } + : connectionName(std::move(connectionName_)) {} ~DatabaseImpl() { auto db = QSqlDatabase::database(connectionName); @@ -65,24 +63,23 @@ class DatabaseImpl { class StatementImpl { public: - StatementImpl(const QString& sql, const QSqlDatabase& db) : query(db) { + StatementImpl(const QString& sql, const QSqlDatabase& db) + : query(db) { if (!query.prepare(sql)) { checkQueryError(query); } } - ~StatementImpl() { - query.clear(); - } + ~StatementImpl() { query.clear(); } QSqlQuery query; int64_t lastInsertRowId = 0; int64_t changes = 0; }; -mapbox::util::variant Database::tryOpen(const std::string &filename, int flags) { +mapbox::util::variant Database::tryOpen(const std::string& filename, int flags) { if (!QSqlDatabase::drivers().contains("QSQLITE")) { - return Exception { ResultCode::CantOpen, "SQLite driver not found." }; + return Exception{ResultCode::CantOpen, "SQLite driver not found."}; } QString connectionName = QString::number(uint64_t(QThread::currentThread())) + incrementCounter(); @@ -107,13 +104,13 @@ mapbox::util::variant Database::tryOpen(const std::string & if (!db.open()) { // Assume every error when opening the data as CANTOPEN. Qt // always returns -1 for `nativeErrorCode()` on database errors. - return Exception { ResultCode::CantOpen, "Error opening the database." }; + return Exception{ResultCode::CantOpen, "Error opening the database."}; } return Database(std::make_unique(connectionName)); } -Database Database::open(const std::string &filename, int flags) { +Database Database::open(const std::string& filename, int flags) { auto result = tryOpen(filename, flags); if (result.is()) { throw result.get(); @@ -123,22 +120,20 @@ Database Database::open(const std::string &filename, int flags) { } Database::Database(std::unique_ptr impl_) - : impl(std::move(impl_)) -{} + : impl(std::move(impl_)) {} -Database::Database(Database &&other) noexcept - : impl(std::move(other.impl)) { +Database::Database(Database&& other) noexcept + : impl(std::move(other.impl)) { assert(impl); } -Database &Database::operator=(Database &&other) noexcept { +Database& Database::operator=(Database&& other) noexcept { std::swap(impl, other.impl); assert(impl); return *this; } -Database::~Database() { -} +Database::~Database() {} void Database::setBusyTimeout(std::chrono::milliseconds timeout) { assert(impl); @@ -163,11 +158,11 @@ void DatabaseImpl::setBusyTimeout(std::chrono::milliseconds timeout) { if (!db.open()) { // Assume every error when opening the data as CANTOPEN. Qt // always returns -1 for `nativeErrorCode()` on database errors. - throw Exception { ResultCode::CantOpen, "Error opening the database." }; + throw Exception{ResultCode::CantOpen, "Error opening the database."}; } } -void Database::exec(const std::string &sql) { +void Database::exec(const std::string& sql) { assert(impl); impl->exec(sql); } @@ -193,8 +188,7 @@ void DatabaseImpl::exec(const std::string& sql) { } Statement::Statement(Database& db, const char* sql) - : impl(std::make_unique(QString(sql), - QSqlDatabase::database(db.impl->connectionName))) { + : impl(std::make_unique(QString(sql), QSqlDatabase::database(db.impl->connectionName))) { assert(impl); } @@ -205,7 +199,8 @@ Statement::~Statement() { #endif } -Query::Query(Statement& stmt_) : stmt(stmt_) { +Query::Query(Statement& stmt_) + : stmt(stmt_) { assert(stmt.impl); #ifndef NDEBUG @@ -314,8 +309,10 @@ void Query::bindBlob(int offset, const void* value_, std::size_t length, bool re } // Field numbering starts at 0. - stmt.impl->query.bindValue(offset - 1, retain ? QByteArray(value, static_cast(length)) : - QByteArray::fromRawData(value, static_cast(length)), QSql::In | QSql::Binary); + stmt.impl->query.bindValue( + offset - 1, + retain ? QByteArray(value, static_cast(length)) : QByteArray::fromRawData(value, static_cast(length)), + QSql::In | QSql::Binary); checkQueryError(stmt.impl->query); } @@ -328,12 +325,12 @@ bool Query::run() { assert(stmt.impl); if (!stmt.impl->query.isValid()) { - if (stmt.impl->query.exec()) { - stmt.impl->lastInsertRowId = stmt.impl->query.lastInsertId().value(); - stmt.impl->changes = stmt.impl->query.numRowsAffected(); - } else { - checkQueryError(stmt.impl->query); - } + if (stmt.impl->query.exec()) { + stmt.impl->lastInsertRowId = stmt.impl->query.lastInsertId().value(); + stmt.impl->changes = stmt.impl->query.numRowsAffected(); + } else { + checkQueryError(stmt.impl->query); + } } const bool hasNext = stmt.impl->query.next(); @@ -347,14 +344,16 @@ template int Query::get(int); template int64_t Query::get(int); template double Query::get(int); -template T Query::get(int offset) { +template +T Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); return value.value(); } -template <> std::vector Query::get(int offset) { +template <> +std::vector Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QByteArray byteArray = stmt.impl->query.value(offset).toByteArray(); checkQueryError(stmt.impl->query); @@ -362,7 +361,8 @@ template <> std::vector Query::get(int offset) { return blob; } -template <> mbgl::Timestamp Query::get(int offset) { +template <> +mbgl::Timestamp Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); @@ -370,48 +370,49 @@ template <> mbgl::Timestamp Query::get(int offset) { std::chrono::system_clock::from_time_t(value.value<::time_t>())); } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { value.value() }; + if (value.isNull()) return {}; + return {value.value()}; } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { value.value() }; + if (value.isNull()) return {}; + return {value.value()}; } -template <> std::string Query::get(int offset) { +template <> +std::string Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QByteArray value = stmt.impl->query.value(offset).toByteArray(); checkQueryError(stmt.impl->query); return std::string(value.constData(), value.size()); } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QByteArray value = stmt.impl->query.value(offset).toByteArray(); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { std::string(value.constData(), value.size()) }; + if (value.isNull()) return {}; + return {std::string(value.constData(), value.size())}; } -template <> std::optional Query::get(int offset) { +template <> +std::optional Query::get(int offset) { assert(stmt.impl && stmt.impl->query.isValid()); QVariant value = stmt.impl->query.value(offset); checkQueryError(stmt.impl->query); - if (value.isNull()) - return {}; - return { std::chrono::time_point_cast( - std::chrono::system_clock::from_time_t(value.value<::time_t>())) }; + if (value.isNull()) return {}; + return { + std::chrono::time_point_cast(std::chrono::system_clock::from_time_t(value.value<::time_t>()))}; } void Query::reset() { @@ -436,15 +437,15 @@ uint64_t Query::changes() const { Transaction::Transaction(Database& db_, Mode mode) : dbImpl(*db_.impl) { switch (mode) { - case Deferred: - dbImpl.exec("BEGIN DEFERRED TRANSACTION"); - break; - case Immediate: - dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); - break; - case Exclusive: - dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); - break; + case Deferred: + dbImpl.exec("BEGIN DEFERRED TRANSACTION"); + break; + case Immediate: + dbImpl.exec("BEGIN IMMEDIATE TRANSACTION"); + break; + case Exclusive: + dbImpl.exec("BEGIN EXCLUSIVE TRANSACTION"); + break; } } diff --git a/platform/qt/src/mbgl/thread.cpp b/platform/qt/src/mbgl/thread.cpp index 6c7d14042d5..cee03b252bf 100644 --- a/platform/qt/src/mbgl/thread.cpp +++ b/platform/qt/src/mbgl/thread.cpp @@ -10,19 +10,15 @@ std::string getCurrentThreadName() { return "unknown"; } -void setCurrentThreadName(const std::string&) { -} +void setCurrentThreadName(const std::string&) {} -void makeThreadLowPriority() { -} +void makeThreadLowPriority() {} void setCurrentThreadPriority(double) {} -void attachThread() { -} +void attachThread() {} -void detachThread() { -} +void detachThread() {} } // namespace platform } // namespace mbgl diff --git a/platform/qt/src/mbgl/thread_local.cpp b/platform/qt/src/mbgl/thread_local.cpp index 60b1d038959..1f69a8aac36 100644 --- a/platform/qt/src/mbgl/thread_local.cpp +++ b/platform/qt/src/mbgl/thread_local.cpp @@ -9,8 +9,9 @@ namespace mbgl { namespace util { namespace impl { -// QThreadStorage tries to be smart and take ownership of the data, which we don't want. So we're -// wrapping it in another type which doesn't own the pointer it contains. +// QThreadStorage tries to be smart and take ownership of the data, which we +// don't want. So we're wrapping it in another type which doesn't own the +// pointer it contains. using StorageType = QThreadStorage>; ThreadLocalBase::ThreadLocalBase() { @@ -20,8 +21,8 @@ ThreadLocalBase::ThreadLocalBase() { } ThreadLocalBase::~ThreadLocalBase() { - // ThreadLocal will not take ownership of the pointer it is managing. The pointer - // needs to be explicitly cleared before we destroy this object. + // ThreadLocal will not take ownership of the pointer it is managing. The + // pointer needs to be explicitly cleared before we destroy this object. assert(!get()); reinterpret_cast(storage).~QThreadStorage(); } @@ -31,7 +32,7 @@ void* ThreadLocalBase::get() { } void ThreadLocalBase::set(void* ptr) { - reinterpret_cast(storage).setLocalData({{ ptr }}); + reinterpret_cast(storage).setLocalData({{ptr}}); } } // namespace impl diff --git a/platform/qt/src/mbgl/timer.cpp b/platform/qt/src/mbgl/timer.cpp index e7e1195c0d2..2980c9de9ec 100644 --- a/platform/qt/src/mbgl/timer.cpp +++ b/platform/qt/src/mbgl/timer.cpp @@ -13,7 +13,7 @@ Timer::Impl::Impl() { connect(&timer, &QTimer::timeout, this, &Timer::Impl::timerFired); } -void Timer::Impl::start(uint64_t timeout, uint64_t repeat_, std::function&& cb) { +void Timer::Impl::start(uint64_t timeout, uint64_t repeat_, std::function&& cb) { repeat = repeat_; callback = std::move(cb); @@ -43,8 +43,7 @@ void Timer::Impl::timerFired() { } Timer::Timer() - : impl(std::make_unique()) { -} + : impl(std::make_unique()) {} Timer::~Timer() = default; @@ -58,5 +57,5 @@ void Timer::stop() { impl->stop(); } -} -} +} // namespace util +} // namespace mbgl diff --git a/platform/qt/src/mbgl/timer_impl.hpp b/platform/qt/src/mbgl/timer_impl.hpp index ea22b20974e..c5d73e12af6 100644 --- a/platform/qt/src/mbgl/timer_impl.hpp +++ b/platform/qt/src/mbgl/timer_impl.hpp @@ -14,7 +14,7 @@ class Timer::Impl : public QObject { public: Impl(); - void start(uint64_t timeout, uint64_t repeat, std::function &&); + void start(uint64_t timeout, uint64_t repeat, std::function &&); void stop(); public slots: diff --git a/platform/qt/src/settings.cpp b/platform/qt/src/settings.cpp index 91dfb98bfd5..86a6c8e15ed 100644 --- a/platform/qt/src/settings.cpp +++ b/platform/qt/src/settings.cpp @@ -10,45 +10,64 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4805) +#pragma warning(disable : 4805) #endif // mbgl::GLContextMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::UniqueGLContext) == mbgl::underlying_type(mbgl::gfx::ContextMode::Unique), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::SharedGLContext) == mbgl::underlying_type(mbgl::gfx::ContextMode::Shared), "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::UniqueGLContext) == + mbgl::underlying_type(mbgl::gfx::ContextMode::Unique), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::SharedGLContext) == + mbgl::underlying_type(mbgl::gfx::ContextMode::Shared), + "error"); // mbgl::MapMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::Continuous) == mbgl::underlying_type(mbgl::MapMode::Continuous), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::Static) == mbgl::underlying_type(mbgl::MapMode::Static), "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::Continuous) == + mbgl::underlying_type(mbgl::MapMode::Continuous), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::Static) == mbgl::underlying_type(mbgl::MapMode::Static), + "error"); // mbgl::ConstrainMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::NoConstrain) == mbgl::underlying_type(mbgl::ConstrainMode::None), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::ConstrainHeightOnly) == mbgl::underlying_type(mbgl::ConstrainMode::HeightOnly), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::ConstrainWidthAndHeight) == mbgl::underlying_type(mbgl::ConstrainMode::WidthAndHeight), "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::NoConstrain) == + mbgl::underlying_type(mbgl::ConstrainMode::None), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::ConstrainHeightOnly) == + mbgl::underlying_type(mbgl::ConstrainMode::HeightOnly), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::ConstrainWidthAndHeight) == + mbgl::underlying_type(mbgl::ConstrainMode::WidthAndHeight), + "error"); // mbgl::ViewportMode -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::DefaultViewport) == mbgl::underlying_type(mbgl::ViewportMode::Default), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Settings::FlippedYViewport) == mbgl::underlying_type(mbgl::ViewportMode::FlippedY), "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::DefaultViewport) == + mbgl::underlying_type(mbgl::ViewportMode::Default), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Settings::FlippedYViewport) == + mbgl::underlying_type(mbgl::ViewportMode::FlippedY), + "error"); #ifdef _MSC_VER #pragma warning(pop) #endif - namespace QMapLibreGL { /*! \class QMapLibreGL::Settings - \brief The Settings class stores the initial configuration for QMapLibreGL::Map. + \brief The Settings class stores the initial configuration for + QMapLibreGL::Map. \inmodule MapLibre Maps SDK for Qt - Settings is used to configure QMapLibreGL::Map at the moment of its creation. - Once created, the Settings of a QMapLibreGL::Map can no longer be changed. + Settings is used to configure QMapLibreGL::Map at the moment of its + creation. Once created, the Settings of a QMapLibreGL::Map can no longer be + changed. - Cache-related settings are shared between all QMapLibreGL::Map instances using the same cache path. - The first map to configure cache properties such as size will force the configuration - to all newly instantiated QMapLibreGL::Map objects using the same cache in the same process. + Cache-related settings are shared between all QMapLibreGL::Map instances + using the same cache path. The first map to configure cache properties such + as size will force the configuration to all newly instantiated + QMapLibreGL::Map objects using the same cache in the same process. */ /*! @@ -56,15 +75,15 @@ namespace QMapLibreGL { This enum sets the expectations for the OpenGL state. - \value UniqueGLContext The OpenGL context is only used by QMapLibreGL::Map, so it is not - reset before each rendering. Use this mode if the intention is to only draw a - fullscreen map. + \value UniqueGLContext The OpenGL context is only used by QMapLibreGL::Map, + so it is not reset before each rendering. Use this mode if the intention is + to only draw a fullscreen map. \value SharedGLContext The OpenGL context is shared and the state will be marked dirty - which invalidates any previously assumed GL state. The embedder is responsible for clearing up the viewport prior to calling - QMapLibreGL::Map::render. The embedder is also responsible for resetting its own - GL state after QMapLibreGL::Map::render has finished, if needed. + QMapLibreGL::Map::render. The embedder is also responsible for resetting its + own GL state after QMapLibreGL::Map::render has finished, if needed. \sa contextMode() */ @@ -95,15 +114,15 @@ namespace QMapLibreGL { This enum determines if the map wraps. - \value NoConstrain The map will wrap on the horizontal axis. Since it doesn't - make sense to wrap on the vertical axis in a Web Mercator projection, the map will scroll - and show some empty space. + \value NoConstrain The map will wrap on the horizontal axis. + Since it doesn't make sense to wrap on the vertical axis in a Web Mercator + projection, the map will scroll and show some empty space. - \value ConstrainHeightOnly The map will wrap around the horizontal axis, like a spinning - globe. This is the recommended constrain mode. + \value ConstrainHeightOnly The map will wrap around the horizontal + axis, like a spinning globe. This is the recommended constrain mode. - \value ConstrainWidthAndHeight The map won't wrap and panning is restricted to the boundaries - of the map. + \value ConstrainWidthAndHeight The map won't wrap and panning is restricted + to the boundaries of the map. \sa constrainMode() */ @@ -125,17 +144,15 @@ namespace QMapLibreGL { configuration is valid for initializing a QMapLibreGL::Map. */ Settings::Settings() - : m_contextMode(Settings::SharedGLContext) - , m_mapMode(Settings::Continuous) - , m_constrainMode(Settings::ConstrainHeightOnly) - , m_viewportMode(Settings::DefaultViewport) - , m_cacheMaximumSize(mbgl::util::DEFAULT_MAX_CACHE_SIZE) - , m_cacheDatabasePath(":memory:") - , m_assetPath(QCoreApplication::applicationDirPath()) - , m_apiKey(qgetenv("MLN_API_KEY")) - , m_tileServerOptionsInternal(new mbgl::TileServerOptions(mbgl::TileServerOptions::DefaultConfiguration())) -{ -} + : m_contextMode(Settings::SharedGLContext), + m_mapMode(Settings::Continuous), + m_constrainMode(Settings::ConstrainHeightOnly), + m_viewportMode(Settings::DefaultViewport), + m_cacheMaximumSize(mbgl::util::DEFAULT_MAX_CACHE_SIZE), + m_cacheDatabasePath(":memory:"), + m_assetPath(QCoreApplication::applicationDirPath()), + m_apiKey(qgetenv("MLN_API_KEY")), + m_tileServerOptionsInternal(new mbgl::TileServerOptions(mbgl::TileServerOptions::DefaultConfiguration())) {} /*! Returns the OpenGL context mode. This is specially important when mixing @@ -143,16 +160,14 @@ Settings::Settings() By default, it is set to Settings::SharedGLContext. */ -Settings::GLContextMode Settings::contextMode() const -{ +Settings::GLContextMode Settings::contextMode() const { return m_contextMode; } /*! Sets the OpenGL context \a mode. */ -void Settings::setContextMode(GLContextMode mode) -{ +void Settings::setContextMode(GLContextMode mode) { m_contextMode = mode; } @@ -168,16 +183,14 @@ void Settings::setContextMode(GLContextMode mode) By default, it is set to QMapLibreGL::Settings::Continuous. */ -Settings::MapMode Settings::mapMode() const -{ +Settings::MapMode Settings::mapMode() const { return m_mapMode; } /*! Sets the map \a mode. */ -void Settings::setMapMode(MapMode mode) -{ +void Settings::setMapMode(MapMode mode) { m_mapMode = mode; } @@ -187,16 +200,14 @@ void Settings::setMapMode(MapMode mode) By default, it is set to QMapLibreGL::Settings::ConstrainHeightOnly. */ -Settings::ConstrainMode Settings::constrainMode() const -{ +Settings::ConstrainMode Settings::constrainMode() const { return m_constrainMode; } /*! Sets the map constrain \a mode. */ -void Settings::setConstrainMode(ConstrainMode mode) -{ +void Settings::setConstrainMode(ConstrainMode mode) { m_constrainMode = mode; } @@ -206,16 +217,14 @@ void Settings::setConstrainMode(ConstrainMode mode) By default, it is set to QMapLibreGL::Settings::DefaultViewport. */ -Settings::ViewportMode Settings::viewportMode() const -{ +Settings::ViewportMode Settings::viewportMode() const { return m_viewportMode; } /*! Sets the viewport \a mode. */ -void Settings::setViewportMode(ViewportMode mode) -{ +void Settings::setViewportMode(ViewportMode mode) { m_viewportMode = mode; } @@ -227,16 +236,14 @@ void Settings::setViewportMode(ViewportMode mode) By default, it is set to 50 MB. */ -unsigned Settings::cacheDatabaseMaximumSize() const -{ +unsigned Settings::cacheDatabaseMaximumSize() const { return m_cacheMaximumSize; } /*! Returns the maximum allowed cache database \a size in bytes. */ -void Settings::setCacheDatabaseMaximumSize(unsigned size) -{ +void Settings::setCacheDatabaseMaximumSize(unsigned size) { m_cacheMaximumSize = size; } @@ -250,8 +257,7 @@ void Settings::setCacheDatabaseMaximumSize(unsigned size) By default, it is set to \c :memory: meaning it will create an in-memory cache instead of a file on disk. */ -QString Settings::cacheDatabasePath() const -{ +QString Settings::cacheDatabasePath() const { return m_cacheDatabasePath; } @@ -260,8 +266,7 @@ QString Settings::cacheDatabasePath() const Setting the \a path to \c :memory: will create an in-memory cache. */ -void Settings::setCacheDatabasePath(const QString &path) -{ +void Settings::setCacheDatabasePath(const QString &path) { m_cacheDatabasePath = path; } @@ -273,16 +278,14 @@ void Settings::setCacheDatabasePath(const QString &path) By default, it is set to the value returned by QCoreApplication::applicationDirPath(). */ -QString Settings::assetPath() const -{ +QString Settings::assetPath() const { return m_assetPath; } /*! Sets the asset \a path. */ -void Settings::setAssetPath(const QString &path) -{ +void Settings::setAssetPath(const QString &path) { m_assetPath = path; } @@ -302,16 +305,14 @@ QString Settings::apiKey() const { MapTiler-hosted and Mapbox-hosted vector tiles and styles require an API key or access token. */ -void Settings::setApiKey(const QString &key) -{ +void Settings::setApiKey(const QString &key) { m_apiKey = key; } /*! Returns the API base URL. */ -QString Settings::apiBaseUrl() const -{ +QString Settings::apiBaseUrl() const { return QString::fromStdString(m_tileServerOptionsInternal->baseURL()); } @@ -322,61 +323,55 @@ QString Settings::apiBaseUrl() const be resolved to. It defaults to "https://api.mapbox.com" but can be changed, for instance, to a tile cache server address. */ -void Settings::setApiBaseUrl(const QString& url) -{ +void Settings::setApiBaseUrl(const QString &url) { m_tileServerOptionsInternal = &m_tileServerOptionsInternal->withBaseURL(url.toStdString()); } /*! Returns the local font family. Returns an empty string if no local font family is set. */ -QString Settings::localFontFamily() const -{ +QString Settings::localFontFamily() const { return m_localFontFamily; } /*! Sets the local font family. - Rendering Chinese/Japanese/Korean (CJK) ideographs and precomposed Hangul Syllables requires - downloading large amounts of font data, which can significantly slow map load times. Use the - localIdeographFontFamily setting to speed up map load times by using locally available fonts - instead of font data fetched from the server. + Rendering Chinese/Japanese/Korean (CJK) ideographs and precomposed Hangul + Syllables requires downloading large amounts of font data, which can + significantly slow map load times. Use the localIdeographFontFamily setting + to speed up map load times by using locally available fonts instead of font + data fetched from the server. */ -void Settings::setLocalFontFamily(const QString &family) -{ +void Settings::setLocalFontFamily(const QString &family) { m_localFontFamily = family; } /*! Returns the client name. Returns an empty string if no client name is set. */ -QString Settings::clientName() const -{ +QString Settings::clientName() const { return m_clientName; } /*! Sets the client name. */ -void Settings::setClientName(const QString &name) -{ +void Settings::setClientName(const QString &name) { m_clientName = name; } /*! Returns the client version. Returns an empty string if no client version is set. */ -QString Settings::clientVersion() const -{ +QString Settings::clientVersion() const { return m_clientVersion; } /*! Sets the client version. */ -void Settings::setClientVersion(const QString &version) -{ +void Settings::setClientVersion(const QString &version) { m_clientVersion = version; } @@ -407,17 +402,16 @@ void Settings::setResourceTransform(const std::function > Settings::defaultStyles() const { +QVector> Settings::defaultStyles() const { QVector> styles; for (const auto &style : tileServerOptionsInternal()->defaultStyles()) { - styles.append(QPair( - QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName()))); + styles.append( + QPair(QString::fromStdString(style.getUrl()), QString::fromStdString(style.getName()))); } return styles; } diff --git a/platform/qt/src/types.cpp b/platform/qt/src/types.cpp index b766e255344..825861e0058 100644 --- a/platform/qt/src/types.cpp +++ b/platform/qt/src/types.cpp @@ -4,9 +4,14 @@ #include "mbgl/util/traits.hpp" // mbgl::FeatureType -static_assert(mbgl::underlying_type(QMapLibreGL::Feature::PointType) == mbgl::underlying_type(mbgl::FeatureType::Point), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Feature::LineStringType) == mbgl::underlying_type(mbgl::FeatureType::LineString), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Feature::PolygonType) == mbgl::underlying_type(mbgl::FeatureType::Polygon), "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Feature::PointType) == mbgl::underlying_type(mbgl::FeatureType::Point), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Feature::LineStringType) == + mbgl::underlying_type(mbgl::FeatureType::LineString), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Feature::PolygonType) == + mbgl::underlying_type(mbgl::FeatureType::Polygon), + "error"); namespace QMapLibreGL { @@ -72,11 +77,13 @@ namespace QMapLibreGL { /*! \enum QMapLibreGL::Feature::Type - This enum is used as basis for geometry disambiguation in QMapLibreGL::Feature. + This enum is used as basis for geometry disambiguation in + QMapLibreGL::Feature. - \value PointType A point geometry type. Means a single or a collection of points. - \value LineStringType A line string geometry type. Means a single or a collection of line strings. - \value PolygonType A polygon geometry type. Means a single or a collection of polygons. + \value PointType A point geometry type. Means a single or a collection + of points. \value LineStringType A line string geometry type. Means a single + or a collection of line strings. \value PolygonType A polygon geometry + type. Means a single or a collection of polygons. */ /*! @@ -113,7 +120,8 @@ namespace QMapLibreGL { Represents a line annotation object, along with its properties. - A line annotation comprises of its geometry and line properties such as opacity, width and color. + A line annotation comprises of its geometry and line properties such as + opacity, width and color. */ /*! @@ -123,14 +131,16 @@ namespace QMapLibreGL { Represents a fill annotation object, along with its properties. - A fill annotation comprises of its geometry and fill properties such as opacity, color and outline color. + A fill annotation comprises of its geometry and fill properties such as + opacity, color and outline color. */ /*! \typedef QMapLibreGL::Annotation Alias for QVariant. - Container that encapsulates either a symbol, a line, a fill or a style sourced annotation. + Container that encapsulates either a symbol, a line, a fill or a style + sourced annotation. */ /*! @@ -165,8 +175,8 @@ namespace QMapLibreGL { \class QMapLibreGL::CustomLayerRenderParameters \inmodule MapLibre Maps SDK for Qt - QMapLibreGL::CustomLayerRenderParameters provides the data passed on each render - pass for a custom layer. + QMapLibreGL::CustomLayerRenderParameters provides the data passed on each + render pass for a custom layer. */ } // namespace QMapLibreGL diff --git a/platform/qt/src/utils.cpp b/platform/qt/src/utils.cpp index e27769728f2..7b670cbc5f8 100644 --- a/platform/qt/src/utils.cpp +++ b/platform/qt/src/utils.cpp @@ -8,8 +8,11 @@ #include // mbgl::NetworkStatus::Status -static_assert(mbgl::underlying_type(QMapLibreGL::Online) == mbgl::underlying_type(mbgl::NetworkStatus::Status::Online), "error"); -static_assert(mbgl::underlying_type(QMapLibreGL::Offline) == mbgl::underlying_type(mbgl::NetworkStatus::Status::Offline), "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Online) == mbgl::underlying_type(mbgl::NetworkStatus::Status::Online), + "error"); +static_assert(mbgl::underlying_type(QMapLibreGL::Offline) == + mbgl::underlying_type(mbgl::NetworkStatus::Status::Offline), + "error"); namespace QMapLibreGL { @@ -27,8 +30,7 @@ namespace QMapLibreGL { Returns the current QMapLibreGL::NetworkMode. */ -NetworkMode networkMode() -{ +NetworkMode networkMode() { return static_cast(mbgl::NetworkStatus::Get()); } @@ -40,34 +42,32 @@ NetworkMode networkMode() File source requests uses the available network when \a mode is set to \b Online, otherwise scoped to the local cache. */ -void setNetworkMode(NetworkMode mode) -{ +void setNetworkMode(NetworkMode mode) { mbgl::NetworkStatus::Set(static_cast(mode)); } /*! Returns the amount of meters per pixel from a given \a latitude and \a zoom. */ -double metersPerPixelAtLatitude(double latitude, double zoom) -{ +double metersPerPixelAtLatitude(double latitude, double zoom) { return mbgl::Projection::getMetersPerPixelAtLatitude(latitude, zoom); } /*! Return the projected meters for a given \a coordinate object. */ -ProjectedMeters projectedMetersForCoordinate(const Coordinate &coordinate) -{ - auto projectedMeters = mbgl::Projection::projectedMetersForLatLng(mbgl::LatLng { coordinate.first, coordinate.second }); +ProjectedMeters projectedMetersForCoordinate(const Coordinate &coordinate) { + auto projectedMeters = mbgl::Projection::projectedMetersForLatLng( + mbgl::LatLng{coordinate.first, coordinate.second}); return ProjectedMeters(projectedMeters.northing(), projectedMeters.easting()); } /*! Returns the coordinate for a given \a projectedMeters object. */ -Coordinate coordinateForProjectedMeters(const ProjectedMeters &projectedMeters) -{ - auto latLng = mbgl::Projection::latLngForProjectedMeters(mbgl::ProjectedMeters { projectedMeters.first, projectedMeters.second }); +Coordinate coordinateForProjectedMeters(const ProjectedMeters &projectedMeters) { + auto latLng = mbgl::Projection::latLngForProjectedMeters( + mbgl::ProjectedMeters{projectedMeters.first, projectedMeters.second}); return Coordinate(latLng.latitude(), latLng.longitude()); } diff --git a/platform/qt/src/utils/conversion.hpp b/platform/qt/src/utils/conversion.hpp index 678588e6e47..9bd5ec46a4f 100644 --- a/platform/qt/src/utils/conversion.hpp +++ b/platform/qt/src/utils/conversion.hpp @@ -16,14 +16,12 @@ namespace mbgl { namespace style { namespace conversion { -std::string convertColor(const QColor &color); +std::string convertColor(const QColor& color); template <> class ConversionTraits { public: - static bool isUndefined(const QVariant& value) { - return value.isNull() || !value.isValid(); - } + static bool isUndefined(const QVariant& value) { return value.isNull() || !value.isValid(); } static bool isArray(const QVariant& value) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) @@ -43,16 +41,15 @@ class ConversionTraits { static bool isObject(const QVariant& value) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - return QMetaType::canConvert(value.metaType(), QMetaType(QMetaType::QVariantMap)) - || value.typeId() == QMetaType::QByteArray + return QMetaType::canConvert(value.metaType(), QMetaType(QMetaType::QVariantMap)) || + value.typeId() == QMetaType::QByteArray #else - return value.canConvert(QVariant::Map) - || value.type() == QVariant::ByteArray + return value.canConvert(QVariant::Map) || value.type() == QVariant::ByteArray #endif - || QString(value.typeName()) == QStringLiteral("QMapLibreGL::Feature") - || value.userType() == qMetaTypeId>() - || value.userType() == qMetaTypeId>() - || value.userType() == qMetaTypeId>(); + || QString(value.typeName()) == QStringLiteral("QMapLibreGL::Feature") || + value.userType() == qMetaTypeId>() || + value.userType() == qMetaTypeId>() || + value.userType() == qMetaTypeId>(); } static std::optional objectMember(const QVariant& value, const char* key) { @@ -142,29 +139,29 @@ class ConversionTraits { static std::optional toValue(const QVariant& value) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) if (value.typeId() == QMetaType::Bool) { - return { value.toBool() }; + return {value.toBool()}; } else if (value.typeId() == QMetaType::QString) { - return { value.toString().toStdString() }; + return {value.toString().toStdString()}; } else if (value.typeId() == QMetaType::QColor) { - return { convertColor(value.value()) }; + return {convertColor(value.value())}; } else if (value.typeId() == QMetaType::Int) { - return { int64_t(value.toInt()) }; + return {int64_t(value.toInt())}; } else if (QMetaType::canConvert(value.metaType(), QMetaType(QMetaType::Double))) { - return { value.toDouble() }; + return {value.toDouble()}; } else { return {}; } #else if (value.type() == QVariant::Bool) { - return { value.toBool() }; + return {value.toBool()}; } else if (value.type() == QVariant::String) { - return { value.toString().toStdString() }; + return {value.toString().toStdString()}; } else if (value.type() == QVariant::Color) { - return { convertColor(value.value()) }; + return {convertColor(value.value())}; } else if (value.type() == QVariant::Int) { - return { int64_t(value.toInt()) }; + return {int64_t(value.toInt())}; } else if (value.canConvert(QVariant::Double)) { - return { value.toDouble() }; + return {value.toDouble()}; } else { return {}; } @@ -173,7 +170,7 @@ class ConversionTraits { static std::optional toGeoJSON(const QVariant& value, Error& error) { if (value.typeName() == QStringLiteral("QMapLibreGL::Feature")) { - return GeoJSON { QMapLibreGL::GeoJSON::asFeature(value.value()) }; + return GeoJSON{QMapLibreGL::GeoJSON::asFeature(value.value())}; } else if (value.userType() == qMetaTypeId>()) { return featureCollectionToGeoJSON(value.value>()); } else if (value.userType() == qMetaTypeId>()) { @@ -185,7 +182,7 @@ class ConversionTraits { #else } else if (value.type() != QVariant::ByteArray) { #endif - error = { "JSON data must be in QByteArray" }; + error = {"JSON data must be in QByteArray"}; return {}; } @@ -194,25 +191,25 @@ class ConversionTraits { } private: - template - static GeoJSON featureCollectionToGeoJSON(const T &features) { + template + static GeoJSON featureCollectionToGeoJSON(const T& features) { mapbox::feature::feature_collection collection; collection.reserve(static_cast(features.size())); - for (const auto &feature : features) { + for (const auto& feature : features) { collection.push_back(QMapLibreGL::GeoJSON::asFeature(feature)); } - return GeoJSON { std::move(collection) }; + return GeoJSON{std::move(collection)}; } }; -template -std::optional convert(const QVariant& value, Error& error, Args&&...args) { +template +std::optional convert(const QVariant& value, Error& error, Args&&... args) { return convert(Convertible(value), error, std::forward(args)...); } -inline std::string convertColor(const QColor &color) { - return QString::asprintf("rgba(%d,%d,%d,%lf)", - color.red(), color.green(), color.blue(), color.alphaF()).toStdString(); +inline std::string convertColor(const QColor& color) { + return QString::asprintf("rgba(%d,%d,%d,%lf)", color.red(), color.green(), color.blue(), color.alphaF()) + .toStdString(); } } // namespace conversion diff --git a/platform/qt/src/utils/geojson.cpp b/platform/qt/src/utils/geojson.cpp index a37e51520e1..6b438e5583d 100644 --- a/platform/qt/src/utils/geojson.cpp +++ b/platform/qt/src/utils/geojson.cpp @@ -5,13 +5,13 @@ namespace QMapLibreGL::GeoJSON { mbgl::Point asPoint(const Coordinate &coordinate) { - return mbgl::Point { coordinate.second, coordinate.first }; + return mbgl::Point{coordinate.second, coordinate.first}; } mbgl::MultiPoint asMultiPoint(const Coordinates &multiPoint) { mbgl::MultiPoint mbglMultiPoint; mbglMultiPoint.reserve(multiPoint.size()); - for (const auto &point: multiPoint) { + for (const auto &point : multiPoint) { mbglMultiPoint.emplace_back(asPoint(point)); } return mbglMultiPoint; @@ -41,7 +41,7 @@ mbgl::Polygon asPolygon(const CoordinatesCollection &polygon) { for (const auto &linearRing : polygon) { mbgl::LinearRing mbglLinearRing; mbglLinearRing.reserve(linearRing.size()); - for (const auto &coordinate: linearRing) { + for (const auto &coordinate : linearRing) { mbglLinearRing.emplace_back(asPoint(coordinate)); } mbglPolygon.emplace_back(std::move(mbglLinearRing)); @@ -62,7 +62,7 @@ mbgl::Value asPropertyValue(const QVariant &value) { auto valueList = [](const QVariantList &list) { std::vector mbglList; mbglList.reserve(list.size()); - for (const auto& listValue : list) { + for (const auto &listValue : list) { mbglList.emplace_back(asPropertyValue(listValue)); } return mbglList; @@ -82,25 +82,25 @@ mbgl::Value asPropertyValue(const QVariant &value) { #else switch (static_cast(value.type())) { #endif - case QMetaType::UnknownType: - return mbgl::NullValue {}; - case QMetaType::Bool: - return { value.toBool() }; - case QMetaType::ULongLong: - return { uint64_t(value.toULongLong()) }; - case QMetaType::LongLong: - return { int64_t(value.toLongLong()) }; - case QMetaType::Double: - return { value.toDouble() }; - case QMetaType::QString: - return { value.toString().toStdString() }; - case QMetaType::QVariantList: - return valueList(value.toList()); - case QMetaType::QVariantMap: - return valueMap(value.toMap()); - default: - qWarning() << "Unsupported feature property value:" << value; - return {}; + case QMetaType::UnknownType: + return mbgl::NullValue{}; + case QMetaType::Bool: + return {value.toBool()}; + case QMetaType::ULongLong: + return {uint64_t(value.toULongLong())}; + case QMetaType::LongLong: + return {int64_t(value.toLongLong())}; + case QMetaType::Double: + return {value.toDouble()}; + case QMetaType::QString: + return {value.toString().toStdString()}; + case QMetaType::QVariantList: + return valueList(value.toList()); + case QMetaType::QVariantMap: + return valueMap(value.toMap()); + default: + qWarning() << "Unsupported feature property value:" << value; + return {}; } } @@ -110,19 +110,19 @@ mbgl::FeatureIdentifier asFeatureIdentifier(const QVariant &id) { #else switch (static_cast(id.type())) { #endif - case QMetaType::UnknownType: - return {}; - case QMetaType::ULongLong: - return { uint64_t(id.toULongLong()) }; - case QMetaType::LongLong: - return { int64_t(id.toLongLong()) }; - case QMetaType::Double: - return { id.toDouble() }; - case QMetaType::QString: - return { id.toString().toStdString() }; - default: - qWarning() << "Unsupported feature identifier:" << id; - return {}; + case QMetaType::UnknownType: + return {}; + case QMetaType::ULongLong: + return {uint64_t(id.toULongLong())}; + case QMetaType::LongLong: + return {int64_t(id.toLongLong())}; + case QMetaType::Double: + return {id.toDouble()}; + case QMetaType::QString: + return {id.toString().toStdString()}; + default: + qWarning() << "Unsupported feature identifier:" << id; + return {}; } } @@ -138,23 +138,23 @@ mbgl::GeoJSONFeature asFeature(const Feature &feature) { if (feature.type == Feature::PointType) { const Coordinates &points = feature.geometry.first().first(); if (points.size() == 1) { - return { asPoint(points.first()), std::move(properties), std::move(id) }; + return {asPoint(points.first()), std::move(properties), std::move(id)}; } else { - return { asMultiPoint(points), std::move(properties), std::move(id) }; + return {asMultiPoint(points), std::move(properties), std::move(id)}; } } else if (feature.type == Feature::LineStringType) { const CoordinatesCollection &lineStrings = feature.geometry.first(); if (lineStrings.size() == 1) { - return { asLineString(lineStrings.first()), std::move(properties), std::move(id) }; + return {asLineString(lineStrings.first()), std::move(properties), std::move(id)}; } else { - return { asMultiLineString(lineStrings), std::move(properties), std::move(id) }; + return {asMultiLineString(lineStrings), std::move(properties), std::move(id)}; } } else { // PolygonType const CoordinatesCollections &polygons = feature.geometry; if (polygons.size() == 1) { - return { asPolygon(polygons.first()), std::move(properties), std::move(id) }; + return {asPolygon(polygons.first()), std::move(properties), std::move(id)}; } else { - return { asMultiPolygon(polygons), std::move(properties), std::move(id) }; + return {asMultiPolygon(polygons), std::move(properties), std::move(id)}; } } }; diff --git a/platform/qt/src/utils/map_observer.cpp b/platform/qt/src/utils/map_observer.cpp index 3773d6544a2..f153df5bb51 100644 --- a/platform/qt/src/utils/map_observer.cpp +++ b/platform/qt/src/utils/map_observer.cpp @@ -8,17 +8,12 @@ namespace QMapLibreGL { -MapObserver::MapObserver(MapPrivate *d) - : d_ptr(d) -{ -} +MapObserver::MapObserver(MapPrivate* d) + : d_ptr(d) {} -MapObserver::~MapObserver() -{ -} +MapObserver::~MapObserver() {} -void MapObserver::onCameraWillChange(mbgl::MapObserver::CameraChangeMode mode) -{ +void MapObserver::onCameraWillChange(mbgl::MapObserver::CameraChangeMode mode) { if (mode == mbgl::MapObserver::CameraChangeMode::Immediate) { emit mapChanged(Map::MapChangeRegionWillChange); } else { @@ -26,13 +21,11 @@ void MapObserver::onCameraWillChange(mbgl::MapObserver::CameraChangeMode mode) } } -void MapObserver::onCameraIsChanging() -{ +void MapObserver::onCameraIsChanging() { emit mapChanged(Map::MapChangeRegionIsChanging); } -void MapObserver::onCameraDidChange(mbgl::MapObserver::CameraChangeMode mode) -{ +void MapObserver::onCameraDidChange(mbgl::MapObserver::CameraChangeMode mode) { if (mode == mbgl::MapObserver::CameraChangeMode::Immediate) { emit mapChanged(Map::MapChangeRegionDidChange); } else { @@ -40,18 +33,15 @@ void MapObserver::onCameraDidChange(mbgl::MapObserver::CameraChangeMode mode) } } -void MapObserver::onWillStartLoadingMap() -{ +void MapObserver::onWillStartLoadingMap() { emit mapChanged(Map::MapChangeWillStartLoadingMap); } -void MapObserver::onDidFinishLoadingMap() -{ +void MapObserver::onDidFinishLoadingMap() { emit mapChanged(Map::MapChangeDidFinishLoadingMap); } -void MapObserver::onDidFailLoadingMap(mbgl::MapLoadError error, const std::string& what) -{ +void MapObserver::onDidFailLoadingMap(mbgl::MapLoadError error, const std::string& what) { emit mapChanged(Map::MapChangeDidFailLoadingMap); Map::MapLoadingFailure type; @@ -74,13 +64,11 @@ void MapObserver::onDidFailLoadingMap(mbgl::MapLoadError error, const std::strin emit mapLoadingFailed(type, description); } -void MapObserver::onWillStartRenderingFrame() -{ +void MapObserver::onWillStartRenderingFrame() { emit mapChanged(Map::MapChangeWillStartRenderingFrame); } -void MapObserver::onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus status) -{ +void MapObserver::onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus status) { if (status.mode == mbgl::MapObserver::RenderMode::Partial) { emit mapChanged(Map::MapChangeDidFinishRenderingFrame); } else { @@ -88,13 +76,11 @@ void MapObserver::onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus } } -void MapObserver::onWillStartRenderingMap() -{ +void MapObserver::onWillStartRenderingMap() { emit mapChanged(Map::MapChangeWillStartRenderingMap); } -void MapObserver::onDidFinishRenderingMap(mbgl::MapObserver::RenderMode mode) -{ +void MapObserver::onDidFinishRenderingMap(mbgl::MapObserver::RenderMode mode) { if (mode == mbgl::MapObserver::RenderMode::Partial) { emit mapChanged(Map::MapChangeDidFinishRenderingMap); } else { @@ -102,13 +88,11 @@ void MapObserver::onDidFinishRenderingMap(mbgl::MapObserver::RenderMode mode) } } -void MapObserver::onDidFinishLoadingStyle() -{ +void MapObserver::onDidFinishLoadingStyle() { emit mapChanged(Map::MapChangeDidFinishLoadingStyle); } -void MapObserver::onSourceChanged(mbgl::style::Source&) -{ +void MapObserver::onSourceChanged(mbgl::style::Source&) { std::string attribution; for (const auto& source : d_ptr->mapObj->getStyle().getSources()) { // Avoid duplicates by using the most complete attribution HTML snippet. diff --git a/platform/qt/src/utils/map_observer.hpp b/platform/qt/src/utils/map_observer.hpp index c45387d56be..4ab0b960209 100644 --- a/platform/qt/src/utils/map_observer.hpp +++ b/platform/qt/src/utils/map_observer.hpp @@ -14,8 +14,7 @@ namespace QMapLibreGL { class MapPrivate; -class MapObserver : public QObject, public mbgl::MapObserver -{ +class MapObserver : public QObject, public mbgl::MapObserver { Q_OBJECT public: @@ -28,13 +27,13 @@ class MapObserver : public QObject, public mbgl::MapObserver void onCameraDidChange(mbgl::MapObserver::CameraChangeMode) final; void onWillStartLoadingMap() final; void onDidFinishLoadingMap() final; - void onDidFailLoadingMap(mbgl::MapLoadError, const std::string&) final; + void onDidFailLoadingMap(mbgl::MapLoadError, const std::string &) final; void onWillStartRenderingFrame() final; void onDidFinishRenderingFrame(mbgl::MapObserver::RenderFrameStatus) final; void onWillStartRenderingMap() final; void onDidFinishRenderingMap(mbgl::MapObserver::RenderMode) final; void onDidFinishLoadingStyle() final; - void onSourceChanged(mbgl::style::Source&) final; + void onSourceChanged(mbgl::style::Source &) final; signals: void mapChanged(Map::MapChange); diff --git a/platform/qt/src/utils/map_renderer.cpp b/platform/qt/src/utils/map_renderer.cpp index b0fced73695..4cfcbc95ba1 100644 --- a/platform/qt/src/utils/map_renderer.cpp +++ b/platform/qt/src/utils/map_renderer.cpp @@ -29,15 +29,15 @@ static auto *getScheduler() { } // namespace - namespace QMapLibreGL { MapRenderer::MapRenderer(qreal pixelRatio, Settings::GLContextMode mode, const QString &localFontFamily) : m_backend(static_cast(mode)), - m_renderer(std::make_unique(m_backend, pixelRatio, - localFontFamily.isEmpty() ? std::nullopt : std::optional { localFontFamily.toStdString() })) - , m_forceScheduler(needsToForceScheduler()) -{ + m_renderer(std::make_unique( + m_backend, + pixelRatio, + localFontFamily.isEmpty() ? std::nullopt : std::optional{localFontFamily.toStdString()})), + m_forceScheduler(needsToForceScheduler()) { // If we don't have a Scheduler on this thread, which // is usually the case for render threads, use a shared // dummy scheduler that needs to be explicitly forced to @@ -53,26 +53,22 @@ MapRenderer::MapRenderer(qreal pixelRatio, Settings::GLContextMode mode, const Q } } -MapRenderer::~MapRenderer() -{ +MapRenderer::~MapRenderer() { MBGL_VERIFY_THREAD(tid); } -void MapRenderer::updateParameters(std::shared_ptr newParameters) -{ +void MapRenderer::updateParameters(std::shared_ptr newParameters) { std::lock_guard lock(m_updateMutex); m_updateParameters = std::move(newParameters); } -void MapRenderer::updateFramebuffer(quint32 fbo, const mbgl::Size &size) -{ +void MapRenderer::updateFramebuffer(quint32 fbo, const mbgl::Size &size) { MBGL_VERIFY_THREAD(tid); m_backend.updateFramebuffer(fbo, size); } -void MapRenderer::render() -{ +void MapRenderer::render() { MBGL_VERIFY_THREAD(tid); std::shared_ptr params; @@ -97,8 +93,7 @@ void MapRenderer::render() } } -void MapRenderer::setObserver(std::shared_ptr observer) -{ +void MapRenderer::setObserver(std::shared_ptr observer) { m_renderer->setObserver(observer.get()); } diff --git a/platform/qt/src/utils/map_renderer.hpp b/platform/qt/src/utils/map_renderer.hpp index e37d384eee2..4b5f0fc5fb0 100644 --- a/platform/qt/src/utils/map_renderer.hpp +++ b/platform/qt/src/utils/map_renderer.hpp @@ -23,8 +23,7 @@ namespace QMapLibreGL { class RendererBackend; -class MapRenderer : public QObject -{ +class MapRenderer : public QObject { Q_OBJECT public: diff --git a/platform/qt/src/utils/renderer_backend.cpp b/platform/qt/src/utils/renderer_backend.cpp index 9ea227ddf7f..5a0a0e16faa 100644 --- a/platform/qt/src/utils/renderer_backend.cpp +++ b/platform/qt/src/utils/renderer_backend.cpp @@ -10,8 +10,8 @@ namespace QMapLibreGL { class RenderableResource final : public mbgl::gl::RenderableResource { public: - RenderableResource(RendererBackend& backend_) : backend(backend_) { - } + RenderableResource(RendererBackend& backend_) + : backend(backend_) {} void bind() override { assert(mbgl::gfx::BackendScope::exists()); @@ -25,8 +25,7 @@ class RenderableResource final : public mbgl::gl::RenderableResource { RendererBackend::RendererBackend(const mbgl::gfx::ContextMode contextMode_) : mbgl::gl::RendererBackend(contextMode_), - mbgl::gfx::Renderable({ 0, 0 }, std::make_unique(*this)) { -} + mbgl::gfx::Renderable({0, 0}, std::make_unique(*this)) {} RendererBackend::~RendererBackend() = default; @@ -45,8 +44,8 @@ void RendererBackend::updateFramebuffer(quint32 fbo, const mbgl::Size& newSize) } /*! - Initializes an OpenGL extension function such as Vertex Array Objects (VAOs), - required by MapLibre Native engine. + Initializes an OpenGL extension function such as Vertex Array Objects + (VAOs), required by MapLibre Native engine. */ mbgl::gl::ProcAddress RendererBackend::getExtensionFunctionPointer(const char* name) { QOpenGLContext* thisContext = QOpenGLContext::currentContext(); diff --git a/platform/qt/src/utils/renderer_backend.hpp b/platform/qt/src/utils/renderer_backend.hpp index 678905ad84a..c83c24338cb 100644 --- a/platform/qt/src/utils/renderer_backend.hpp +++ b/platform/qt/src/utils/renderer_backend.hpp @@ -7,8 +7,7 @@ namespace QMapLibreGL { -class RendererBackend final : public mbgl::gl::RendererBackend, - public mbgl::gfx::Renderable { +class RendererBackend final : public mbgl::gl::RendererBackend, public mbgl::gfx::Renderable { public: RendererBackend(mbgl::gfx::ContextMode); ~RendererBackend() override; @@ -18,9 +17,7 @@ class RendererBackend final : public mbgl::gl::RendererBackend, // mbgl::gfx::RendererBackend implementation public: - mbgl::gfx::Renderable& getDefaultRenderable() override { - return *this; - } + mbgl::gfx::Renderable& getDefaultRenderable() override { return *this; } protected: // No-op, implicit mode. diff --git a/platform/qt/src/utils/renderer_observer.hpp b/platform/qt/src/utils/renderer_observer.hpp index 3fd515f9944..29dc29125a2 100644 --- a/platform/qt/src/utils/renderer_observer.hpp +++ b/platform/qt/src/utils/renderer_observer.hpp @@ -15,37 +15,26 @@ namespace QMapLibreGL { class RendererObserver : public mbgl::RendererObserver { public: RendererObserver(mbgl::util::RunLoop& mapRunLoop, mbgl::RendererObserver& delegate_) - : mailbox(std::make_shared(mapRunLoop)) - , delegate(delegate_, mailbox) { - } + : mailbox(std::make_shared(mapRunLoop)), + delegate(delegate_, mailbox) {} - ~RendererObserver() { - mailbox->close(); - } + ~RendererObserver() { mailbox->close(); } - void onInvalidate() final { - delegate.invoke(&mbgl::RendererObserver::onInvalidate); - } + void onInvalidate() final { delegate.invoke(&mbgl::RendererObserver::onInvalidate); } void onResourceError(std::exception_ptr err) final { delegate.invoke(&mbgl::RendererObserver::onResourceError, err); } - void onWillStartRenderingMap() final { - delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingMap); - } + void onWillStartRenderingMap() final { delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingMap); } - void onWillStartRenderingFrame() final { - delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingFrame); - } + void onWillStartRenderingFrame() final { delegate.invoke(&mbgl::RendererObserver::onWillStartRenderingFrame); } void onDidFinishRenderingFrame(RenderMode mode, bool repaintNeeded, bool placementChanged) final { delegate.invoke(&mbgl::RendererObserver::onDidFinishRenderingFrame, mode, repaintNeeded, placementChanged); } - void onDidFinishRenderingMap() final { - delegate.invoke(&mbgl::RendererObserver::onDidFinishRenderingMap); - } + void onDidFinishRenderingMap() final { delegate.invoke(&mbgl::RendererObserver::onDidFinishRenderingMap); } private: std::shared_ptr mailbox{}; diff --git a/platform/qt/src/utils/scheduler.cpp b/platform/qt/src/utils/scheduler.cpp index 4b2c1322510..bcc5e97f1b5 100644 --- a/platform/qt/src/utils/scheduler.cpp +++ b/platform/qt/src/utils/scheduler.cpp @@ -6,12 +6,9 @@ namespace QMapLibreGL { -Scheduler::Scheduler() -{ -} +Scheduler::Scheduler() {} -Scheduler::~Scheduler() -{ +Scheduler::~Scheduler() { MBGL_VERIFY_THREAD(tid); } @@ -24,8 +21,7 @@ void Scheduler::schedule(std::function function) { emit needsProcessing(); } -void Scheduler::processEvents() -{ +void Scheduler::processEvents() { std::queue> taskQueue; { std::unique_lock lock(m_taskQueueMutex); diff --git a/platform/qt/src/utils/scheduler.hpp b/platform/qt/src/utils/scheduler.hpp index 2b69ea769fc..cbe4dfc13c0 100644 --- a/platform/qt/src/utils/scheduler.hpp +++ b/platform/qt/src/utils/scheduler.hpp @@ -11,8 +11,7 @@ namespace QMapLibreGL { -class Scheduler : public QObject, public mbgl::Scheduler -{ +class Scheduler : public QObject, public mbgl::Scheduler { Q_OBJECT public: @@ -36,4 +35,4 @@ class Scheduler : public QObject, public mbgl::Scheduler mapbox::base::WeakPtrFactory weakFactory{this}; }; -} // namepace QMapLibreGL +} // namespace QMapLibreGL diff --git a/platform/qt/test/qmaplibregl.test.cpp b/platform/qt/test/qmaplibregl.test.cpp index b5dd6ea9b76..ef685a36cbe 100644 --- a/platform/qt/test/qmaplibregl.test.cpp +++ b/platform/qt/test/qmaplibregl.test.cpp @@ -10,7 +10,10 @@ #include -QMapLibreGLTest::QMapLibreGLTest() : size(512, 512), fbo((assert(widget.context()->isValid()), widget.makeCurrent(), size)), map(nullptr, settings, size) { +QMapLibreGLTest::QMapLibreGLTest() + : size(512, 512), + fbo((assert(widget.context()->isValid()), widget.makeCurrent(), size)), + map(nullptr, settings, size) { connect(&map, &QMapLibreGL::mapChanged, this, &QMapLibreGLTest::onMapChanged); connect(&map, &QMapLibreGL::needsRendering, this, &QMapLibreGLTest::onNeedsRendering); map.resize(fbo.size()); @@ -42,7 +45,6 @@ void QMapLibreGLTest::onNeedsRendering() { map.render(); } - TEST_F(QMapLibreGLTest, TEST_DISABLED_ON_CI(styleJson)) { QFile f("test/fixtures/resources/style_vector.json"); diff --git a/platform/windows/include/gl_functions_wgl.h b/platform/windows/include/gl_functions_wgl.h index f2b01d7174c..4cd126aaf65 100644 --- a/platform/windows/include/gl_functions_wgl.h +++ b/platform/windows/include/gl_functions_wgl.h @@ -83,7 +83,8 @@ PFNGLGETBOOLEANVPROC wgl_glGetBooleanv = NULL; PFNGLGETBUFFERPARAMETERIVPROC wgl_glGetBufferParameteriv = NULL; PFNGLGETERRORPROC wgl_glGetError = NULL; PFNGLGETFLOATVPROC wgl_glGetFloatv = NULL; -PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC wgl_glGetFramebufferAttachmentParameteriv = NULL; +PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC +wgl_glGetFramebufferAttachmentParameteriv = NULL; PFNGLGETINTEGERVPROC wgl_glGetIntegerv = NULL; PFNGLGETPROGRAMINFOLOGPROC wgl_glGetProgramInfoLog = NULL; PFNGLGETPROGRAMIVPROC wgl_glGetProgramiv = NULL; @@ -280,12 +281,12 @@ PFNWGLGETEXTENSIONSSTRINGEXTPROC wgl_wglGetExtensionsStringEXT = NULL; HMODULE opengl32 = NULL; -typedef PROC (WINAPI * PFNWGLLOADERWGLGETPROCADDRESSPROC) (LPCSTR lpszProc); +typedef PROC(WINAPI* PFNWGLLOADERWGLGETPROCADDRESSPROC)(LPCSTR lpszProc); PFNWGLLOADERWGLGETPROCADDRESSPROC wgl_wglGetProcAddress = NULL; PROC WINAPI wgl_GetProcAddress(LPCSTR procName) { PROC proc = NULL; - proc = wgl_wglGetProcAddress(procName); + proc = wgl_wglGetProcAddress(procName); if (!proc) { proc = GetProcAddress(opengl32, procName); @@ -295,160 +296,164 @@ PROC WINAPI wgl_GetProcAddress(LPCSTR procName) { } void loadWGL() { - if(opengl32) { - return; - } + if (opengl32) { + return; + } - opengl32 = LoadLibraryA("opengl32.dll"); - wgl_wglGetProcAddress = (PFNWGLLOADERWGLGETPROCADDRESSPROC)GetProcAddress(opengl32, "wglGetProcAddress"); + opengl32 = LoadLibraryA("opengl32.dll"); + wgl_wglGetProcAddress = (PFNWGLLOADERWGLGETPROCADDRESSPROC)GetProcAddress(opengl32, "wglGetProcAddress"); /* OpenGL ES 2.0 */ - - wgl_glActiveTexture = (PFNGLACTIVETEXTUREPROC)wgl_GetProcAddress("glActiveTexture"); - wgl_glAttachShader = (PFNGLATTACHSHADERPROC)wgl_GetProcAddress("glAttachShader"); - wgl_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)wgl_GetProcAddress("glBindAttribLocation"); - wgl_glBindBuffer = (PFNGLBINDBUFFERPROC)wgl_GetProcAddress("glBindBuffer"); - wgl_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wgl_GetProcAddress("glBindFramebuffer"); - wgl_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wgl_GetProcAddress("glBindRenderbuffer"); - wgl_glBindTexture = (PFNGLBINDTEXTUREPROC)wgl_GetProcAddress("glBindTexture"); - wgl_glBlendColor = (PFNGLBLENDCOLORPROC)wgl_GetProcAddress("glBlendColor"); - wgl_glBlendEquation = (PFNGLBLENDEQUATIONPROC)wgl_GetProcAddress("glBlendEquation"); - wgl_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)wgl_GetProcAddress("glBlendEquationSeparate"); - wgl_glBlendFunc = (PFNGLBLENDFUNCPROC)wgl_GetProcAddress("glBlendFunc"); - wgl_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)wgl_GetProcAddress("glBlendFuncSeparate"); - wgl_glBufferData = (PFNGLBUFFERDATAPROC)wgl_GetProcAddress("glBufferData"); - wgl_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)wgl_GetProcAddress("glBufferSubData"); - wgl_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wgl_GetProcAddress("glCheckFramebufferStatus"); - wgl_glClear = (PFNGLCLEARPROC)wgl_GetProcAddress("glClear"); - wgl_glClearColor = (PFNGLCLEARCOLORPROC)wgl_GetProcAddress("glClearColor"); - wgl_glClearDepthf = (PFNGLCLEARDEPTHFPROC)wgl_GetProcAddress("glClearDepthf"); - wgl_glClearStencil = (PFNGLCLEARSTENCILPROC)wgl_GetProcAddress("glClearStencil"); - wgl_glColorMask = (PFNGLCOLORMASKPROC)wgl_GetProcAddress("glColorMask"); - wgl_glCompileShader = (PFNGLCOMPILESHADERPROC)wgl_GetProcAddress("glCompileShader"); - wgl_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexImage2D"); - wgl_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexSubImage2D"); - wgl_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)wgl_GetProcAddress("glCopyTexImage2D"); - wgl_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCopyTexSubImage2D"); - wgl_glCreateProgram = (PFNGLCREATEPROGRAMPROC)wgl_GetProcAddress("glCreateProgram"); - wgl_glCreateShader = (PFNGLCREATESHADERPROC)wgl_GetProcAddress("glCreateShader"); - wgl_glCullFace = (PFNGLCULLFACEPROC)wgl_GetProcAddress("glCullFace"); - wgl_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)wgl_GetProcAddress("glDeleteBuffers"); - wgl_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wgl_GetProcAddress("glDeleteFramebuffers"); - wgl_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wgl_GetProcAddress("glDeleteProgram"); - wgl_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wgl_GetProcAddress("glDeleteRenderbuffers"); - wgl_glDeleteShader = (PFNGLDELETESHADERPROC)wgl_GetProcAddress("glDeleteShader"); - wgl_glDeleteTextures = (PFNGLDELETETEXTURESPROC)wgl_GetProcAddress("glDeleteTextures"); - wgl_glDepthFunc = (PFNGLDEPTHFUNCPROC)wgl_GetProcAddress("glDepthFunc"); - wgl_glDepthMask = (PFNGLDEPTHMASKPROC)wgl_GetProcAddress("glDepthMask"); - wgl_glDepthRangef = (PFNGLDEPTHRANGEFPROC)wgl_GetProcAddress("glDepthRangef"); - wgl_glDetachShader = (PFNGLDETACHSHADERPROC)wgl_GetProcAddress("glDetachShader"); - wgl_glDisable = (PFNGLDISABLEPROC)wgl_GetProcAddress("glDisable"); - wgl_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress("glDisableVertexAttribArray"); - wgl_glDrawArrays = (PFNGLDRAWARRAYSPROC)wgl_GetProcAddress("glDrawArrays"); - wgl_glDrawElements = (PFNGLDRAWELEMENTSPROC)wgl_GetProcAddress("glDrawElements"); - wgl_glEnable = (PFNGLENABLEPROC)wgl_GetProcAddress("glEnable"); - wgl_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress("glEnableVertexAttribArray"); - wgl_glFinish = (PFNGLFINISHPROC)wgl_GetProcAddress("glFinish"); - wgl_glFlush = (PFNGLFLUSHPROC)wgl_GetProcAddress("glFlush"); - wgl_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wgl_GetProcAddress("glFramebufferRenderbuffer"); - wgl_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wgl_GetProcAddress("glFramebufferTexture2D"); - wgl_glFrontFace = (PFNGLFRONTFACEPROC)wgl_GetProcAddress("glFrontFace"); - wgl_glGenBuffers = (PFNGLGENBUFFERSPROC)wgl_GetProcAddress("glGenBuffers"); - wgl_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wgl_GetProcAddress("glGenerateMipmap"); - wgl_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wgl_GetProcAddress("glGenFramebuffers"); - wgl_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wgl_GetProcAddress("glGenRenderbuffers"); - wgl_glGenTextures = (PFNGLGENTEXTURESPROC)wgl_GetProcAddress("glGenTextures"); - wgl_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)wgl_GetProcAddress("glGetActiveAttrib"); - wgl_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)wgl_GetProcAddress("glGetActiveUniform"); - wgl_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)wgl_GetProcAddress("glGetAttachedShaders"); - wgl_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)wgl_GetProcAddress("glGetAttribLocation"); - wgl_glGetBooleanv = (PFNGLGETBOOLEANVPROC)wgl_GetProcAddress("glGetBooleanv"); - wgl_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)wgl_GetProcAddress("glGetBufferParameteriv"); - wgl_glGetError = (PFNGLGETERRORPROC)wgl_GetProcAddress("glGetError"); - wgl_glGetFloatv = (PFNGLGETFLOATVPROC)wgl_GetProcAddress("glGetFloatv"); - wgl_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)wgl_GetProcAddress("glGetFramebufferAttachmentParameteriv"); - wgl_glGetIntegerv = (PFNGLGETINTEGERVPROC)wgl_GetProcAddress("glGetIntegerv"); - wgl_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)wgl_GetProcAddress("glGetProgramInfoLog"); - wgl_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)wgl_GetProcAddress("glGetProgramiv"); - wgl_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)wgl_GetProcAddress("glGetRenderbufferParameteriv"); - wgl_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wgl_GetProcAddress("glGetShaderInfoLog"); - wgl_glGetShaderiv = (PFNGLGETSHADERIVPROC)wgl_GetProcAddress("glGetShaderiv"); - wgl_glGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)wgl_GetProcAddress("glGetShaderPrecisionFormat"); - wgl_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)wgl_GetProcAddress("glGetShaderSource"); - wgl_glGetString = (PFNGLGETSTRINGPROC)wgl_GetProcAddress("glGetString"); - wgl_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)wgl_GetProcAddress("glGetTexParameterfv"); - wgl_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)wgl_GetProcAddress("glGetTexParameteriv"); - wgl_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)wgl_GetProcAddress("glGetUniformfv"); - wgl_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)wgl_GetProcAddress("glGetUniformiv"); - wgl_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wgl_GetProcAddress("glGetUniformLocation"); - wgl_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)wgl_GetProcAddress("glGetVertexAttribfv"); - wgl_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)wgl_GetProcAddress("glGetVertexAttribiv"); - wgl_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)wgl_GetProcAddress("glGetVertexAttribPointerv"); - wgl_glHint = (PFNGLHINTPROC)wgl_GetProcAddress("glHint"); - wgl_glIsBuffer = (PFNGLISBUFFERPROC)wgl_GetProcAddress("glIsBuffer"); - wgl_glIsEnabled = (PFNGLISENABLEDPROC)wgl_GetProcAddress("glIsEnabled"); - wgl_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wgl_GetProcAddress("glIsFramebuffer"); - wgl_glIsProgram = (PFNGLISPROGRAMPROC)wgl_GetProcAddress("glIsProgram"); - wgl_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wgl_GetProcAddress("glIsRenderbuffer"); - wgl_glIsShader = (PFNGLISSHADERPROC)wgl_GetProcAddress("glIsShader"); - wgl_glIsTexture = (PFNGLISTEXTUREPROC)wgl_GetProcAddress("glIsTexture"); - wgl_glLineWidth = (PFNGLLINEWIDTHPROC)wgl_GetProcAddress("glLineWidth"); - wgl_glLinkProgram = (PFNGLLINKPROGRAMPROC)wgl_GetProcAddress("glLinkProgram"); - wgl_glPixelStorei = (PFNGLPIXELSTOREIPROC)wgl_GetProcAddress("glPixelStorei"); - wgl_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)wgl_GetProcAddress("glPolygonOffset"); - wgl_glReadPixels = (PFNGLREADPIXELSPROC)wgl_GetProcAddress("glReadPixels"); + + wgl_glActiveTexture = (PFNGLACTIVETEXTUREPROC)wgl_GetProcAddress("glActiveTexture"); + wgl_glAttachShader = (PFNGLATTACHSHADERPROC)wgl_GetProcAddress("glAttachShader"); + wgl_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)wgl_GetProcAddress("glBindAttribLocation"); + wgl_glBindBuffer = (PFNGLBINDBUFFERPROC)wgl_GetProcAddress("glBindBuffer"); + wgl_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wgl_GetProcAddress("glBindFramebuffer"); + wgl_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wgl_GetProcAddress("glBindRenderbuffer"); + wgl_glBindTexture = (PFNGLBINDTEXTUREPROC)wgl_GetProcAddress("glBindTexture"); + wgl_glBlendColor = (PFNGLBLENDCOLORPROC)wgl_GetProcAddress("glBlendColor"); + wgl_glBlendEquation = (PFNGLBLENDEQUATIONPROC)wgl_GetProcAddress("glBlendEquation"); + wgl_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)wgl_GetProcAddress("glBlendEquationSeparate"); + wgl_glBlendFunc = (PFNGLBLENDFUNCPROC)wgl_GetProcAddress("glBlendFunc"); + wgl_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)wgl_GetProcAddress("glBlendFuncSeparate"); + wgl_glBufferData = (PFNGLBUFFERDATAPROC)wgl_GetProcAddress("glBufferData"); + wgl_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)wgl_GetProcAddress("glBufferSubData"); + wgl_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wgl_GetProcAddress("glCheckFramebufferStatus"); + wgl_glClear = (PFNGLCLEARPROC)wgl_GetProcAddress("glClear"); + wgl_glClearColor = (PFNGLCLEARCOLORPROC)wgl_GetProcAddress("glClearColor"); + wgl_glClearDepthf = (PFNGLCLEARDEPTHFPROC)wgl_GetProcAddress("glClearDepthf"); + wgl_glClearStencil = (PFNGLCLEARSTENCILPROC)wgl_GetProcAddress("glClearStencil"); + wgl_glColorMask = (PFNGLCOLORMASKPROC)wgl_GetProcAddress("glColorMask"); + wgl_glCompileShader = (PFNGLCOMPILESHADERPROC)wgl_GetProcAddress("glCompileShader"); + wgl_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexImage2D"); + wgl_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCompressedTexSubImage2D"); + wgl_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)wgl_GetProcAddress("glCopyTexImage2D"); + wgl_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glCopyTexSubImage2D"); + wgl_glCreateProgram = (PFNGLCREATEPROGRAMPROC)wgl_GetProcAddress("glCreateProgram"); + wgl_glCreateShader = (PFNGLCREATESHADERPROC)wgl_GetProcAddress("glCreateShader"); + wgl_glCullFace = (PFNGLCULLFACEPROC)wgl_GetProcAddress("glCullFace"); + wgl_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)wgl_GetProcAddress("glDeleteBuffers"); + wgl_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wgl_GetProcAddress("glDeleteFramebuffers"); + wgl_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wgl_GetProcAddress("glDeleteProgram"); + wgl_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wgl_GetProcAddress("glDeleteRenderbuffers"); + wgl_glDeleteShader = (PFNGLDELETESHADERPROC)wgl_GetProcAddress("glDeleteShader"); + wgl_glDeleteTextures = (PFNGLDELETETEXTURESPROC)wgl_GetProcAddress("glDeleteTextures"); + wgl_glDepthFunc = (PFNGLDEPTHFUNCPROC)wgl_GetProcAddress("glDepthFunc"); + wgl_glDepthMask = (PFNGLDEPTHMASKPROC)wgl_GetProcAddress("glDepthMask"); + wgl_glDepthRangef = (PFNGLDEPTHRANGEFPROC)wgl_GetProcAddress("glDepthRangef"); + wgl_glDetachShader = (PFNGLDETACHSHADERPROC)wgl_GetProcAddress("glDetachShader"); + wgl_glDisable = (PFNGLDISABLEPROC)wgl_GetProcAddress("glDisable"); + wgl_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress( + "glDisableVertexAttribArray"); + wgl_glDrawArrays = (PFNGLDRAWARRAYSPROC)wgl_GetProcAddress("glDrawArrays"); + wgl_glDrawElements = (PFNGLDRAWELEMENTSPROC)wgl_GetProcAddress("glDrawElements"); + wgl_glEnable = (PFNGLENABLEPROC)wgl_GetProcAddress("glEnable"); + wgl_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)wgl_GetProcAddress("glEnableVertexAttribArray"); + wgl_glFinish = (PFNGLFINISHPROC)wgl_GetProcAddress("glFinish"); + wgl_glFlush = (PFNGLFLUSHPROC)wgl_GetProcAddress("glFlush"); + wgl_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wgl_GetProcAddress("glFramebufferRenderbuffer"); + wgl_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wgl_GetProcAddress("glFramebufferTexture2D"); + wgl_glFrontFace = (PFNGLFRONTFACEPROC)wgl_GetProcAddress("glFrontFace"); + wgl_glGenBuffers = (PFNGLGENBUFFERSPROC)wgl_GetProcAddress("glGenBuffers"); + wgl_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wgl_GetProcAddress("glGenerateMipmap"); + wgl_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wgl_GetProcAddress("glGenFramebuffers"); + wgl_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wgl_GetProcAddress("glGenRenderbuffers"); + wgl_glGenTextures = (PFNGLGENTEXTURESPROC)wgl_GetProcAddress("glGenTextures"); + wgl_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)wgl_GetProcAddress("glGetActiveAttrib"); + wgl_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)wgl_GetProcAddress("glGetActiveUniform"); + wgl_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)wgl_GetProcAddress("glGetAttachedShaders"); + wgl_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)wgl_GetProcAddress("glGetAttribLocation"); + wgl_glGetBooleanv = (PFNGLGETBOOLEANVPROC)wgl_GetProcAddress("glGetBooleanv"); + wgl_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)wgl_GetProcAddress("glGetBufferParameteriv"); + wgl_glGetError = (PFNGLGETERRORPROC)wgl_GetProcAddress("glGetError"); + wgl_glGetFloatv = (PFNGLGETFLOATVPROC)wgl_GetProcAddress("glGetFloatv"); + wgl_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)wgl_GetProcAddress( + "glGetFramebufferAttachmentParameteriv"); + wgl_glGetIntegerv = (PFNGLGETINTEGERVPROC)wgl_GetProcAddress("glGetIntegerv"); + wgl_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)wgl_GetProcAddress("glGetProgramInfoLog"); + wgl_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)wgl_GetProcAddress("glGetProgramiv"); + wgl_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)wgl_GetProcAddress( + "glGetRenderbufferParameteriv"); + wgl_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wgl_GetProcAddress("glGetShaderInfoLog"); + wgl_glGetShaderiv = (PFNGLGETSHADERIVPROC)wgl_GetProcAddress("glGetShaderiv"); + wgl_glGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)wgl_GetProcAddress( + "glGetShaderPrecisionFormat"); + wgl_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)wgl_GetProcAddress("glGetShaderSource"); + wgl_glGetString = (PFNGLGETSTRINGPROC)wgl_GetProcAddress("glGetString"); + wgl_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)wgl_GetProcAddress("glGetTexParameterfv"); + wgl_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)wgl_GetProcAddress("glGetTexParameteriv"); + wgl_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)wgl_GetProcAddress("glGetUniformfv"); + wgl_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)wgl_GetProcAddress("glGetUniformiv"); + wgl_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wgl_GetProcAddress("glGetUniformLocation"); + wgl_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)wgl_GetProcAddress("glGetVertexAttribfv"); + wgl_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)wgl_GetProcAddress("glGetVertexAttribiv"); + wgl_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)wgl_GetProcAddress("glGetVertexAttribPointerv"); + wgl_glHint = (PFNGLHINTPROC)wgl_GetProcAddress("glHint"); + wgl_glIsBuffer = (PFNGLISBUFFERPROC)wgl_GetProcAddress("glIsBuffer"); + wgl_glIsEnabled = (PFNGLISENABLEDPROC)wgl_GetProcAddress("glIsEnabled"); + wgl_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wgl_GetProcAddress("glIsFramebuffer"); + wgl_glIsProgram = (PFNGLISPROGRAMPROC)wgl_GetProcAddress("glIsProgram"); + wgl_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wgl_GetProcAddress("glIsRenderbuffer"); + wgl_glIsShader = (PFNGLISSHADERPROC)wgl_GetProcAddress("glIsShader"); + wgl_glIsTexture = (PFNGLISTEXTUREPROC)wgl_GetProcAddress("glIsTexture"); + wgl_glLineWidth = (PFNGLLINEWIDTHPROC)wgl_GetProcAddress("glLineWidth"); + wgl_glLinkProgram = (PFNGLLINKPROGRAMPROC)wgl_GetProcAddress("glLinkProgram"); + wgl_glPixelStorei = (PFNGLPIXELSTOREIPROC)wgl_GetProcAddress("glPixelStorei"); + wgl_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)wgl_GetProcAddress("glPolygonOffset"); + wgl_glReadPixels = (PFNGLREADPIXELSPROC)wgl_GetProcAddress("glReadPixels"); wgl_glReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)wgl_GetProcAddress("glReleaseShaderCompiler"); - wgl_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wgl_GetProcAddress("glRenderbufferStorage"); - wgl_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)wgl_GetProcAddress("glSampleCoverage"); - wgl_glScissor = (PFNGLSCISSORPROC)wgl_GetProcAddress("glScissor"); + wgl_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wgl_GetProcAddress("glRenderbufferStorage"); + wgl_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)wgl_GetProcAddress("glSampleCoverage"); + wgl_glScissor = (PFNGLSCISSORPROC)wgl_GetProcAddress("glScissor"); wgl_glShaderBinary = (PFNGLSHADERBINARYPROC)wgl_GetProcAddress("glShaderBinary"); - wgl_glShaderSource = (PFNGLSHADERSOURCEPROC)wgl_GetProcAddress("glShaderSource"); - wgl_glStencilFunc = (PFNGLSTENCILFUNCPROC)wgl_GetProcAddress("glStencilFunc"); - wgl_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)wgl_GetProcAddress("glStencilFuncSeparate"); - wgl_glStencilMask = (PFNGLSTENCILMASKPROC)wgl_GetProcAddress("glStencilMask"); - wgl_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)wgl_GetProcAddress("glStencilMaskSeparate"); - wgl_glStencilOp = (PFNGLSTENCILOPPROC)wgl_GetProcAddress("glStencilOp"); - wgl_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)wgl_GetProcAddress("glStencilOpSeparate"); - wgl_glTexImage2D = (PFNGLTEXIMAGE2DPROC)wgl_GetProcAddress("glTexImage2D"); - wgl_glTexParameterf = (PFNGLTEXPARAMETERFPROC)wgl_GetProcAddress("glTexParameterf"); - wgl_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)wgl_GetProcAddress("glTexParameterfv"); - wgl_glTexParameteri = (PFNGLTEXPARAMETERIPROC)wgl_GetProcAddress("glTexParameteri"); - wgl_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)wgl_GetProcAddress("glTexParameteriv"); - wgl_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glTexSubImage2D"); - wgl_glUniform1f = (PFNGLUNIFORM1FPROC)wgl_GetProcAddress("glUniform1f"); - wgl_glUniform1fv = (PFNGLUNIFORM1FVPROC)wgl_GetProcAddress("glUniform1fv"); - wgl_glUniform1i = (PFNGLUNIFORM1IPROC)wgl_GetProcAddress("glUniform1i"); - wgl_glUniform1iv = (PFNGLUNIFORM1IVPROC)wgl_GetProcAddress("glUniform1iv"); - wgl_glUniform2f = (PFNGLUNIFORM2FPROC)wgl_GetProcAddress("glUniform2f"); - wgl_glUniform2fv = (PFNGLUNIFORM2FVPROC)wgl_GetProcAddress("glUniform2fv"); - wgl_glUniform2i = (PFNGLUNIFORM2IPROC)wgl_GetProcAddress("glUniform2i"); - wgl_glUniform2iv = (PFNGLUNIFORM2IVPROC)wgl_GetProcAddress("glUniform2iv"); - wgl_glUniform3f = (PFNGLUNIFORM3FPROC)wgl_GetProcAddress("glUniform3f"); - wgl_glUniform3fv = (PFNGLUNIFORM3FVPROC)wgl_GetProcAddress("glUniform3fv"); - wgl_glUniform3i = (PFNGLUNIFORM3IPROC)wgl_GetProcAddress("glUniform3i"); - wgl_glUniform3iv = (PFNGLUNIFORM3IVPROC)wgl_GetProcAddress("glUniform3iv"); - wgl_glUniform4f = (PFNGLUNIFORM4FPROC)wgl_GetProcAddress("glUniform4f"); - wgl_glUniform4fv = (PFNGLUNIFORM4FVPROC)wgl_GetProcAddress("glUniform4fv"); - wgl_glUniform4i = (PFNGLUNIFORM4IPROC)wgl_GetProcAddress("glUniform4i"); - wgl_glUniform4iv = (PFNGLUNIFORM4IVPROC)wgl_GetProcAddress("glUniform4iv"); - wgl_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)wgl_GetProcAddress("glUniformMatrix2fv"); - wgl_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)wgl_GetProcAddress("glUniformMatrix3fv"); - wgl_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wgl_GetProcAddress("glUniformMatrix4fv"); - wgl_glUseProgram = (PFNGLUSEPROGRAMPROC)wgl_GetProcAddress("glUseProgram"); - wgl_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)wgl_GetProcAddress("glValidateProgram"); - wgl_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)wgl_GetProcAddress("glVertexAttrib1f"); - wgl_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)wgl_GetProcAddress("glVertexAttrib1fv"); - wgl_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)wgl_GetProcAddress("glVertexAttrib2f"); - wgl_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)wgl_GetProcAddress("glVertexAttrib2fv"); - wgl_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)wgl_GetProcAddress("glVertexAttrib3f"); - wgl_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)wgl_GetProcAddress("glVertexAttrib3fv"); - wgl_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)wgl_GetProcAddress("glVertexAttrib4f"); - wgl_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)wgl_GetProcAddress("glVertexAttrib4fv"); - wgl_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)wgl_GetProcAddress("glVertexAttribPointer"); - wgl_glViewport = (PFNGLVIEWPORTPROC)wgl_GetProcAddress("glViewport"); + wgl_glShaderSource = (PFNGLSHADERSOURCEPROC)wgl_GetProcAddress("glShaderSource"); + wgl_glStencilFunc = (PFNGLSTENCILFUNCPROC)wgl_GetProcAddress("glStencilFunc"); + wgl_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)wgl_GetProcAddress("glStencilFuncSeparate"); + wgl_glStencilMask = (PFNGLSTENCILMASKPROC)wgl_GetProcAddress("glStencilMask"); + wgl_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)wgl_GetProcAddress("glStencilMaskSeparate"); + wgl_glStencilOp = (PFNGLSTENCILOPPROC)wgl_GetProcAddress("glStencilOp"); + wgl_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)wgl_GetProcAddress("glStencilOpSeparate"); + wgl_glTexImage2D = (PFNGLTEXIMAGE2DPROC)wgl_GetProcAddress("glTexImage2D"); + wgl_glTexParameterf = (PFNGLTEXPARAMETERFPROC)wgl_GetProcAddress("glTexParameterf"); + wgl_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)wgl_GetProcAddress("glTexParameterfv"); + wgl_glTexParameteri = (PFNGLTEXPARAMETERIPROC)wgl_GetProcAddress("glTexParameteri"); + wgl_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)wgl_GetProcAddress("glTexParameteriv"); + wgl_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)wgl_GetProcAddress("glTexSubImage2D"); + wgl_glUniform1f = (PFNGLUNIFORM1FPROC)wgl_GetProcAddress("glUniform1f"); + wgl_glUniform1fv = (PFNGLUNIFORM1FVPROC)wgl_GetProcAddress("glUniform1fv"); + wgl_glUniform1i = (PFNGLUNIFORM1IPROC)wgl_GetProcAddress("glUniform1i"); + wgl_glUniform1iv = (PFNGLUNIFORM1IVPROC)wgl_GetProcAddress("glUniform1iv"); + wgl_glUniform2f = (PFNGLUNIFORM2FPROC)wgl_GetProcAddress("glUniform2f"); + wgl_glUniform2fv = (PFNGLUNIFORM2FVPROC)wgl_GetProcAddress("glUniform2fv"); + wgl_glUniform2i = (PFNGLUNIFORM2IPROC)wgl_GetProcAddress("glUniform2i"); + wgl_glUniform2iv = (PFNGLUNIFORM2IVPROC)wgl_GetProcAddress("glUniform2iv"); + wgl_glUniform3f = (PFNGLUNIFORM3FPROC)wgl_GetProcAddress("glUniform3f"); + wgl_glUniform3fv = (PFNGLUNIFORM3FVPROC)wgl_GetProcAddress("glUniform3fv"); + wgl_glUniform3i = (PFNGLUNIFORM3IPROC)wgl_GetProcAddress("glUniform3i"); + wgl_glUniform3iv = (PFNGLUNIFORM3IVPROC)wgl_GetProcAddress("glUniform3iv"); + wgl_glUniform4f = (PFNGLUNIFORM4FPROC)wgl_GetProcAddress("glUniform4f"); + wgl_glUniform4fv = (PFNGLUNIFORM4FVPROC)wgl_GetProcAddress("glUniform4fv"); + wgl_glUniform4i = (PFNGLUNIFORM4IPROC)wgl_GetProcAddress("glUniform4i"); + wgl_glUniform4iv = (PFNGLUNIFORM4IVPROC)wgl_GetProcAddress("glUniform4iv"); + wgl_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)wgl_GetProcAddress("glUniformMatrix2fv"); + wgl_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)wgl_GetProcAddress("glUniformMatrix3fv"); + wgl_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wgl_GetProcAddress("glUniformMatrix4fv"); + wgl_glUseProgram = (PFNGLUSEPROGRAMPROC)wgl_GetProcAddress("glUseProgram"); + wgl_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)wgl_GetProcAddress("glValidateProgram"); + wgl_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)wgl_GetProcAddress("glVertexAttrib1f"); + wgl_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)wgl_GetProcAddress("glVertexAttrib1fv"); + wgl_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)wgl_GetProcAddress("glVertexAttrib2f"); + wgl_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)wgl_GetProcAddress("glVertexAttrib2fv"); + wgl_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)wgl_GetProcAddress("glVertexAttrib3f"); + wgl_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)wgl_GetProcAddress("glVertexAttrib3fv"); + wgl_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)wgl_GetProcAddress("glVertexAttrib4f"); + wgl_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)wgl_GetProcAddress("glVertexAttrib4fv"); + wgl_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)wgl_GetProcAddress("glVertexAttribPointer"); + wgl_glViewport = (PFNGLVIEWPORTPROC)wgl_GetProcAddress("glViewport"); /* OpenGL ES 3.0 */ - + wgl_glReadBuffer = (PFNGLREADBUFFERPROC)wgl_GetProcAddress("glReadBuffer"); wgl_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)wgl_GetProcAddress("glDrawRangeElements"); wgl_glTexImage3D = (PFNGLTEXIMAGE3DPROC)wgl_GetProcAddress("glTexImage3D"); @@ -473,7 +478,8 @@ void loadWGL() { wgl_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)wgl_GetProcAddress("glUniformMatrix3x4fv"); wgl_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)wgl_GetProcAddress("glUniformMatrix4x3fv"); wgl_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)wgl_GetProcAddress("glBlitFramebuffer"); - wgl_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)wgl_GetProcAddress("glRenderbufferStorageMultisample"); + wgl_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)wgl_GetProcAddress( + "glRenderbufferStorageMultisample"); wgl_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)wgl_GetProcAddress("glFramebufferTextureLayer"); wgl_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)wgl_GetProcAddress("glMapBufferRange"); wgl_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)wgl_GetProcAddress("glFlushMappedBufferRange"); @@ -486,8 +492,10 @@ void loadWGL() { wgl_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glEndTransformFeedback"); wgl_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)wgl_GetProcAddress("glBindBufferRange"); wgl_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)wgl_GetProcAddress("glBindBufferBase"); - wgl_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)wgl_GetProcAddress("glTransformFeedbackVaryings"); - wgl_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)wgl_GetProcAddress("glGetTransformFeedbackVarying"); + wgl_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)wgl_GetProcAddress( + "glTransformFeedbackVaryings"); + wgl_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)wgl_GetProcAddress( + "glGetTransformFeedbackVarying"); wgl_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)wgl_GetProcAddress("glVertexAttribIPointer"); wgl_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)wgl_GetProcAddress("glGetVertexAttribIiv"); wgl_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)wgl_GetProcAddress("glGetVertexAttribIuiv"); @@ -515,7 +523,8 @@ void loadWGL() { wgl_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)wgl_GetProcAddress("glGetActiveUniformsiv"); wgl_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)wgl_GetProcAddress("glGetUniformBlockIndex"); wgl_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)wgl_GetProcAddress("glGetActiveUniformBlockiv"); - wgl_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)wgl_GetProcAddress("glGetActiveUniformBlockName"); + wgl_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)wgl_GetProcAddress( + "glGetActiveUniformBlockName"); wgl_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)wgl_GetProcAddress("glUniformBlockBinding"); wgl_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)wgl_GetProcAddress("glDrawArraysInstanced"); wgl_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)wgl_GetProcAddress("glDrawElementsInstanced"); @@ -540,7 +549,8 @@ void loadWGL() { wgl_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)wgl_GetProcAddress("glGetSamplerParameterfv"); wgl_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)wgl_GetProcAddress("glVertexAttribDivisor"); wgl_glBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glBindTransformFeedback"); - wgl_glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)wgl_GetProcAddress("glDeleteTransformFeedbacks"); + wgl_glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)wgl_GetProcAddress( + "glDeleteTransformFeedbacks"); wgl_glGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)wgl_GetProcAddress("glGenTransformFeedbacks"); wgl_glIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glIsTransformFeedback"); wgl_glPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)wgl_GetProcAddress("glPauseTransformFeedback"); @@ -549,17 +559,19 @@ void loadWGL() { wgl_glProgramBinary = (PFNGLPROGRAMBINARYPROC)wgl_GetProcAddress("glProgramBinary"); wgl_glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)wgl_GetProcAddress("glProgramParameteri"); wgl_glInvalidateFramebuffer = (PFNGLINVALIDATEFRAMEBUFFERPROC)wgl_GetProcAddress("glInvalidateFramebuffer"); - wgl_glInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)wgl_GetProcAddress("glInvalidateSubFramebuffer"); + wgl_glInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)wgl_GetProcAddress( + "glInvalidateSubFramebuffer"); wgl_glTexStorage2D = (PFNGLTEXSTORAGE2DPROC)wgl_GetProcAddress("glTexStorage2D"); wgl_glTexStorage3D = (PFNGLTEXSTORAGE3DPROC)wgl_GetProcAddress("glTexStorage3D"); wgl_glGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC)wgl_GetProcAddress("glGetInternalformativ"); - + /* OpenGL Windows Extensions */ - - wgl_wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wgl_GetProcAddress("wglChoosePixelFormatARB"); - wgl_wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wgl_GetProcAddress("wglCreateContextAttribsARB"); - wgl_wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wgl_GetProcAddress("wglGetExtensionsStringARB"); - wgl_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wgl_GetProcAddress("wglGetExtensionsStringEXT"); + + wgl_wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wgl_GetProcAddress("wglChoosePixelFormatARB"); + wgl_wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wgl_GetProcAddress( + "wglCreateContextAttribsARB"); + wgl_wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wgl_GetProcAddress("wglGetExtensionsStringARB"); + wgl_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wgl_GetProcAddress("wglGetExtensionsStringEXT"); } #ifdef __cplusplus @@ -571,263 +583,1203 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = [](GLenum texture) { if (!opengl32) loadWGL(); ::wgl_glActiveTexture(texture); }; -void (* const glAttachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glAttachShader(program, shader); }; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = [](GLuint program, GLuint index, const GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glBindAttribLocation(program, index, name); }; -void (* const glBindBuffer)(GLenum, GLuint) = [](GLenum target, GLuint buffer) { if (!opengl32) loadWGL(); ::wgl_glBindBuffer(target, buffer); }; -void (* const glBindFramebuffer)(GLenum, GLuint) = [](GLenum target, GLuint framebuffer) { if (!opengl32) loadWGL(); ::wgl_glBindFramebuffer(target, framebuffer); }; -void (* const glBindRenderbuffer)(GLenum, GLuint) = [](GLenum target, GLuint renderbuffer) { if (!opengl32) loadWGL(); ::wgl_glBindRenderbuffer(target, renderbuffer); }; -void (* const glBindTexture)(GLenum, GLuint) = [](GLenum target, GLuint texture) { if (!opengl32) loadWGL(); ::wgl_glBindTexture(target, texture); }; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { if (!opengl32) loadWGL(); ::wgl_glBlendColor(red, green, blue, alpha); }; -void (* const glBlendEquation)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glBlendEquation(mode); }; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = [](GLenum modeRGB, GLenum modeAlpha) { if (!opengl32) loadWGL(); ::wgl_glBlendEquationSeparate(modeRGB, modeAlpha); }; -void (* const glBlendFunc)(GLenum, GLenum) = [](GLenum sfactor, GLenum dfactor) { if (!opengl32) loadWGL(); ::wgl_glBlendFunc(sfactor, dfactor); }; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = [](GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) { if (!opengl32) loadWGL(); ::wgl_glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); }; -void (* const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = [](GLenum target, GLsizeiptr size, const void* data, GLenum usage) { if (!opengl32) loadWGL(); ::wgl_glBufferData(target, size, data, usage); }; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = [](GLenum target, GLintptr offset, GLsizeiptr size, const void* data) { if (!opengl32) loadWGL(); ::wgl_glBufferSubData(target, offset, size, data); }; -GLenum(* const glCheckFramebufferStatus)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); return ::wgl_glCheckFramebufferStatus(target); }; -void (* const glClear)(GLbitfield) = [](GLbitfield mask) { if (!opengl32) loadWGL(); ::wgl_glClear(mask); }; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { if (!opengl32) loadWGL(); ::wgl_glClearColor(red, green, blue, alpha); }; -void (* const glClearDepthf)(GLfloat) = [](GLfloat d) { if (!opengl32) loadWGL(); ::wgl_glClearDepthf(d); }; -void (* const glClearStencil)(GLint) = [](GLint s) { if (!opengl32) loadWGL(); ::wgl_glClearStencil(s); }; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = [](GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { if (!opengl32) loadWGL(); ::wgl_glColorMask(red, green, blue, alpha); }; -void (* const glCompileShader)(GLuint) = [](GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glCompileShader(shader); }; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = [](GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); }; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); }; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = [](GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) { if (!opengl32) loadWGL(); ::wgl_glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); }; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); }; -GLuint(* const glCreateProgram)() = [](void) { if (!opengl32) loadWGL(); return ::wgl_glCreateProgram(); }; -GLuint(* const glCreateShader)(GLenum) = [](GLenum type) { if (!opengl32) loadWGL(); return ::wgl_glCreateShader(type); }; -void (* const glCullFace)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glCullFace(mode); }; -void (* const glDeleteBuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* buffers) { if (!opengl32) loadWGL(); ::wgl_glDeleteBuffers(n, buffers); }; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* framebuffers) { if (!opengl32) loadWGL(); ::wgl_glDeleteFramebuffers(n, framebuffers); }; -void (* const glDeleteProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glDeleteProgram(program); }; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* renderbuffers) { if (!opengl32) loadWGL(); ::wgl_glDeleteRenderbuffers(n, renderbuffers); }; -void (* const glDeleteShader)(GLuint) = [](GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glDeleteShader(shader); }; -void (* const glDeleteTextures)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* textures) { if (!opengl32) loadWGL(); ::wgl_glDeleteTextures(n, textures); }; -void (* const glDepthFunc)(GLenum) = [](GLenum func) { if (!opengl32) loadWGL(); ::wgl_glDepthFunc(func); }; -void (* const glDepthMask)(GLboolean) = [](GLboolean flag) { if (!opengl32) loadWGL(); ::wgl_glDepthMask(flag); }; -void (* const glDepthRangef)(GLfloat, GLfloat) = [](GLfloat n, GLfloat f) { if (!opengl32) loadWGL(); ::wgl_glDepthRangef(n, f); }; -void (* const glDetachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { if (!opengl32) loadWGL(); ::wgl_glDetachShader(program, shader); }; -void (* const glDisable)(GLenum) = [](GLenum cap) { if (!opengl32) loadWGL(); ::wgl_glDisable(cap); }; -void (* const glDisableVertexAttribArray)(GLuint) = [](GLuint index) { if (!opengl32) loadWGL(); ::wgl_glDisableVertexAttribArray(index); }; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = [](GLenum mode, GLint first, GLsizei count) { if (!opengl32) loadWGL(); ::wgl_glDrawArrays(mode, first, count); }; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = [](GLenum mode, GLsizei count, GLenum type, const void* indices) { if (!opengl32) loadWGL(); ::wgl_glDrawElements(mode, count, type, indices); }; -void (* const glEnable)(GLenum) = [](GLenum cap) { if (!opengl32) loadWGL(); ::wgl_glEnable(cap); }; -void (* const glEnableVertexAttribArray)(GLuint) = [](GLuint index) { if (!opengl32) loadWGL(); ::wgl_glEnableVertexAttribArray(index); }; -void (* const glFinish)() = [](void) { if (!opengl32) loadWGL(); ::wgl_glFinish(); }; -void (* const glFlush)() = [](void) { if (!opengl32) loadWGL(); ::wgl_glFlush(); }; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = [](GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { if (!opengl32) loadWGL(); ::wgl_glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); }; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = [](GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { if (!opengl32) loadWGL(); ::wgl_glFramebufferTexture2D(target, attachment, textarget, texture, level); }; -void (* const glFrontFace)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glFrontFace(mode); }; -void (* const glGenBuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* buffers) { if (!opengl32) loadWGL(); ::wgl_glGenBuffers(n, buffers); }; -void (* const glGenerateMipmap)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); ::wgl_glGenerateMipmap(target); }; -void (* const glGenFramebuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* framebuffers) { if (!opengl32) loadWGL(); ::wgl_glGenFramebuffers(n, framebuffers); }; -void (* const glGenRenderbuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* renderbuffers) { if (!opengl32) loadWGL(); ::wgl_glGenRenderbuffers(n, renderbuffers); }; -void (* const glGenTextures)(GLsizei, GLuint*) = [](GLsizei n, GLuint* textures) { if (!opengl32) loadWGL(); ::wgl_glGenTextures(n, textures); }; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glGetActiveAttrib(program, index, bufSize, length, size, type, name); }; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniform(program, index, bufSize, length, size, type, name); }; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = [](GLuint program, GLsizei maxCount, GLsizei* count, GLuint* shaders) { if (!opengl32) loadWGL(); ::wgl_glGetAttachedShaders(program, maxCount, count, shaders); }; -GLint(* const glGetAttribLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { if (!opengl32) loadWGL(); return ::wgl_glGetAttribLocation(program, name); }; -void (* const glGetBooleanv)(GLenum, GLboolean*) = [](GLenum pname, GLboolean* data) { if (!opengl32) loadWGL(); ::wgl_glGetBooleanv(pname, data); }; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetBufferParameteriv(target, pname, params); }; -GLenum(* const glGetError)() = [](void) { if (!opengl32) loadWGL(); return ::wgl_glGetError(); }; -void (* const glGetFloatv)(GLenum, GLfloat*) = [](GLenum pname, GLfloat* data) { if (!opengl32) loadWGL(); ::wgl_glGetFloatv(pname, data); }; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint*) = [](GLenum target, GLenum attachment, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); }; -void (* const glGetIntegerv)(GLenum, GLint*) = [](GLenum pname, GLint* data) { if (!opengl32) loadWGL(); ::wgl_glGetIntegerv(pname, data); }; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { if (!opengl32) loadWGL(); ::wgl_glGetProgramInfoLog(program, bufSize, length, infoLog); }; -void (* const glGetProgramiv)(GLuint, GLenum, GLint*) = [](GLuint program, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetProgramiv(program, pname, params); }; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetRenderbufferParameteriv(target, pname, params); }; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { if (!opengl32) loadWGL(); ::wgl_glGetShaderInfoLog(shader, bufSize, length, infoLog); }; -void (* const glGetShaderiv)(GLuint, GLenum, GLint*) = [](GLuint shader, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetShaderiv(shader, pname, params); }; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = [](GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) { if (!opengl32) loadWGL(); ::wgl_glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); }; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source) { if (!opengl32) loadWGL(); ::wgl_glGetShaderSource(shader, bufSize, length, source); }; -const GLubyte* (* const glGetString)(GLenum) = [](GLenum name) { if (!opengl32) loadWGL(); return ::wgl_glGetString(name); }; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = [](GLenum target, GLenum pname, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetTexParameterfv(target, pname, params); }; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetTexParameteriv(target, pname, params); }; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat*) = [](GLuint program, GLint location, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetUniformfv(program, location, params); }; -void (* const glGetUniformiv)(GLuint, GLint, GLint*) = [](GLuint program, GLint location, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetUniformiv(program, location, params); }; -GLint(* const glGetUniformLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { if (!opengl32) loadWGL(); return ::wgl_glGetUniformLocation(program, name); }; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = [](GLuint index, GLenum pname, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribfv(index, pname, params); }; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribiv(index, pname, params); }; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = [](GLuint index, GLenum pname, void** pointer) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribPointerv(index, pname, pointer); }; -void (* const glHint)(GLenum, GLenum) = [](GLenum target, GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glHint(target, mode); }; -GLboolean(* const glIsBuffer)(GLuint) = [](GLuint buffer) { if (!opengl32) loadWGL(); return ::wgl_glIsBuffer(buffer); }; -GLboolean(* const glIsEnabled)(GLenum) = [](GLenum cap) { if (!opengl32) loadWGL(); return ::wgl_glIsEnabled(cap); }; -GLboolean(* const glIsFramebuffer)(GLuint) = [](GLuint framebuffer) { if (!opengl32) loadWGL(); return ::wgl_glIsFramebuffer(framebuffer); }; -GLboolean(* const glIsProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); return ::wgl_glIsProgram(program); }; -GLboolean(* const glIsRenderbuffer)(GLuint) = [](GLuint renderbuffer) { if (!opengl32) loadWGL(); return ::wgl_glIsRenderbuffer(renderbuffer); }; -GLboolean(* const glIsShader)(GLuint) = [](GLuint shader) { if (!opengl32) loadWGL(); return ::wgl_glIsShader(shader); }; -GLboolean(* const glIsTexture)(GLuint) = [](GLuint texture) { if (!opengl32) loadWGL(); return ::wgl_glIsTexture(texture); }; -void (* const glLineWidth)(GLfloat) = [](GLfloat width) { if (!opengl32) loadWGL(); ::wgl_glLineWidth(width); }; -void (* const glLinkProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glLinkProgram(program); }; -void (* const glPixelStorei)(GLenum, GLint) = [](GLenum pname, GLint param) { if (!opengl32) loadWGL(); ::wgl_glPixelStorei(pname, param); }; -void (* const glPolygonOffset)(GLfloat, GLfloat) = [](GLfloat factor, GLfloat units) { if (!opengl32) loadWGL(); ::wgl_glPolygonOffset(factor, units); }; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = [](GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) { if (!opengl32) loadWGL(); ::wgl_glReadPixels(x, y, width, height, format, type, pixels); }; -void (* const glReleaseShaderCompiler)() = []() { if (!opengl32) loadWGL(); ::wgl_glReleaseShaderCompiler(); }; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = [](GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glRenderbufferStorage(target, internalformat, width, height); }; -void (* const glSampleCoverage)(GLfloat, GLboolean) = [](GLfloat value, GLboolean invert) { if (!opengl32) loadWGL(); ::wgl_glSampleCoverage(value, invert); }; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glScissor(x, y, width, height); }; -void (* const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = [](GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length) { if (!opengl32) loadWGL(); ::wgl_glShaderBinary(n, shaders, binaryformat, binary, length); }; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = [](GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length) { if (!opengl32) loadWGL(); ::wgl_glShaderSource(shader, count, string, length); }; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = [](GLenum func, GLint ref, GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilFunc(func, ref, mask); }; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = [](GLenum face, GLenum func, GLint ref, GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilFuncSeparate(face, func, ref, mask); }; -void (* const glStencilMask)(GLuint) = [](GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilMask(mask); }; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = [](GLenum face, GLuint mask) { if (!opengl32) loadWGL(); ::wgl_glStencilMaskSeparate(face, mask); }; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = [](GLenum fail, GLenum zfail, GLenum zpass) { if (!opengl32) loadWGL(); ::wgl_glStencilOp(fail, zfail, zpass); }; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = [](GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) { if (!opengl32) loadWGL(); ::wgl_glStencilOpSeparate(face, sfail, dpfail, dppass); }; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = [](GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); }; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = [](GLenum target, GLenum pname, GLfloat param) { if (!opengl32) loadWGL(); ::wgl_glTexParameterf(target, pname, param); }; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = [](GLenum target, GLenum pname, const GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glTexParameterfv(target, pname, params); }; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = [](GLenum target, GLenum pname, GLint param) { if (!opengl32) loadWGL(); ::wgl_glTexParameteri(target, pname, param); }; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint*) = [](GLenum target, GLenum pname, const GLint* params) { if (!opengl32) loadWGL(); ::wgl_glTexParameteriv(target, pname, params); }; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); }; -void (* const glUniform1f)(GLint, GLfloat) = [](GLint location, GLfloat v0) { if (!opengl32) loadWGL(); ::wgl_glUniform1f(location, v0); }; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform1fv(location, count, value); }; -void (* const glUniform1i)(GLint, GLint) = [](GLint location, GLint v0) { if (!opengl32) loadWGL(); ::wgl_glUniform1i(location, v0); }; -void (* const glUniform1iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform1iv(location, count, value); }; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1) { if (!opengl32) loadWGL(); ::wgl_glUniform2f(location, v0, v1); }; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform2fv(location, count, value); }; -void (* const glUniform2i)(GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1) { if (!opengl32) loadWGL(); ::wgl_glUniform2i(location, v0, v1); }; -void (* const glUniform2iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform2iv(location, count, value); }; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { if (!opengl32) loadWGL(); ::wgl_glUniform3f(location, v0, v1, v2); }; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform3fv(location, count, value); }; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1, GLint v2) { if (!opengl32) loadWGL(); ::wgl_glUniform3i(location, v0, v1, v2); }; -void (* const glUniform3iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform3iv(location, count, value); }; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { if (!opengl32) loadWGL(); ::wgl_glUniform4f(location, v0, v1, v2, v3); }; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniform4fv(location, count, value); }; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { if (!opengl32) loadWGL(); ::wgl_glUniform4i(location, v0, v1, v2, v3); }; -void (* const glUniform4iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform4iv(location, count, value); }; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix2fv(location, count, transpose, value); }; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix3fv(location, count, transpose, value); }; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix4fv(location, count, transpose, value); }; -void (* const glUseProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glUseProgram(program); }; -void (* const glValidateProgram)(GLuint) = [](GLuint program) { if (!opengl32) loadWGL(); ::wgl_glValidateProgram(program); }; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = [](GLuint index, GLfloat x) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib1f(index, x); }; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib1fv(index, v); }; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib2f(index, x, y); }; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib2fv(index, v); }; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y, GLfloat z) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib3f(index, x, y, z); }; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib3fv(index, v); }; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib4f(index, x, y, z, w); }; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttrib4fv(index, v); }; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = [](GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribPointer(index, size, type, normalized, stride, pointer); }; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glViewport(x, y, width, height); }; +void (*const glActiveTexture)(GLenum) = [](GLenum texture) { + if (!opengl32) loadWGL(); + ::wgl_glActiveTexture(texture); +}; +void (*const glAttachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glAttachShader(program, shader); +}; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = + [](GLuint program, GLuint index, const GLchar* name) { + if (!opengl32) loadWGL(); + ::wgl_glBindAttribLocation(program, index, name); + }; +void (*const glBindBuffer)(GLenum, GLuint) = [](GLenum target, GLuint buffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindBuffer(target, buffer); +}; +void (*const glBindFramebuffer)(GLenum, GLuint) = [](GLenum target, GLuint framebuffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindFramebuffer(target, framebuffer); +}; +void (*const glBindRenderbuffer)(GLenum, GLuint) = [](GLenum target, GLuint renderbuffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindRenderbuffer(target, renderbuffer); +}; +void (*const glBindTexture)(GLenum, GLuint) = [](GLenum target, GLuint texture) { + if (!opengl32) loadWGL(); + ::wgl_glBindTexture(target, texture); +}; +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = + [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { + if (!opengl32) loadWGL(); + ::wgl_glBlendColor(red, green, blue, alpha); + }; +void (*const glBlendEquation)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glBlendEquation(mode); +}; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = [](GLenum modeRGB, GLenum modeAlpha) { + if (!opengl32) loadWGL(); + ::wgl_glBlendEquationSeparate(modeRGB, modeAlpha); +}; +void (*const glBlendFunc)(GLenum, GLenum) = [](GLenum sfactor, GLenum dfactor) { + if (!opengl32) loadWGL(); + ::wgl_glBlendFunc(sfactor, dfactor); +}; +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = + [](GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) { + if (!opengl32) loadWGL(); + ::wgl_glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); + }; +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = + [](GLenum target, GLsizeiptr size, const void* data, GLenum usage) { + if (!opengl32) loadWGL(); + ::wgl_glBufferData(target, size, data, usage); + }; +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = + [](GLenum target, GLintptr offset, GLsizeiptr size, const void* data) { + if (!opengl32) loadWGL(); + ::wgl_glBufferSubData(target, offset, size, data); + }; +GLenum (*const glCheckFramebufferStatus)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + return ::wgl_glCheckFramebufferStatus(target); +}; +void (*const glClear)(GLbitfield) = [](GLbitfield mask) { + if (!opengl32) loadWGL(); + ::wgl_glClear(mask); +}; +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = + [](GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { + if (!opengl32) loadWGL(); + ::wgl_glClearColor(red, green, blue, alpha); + }; +void (*const glClearDepthf)(GLfloat) = [](GLfloat d) { + if (!opengl32) loadWGL(); + ::wgl_glClearDepthf(d); +}; +void (*const glClearStencil)(GLint) = [](GLint s) { + if (!opengl32) loadWGL(); + ::wgl_glClearStencil(s); +}; +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = + [](GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { + if (!opengl32) loadWGL(); + ::wgl_glColorMask(red, green, blue, alpha); + }; +void (*const glCompileShader)(GLuint) = [](GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glCompileShader(shader); +}; +void (*const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = + [](GLenum target, + GLint level, + GLenum internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLsizei imageSize, + const void* data) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); + }; +void (*const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = + [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLsizei width, + GLsizei height, + GLenum format, + GLsizei imageSize, + const void* data) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); + }; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = [](GLenum target, + GLint level, + GLenum internalformat, + GLint x, + GLint y, + GLsizei width, + GLsizei height, + GLint border) { + if (!opengl32) loadWGL(); + ::wgl_glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); +}; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = + [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + }; +GLuint (*const glCreateProgram)() = [](void) { + if (!opengl32) loadWGL(); + return ::wgl_glCreateProgram(); +}; +GLuint (*const glCreateShader)(GLenum) = [](GLenum type) { + if (!opengl32) loadWGL(); + return ::wgl_glCreateShader(type); +}; +void (*const glCullFace)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glCullFace(mode); +}; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* buffers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteBuffers(n, buffers); +}; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* framebuffers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteFramebuffers(n, framebuffers); +}; +void (*const glDeleteProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteProgram(program); +}; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* renderbuffers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteRenderbuffers(n, renderbuffers); +}; +void (*const glDeleteShader)(GLuint) = [](GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteShader(shader); +}; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* textures) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteTextures(n, textures); +}; +void (*const glDepthFunc)(GLenum) = [](GLenum func) { + if (!opengl32) loadWGL(); + ::wgl_glDepthFunc(func); +}; +void (*const glDepthMask)(GLboolean) = [](GLboolean flag) { + if (!opengl32) loadWGL(); + ::wgl_glDepthMask(flag); +}; +void (*const glDepthRangef)(GLfloat, GLfloat) = [](GLfloat n, GLfloat f) { + if (!opengl32) loadWGL(); + ::wgl_glDepthRangef(n, f); +}; +void (*const glDetachShader)(GLuint, GLuint) = [](GLuint program, GLuint shader) { + if (!opengl32) loadWGL(); + ::wgl_glDetachShader(program, shader); +}; +void (*const glDisable)(GLenum) = [](GLenum cap) { + if (!opengl32) loadWGL(); + ::wgl_glDisable(cap); +}; +void (*const glDisableVertexAttribArray)(GLuint) = [](GLuint index) { + if (!opengl32) loadWGL(); + ::wgl_glDisableVertexAttribArray(index); +}; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = [](GLenum mode, GLint first, GLsizei count) { + if (!opengl32) loadWGL(); + ::wgl_glDrawArrays(mode, first, count); +}; +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = + [](GLenum mode, GLsizei count, GLenum type, const void* indices) { + if (!opengl32) loadWGL(); + ::wgl_glDrawElements(mode, count, type, indices); + }; +void (*const glEnable)(GLenum) = [](GLenum cap) { + if (!opengl32) loadWGL(); + ::wgl_glEnable(cap); +}; +void (*const glEnableVertexAttribArray)(GLuint) = [](GLuint index) { + if (!opengl32) loadWGL(); + ::wgl_glEnableVertexAttribArray(index); +}; +void (*const glFinish)() = [](void) { + if (!opengl32) loadWGL(); + ::wgl_glFinish(); +}; +void (*const glFlush)() = [](void) { + if (!opengl32) loadWGL(); + ::wgl_glFlush(); +}; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = + [](GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { + if (!opengl32) loadWGL(); + ::wgl_glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); + }; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = + [](GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { + if (!opengl32) loadWGL(); + ::wgl_glFramebufferTexture2D(target, attachment, textarget, texture, level); + }; +void (*const glFrontFace)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glFrontFace(mode); +}; +void (*const glGenBuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* buffers) { + if (!opengl32) loadWGL(); + ::wgl_glGenBuffers(n, buffers); +}; +void (*const glGenerateMipmap)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + ::wgl_glGenerateMipmap(target); +}; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* framebuffers) { + if (!opengl32) loadWGL(); + ::wgl_glGenFramebuffers(n, framebuffers); +}; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = [](GLsizei n, GLuint* renderbuffers) { + if (!opengl32) loadWGL(); + ::wgl_glGenRenderbuffers(n, renderbuffers); +}; +void (*const glGenTextures)(GLsizei, GLuint*) = [](GLsizei n, GLuint* textures) { + if (!opengl32) loadWGL(); + ::wgl_glGenTextures(n, textures); +}; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = + [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveAttrib(program, index, bufSize, length, size, type, name); + }; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = + [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniform(program, index, bufSize, length, size, type, name); + }; +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = + [](GLuint program, GLsizei maxCount, GLsizei* count, GLuint* shaders) { + if (!opengl32) loadWGL(); + ::wgl_glGetAttachedShaders(program, maxCount, count, shaders); + }; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetAttribLocation(program, name); +}; +void (*const glGetBooleanv)(GLenum, GLboolean*) = [](GLenum pname, GLboolean* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetBooleanv(pname, data); +}; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetBufferParameteriv(target, pname, params); +}; +GLenum (*const glGetError)() = [](void) { + if (!opengl32) loadWGL(); + return ::wgl_glGetError(); +}; +void (*const glGetFloatv)(GLenum, GLfloat*) = [](GLenum pname, GLfloat* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetFloatv(pname, data); +}; +void (*const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint*) = + [](GLenum target, GLenum attachment, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); + }; +void (*const glGetIntegerv)(GLenum, GLint*) = [](GLenum pname, GLint* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetIntegerv(pname, data); +}; +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = + [](GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { + if (!opengl32) loadWGL(); + ::wgl_glGetProgramInfoLog(program, bufSize, length, infoLog); + }; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = [](GLuint program, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetProgramiv(program, pname, params); +}; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetRenderbufferParameteriv(target, pname, params); +}; +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = + [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderInfoLog(shader, bufSize, length, infoLog); + }; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = [](GLuint shader, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderiv(shader, pname, params); +}; +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = + [](GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); + }; +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = + [](GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* source) { + if (!opengl32) loadWGL(); + ::wgl_glGetShaderSource(shader, bufSize, length, source); + }; +const GLubyte* (*const glGetString)(GLenum) = [](GLenum name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetString(name); +}; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = [](GLenum target, GLenum pname, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetTexParameterfv(target, pname, params); +}; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetTexParameteriv(target, pname, params); +}; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = [](GLuint program, GLint location, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformfv(program, location, params); +}; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = [](GLuint program, GLint location, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformiv(program, location, params); +}; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetUniformLocation(program, name); +}; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = [](GLuint index, GLenum pname, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribfv(index, pname, params); +}; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribiv(index, pname, params); +}; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = [](GLuint index, GLenum pname, void** pointer) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribPointerv(index, pname, pointer); +}; +void (*const glHint)(GLenum, GLenum) = [](GLenum target, GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glHint(target, mode); +}; +GLboolean (*const glIsBuffer)(GLuint) = [](GLuint buffer) { + if (!opengl32) loadWGL(); + return ::wgl_glIsBuffer(buffer); +}; +GLboolean (*const glIsEnabled)(GLenum) = [](GLenum cap) { + if (!opengl32) loadWGL(); + return ::wgl_glIsEnabled(cap); +}; +GLboolean (*const glIsFramebuffer)(GLuint) = [](GLuint framebuffer) { + if (!opengl32) loadWGL(); + return ::wgl_glIsFramebuffer(framebuffer); +}; +GLboolean (*const glIsProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + return ::wgl_glIsProgram(program); +}; +GLboolean (*const glIsRenderbuffer)(GLuint) = [](GLuint renderbuffer) { + if (!opengl32) loadWGL(); + return ::wgl_glIsRenderbuffer(renderbuffer); +}; +GLboolean (*const glIsShader)(GLuint) = [](GLuint shader) { + if (!opengl32) loadWGL(); + return ::wgl_glIsShader(shader); +}; +GLboolean (*const glIsTexture)(GLuint) = [](GLuint texture) { + if (!opengl32) loadWGL(); + return ::wgl_glIsTexture(texture); +}; +void (*const glLineWidth)(GLfloat) = [](GLfloat width) { + if (!opengl32) loadWGL(); + ::wgl_glLineWidth(width); +}; +void (*const glLinkProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glLinkProgram(program); +}; +void (*const glPixelStorei)(GLenum, GLint) = [](GLenum pname, GLint param) { + if (!opengl32) loadWGL(); + ::wgl_glPixelStorei(pname, param); +}; +void (*const glPolygonOffset)(GLfloat, GLfloat) = [](GLfloat factor, GLfloat units) { + if (!opengl32) loadWGL(); + ::wgl_glPolygonOffset(factor, units); +}; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = + [](GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glReadPixels(x, y, width, height, format, type, pixels); + }; +void (*const glReleaseShaderCompiler)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glReleaseShaderCompiler(); +}; +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = + [](GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glRenderbufferStorage(target, internalformat, width, height); + }; +void (*const glSampleCoverage)(GLfloat, GLboolean) = [](GLfloat value, GLboolean invert) { + if (!opengl32) loadWGL(); + ::wgl_glSampleCoverage(value, invert); +}; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glScissor(x, y, width, height); +}; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = + [](GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length) { + if (!opengl32) loadWGL(); + ::wgl_glShaderBinary(n, shaders, binaryformat, binary, length); + }; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = + [](GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length) { + if (!opengl32) loadWGL(); + ::wgl_glShaderSource(shader, count, string, length); + }; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = [](GLenum func, GLint ref, GLuint mask) { + if (!opengl32) loadWGL(); + ::wgl_glStencilFunc(func, ref, mask); +}; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = + [](GLenum face, GLenum func, GLint ref, GLuint mask) { + if (!opengl32) loadWGL(); + ::wgl_glStencilFuncSeparate(face, func, ref, mask); + }; +void (*const glStencilMask)(GLuint) = [](GLuint mask) { + if (!opengl32) loadWGL(); + ::wgl_glStencilMask(mask); +}; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = [](GLenum face, GLuint mask) { + if (!opengl32) loadWGL(); + ::wgl_glStencilMaskSeparate(face, mask); +}; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = [](GLenum fail, GLenum zfail, GLenum zpass) { + if (!opengl32) loadWGL(); + ::wgl_glStencilOp(fail, zfail, zpass); +}; +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = + [](GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) { + if (!opengl32) loadWGL(); + ::wgl_glStencilOpSeparate(face, sfail, dpfail, dppass); + }; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = + [](GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); + }; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = [](GLenum target, GLenum pname, GLfloat param) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameterf(target, pname, param); +}; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = + [](GLenum target, GLenum pname, const GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameterfv(target, pname, params); + }; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = [](GLenum target, GLenum pname, GLint param) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameteri(target, pname, param); +}; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = [](GLenum target, GLenum pname, const GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glTexParameteriv(target, pname, params); +}; +void (*const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = + [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + const void* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); + }; +void (*const glUniform1f)(GLint, GLfloat) = [](GLint location, GLfloat v0) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1f(location, v0); +}; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1fv(location, count, value); +}; +void (*const glUniform1i)(GLint, GLint) = [](GLint location, GLint v0) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1i(location, v0); +}; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1iv(location, count, value); +}; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2f(location, v0, v1); +}; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2fv(location, count, value); +}; +void (*const glUniform2i)(GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2i(location, v0, v1); +}; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2iv(location, count, value); +}; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3f(location, v0, v1, v2); +}; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3fv(location, count, value); +}; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = [](GLint location, GLint v0, GLint v1, GLint v2) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3i(location, v0, v1, v2); +}; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3iv(location, count, value); +}; +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = + [](GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4f(location, v0, v1, v2, v3); + }; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = [](GLint location, GLsizei count, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4fv(location, count, value); +}; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = + [](GLint location, GLint v0, GLint v1, GLint v2, GLint v3) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4i(location, v0, v1, v2, v3); + }; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = [](GLint location, GLsizei count, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4iv(location, count, value); +}; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix2fv(location, count, transpose, value); + }; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix3fv(location, count, transpose, value); + }; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix4fv(location, count, transpose, value); + }; +void (*const glUseProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glUseProgram(program); +}; +void (*const glValidateProgram)(GLuint) = [](GLuint program) { + if (!opengl32) loadWGL(); + ::wgl_glValidateProgram(program); +}; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = [](GLuint index, GLfloat x) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib1f(index, x); +}; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib1fv(index, v); +}; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib2f(index, x, y); +}; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib2fv(index, v); +}; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = [](GLuint index, GLfloat x, GLfloat y, GLfloat z) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib3f(index, x, y, z); +}; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib3fv(index, v); +}; +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = + [](GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib4f(index, x, y, z, w); + }; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = [](GLuint index, const GLfloat* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttrib4fv(index, v); +}; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = + [](GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribPointer(index, size, type, normalized, stride, pointer); + }; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = [](GLint x, GLint y, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glViewport(x, y, width, height); +}; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = [](GLenum mode) { if (!opengl32) loadWGL(); ::wgl_glReadBuffer(mode); }; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = [](GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) { if (!opengl32) loadWGL(); ::wgl_glDrawRangeElements(mode, start, end, count, type, indices); }; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = [](GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels); }; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels) { if (!opengl32) loadWGL(); ::wgl_glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); }; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height); }; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = [](GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data); }; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = [](GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data) { if (!opengl32) loadWGL(); ::wgl_glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data); }; -void (* const glGenQueries)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glGenQueries(n, ids); }; -void (* const glDeleteQueries)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glDeleteQueries(n, ids); }; -GLboolean (* const glIsQuery)(GLuint) = [](GLuint id) { if (!opengl32) loadWGL(); return ::wgl_glIsQuery(id); }; -void (* const glBeginQuery)(GLenum, GLuint) = [](GLenum target, GLuint id) { if (!opengl32) loadWGL(); ::wgl_glBeginQuery(target, id); }; -void (* const glEndQuery)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); ::wgl_glEndQuery(target); }; -void (* const glGetQueryiv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetQueryiv(target, pname, params); }; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](GLuint id, GLenum pname, GLuint* params) { if (!opengl32) loadWGL(); ::wgl_glGetQueryObjectuiv(id, pname, params); }; -GLboolean (* const glUnmapBuffer)(GLenum) = [](GLenum target) { if (!opengl32) loadWGL(); return ::wgl_glUnmapBuffer(target); }; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](GLenum target, GLenum pname, GLvoid** params) { if (!opengl32) loadWGL(); ::wgl_glGetBufferPointerv(target, pname, params); }; -void (* const glDrawBuffers)(GLsizei, const GLenum*) = [](GLsizei n, const GLenum* bufs) { if (!opengl32) loadWGL(); ::wgl_glDrawBuffers(n, bufs); }; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix2x3fv(location, count, transpose, value); }; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix3x2fv(location, count, transpose, value); }; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix2x4fv(location, count, transpose, value); }; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix4x2fv(location, count, transpose, value); }; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix3x4fv(location, count, transpose, value); }; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glUniformMatrix4x3fv(location, count, transpose, value); }; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = [](GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) { if (!opengl32) loadWGL(); ::wgl_glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); }; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glRenderbufferStorageMultisample(target, samples, internalformat, width, height); }; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = [](GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) { if (!opengl32) loadWGL(); ::wgl_glFramebufferTextureLayer(target, attachment, texture, level, layer); }; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = [](GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) { if (!opengl32) loadWGL(); return ::wgl_glMapBufferRange(target, offset, length, access); }; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = [](GLenum target, GLintptr offset, GLsizeiptr length) { if (!opengl32) loadWGL(); ::wgl_glFlushMappedBufferRange(target, offset, length); }; -void (* const glBindVertexArray)(GLuint) = [](GLuint array) { if (!opengl32) loadWGL(); ::wgl_glBindVertexArray(array); }; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* arrays) { if (!opengl32) loadWGL(); ::wgl_glDeleteVertexArrays(n, arrays); }; -void (* const glGenVertexArrays)(GLsizei, GLuint*) = [](GLsizei n, GLuint* arrays) { if (!opengl32) loadWGL(); ::wgl_glGenVertexArrays(n, arrays); }; -GLboolean (* const glIsVertexArray)(GLuint) = [](GLuint array) { if (!opengl32) loadWGL(); return ::wgl_glIsVertexArray(array); }; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](GLenum target, GLuint index, GLint* data) { if (!opengl32) loadWGL(); ::wgl_glGetIntegeri_v(target, index, data); }; -void (* const glBeginTransformFeedback)(GLenum) = [](GLenum primitiveMode) { if (!opengl32) loadWGL(); ::wgl_glBeginTransformFeedback(primitiveMode); }; -void (* const glEndTransformFeedback)() = []() { if (!opengl32) loadWGL(); ::wgl_glEndTransformFeedback(); }; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = [](GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { if (!opengl32) loadWGL(); ::wgl_glBindBufferRange(target, index, buffer, offset, size); }; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = [](GLenum target, GLuint index, GLuint buffer) { if (!opengl32) loadWGL(); ::wgl_glBindBufferBase(target, index, buffer); }; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = [](GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) { if (!opengl32) loadWGL(); ::wgl_glTransformFeedbackVaryings(program, count, varyings, bufferMode); }; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) { if (!opengl32) loadWGL(); ::wgl_glGetTransformFeedbackVarying(program, index, bufSize, length, size, type, name); }; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = [](GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribIPointer(index, size, type, stride, pointer); }; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribIiv(index, pname, params); }; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](GLuint index, GLenum pname, GLuint* params) { if (!opengl32) loadWGL(); ::wgl_glGetVertexAttribIuiv(index, pname, params); }; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = [](GLuint index, GLint x, GLint y, GLint z, GLint w) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4i(index, x, y, z, w); }; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = [](GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4ui(index, x, y, z, w); }; -void (* const glVertexAttribI4iv)(GLuint, const GLint*) = [](GLuint index, const GLint* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4iv(index, v); }; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](GLuint index, const GLuint* v) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribI4uiv(index, v); }; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](GLuint program, GLint location, GLuint* params) { if (!opengl32) loadWGL(); ::wgl_glGetUniformuiv(program, location, params); }; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { if (!opengl32) loadWGL(); return ::wgl_glGetFragDataLocation(program, name); }; -void (* const glUniform1ui)(GLint, GLuint) = [](GLint location, GLuint v0) { if (!opengl32) loadWGL(); ::wgl_glUniform1ui(location, v0); }; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1) { if (!opengl32) loadWGL(); ::wgl_glUniform2ui(location, v0, v1); }; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1, GLuint v2) { if (!opengl32) loadWGL(); ::wgl_glUniform3ui(location, v0, v1, v2); }; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) { if (!opengl32) loadWGL(); ::wgl_glUniform4ui(location, v0, v1, v2, v3); }; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform1uiv(location, count, value); }; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform2uiv(location, count, value); }; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform3uiv(location, count, value); }; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glUniform4uiv(location, count, value); }; -void (* const glClearBufferiv)(GLenum, GLint, const GLint*) = [](GLenum buffer, GLint drawbuffer, const GLint* value) { if (!opengl32) loadWGL(); ::wgl_glClearBufferiv(buffer, drawbuffer, value); }; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint*) = [](GLenum buffer, GLint drawbuffer, const GLuint* value) { if (!opengl32) loadWGL(); ::wgl_glClearBufferuiv(buffer, drawbuffer, value); }; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat*) = [](GLenum buffer, GLint drawbuffer, const GLfloat* value) { if (!opengl32) loadWGL(); ::wgl_glClearBufferfv(buffer, drawbuffer, value); }; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = [](GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) { if (!opengl32) loadWGL(); ::wgl_glClearBufferfi(buffer, drawbuffer, depth, stencil); }; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = [](GLenum name, GLuint index) { if (!opengl32) loadWGL(); return ::wgl_glGetStringi(name, index); }; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = [](GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { if (!opengl32) loadWGL(); ::wgl_glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); }; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = [](GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) { if (!opengl32) loadWGL(); ::wgl_glGetUniformIndices(program, uniformCount, uniformNames, uniformIndices); }; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = [](GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params); }; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](GLuint program, const GLchar* uniformBlockName) { if (!opengl32) loadWGL(); return ::wgl_glGetUniformBlockIndex(program, uniformBlockName); }; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = [](GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniformBlockiv(program, uniformBlockIndex, pname, params); }; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = [](GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) { if (!opengl32) loadWGL(); ::wgl_glGetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName); }; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = [](GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) { if (!opengl32) loadWGL(); ::wgl_glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding); }; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = [](GLenum mode, GLint first, GLsizei count, GLsizei instancecount) { if (!opengl32) loadWGL(); ::wgl_glDrawArraysInstanced(mode, first, count, instancecount); }; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = [](GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount) { if (!opengl32) loadWGL(); ::wgl_glDrawElementsInstanced(mode, count, type, indices, instancecount); }; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = [](GLenum condition, GLbitfield flags) { if (!opengl32) loadWGL(); return ::wgl_glFenceSync(condition, flags); }; -GLboolean (* const glIsSync)(GLsync) = [](GLsync sync) { if (!opengl32) loadWGL(); return ::wgl_glIsSync(sync); }; -void (* const glDeleteSync)(GLsync) = [](GLsync sync) { if (!opengl32) loadWGL(); ::wgl_glDeleteSync(sync); }; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { if (!opengl32) loadWGL(); return ::wgl_glClientWaitSync(sync, flags, timeout); }; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { if (!opengl32) loadWGL(); ::wgl_glWaitSync(sync, flags, timeout); }; -void (* const glGetInteger64v)(GLenum, GLint64*) = [](GLenum pname, GLint64* params) { if (!opengl32) loadWGL(); ::wgl_glGetInteger64v(pname, params); }; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = [](GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) { if (!opengl32) loadWGL(); ::wgl_glGetSynciv(sync, pname, bufSize, length, values); }; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](GLenum target, GLuint index, GLint64* data) { if (!opengl32) loadWGL(); ::wgl_glGetInteger64i_v(target, index, data); }; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](GLenum target, GLenum pname, GLint64* params) { if (!opengl32) loadWGL(); ::wgl_glGetBufferParameteri64v(target, pname, params); }; -void (* const glGenSamplers)(GLsizei, GLuint*) = [](GLsizei count, GLuint* samplers) { if (!opengl32) loadWGL(); ::wgl_glGenSamplers(count, samplers); }; -void (* const glDeleteSamplers)(GLsizei, const GLuint*) = [](GLsizei count, const GLuint* samplers) { if (!opengl32) loadWGL(); ::wgl_glDeleteSamplers(count, samplers); }; -GLboolean (* const glIsSampler)(GLuint) = [](GLuint sampler) { if (!opengl32) loadWGL(); return ::wgl_glIsSampler(sampler); }; -void (* const glBindSampler)(GLuint, GLuint) = [](GLuint unit, GLuint sampler) { if (!opengl32) loadWGL(); ::wgl_glBindSampler(unit, sampler); }; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = [](GLuint sampler, GLenum pname, GLint param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameteri(sampler, pname, param); }; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = [](GLuint sampler, GLenum pname, const GLint* param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameteriv(sampler, pname, param); }; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](GLuint sampler, GLenum pname, GLfloat param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameterf(sampler, pname, param); }; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = [](GLuint sampler, GLenum pname, const GLfloat* param) { if (!opengl32) loadWGL(); ::wgl_glSamplerParameterfv(sampler, pname, param); }; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](GLuint sampler, GLenum pname, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetSamplerParameteriv(sampler, pname, params); }; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](GLuint sampler, GLenum pname, GLfloat* params) { if (!opengl32) loadWGL(); ::wgl_glGetSamplerParameterfv(sampler, pname, params); }; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = [](GLuint index, GLuint divisor) { if (!opengl32) loadWGL(); ::wgl_glVertexAttribDivisor(index, divisor); }; -void (* const glBindTransformFeedback)(GLenum, GLuint) = [](GLenum target, GLuint id) { if (!opengl32) loadWGL(); ::wgl_glBindTransformFeedback(target, id); }; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glDeleteTransformFeedbacks(n, ids); }; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { if (!opengl32) loadWGL(); ::wgl_glGenTransformFeedbacks(n, ids); }; -GLboolean (* const glIsTransformFeedback)(GLuint) = [](GLuint id) { if (!opengl32) loadWGL(); return ::wgl_glIsTransformFeedback(id); }; -void (* const glPauseTransformFeedback)() = []() { if (!opengl32) loadWGL(); ::wgl_glPauseTransformFeedback(); }; -void (* const glResumeTransformFeedback)() = []() { if (!opengl32) loadWGL(); ::wgl_glResumeTransformFeedback(); }; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = [](GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) { if (!opengl32) loadWGL(); ::wgl_glGetProgramBinary(program, bufSize, length, binaryFormat, binary); }; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = [](GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) { if (!opengl32) loadWGL(); ::wgl_glProgramBinary(program, binaryFormat, binary, length); }; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = [](GLuint program, GLenum pname, GLint value) { if (!opengl32) loadWGL(); ::wgl_glProgramParameteri(program, pname, value); }; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = [](GLenum target, GLsizei numAttachments, const GLenum* attachments) { if (!opengl32) loadWGL(); ::wgl_glInvalidateFramebuffer(target, numAttachments, attachments); }; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = [](GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glInvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height); }; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) { if (!opengl32) loadWGL(); ::wgl_glTexStorage2D(target, levels, internalformat, width, height); }; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) { if (!opengl32) loadWGL(); ::wgl_glTexStorage3D(target, levels, internalformat, width, height, depth); }; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = [](GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) { if (!opengl32) loadWGL(); ::wgl_glGetInternalformativ(target, internalformat, pname, bufSize, params); }; +void (*const glReadBuffer)(GLenum) = [](GLenum mode) { + if (!opengl32) loadWGL(); + ::wgl_glReadBuffer(mode); +}; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = + [](GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) { + if (!opengl32) loadWGL(); + ::wgl_glDrawRangeElements(mode, start, end, count, type, indices); + }; +void (*const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = + [](GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border, + GLenum format, + GLenum type, + const GLvoid* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels); + }; +void (*const glTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = + [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + const GLvoid* pixels) { + if (!opengl32) loadWGL(); + ::wgl_glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); + }; +void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = + [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLint x, + GLint y, + GLsizei width, + GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height); + }; +void (*const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = + [](GLenum target, + GLint level, + GLenum internalformat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border, + GLsizei imageSize, + const GLvoid* data) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data); + }; +void (*const glCompressedTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = + [](GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLsizei imageSize, + const GLvoid* data) { + if (!opengl32) loadWGL(); + ::wgl_glCompressedTexSubImage3D( + target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data); + }; +void (*const glGenQueries)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glGenQueries(n, ids); +}; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteQueries(n, ids); +}; +GLboolean (*const glIsQuery)(GLuint) = [](GLuint id) { + if (!opengl32) loadWGL(); + return ::wgl_glIsQuery(id); +}; +void (*const glBeginQuery)(GLenum, GLuint) = [](GLenum target, GLuint id) { + if (!opengl32) loadWGL(); + ::wgl_glBeginQuery(target, id); +}; +void (*const glEndQuery)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + ::wgl_glEndQuery(target); +}; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = [](GLenum target, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetQueryiv(target, pname, params); +}; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = [](GLuint id, GLenum pname, GLuint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetQueryObjectuiv(id, pname, params); +}; +GLboolean (*const glUnmapBuffer)(GLenum) = [](GLenum target) { + if (!opengl32) loadWGL(); + return ::wgl_glUnmapBuffer(target); +}; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = [](GLenum target, GLenum pname, GLvoid** params) { + if (!opengl32) loadWGL(); + ::wgl_glGetBufferPointerv(target, pname, params); +}; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = [](GLsizei n, const GLenum* bufs) { + if (!opengl32) loadWGL(); + ::wgl_glDrawBuffers(n, bufs); +}; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix2x3fv(location, count, transpose, value); + }; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix3x2fv(location, count, transpose, value); + }; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix2x4fv(location, count, transpose, value); + }; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix4x2fv(location, count, transpose, value); + }; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix3x4fv(location, count, transpose, value); + }; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = + [](GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniformMatrix4x3fv(location, count, transpose, value); + }; +void (*const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = + [](GLint srcX0, + GLint srcY0, + GLint srcX1, + GLint srcY1, + GLint dstX0, + GLint dstY0, + GLint dstX1, + GLint dstY1, + GLbitfield mask, + GLenum filter) { + if (!opengl32) loadWGL(); + ::wgl_glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); + }; +void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = + [](GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glRenderbufferStorageMultisample(target, samples, internalformat, width, height); + }; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = + [](GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) { + if (!opengl32) loadWGL(); + ::wgl_glFramebufferTextureLayer(target, attachment, texture, level, layer); + }; +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = + [](GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) { + if (!opengl32) loadWGL(); + return ::wgl_glMapBufferRange(target, offset, length, access); + }; +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = + [](GLenum target, GLintptr offset, GLsizeiptr length) { + if (!opengl32) loadWGL(); + ::wgl_glFlushMappedBufferRange(target, offset, length); + }; +void (*const glBindVertexArray)(GLuint) = [](GLuint array) { + if (!opengl32) loadWGL(); + ::wgl_glBindVertexArray(array); +}; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* arrays) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteVertexArrays(n, arrays); +}; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = [](GLsizei n, GLuint* arrays) { + if (!opengl32) loadWGL(); + ::wgl_glGenVertexArrays(n, arrays); +}; +GLboolean (*const glIsVertexArray)(GLuint) = [](GLuint array) { + if (!opengl32) loadWGL(); + return ::wgl_glIsVertexArray(array); +}; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = [](GLenum target, GLuint index, GLint* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetIntegeri_v(target, index, data); +}; +void (*const glBeginTransformFeedback)(GLenum) = [](GLenum primitiveMode) { + if (!opengl32) loadWGL(); + ::wgl_glBeginTransformFeedback(primitiveMode); +}; +void (*const glEndTransformFeedback)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glEndTransformFeedback(); +}; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = + [](GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) { + if (!opengl32) loadWGL(); + ::wgl_glBindBufferRange(target, index, buffer, offset, size); + }; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = [](GLenum target, GLuint index, GLuint buffer) { + if (!opengl32) loadWGL(); + ::wgl_glBindBufferBase(target, index, buffer); +}; +void (*const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar* const*, GLenum) = + [](GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) { + if (!opengl32) loadWGL(); + ::wgl_glTransformFeedbackVaryings(program, count, varyings, bufferMode); + }; +void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = + [](GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) { + if (!opengl32) loadWGL(); + ::wgl_glGetTransformFeedbackVarying(program, index, bufSize, length, size, type, name); + }; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = + [](GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribIPointer(index, size, type, stride, pointer); + }; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = [](GLuint index, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribIiv(index, pname, params); +}; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = [](GLuint index, GLenum pname, GLuint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetVertexAttribIuiv(index, pname, params); +}; +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = + [](GLuint index, GLint x, GLint y, GLint z, GLint w) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4i(index, x, y, z, w); + }; +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = + [](GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4ui(index, x, y, z, w); + }; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = [](GLuint index, const GLint* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4iv(index, v); +}; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = [](GLuint index, const GLuint* v) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribI4uiv(index, v); +}; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = [](GLuint program, GLint location, GLuint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformuiv(program, location, params); +}; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = [](GLuint program, const GLchar* name) { + if (!opengl32) loadWGL(); + return ::wgl_glGetFragDataLocation(program, name); +}; +void (*const glUniform1ui)(GLint, GLuint) = [](GLint location, GLuint v0) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1ui(location, v0); +}; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2ui(location, v0, v1); +}; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = [](GLint location, GLuint v0, GLuint v1, GLuint v2) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3ui(location, v0, v1, v2); +}; +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = + [](GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4ui(location, v0, v1, v2, v3); + }; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform1uiv(location, count, value); +}; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform2uiv(location, count, value); +}; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform3uiv(location, count, value); +}; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = [](GLint location, GLsizei count, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glUniform4uiv(location, count, value); +}; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = [](GLenum buffer, GLint drawbuffer, const GLint* value) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferiv(buffer, drawbuffer, value); +}; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = + [](GLenum buffer, GLint drawbuffer, const GLuint* value) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferuiv(buffer, drawbuffer, value); + }; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = + [](GLenum buffer, GLint drawbuffer, const GLfloat* value) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferfv(buffer, drawbuffer, value); + }; +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = + [](GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) { + if (!opengl32) loadWGL(); + ::wgl_glClearBufferfi(buffer, drawbuffer, depth, stencil); + }; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = [](GLenum name, GLuint index) { + if (!opengl32) loadWGL(); + return ::wgl_glGetStringi(name, index); +}; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = + [](GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) { + if (!opengl32) loadWGL(); + ::wgl_glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); + }; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = + [](GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) { + if (!opengl32) loadWGL(); + ::wgl_glGetUniformIndices(program, uniformCount, uniformNames, uniformIndices); + }; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = + [](GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params); + }; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = [](GLuint program, const GLchar* uniformBlockName) { + if (!opengl32) loadWGL(); + return ::wgl_glGetUniformBlockIndex(program, uniformBlockName); +}; +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = + [](GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniformBlockiv(program, uniformBlockIndex, pname, params); + }; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = + [](GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) { + if (!opengl32) loadWGL(); + ::wgl_glGetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName); + }; +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = + [](GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) { + if (!opengl32) loadWGL(); + ::wgl_glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding); + }; +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = + [](GLenum mode, GLint first, GLsizei count, GLsizei instancecount) { + if (!opengl32) loadWGL(); + ::wgl_glDrawArraysInstanced(mode, first, count, instancecount); + }; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = + [](GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instancecount) { + if (!opengl32) loadWGL(); + ::wgl_glDrawElementsInstanced(mode, count, type, indices, instancecount); + }; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = [](GLenum condition, GLbitfield flags) { + if (!opengl32) loadWGL(); + return ::wgl_glFenceSync(condition, flags); +}; +GLboolean (*const glIsSync)(GLsync) = [](GLsync sync) { + if (!opengl32) loadWGL(); + return ::wgl_glIsSync(sync); +}; +void (*const glDeleteSync)(GLsync) = [](GLsync sync) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteSync(sync); +}; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { + if (!opengl32) loadWGL(); + return ::wgl_glClientWaitSync(sync, flags, timeout); +}; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = [](GLsync sync, GLbitfield flags, GLuint64 timeout) { + if (!opengl32) loadWGL(); + ::wgl_glWaitSync(sync, flags, timeout); +}; +void (*const glGetInteger64v)(GLenum, GLint64*) = [](GLenum pname, GLint64* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetInteger64v(pname, params); +}; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = + [](GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) { + if (!opengl32) loadWGL(); + ::wgl_glGetSynciv(sync, pname, bufSize, length, values); + }; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = [](GLenum target, GLuint index, GLint64* data) { + if (!opengl32) loadWGL(); + ::wgl_glGetInteger64i_v(target, index, data); +}; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = [](GLenum target, GLenum pname, GLint64* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetBufferParameteri64v(target, pname, params); +}; +void (*const glGenSamplers)(GLsizei, GLuint*) = [](GLsizei count, GLuint* samplers) { + if (!opengl32) loadWGL(); + ::wgl_glGenSamplers(count, samplers); +}; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = [](GLsizei count, const GLuint* samplers) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteSamplers(count, samplers); +}; +GLboolean (*const glIsSampler)(GLuint) = [](GLuint sampler) { + if (!opengl32) loadWGL(); + return ::wgl_glIsSampler(sampler); +}; +void (*const glBindSampler)(GLuint, GLuint) = [](GLuint unit, GLuint sampler) { + if (!opengl32) loadWGL(); + ::wgl_glBindSampler(unit, sampler); +}; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = [](GLuint sampler, GLenum pname, GLint param) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameteri(sampler, pname, param); +}; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = + [](GLuint sampler, GLenum pname, const GLint* param) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameteriv(sampler, pname, param); + }; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = [](GLuint sampler, GLenum pname, GLfloat param) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameterf(sampler, pname, param); +}; +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = + [](GLuint sampler, GLenum pname, const GLfloat* param) { + if (!opengl32) loadWGL(); + ::wgl_glSamplerParameterfv(sampler, pname, param); + }; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = [](GLuint sampler, GLenum pname, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetSamplerParameteriv(sampler, pname, params); +}; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = [](GLuint sampler, GLenum pname, GLfloat* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetSamplerParameterfv(sampler, pname, params); +}; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = [](GLuint index, GLuint divisor) { + if (!opengl32) loadWGL(); + ::wgl_glVertexAttribDivisor(index, divisor); +}; +void (*const glBindTransformFeedback)(GLenum, GLuint) = [](GLenum target, GLuint id) { + if (!opengl32) loadWGL(); + ::wgl_glBindTransformFeedback(target, id); +}; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = [](GLsizei n, const GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glDeleteTransformFeedbacks(n, ids); +}; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = [](GLsizei n, GLuint* ids) { + if (!opengl32) loadWGL(); + ::wgl_glGenTransformFeedbacks(n, ids); +}; +GLboolean (*const glIsTransformFeedback)(GLuint) = [](GLuint id) { + if (!opengl32) loadWGL(); + return ::wgl_glIsTransformFeedback(id); +}; +void (*const glPauseTransformFeedback)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glPauseTransformFeedback(); +}; +void (*const glResumeTransformFeedback)() = []() { + if (!opengl32) loadWGL(); + ::wgl_glResumeTransformFeedback(); +}; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = + [](GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) { + if (!opengl32) loadWGL(); + ::wgl_glGetProgramBinary(program, bufSize, length, binaryFormat, binary); + }; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = + [](GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) { + if (!opengl32) loadWGL(); + ::wgl_glProgramBinary(program, binaryFormat, binary, length); + }; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = [](GLuint program, GLenum pname, GLint value) { + if (!opengl32) loadWGL(); + ::wgl_glProgramParameteri(program, pname, value); +}; +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = + [](GLenum target, GLsizei numAttachments, const GLenum* attachments) { + if (!opengl32) loadWGL(); + ::wgl_glInvalidateFramebuffer(target, numAttachments, attachments); + }; +void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = + [](GLenum target, + GLsizei numAttachments, + const GLenum* attachments, + GLint x, + GLint y, + GLsizei width, + GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glInvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height); + }; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = + [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) { + if (!opengl32) loadWGL(); + ::wgl_glTexStorage2D(target, levels, internalformat, width, height); + }; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = + [](GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) { + if (!opengl32) loadWGL(); + ::wgl_glTexStorage3D(target, levels, internalformat, width, height, depth); + }; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = + [](GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) { + if (!opengl32) loadWGL(); + ::wgl_glGetInternalformativ(target, internalformat, pname, bufSize, params); + }; /* OpenGL Windows Extensions */ -BOOL(* const wglChoosePixelFormatARB)(HDC, const int*, const FLOAT*, UINT, int*, UINT*) = [](HDC hdc, const int* piAttribIList, const FLOAT* pfAttribFList, UINT nMaxFormats, int* piFormats, UINT* nNumFormats) { if (!opengl32) loadWGL(); return ::wgl_wglChoosePixelFormatARB(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats); }; -HGLRC(* const wglCreateContextAttribsARB)(HDC, HGLRC, const int*) = [](HDC hDC, HGLRC hShareContext, const int* attribList) { if (!opengl32) loadWGL(); return ::wgl_wglCreateContextAttribsARB(hDC, hShareContext, attribList); }; -const char* (* const wglGetExtensionsStringARB)(HDC) = [](HDC hdc) { if (!opengl32) loadWGL(); return ::wgl_wglGetExtensionsStringARB(hdc); }; -const char* (* const wglGetExtensionsStringEXT)() = [](void) { if (!opengl32) loadWGL(); return ::wgl_wglGetExtensionsStringEXT(); }; +BOOL(*const wglChoosePixelFormatARB) +(HDC, const int*, const FLOAT*, UINT, int*, UINT*) = [](HDC hdc, + const int* piAttribIList, + const FLOAT* pfAttribFList, + UINT nMaxFormats, + int* piFormats, + UINT* nNumFormats) { + if (!opengl32) loadWGL(); + return ::wgl_wglChoosePixelFormatARB(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats); +}; +HGLRC(*const wglCreateContextAttribsARB) +(HDC, HGLRC, const int*) = [](HDC hDC, HGLRC hShareContext, const int* attribList) { + if (!opengl32) loadWGL(); + return ::wgl_wglCreateContextAttribsARB(hDC, hShareContext, attribList); +}; +const char* (*const wglGetExtensionsStringARB)(HDC) = [](HDC hdc) { + if (!opengl32) loadWGL(); + return ::wgl_wglGetExtensionsStringARB(hdc); +}; +const char* (*const wglGetExtensionsStringEXT)() = [](void) { + if (!opengl32) loadWGL(); + return ::wgl_wglGetExtensionsStringEXT(); +}; -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl #endif diff --git a/platform/windows/include/thread.h b/platform/windows/include/thread.h index b701c2e8802..ba325cdef17 100644 --- a/platform/windows/include/thread.h +++ b/platform/windows/include/thread.h @@ -21,22 +21,21 @@ extern "C" { // const DWORD MS_VC_EXCEPTION = 0x406D1388; -#pragma pack(push,8) -typedef struct tagTHREADNAME_INFO -{ - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). +#pragma pack(push, 8) +typedef struct tagTHREADNAME_INFO { + DWORD dwType; // Must be 0x1000. + LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. + DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) void SetThreadName(DWORD dwThreadID, const char* threadName); typedef struct structTHREAD_INFO { - DWORD id; - DWORD key; - char* name; + DWORD id; + DWORD key; + char* name; } THREAD_INFO; #ifdef __cplusplus @@ -47,13 +46,9 @@ extern DWORD selfThreadKey; class DummyClassThread { public: - DummyClassThread() { - selfThreadKey = TlsAlloc(); - } + DummyClassThread() { selfThreadKey = TlsAlloc(); } - ~DummyClassThread() { - TlsFree(selfThreadKey); - } + ~DummyClassThread() { TlsFree(selfThreadKey); } }; extern DummyClassThread dummyClassThread; @@ -66,7 +61,7 @@ std::string getCurrentThreadName(); void setCurrentThreadName(const std::string& name); void makeThreadLowPriority(); void setCurrentThreadPriority(double priority); -} -} +} // namespace platform +} // namespace mbgl #endif diff --git a/platform/windows/src/gl_functions.cpp b/platform/windows/src/gl_functions.cpp index 6453416e252..20ee276cf2d 100644 --- a/platform/windows/src/gl_functions.cpp +++ b/platform/windows/src/gl_functions.cpp @@ -14,255 +14,274 @@ namespace platform { /* OpenGL ES 2.0 */ -void (* const glActiveTexture)(GLenum) = ::glActiveTexture; -void (* const glAttachShader)(GLuint, GLuint) = ::glAttachShader; -void (* const glBindAttribLocation)(GLuint, GLuint, const GLchar *) = ::glBindAttribLocation; -void (* const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; -void (* const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; -void (* const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; -void (* const glBindTexture)(GLenum, GLuint) = ::glBindTexture; -void (* const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; -void (* const glBlendEquation)(GLenum) = ::glBlendEquation; -void (* const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; -void (* const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; -void (* const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; -void (* const glBufferData)(GLenum, GLsizeiptr, const void *, GLenum) = ::glBufferData; -void (* const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void *) = ::glBufferSubData; -GLenum (* const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; -void (* const glClear)(GLbitfield) = ::glClear; -void (* const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; -void (* const glClearDepthf)(GLfloat) = ::glClearDepthf; -void (* const glClearStencil)(GLint) = ::glClearStencil; -void (* const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; -void (* const glCompileShader)(GLuint) = ::glCompileShader; -void (* const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void *) = ::glCompressedTexImage2D; -void (* const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void *) = ::glCompressedTexSubImage2D; -void (* const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; -void (* const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; -GLuint (* const glCreateProgram)() = ::glCreateProgram; -GLuint (* const glCreateShader)(GLenum) = ::glCreateShader; -void (* const glCullFace)(GLenum) = ::glCullFace; -void (* const glDeleteBuffers)(GLsizei, const GLuint *) = ::glDeleteBuffers; -void (* const glDeleteFramebuffers)(GLsizei, const GLuint *) = ::glDeleteFramebuffers; -void (* const glDeleteProgram)(GLuint) = ::glDeleteProgram; -void (* const glDeleteRenderbuffers)(GLsizei, const GLuint *) = ::glDeleteRenderbuffers; -void (* const glDeleteShader)(GLuint) = ::glDeleteShader; -void (* const glDeleteTextures)(GLsizei, const GLuint *) = ::glDeleteTextures; -void (* const glDepthFunc)(GLenum) = ::glDepthFunc; -void (* const glDepthMask)(GLboolean) = ::glDepthMask; -void (* const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; -void (* const glDetachShader)(GLuint, GLuint) = ::glDetachShader; -void (* const glDisable)(GLenum) = ::glDisable; -void (* const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; -void (* const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; -void (* const glDrawElements)(GLenum, GLsizei, GLenum, const void *) = ::glDrawElements; -void (* const glEnable)(GLenum) = ::glEnable; -void (* const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; -void (* const glFinish)() = ::glFinish; -void (* const glFlush)() = ::glFlush; -void (* const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; -void (* const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; -void (* const glFrontFace)(GLenum) = ::glFrontFace; -void (* const glGenBuffers)(GLsizei, GLuint *) = ::glGenBuffers; -void (* const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; -void (* const glGenFramebuffers)(GLsizei, GLuint *) = ::glGenFramebuffers; -void (* const glGenRenderbuffers)(GLsizei, GLuint *) = ::glGenRenderbuffers; -void (* const glGenTextures)(GLsizei, GLuint *) = ::glGenTextures; -void (* const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveAttrib; -void (* const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *) = ::glGetActiveUniform; -void (* const glGetAttachedShaders)(GLuint, GLsizei, GLsizei *, GLuint *) = ::glGetAttachedShaders; -GLint (* const glGetAttribLocation)(GLuint, const GLchar *) = ::glGetAttribLocation; -void (* const glGetBooleanv)(GLenum, GLboolean *) = ::glGetBooleanv; -void (* const glGetBufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetBufferParameteriv; -GLenum (* const glGetError)() = ::glGetError; -void (* const glGetFloatv)(GLenum, GLfloat *) = ::glGetFloatv; -void (* const glGetFramebufferAttachmentParameteriv)(GLenum, GLenum, GLenum, GLint *) = ::glGetFramebufferAttachmentParameteriv; -void (* const glGetIntegerv)(GLenum, GLint *) = ::glGetIntegerv; -void (* const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetProgramInfoLog; -void (* const glGetProgramiv)(GLuint, GLenum, GLint *) = ::glGetProgramiv; -void (* const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint *) = ::glGetRenderbufferParameteriv; -void (* const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderInfoLog; -void (* const glGetShaderiv)(GLuint, GLenum, GLint *) = ::glGetShaderiv; -void (* const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint *, GLint *) = ::glGetShaderPrecisionFormat; -void (* const glGetShaderSource)(GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetShaderSource; -const GLubyte *(* const glGetString)(GLenum) = ::glGetString; -void (* const glGetTexParameterfv)(GLenum, GLenum, GLfloat *) = ::glGetTexParameterfv; -void (* const glGetTexParameteriv)(GLenum, GLenum, GLint *) = ::glGetTexParameteriv; -void (* const glGetUniformfv)(GLuint, GLint, GLfloat *) = ::glGetUniformfv; -void (* const glGetUniformiv)(GLuint, GLint, GLint *) = ::glGetUniformiv; -GLint (* const glGetUniformLocation)(GLuint, const GLchar *) = ::glGetUniformLocation; -void (* const glGetVertexAttribfv)(GLuint, GLenum, GLfloat *) = ::glGetVertexAttribfv; -void (* const glGetVertexAttribiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribiv; -void (* const glGetVertexAttribPointerv)(GLuint, GLenum, void **) = ::glGetVertexAttribPointerv; -void (* const glHint)(GLenum, GLenum) = ::glHint; -GLboolean (* const glIsBuffer)(GLuint) = ::glIsBuffer; -GLboolean (* const glIsEnabled)(GLenum) = ::glIsEnabled; -GLboolean (* const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; -GLboolean (* const glIsProgram)(GLuint) = ::glIsProgram; -GLboolean (* const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; -GLboolean (* const glIsShader)(GLuint) = ::glIsShader; -GLboolean (* const glIsTexture)(GLuint) = ::glIsTexture; -void (* const glLineWidth)(GLfloat) = ::glLineWidth; -void (* const glLinkProgram)(GLuint) = ::glLinkProgram; -void (* const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; -void (* const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; -void (* const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *) = ::glReadPixels; -void (* const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; -void (* const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; -void (* const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; -void (* const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; -void (* const glShaderBinary)(GLsizei, const GLuint *, GLenum, const GLvoid *, GLsizei) = ::glShaderBinary; -void (* const glShaderSource)(GLuint, GLsizei, const GLchar * const*, const GLint *) = ::glShaderSource; -void (* const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; -void (* const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; -void (* const glStencilMask)(GLuint) = ::glStencilMask; -void (* const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; -void (* const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; -void (* const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; -void (* const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *) = ::glTexImage2D; -void (* const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; -void (* const glTexParameterfv)(GLenum, GLenum, const GLfloat *) = ::glTexParameterfv; -void (* const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; -void (* const glTexParameteriv)(GLenum, GLenum, const GLint *) = ::glTexParameteriv; -void (* const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *) = ::glTexSubImage2D; -void (* const glUniform1f)(GLint, GLfloat) = ::glUniform1f; -void (* const glUniform1fv)(GLint, GLsizei, const GLfloat *) = ::glUniform1fv; -void (* const glUniform1i)(GLint, GLint) = ::glUniform1i; -void (* const glUniform1iv)(GLint, GLsizei, const GLint *) = ::glUniform1iv; -void (* const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; -void (* const glUniform2fv)(GLint, GLsizei, const GLfloat *) = ::glUniform2fv; -void (* const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; -void (* const glUniform2iv)(GLint, GLsizei, const GLint *) = ::glUniform2iv; -void (* const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; -void (* const glUniform3fv)(GLint, GLsizei, const GLfloat *) = ::glUniform3fv; -void (* const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; -void (* const glUniform3iv)(GLint, GLsizei, const GLint *) = ::glUniform3iv; -void (* const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; -void (* const glUniform4fv)(GLint, GLsizei, const GLfloat *) = ::glUniform4fv; -void (* const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; -void (* const glUniform4iv)(GLint, GLsizei, const GLint *) = ::glUniform4iv; -void (* const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2fv; -void (* const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3fv; -void (* const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4fv; -void (* const glUseProgram)(GLuint) = ::glUseProgram; -void (* const glValidateProgram)(GLuint) = ::glValidateProgram; -void (* const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; -void (* const glVertexAttrib1fv)(GLuint, const GLfloat *) = ::glVertexAttrib1fv; -void (* const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; -void (* const glVertexAttrib2fv)(GLuint, const GLfloat *) = ::glVertexAttrib2fv; -void (* const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; -void (* const glVertexAttrib3fv)(GLuint, const GLfloat *) = ::glVertexAttrib3fv; -void (* const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; -void (* const glVertexAttrib4fv)(GLuint, const GLfloat *) = ::glVertexAttrib4fv; -void (* const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void *) = ::glVertexAttribPointer; -void (* const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; +void (*const glActiveTexture)(GLenum) = ::glActiveTexture; +void (*const glAttachShader)(GLuint, GLuint) = ::glAttachShader; +void (*const glBindAttribLocation)(GLuint, GLuint, const GLchar*) = ::glBindAttribLocation; +void (*const glBindBuffer)(GLenum, GLuint) = ::glBindBuffer; +void (*const glBindFramebuffer)(GLenum, GLuint) = ::glBindFramebuffer; +void (*const glBindRenderbuffer)(GLenum, GLuint) = ::glBindRenderbuffer; +void (*const glBindTexture)(GLenum, GLuint) = ::glBindTexture; +void (*const glBlendColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glBlendColor; +void (*const glBlendEquation)(GLenum) = ::glBlendEquation; +void (*const glBlendEquationSeparate)(GLenum, GLenum) = ::glBlendEquationSeparate; +void (*const glBlendFunc)(GLenum, GLenum) = ::glBlendFunc; +void (*const glBlendFuncSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glBlendFuncSeparate; +void (*const glBufferData)(GLenum, GLsizeiptr, const void*, GLenum) = ::glBufferData; +void (*const glBufferSubData)(GLenum, GLintptr, GLsizeiptr, const void*) = ::glBufferSubData; +GLenum (*const glCheckFramebufferStatus)(GLenum) = ::glCheckFramebufferStatus; +void (*const glClear)(GLbitfield) = ::glClear; +void (*const glClearColor)(GLfloat, GLfloat, GLfloat, GLfloat) = ::glClearColor; +void (*const glClearDepthf)(GLfloat) = ::glClearDepthf; +void (*const glClearStencil)(GLint) = ::glClearStencil; +void (*const glColorMask)(GLboolean, GLboolean, GLboolean, GLboolean) = ::glColorMask; +void (*const glCompileShader)(GLuint) = ::glCompileShader; +void (*const glCompressedTexImage2D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const void*) = + ::glCompressedTexImage2D; +void (*const glCompressedTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const void*) = + ::glCompressedTexSubImage2D; +void (*const glCopyTexImage2D)(GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint) = ::glCopyTexImage2D; +void (*const glCopyTexSubImage2D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage2D; +GLuint (*const glCreateProgram)() = ::glCreateProgram; +GLuint (*const glCreateShader)(GLenum) = ::glCreateShader; +void (*const glCullFace)(GLenum) = ::glCullFace; +void (*const glDeleteBuffers)(GLsizei, const GLuint*) = ::glDeleteBuffers; +void (*const glDeleteFramebuffers)(GLsizei, const GLuint*) = ::glDeleteFramebuffers; +void (*const glDeleteProgram)(GLuint) = ::glDeleteProgram; +void (*const glDeleteRenderbuffers)(GLsizei, const GLuint*) = ::glDeleteRenderbuffers; +void (*const glDeleteShader)(GLuint) = ::glDeleteShader; +void (*const glDeleteTextures)(GLsizei, const GLuint*) = ::glDeleteTextures; +void (*const glDepthFunc)(GLenum) = ::glDepthFunc; +void (*const glDepthMask)(GLboolean) = ::glDepthMask; +void (*const glDepthRangef)(GLfloat, GLfloat) = ::glDepthRangef; +void (*const glDetachShader)(GLuint, GLuint) = ::glDetachShader; +void (*const glDisable)(GLenum) = ::glDisable; +void (*const glDisableVertexAttribArray)(GLuint) = ::glDisableVertexAttribArray; +void (*const glDrawArrays)(GLenum, GLint, GLsizei) = ::glDrawArrays; +void (*const glDrawElements)(GLenum, GLsizei, GLenum, const void*) = ::glDrawElements; +void (*const glEnable)(GLenum) = ::glEnable; +void (*const glEnableVertexAttribArray)(GLuint) = ::glEnableVertexAttribArray; +void (*const glFinish)() = ::glFinish; +void (*const glFlush)() = ::glFlush; +void (*const glFramebufferRenderbuffer)(GLenum, GLenum, GLenum, GLuint) = ::glFramebufferRenderbuffer; +void (*const glFramebufferTexture2D)(GLenum, GLenum, GLenum, GLuint, GLint) = ::glFramebufferTexture2D; +void (*const glFrontFace)(GLenum) = ::glFrontFace; +void (*const glGenBuffers)(GLsizei, GLuint*) = ::glGenBuffers; +void (*const glGenerateMipmap)(GLenum) = ::glGenerateMipmap; +void (*const glGenFramebuffers)(GLsizei, GLuint*) = ::glGenFramebuffers; +void (*const glGenRenderbuffers)(GLsizei, GLuint*) = ::glGenRenderbuffers; +void (*const glGenTextures)(GLsizei, GLuint*) = ::glGenTextures; +void (*const glGetActiveAttrib)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveAttrib; +void (*const glGetActiveUniform)(GLuint, GLuint, GLsizei, GLsizei*, GLint*, GLenum*, GLchar*) = ::glGetActiveUniform; +void (*const glGetAttachedShaders)(GLuint, GLsizei, GLsizei*, GLuint*) = ::glGetAttachedShaders; +GLint (*const glGetAttribLocation)(GLuint, const GLchar*) = ::glGetAttribLocation; +void (*const glGetBooleanv)(GLenum, GLboolean*) = ::glGetBooleanv; +void (*const glGetBufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetBufferParameteriv; +GLenum (*const glGetError)() = ::glGetError; +void (*const glGetFloatv)(GLenum, GLfloat*) = ::glGetFloatv; +void (*const glGetFramebufferAttachmentParameteriv)(GLenum, + GLenum, + GLenum, + GLint*) = ::glGetFramebufferAttachmentParameteriv; +void (*const glGetIntegerv)(GLenum, GLint*) = ::glGetIntegerv; +void (*const glGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetProgramInfoLog; +void (*const glGetProgramiv)(GLuint, GLenum, GLint*) = ::glGetProgramiv; +void (*const glGetRenderbufferParameteriv)(GLenum, GLenum, GLint*) = ::glGetRenderbufferParameteriv; +void (*const glGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderInfoLog; +void (*const glGetShaderiv)(GLuint, GLenum, GLint*) = ::glGetShaderiv; +void (*const glGetShaderPrecisionFormat)(GLenum, GLenum, GLint*, GLint*) = ::glGetShaderPrecisionFormat; +void (*const glGetShaderSource)(GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetShaderSource; +const GLubyte* (*const glGetString)(GLenum) = ::glGetString; +void (*const glGetTexParameterfv)(GLenum, GLenum, GLfloat*) = ::glGetTexParameterfv; +void (*const glGetTexParameteriv)(GLenum, GLenum, GLint*) = ::glGetTexParameteriv; +void (*const glGetUniformfv)(GLuint, GLint, GLfloat*) = ::glGetUniformfv; +void (*const glGetUniformiv)(GLuint, GLint, GLint*) = ::glGetUniformiv; +GLint (*const glGetUniformLocation)(GLuint, const GLchar*) = ::glGetUniformLocation; +void (*const glGetVertexAttribfv)(GLuint, GLenum, GLfloat*) = ::glGetVertexAttribfv; +void (*const glGetVertexAttribiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribiv; +void (*const glGetVertexAttribPointerv)(GLuint, GLenum, void**) = ::glGetVertexAttribPointerv; +void (*const glHint)(GLenum, GLenum) = ::glHint; +GLboolean (*const glIsBuffer)(GLuint) = ::glIsBuffer; +GLboolean (*const glIsEnabled)(GLenum) = ::glIsEnabled; +GLboolean (*const glIsFramebuffer)(GLuint) = ::glIsFramebuffer; +GLboolean (*const glIsProgram)(GLuint) = ::glIsProgram; +GLboolean (*const glIsRenderbuffer)(GLuint) = ::glIsRenderbuffer; +GLboolean (*const glIsShader)(GLuint) = ::glIsShader; +GLboolean (*const glIsTexture)(GLuint) = ::glIsTexture; +void (*const glLineWidth)(GLfloat) = ::glLineWidth; +void (*const glLinkProgram)(GLuint) = ::glLinkProgram; +void (*const glPixelStorei)(GLenum, GLint) = ::glPixelStorei; +void (*const glPolygonOffset)(GLfloat, GLfloat) = ::glPolygonOffset; +void (*const glReadPixels)(GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*) = ::glReadPixels; +void (*const glReleaseShaderCompiler)() = ::glReleaseShaderCompiler; +void (*const glRenderbufferStorage)(GLenum, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorage; +void (*const glSampleCoverage)(GLfloat, GLboolean) = ::glSampleCoverage; +void (*const glScissor)(GLint, GLint, GLsizei, GLsizei) = ::glScissor; +void (*const glShaderBinary)(GLsizei, const GLuint*, GLenum, const GLvoid*, GLsizei) = ::glShaderBinary; +void (*const glShaderSource)(GLuint, GLsizei, const GLchar* const*, const GLint*) = ::glShaderSource; +void (*const glStencilFunc)(GLenum, GLint, GLuint) = ::glStencilFunc; +void (*const glStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint) = ::glStencilFuncSeparate; +void (*const glStencilMask)(GLuint) = ::glStencilMask; +void (*const glStencilMaskSeparate)(GLenum, GLuint) = ::glStencilMaskSeparate; +void (*const glStencilOp)(GLenum, GLenum, GLenum) = ::glStencilOp; +void (*const glStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum) = ::glStencilOpSeparate; +void (*const glTexImage2D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*) = ::glTexImage2D; +void (*const glTexParameterf)(GLenum, GLenum, GLfloat) = ::glTexParameterf; +void (*const glTexParameterfv)(GLenum, GLenum, const GLfloat*) = ::glTexParameterfv; +void (*const glTexParameteri)(GLenum, GLenum, GLint) = ::glTexParameteri; +void (*const glTexParameteriv)(GLenum, GLenum, const GLint*) = ::glTexParameteriv; +void (*const glTexSubImage2D)(GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) = + ::glTexSubImage2D; +void (*const glUniform1f)(GLint, GLfloat) = ::glUniform1f; +void (*const glUniform1fv)(GLint, GLsizei, const GLfloat*) = ::glUniform1fv; +void (*const glUniform1i)(GLint, GLint) = ::glUniform1i; +void (*const glUniform1iv)(GLint, GLsizei, const GLint*) = ::glUniform1iv; +void (*const glUniform2f)(GLint, GLfloat, GLfloat) = ::glUniform2f; +void (*const glUniform2fv)(GLint, GLsizei, const GLfloat*) = ::glUniform2fv; +void (*const glUniform2i)(GLint, GLint, GLint) = ::glUniform2i; +void (*const glUniform2iv)(GLint, GLsizei, const GLint*) = ::glUniform2iv; +void (*const glUniform3f)(GLint, GLfloat, GLfloat, GLfloat) = ::glUniform3f; +void (*const glUniform3fv)(GLint, GLsizei, const GLfloat*) = ::glUniform3fv; +void (*const glUniform3i)(GLint, GLint, GLint, GLint) = ::glUniform3i; +void (*const glUniform3iv)(GLint, GLsizei, const GLint*) = ::glUniform3iv; +void (*const glUniform4f)(GLint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glUniform4f; +void (*const glUniform4fv)(GLint, GLsizei, const GLfloat*) = ::glUniform4fv; +void (*const glUniform4i)(GLint, GLint, GLint, GLint, GLint) = ::glUniform4i; +void (*const glUniform4iv)(GLint, GLsizei, const GLint*) = ::glUniform4iv; +void (*const glUniformMatrix2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2fv; +void (*const glUniformMatrix3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3fv; +void (*const glUniformMatrix4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4fv; +void (*const glUseProgram)(GLuint) = ::glUseProgram; +void (*const glValidateProgram)(GLuint) = ::glValidateProgram; +void (*const glVertexAttrib1f)(GLuint, GLfloat) = ::glVertexAttrib1f; +void (*const glVertexAttrib1fv)(GLuint, const GLfloat*) = ::glVertexAttrib1fv; +void (*const glVertexAttrib2f)(GLuint, GLfloat, GLfloat) = ::glVertexAttrib2f; +void (*const glVertexAttrib2fv)(GLuint, const GLfloat*) = ::glVertexAttrib2fv; +void (*const glVertexAttrib3f)(GLuint, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib3f; +void (*const glVertexAttrib3fv)(GLuint, const GLfloat*) = ::glVertexAttrib3fv; +void (*const glVertexAttrib4f)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat) = ::glVertexAttrib4f; +void (*const glVertexAttrib4fv)(GLuint, const GLfloat*) = ::glVertexAttrib4fv; +void (*const glVertexAttribPointer)(GLuint, GLint, GLenum, GLboolean, GLsizei, const void*) = ::glVertexAttribPointer; +void (*const glViewport)(GLint, GLint, GLsizei, GLsizei) = ::glViewport; /* OpenGL ES 3.0 */ -void (* const glReadBuffer)(GLenum) = ::glReadBuffer; -void (* const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *) = ::glDrawRangeElements; -void (* const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *) = ::glTexImage3D; -void (* const glTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *) = ::glTexSubImage3D; -void (* const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = ::glCopyTexSubImage3D; -void (* const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *) = ::glCompressedTexImage3D; -void (* const glCompressedTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *) = ::glCompressedTexSubImage3D; -void (* const glGenQueries)(GLsizei, GLuint *) = ::glGenQueries; -void (* const glDeleteQueries)(GLsizei, const GLuint *) = ::glDeleteQueries; -GLboolean (* const glIsQuery)(GLuint) = ::glIsQuery; -void (* const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; -void (* const glEndQuery)(GLenum) = ::glEndQuery; -void (* const glGetQueryiv)(GLenum, GLenum, GLint *) = ::glGetQueryiv; -void (* const glGetQueryObjectuiv)(GLuint, GLenum, GLuint *) = ::glGetQueryObjectuiv; -GLboolean (* const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; -void (* const glGetBufferPointerv)(GLenum, GLenum, GLvoid **) = ::glGetBufferPointerv; -void (* const glDrawBuffers)(GLsizei, const GLenum *) = ::glDrawBuffers; -void (* const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x3fv; -void (* const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x2fv; -void (* const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix2x4fv; -void (* const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x2fv; -void (* const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix3x4fv; -void (* const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat *) = ::glUniformMatrix4x3fv; -void (* const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = ::glBlitFramebuffer; -void (* const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glRenderbufferStorageMultisample; -void (* const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; -GLvoid* (* const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; -void (* const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; -void (* const glBindVertexArray)(GLuint) = ::glBindVertexArray; -void (* const glDeleteVertexArrays)(GLsizei, const GLuint *) = ::glDeleteVertexArrays; -void (* const glGenVertexArrays)(GLsizei, GLuint *) = ::glGenVertexArrays; -GLboolean (* const glIsVertexArray)(GLuint) = ::glIsVertexArray; -void (* const glGetIntegeri_v)(GLenum, GLuint, GLint *) = ::glGetIntegeri_v; -void (* const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; -void (* const glEndTransformFeedback)() = ::glEndTransformFeedback; -void (* const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; -void (* const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; -void (* const glTransformFeedbackVaryings)(GLuint, GLsizei, const GLchar * const*, GLenum) = ::glTransformFeedbackVaryings; -void (* const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei *, GLsizei *, GLenum *, GLchar *) = ::glGetTransformFeedbackVarying; -void (* const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid *) = ::glVertexAttribIPointer; -void (* const glGetVertexAttribIiv)(GLuint, GLenum, GLint *) = ::glGetVertexAttribIiv; -void (* const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint *) = ::glGetVertexAttribIuiv; -void (* const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; -void (* const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; -void (* const glVertexAttribI4iv)(GLuint, const GLint *) = ::glVertexAttribI4iv; -void (* const glVertexAttribI4uiv)(GLuint, const GLuint *) = ::glVertexAttribI4uiv; -void (* const glGetUniformuiv)(GLuint, GLint, GLuint *) = ::glGetUniformuiv; -GLint (* const glGetFragDataLocation)(GLuint, const GLchar *) = ::glGetFragDataLocation; -void (* const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; -void (* const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; -void (* const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; -void (* const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; -void (* const glUniform1uiv)(GLint, GLsizei, const GLuint *) = ::glUniform1uiv; -void (* const glUniform2uiv)(GLint, GLsizei, const GLuint *) = ::glUniform2uiv; -void (* const glUniform3uiv)(GLint, GLsizei, const GLuint *) = ::glUniform3uiv; -void (* const glUniform4uiv)(GLint, GLsizei, const GLuint *) = ::glUniform4uiv; -void (* const glClearBufferiv)(GLenum, GLint, const GLint *) = ::glClearBufferiv; -void (* const glClearBufferuiv)(GLenum, GLint, const GLuint *) = ::glClearBufferuiv; -void (* const glClearBufferfv)(GLenum, GLint, const GLfloat *) = ::glClearBufferfv; -void (* const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; -const GLubyte* (* const glGetStringi)(GLenum, GLuint) = ::glGetStringi; -void (* const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; -void (* const glGetUniformIndices)(GLuint, GLsizei, const GLchar * const*, GLuint *) = ::glGetUniformIndices; -void (* const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint *, GLenum, GLint *) = ::glGetActiveUniformsiv; -GLuint (* const glGetUniformBlockIndex)(GLuint, const GLchar *) = ::glGetUniformBlockIndex; -void (* const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint *) = ::glGetActiveUniformBlockiv; -void (* const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei *, GLchar *) = ::glGetActiveUniformBlockName; -void (* const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; -void (* const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; -void (* const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid *, GLsizei) = ::glDrawElementsInstanced; -GLsync (* const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; -GLboolean (* const glIsSync)(GLsync) = ::glIsSync; -void (* const glDeleteSync)(GLsync) = ::glDeleteSync; -GLenum (* const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; -void (* const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; -void (* const glGetInteger64v)(GLenum, GLint64 *) = ::glGetInteger64v; -void (* const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei *, GLint *) = ::glGetSynciv; -void (* const glGetInteger64i_v)(GLenum, GLuint, GLint64 *) = ::glGetInteger64i_v; -void (* const glGetBufferParameteri64v)(GLenum, GLenum, GLint64 *) = ::glGetBufferParameteri64v; -void (* const glGenSamplers)(GLsizei, GLuint *) = ::glGenSamplers; -void (* const glDeleteSamplers)(GLsizei, const GLuint *) = ::glDeleteSamplers; -GLboolean (* const glIsSampler)(GLuint) = ::glIsSampler; -void (* const glBindSampler)(GLuint, GLuint) = ::glBindSampler; -void (* const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; -void (* const glSamplerParameteriv)(GLuint, GLenum, const GLint *) = ::glSamplerParameteriv; -void (* const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; -void (* const glSamplerParameterfv)(GLuint, GLenum, const GLfloat *) = ::glSamplerParameterfv; -void (* const glGetSamplerParameteriv)(GLuint, GLenum, GLint *) = ::glGetSamplerParameteriv; -void (* const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat *) = ::glGetSamplerParameterfv; -void (* const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; -void (* const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; -void (* const glDeleteTransformFeedbacks)(GLsizei, const GLuint *) = ::glDeleteTransformFeedbacks; -void (* const glGenTransformFeedbacks)(GLsizei, GLuint *) = ::glGenTransformFeedbacks; -GLboolean (* const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; -void (* const glPauseTransformFeedback)() = ::glPauseTransformFeedback; -void (* const glResumeTransformFeedback)() = ::glResumeTransformFeedback; -void (* const glGetProgramBinary)(GLuint, GLsizei, GLsizei *, GLenum *, GLvoid *) = ::glGetProgramBinary; -void (* const glProgramBinary)(GLuint, GLenum, const GLvoid *, GLsizei) = ::glProgramBinary; -void (* const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; -void (* const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum *) = ::glInvalidateFramebuffer; -void (* const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum *, GLint, GLint, GLsizei, GLsizei) = ::glInvalidateSubFramebuffer; -void (* const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; -void (* const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; -void (* const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint *) = ::glGetInternalformativ; +void (*const glReadBuffer)(GLenum) = ::glReadBuffer; +void (*const glDrawRangeElements)(GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid*) = ::glDrawRangeElements; +void (*const glTexImage3D)(GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid*) = + ::glTexImage3D; +void (*const glTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid*) = ::glTexSubImage3D; +void (*const glCopyTexSubImage3D)(GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei) = + ::glCopyTexSubImage3D; +void (*const glCompressedTexImage3D)(GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid*) = + ::glCompressedTexImage3D; +void (*const glCompressedTexSubImage3D)( + GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid*) = + ::glCompressedTexSubImage3D; +void (*const glGenQueries)(GLsizei, GLuint*) = ::glGenQueries; +void (*const glDeleteQueries)(GLsizei, const GLuint*) = ::glDeleteQueries; +GLboolean (*const glIsQuery)(GLuint) = ::glIsQuery; +void (*const glBeginQuery)(GLenum, GLuint) = ::glBeginQuery; +void (*const glEndQuery)(GLenum) = ::glEndQuery; +void (*const glGetQueryiv)(GLenum, GLenum, GLint*) = ::glGetQueryiv; +void (*const glGetQueryObjectuiv)(GLuint, GLenum, GLuint*) = ::glGetQueryObjectuiv; +GLboolean (*const glUnmapBuffer)(GLenum) = ::glUnmapBuffer; +void (*const glGetBufferPointerv)(GLenum, GLenum, GLvoid**) = ::glGetBufferPointerv; +void (*const glDrawBuffers)(GLsizei, const GLenum*) = ::glDrawBuffers; +void (*const glUniformMatrix2x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x3fv; +void (*const glUniformMatrix3x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x2fv; +void (*const glUniformMatrix2x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix2x4fv; +void (*const glUniformMatrix4x2fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x2fv; +void (*const glUniformMatrix3x4fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix3x4fv; +void (*const glUniformMatrix4x3fv)(GLint, GLsizei, GLboolean, const GLfloat*) = ::glUniformMatrix4x3fv; +void (*const glBlitFramebuffer)(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) = + ::glBlitFramebuffer; +void (*const glRenderbufferStorageMultisample)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = + ::glRenderbufferStorageMultisample; +void (*const glFramebufferTextureLayer)(GLenum, GLenum, GLuint, GLint, GLint) = ::glFramebufferTextureLayer; +GLvoid* (*const glMapBufferRange)(GLenum, GLintptr, GLsizeiptr, GLbitfield) = ::glMapBufferRange; +void (*const glFlushMappedBufferRange)(GLenum, GLintptr, GLsizeiptr) = ::glFlushMappedBufferRange; +void (*const glBindVertexArray)(GLuint) = ::glBindVertexArray; +void (*const glDeleteVertexArrays)(GLsizei, const GLuint*) = ::glDeleteVertexArrays; +void (*const glGenVertexArrays)(GLsizei, GLuint*) = ::glGenVertexArrays; +GLboolean (*const glIsVertexArray)(GLuint) = ::glIsVertexArray; +void (*const glGetIntegeri_v)(GLenum, GLuint, GLint*) = ::glGetIntegeri_v; +void (*const glBeginTransformFeedback)(GLenum) = ::glBeginTransformFeedback; +void (*const glEndTransformFeedback)() = ::glEndTransformFeedback; +void (*const glBindBufferRange)(GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) = ::glBindBufferRange; +void (*const glBindBufferBase)(GLenum, GLuint, GLuint) = ::glBindBufferBase; +void (*const glTransformFeedbackVaryings)(GLuint, + GLsizei, + const GLchar* const*, + GLenum) = ::glTransformFeedbackVaryings; +void (*const glGetTransformFeedbackVarying)(GLuint, GLuint, GLsizei, GLsizei*, GLsizei*, GLenum*, GLchar*) = + ::glGetTransformFeedbackVarying; +void (*const glVertexAttribIPointer)(GLuint, GLint, GLenum, GLsizei, const GLvoid*) = ::glVertexAttribIPointer; +void (*const glGetVertexAttribIiv)(GLuint, GLenum, GLint*) = ::glGetVertexAttribIiv; +void (*const glGetVertexAttribIuiv)(GLuint, GLenum, GLuint*) = ::glGetVertexAttribIuiv; +void (*const glVertexAttribI4i)(GLuint, GLint, GLint, GLint, GLint) = ::glVertexAttribI4i; +void (*const glVertexAttribI4ui)(GLuint, GLuint, GLuint, GLuint, GLuint) = ::glVertexAttribI4ui; +void (*const glVertexAttribI4iv)(GLuint, const GLint*) = ::glVertexAttribI4iv; +void (*const glVertexAttribI4uiv)(GLuint, const GLuint*) = ::glVertexAttribI4uiv; +void (*const glGetUniformuiv)(GLuint, GLint, GLuint*) = ::glGetUniformuiv; +GLint (*const glGetFragDataLocation)(GLuint, const GLchar*) = ::glGetFragDataLocation; +void (*const glUniform1ui)(GLint, GLuint) = ::glUniform1ui; +void (*const glUniform2ui)(GLint, GLuint, GLuint) = ::glUniform2ui; +void (*const glUniform3ui)(GLint, GLuint, GLuint, GLuint) = ::glUniform3ui; +void (*const glUniform4ui)(GLint, GLuint, GLuint, GLuint, GLuint) = ::glUniform4ui; +void (*const glUniform1uiv)(GLint, GLsizei, const GLuint*) = ::glUniform1uiv; +void (*const glUniform2uiv)(GLint, GLsizei, const GLuint*) = ::glUniform2uiv; +void (*const glUniform3uiv)(GLint, GLsizei, const GLuint*) = ::glUniform3uiv; +void (*const glUniform4uiv)(GLint, GLsizei, const GLuint*) = ::glUniform4uiv; +void (*const glClearBufferiv)(GLenum, GLint, const GLint*) = ::glClearBufferiv; +void (*const glClearBufferuiv)(GLenum, GLint, const GLuint*) = ::glClearBufferuiv; +void (*const glClearBufferfv)(GLenum, GLint, const GLfloat*) = ::glClearBufferfv; +void (*const glClearBufferfi)(GLenum, GLint, GLfloat, GLint) = ::glClearBufferfi; +const GLubyte* (*const glGetStringi)(GLenum, GLuint) = ::glGetStringi; +void (*const glCopyBufferSubData)(GLenum, GLenum, GLintptr, GLintptr, GLsizeiptr) = ::glCopyBufferSubData; +void (*const glGetUniformIndices)(GLuint, GLsizei, const GLchar* const*, GLuint*) = ::glGetUniformIndices; +void (*const glGetActiveUniformsiv)(GLuint, GLsizei, const GLuint*, GLenum, GLint*) = ::glGetActiveUniformsiv; +GLuint (*const glGetUniformBlockIndex)(GLuint, const GLchar*) = ::glGetUniformBlockIndex; +void (*const glGetActiveUniformBlockiv)(GLuint, GLuint, GLenum, GLint*) = ::glGetActiveUniformBlockiv; +void (*const glGetActiveUniformBlockName)(GLuint, GLuint, GLsizei, GLsizei*, GLchar*) = ::glGetActiveUniformBlockName; +void (*const glUniformBlockBinding)(GLuint, GLuint, GLuint) = ::glUniformBlockBinding; +void (*const glDrawArraysInstanced)(GLenum, GLint, GLsizei, GLsizei) = ::glDrawArraysInstanced; +void (*const glDrawElementsInstanced)(GLenum, GLsizei, GLenum, const GLvoid*, GLsizei) = ::glDrawElementsInstanced; +GLsync (*const glFenceSync)(GLenum, GLbitfield) = ::glFenceSync; +GLboolean (*const glIsSync)(GLsync) = ::glIsSync; +void (*const glDeleteSync)(GLsync) = ::glDeleteSync; +GLenum (*const glClientWaitSync)(GLsync, GLbitfield, GLuint64) = ::glClientWaitSync; +void (*const glWaitSync)(GLsync, GLbitfield, GLuint64) = ::glWaitSync; +void (*const glGetInteger64v)(GLenum, GLint64*) = ::glGetInteger64v; +void (*const glGetSynciv)(GLsync, GLenum, GLsizei, GLsizei*, GLint*) = ::glGetSynciv; +void (*const glGetInteger64i_v)(GLenum, GLuint, GLint64*) = ::glGetInteger64i_v; +void (*const glGetBufferParameteri64v)(GLenum, GLenum, GLint64*) = ::glGetBufferParameteri64v; +void (*const glGenSamplers)(GLsizei, GLuint*) = ::glGenSamplers; +void (*const glDeleteSamplers)(GLsizei, const GLuint*) = ::glDeleteSamplers; +GLboolean (*const glIsSampler)(GLuint) = ::glIsSampler; +void (*const glBindSampler)(GLuint, GLuint) = ::glBindSampler; +void (*const glSamplerParameteri)(GLuint, GLenum, GLint) = ::glSamplerParameteri; +void (*const glSamplerParameteriv)(GLuint, GLenum, const GLint*) = ::glSamplerParameteriv; +void (*const glSamplerParameterf)(GLuint, GLenum, GLfloat) = ::glSamplerParameterf; +void (*const glSamplerParameterfv)(GLuint, GLenum, const GLfloat*) = ::glSamplerParameterfv; +void (*const glGetSamplerParameteriv)(GLuint, GLenum, GLint*) = ::glGetSamplerParameteriv; +void (*const glGetSamplerParameterfv)(GLuint, GLenum, GLfloat*) = ::glGetSamplerParameterfv; +void (*const glVertexAttribDivisor)(GLuint, GLuint) = ::glVertexAttribDivisor; +void (*const glBindTransformFeedback)(GLenum, GLuint) = ::glBindTransformFeedback; +void (*const glDeleteTransformFeedbacks)(GLsizei, const GLuint*) = ::glDeleteTransformFeedbacks; +void (*const glGenTransformFeedbacks)(GLsizei, GLuint*) = ::glGenTransformFeedbacks; +GLboolean (*const glIsTransformFeedback)(GLuint) = ::glIsTransformFeedback; +void (*const glPauseTransformFeedback)() = ::glPauseTransformFeedback; +void (*const glResumeTransformFeedback)() = ::glResumeTransformFeedback; +void (*const glGetProgramBinary)(GLuint, GLsizei, GLsizei*, GLenum*, GLvoid*) = ::glGetProgramBinary; +void (*const glProgramBinary)(GLuint, GLenum, const GLvoid*, GLsizei) = ::glProgramBinary; +void (*const glProgramParameteri)(GLuint, GLenum, GLint) = ::glProgramParameteri; +void (*const glInvalidateFramebuffer)(GLenum, GLsizei, const GLenum*) = ::glInvalidateFramebuffer; +void (*const glInvalidateSubFramebuffer)(GLenum, GLsizei, const GLenum*, GLint, GLint, GLsizei, GLsizei) = + ::glInvalidateSubFramebuffer; +void (*const glTexStorage2D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei) = ::glTexStorage2D; +void (*const glTexStorage3D)(GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei) = ::glTexStorage3D; +void (*const glGetInternalformativ)(GLenum, GLenum, GLenum, GLsizei, GLint*) = ::glGetInternalformativ; -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl diff --git a/platform/windows/src/headless_backend_egl.cpp b/platform/windows/src/headless_backend_egl.cpp index 68b931916bf..554f9b9043e 100644 --- a/platform/windows/src/headless_backend_egl.cpp +++ b/platform/windows/src/headless_backend_egl.cpp @@ -12,12 +12,14 @@ namespace mbgl { namespace gl { -// This class provides a singleton that contains information about the configuration used for -// instantiating new headless rendering contexts. +// This class provides a singleton that contains information about the +// configuration used for instantiating new headless rendering contexts. class EGLDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; public: EGLDisplayConfig(Key) { @@ -38,22 +40,17 @@ class EGLDisplayConfig { throw std::runtime_error("eglBindAPI() failed"); } - const EGLint attribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_NONE - }; + const EGLint attribs[] = {EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE}; - // Note: we're choosing an arbitrary pixel format, since we're not using the default surface - // anyway; all rendering will be directed to framebuffers which have their own configuration. + // Note: we're choosing an arbitrary pixel format, since we're not using + // the default surface anyway; all rendering will be directed to + // framebuffers which have their own configuration. if (!eglChooseConfig(display, attribs, &config, 1, &numConfigs) || numConfigs != 1) { throw std::runtime_error("Failed to choose ARGB config.\n"); } } - ~EGLDisplayConfig() { - eglTerminate(display); - } + ~EGLDisplayConfig() { eglTerminate(display); } static std::shared_ptr create() { static std::weak_ptr instance; @@ -72,33 +69,26 @@ class EGLDisplayConfig { class EGLBackendImpl : public HeadlessBackend::Impl { public: EGLBackendImpl() { - // EGL initializes the context client version to 1 by default. We want to - // use OpenGL ES 2.0 which has the ability to create shader and program - // objects and also to write vertex and fragment shaders in the OpenGL ES - // Shading Language. - const EGLint attribs[] = { - EGL_CONTEXT_CLIENT_VERSION, 2, - EGL_NONE - }; + // EGL initializes the context client version to 1 by default. We want + // to use OpenGL ES 2.0 which has the ability to create shader and + // program objects and also to write vertex and fragment shaders in the + // OpenGL ES Shading Language. + const EGLint attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; eglContext = eglCreateContext(eglDisplay->display, eglDisplay->config, EGL_NO_CONTEXT, attribs); if (eglContext == EGL_NO_CONTEXT) { std::ostringstream logMsg; - logMsg << "eglCreateContext() returned error 0x" << std::setw(4) << std::setfill('0') << std::hex << eglGetError(); + logMsg << "eglCreateContext() returned error 0x" << std::setw(4) << std::setfill('0') << std::hex + << eglGetError(); mbgl::Log::Error(mbgl::Event::OpenGL, logMsg.str()); throw std::runtime_error("Error creating the EGL context object.\n"); } - // Create a dummy pbuffer. We will render to framebuffers anyway, but we need a pbuffer to - // activate the context. - // Note that to be able to create pbuffer surfaces, we need to choose a config that - // includes EGL_SURFACE_TYPE, EGL_PBUFFER_BIT in HeadlessDisplay. - const EGLint surfAttribs[] = { - EGL_WIDTH, 8, - EGL_HEIGHT, 8, - EGL_LARGEST_PBUFFER, EGL_TRUE, - EGL_NONE - }; + // Create a dummy pbuffer. We will render to framebuffers anyway, but we + // need a pbuffer to activate the context. Note that to be able to + // create pbuffer surfaces, we need to choose a config that includes + // EGL_SURFACE_TYPE, EGL_PBUFFER_BIT in HeadlessDisplay. + const EGLint surfAttribs[] = {EGL_WIDTH, 8, EGL_HEIGHT, 8, EGL_LARGEST_PBUFFER, EGL_TRUE, EGL_NONE}; eglSurface = eglCreatePbufferSurface(eglDisplay->display, eglDisplay->config, surfAttribs); if (eglSurface == EGL_NO_SURFACE) { @@ -118,9 +108,7 @@ class EGLBackendImpl : public HeadlessBackend::Impl { } } - gl::ProcAddress getExtensionFunctionPointer(const char* name) final { - return eglGetProcAddress(name); - } + gl::ProcAddress getExtensionFunctionPointer(const char* name) final { return eglGetProcAddress(name); } void activateContext() final { if (!eglMakeCurrent(eglDisplay->display, eglSurface, eglSurface, eglContext)) { diff --git a/platform/windows/src/headless_backend_osmesa.cpp b/platform/windows/src/headless_backend_osmesa.cpp index 1484fcdd596..c00dc118a35 100644 --- a/platform/windows/src/headless_backend_osmesa.cpp +++ b/platform/windows/src/headless_backend_osmesa.cpp @@ -9,35 +9,34 @@ namespace mbgl { namespace gl { -// This class provides a singleton that contains information about the configuration used for -// instantiating new headless rendering contexts. +// This class provides a singleton that contains information about the +// configuration used for instantiating new headless rendering contexts. class OSMesaBackendImpl final : public HeadlessBackend::Impl { public: OSMesaBackendImpl() { - context = OSMesaCreateContextAttribs(std::initializer_list({ - OSMESA_FORMAT, OSMESA_RGBA, - OSMESA_DEPTH_BITS, 24, - OSMESA_STENCIL_BITS, 8, - OSMESA_PROFILE, OSMESA_COMPAT_PROFILE, - NULL - }).begin(), NULL); + context = OSMesaCreateContextAttribs(std::initializer_list({OSMESA_FORMAT, + OSMESA_RGBA, + OSMESA_DEPTH_BITS, + 24, + OSMESA_STENCIL_BITS, + 8, + OSMESA_PROFILE, + OSMESA_COMPAT_PROFILE, + NULL}) + .begin(), + NULL); } - ~OSMesaBackendImpl() final { - OSMesaDestroyContext(context); - } + ~OSMesaBackendImpl() final { OSMesaDestroyContext(context); } gl::ProcAddress getExtensionFunctionPointer(const char* name) final { return (ProcAddress)::OSMesaGetProcAddress(name); } - void activateContext() final { - OSMesaMakeCurrent(context, buffer.get(), GL_UNSIGNED_BYTE, 2048, 2048); - } + void activateContext() final { OSMesaMakeCurrent(context, buffer.get(), GL_UNSIGNED_BYTE, 2048, 2048); } - void deactivateContext() final { - } + void deactivateContext() final {} private: std::unique_ptr buffer = std::make_unique(2048 * 2048 * 4); diff --git a/platform/windows/src/headless_backend_wgl.cpp b/platform/windows/src/headless_backend_wgl.cpp index dcfeec534c7..84ead07280a 100644 --- a/platform/windows/src/headless_backend_wgl.cpp +++ b/platform/windows/src/headless_backend_wgl.cpp @@ -16,14 +16,16 @@ namespace mbgl { namespace gl { -// This class provides a singleton that contains information about the configuration used for -// instantiating new headless rendering contexts. +// This class provides a singleton that contains information about the +// configuration used for instantiating new headless rendering contexts. class WGLDisplayConfig { private: // Key for singleton construction. - struct Key { explicit Key() = default; }; + struct Key { + explicit Key() = default; + }; - WNDCLASSEXA helperWindowClass = { sizeof(WNDCLASSEXA) }; + WNDCLASSEXA helperWindowClass = {sizeof(WNDCLASSEXA)}; HWND helperWindowHandle = NULL; HDC helperWindowDeviceContext = NULL; HGLRC helperWindowRenderingContext = NULL; @@ -33,7 +35,9 @@ class WGLDisplayConfig { MSG message; helperWindowClass.style = CS_OWNDC; - helperWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, uMsg, wParam, lParam); }; + helperWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + return DefWindowProc(hWnd, uMsg, wParam, lParam); + }; helperWindowClass.lpszClassName = "WGL Helper Window"; GetModuleHandleExA(0, NULL, &helperWindowClass.hInstance); @@ -42,17 +46,18 @@ class WGLDisplayConfig { throw std::runtime_error("Failed to register helper window class"); } - helperWindowHandle = CreateWindowExA( - 0, - helperWindowClass.lpszClassName, - "WGL Helper Window", - WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - 0, 0, 1, 1, - NULL, - NULL, - helperWindowClass.hInstance, - NULL - ); + helperWindowHandle = CreateWindowExA(0, + helperWindowClass.lpszClassName, + "WGL Helper Window", + WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + 0, + 0, + 1, + 1, + NULL, + NULL, + helperWindowClass.hInstance, + NULL); if (!helperWindowHandle) { Log::Error(Event::OpenGL, "Failed to create helper window"); @@ -79,18 +84,16 @@ class WGLDisplayConfig { bool StringInExtensionString(const char* string, const char* extensions) { const char* start = extensions; - while(true) { + while (true) { const char* where; const char* terminator; where = strstr(start, string); - if (!where) - return false; + if (!where) return false; terminator = where + strlen(string); if (where == start || *(where - 1) == ' ') { - if (*terminator == ' ' || *terminator == '\0') - break; + if (*terminator == ' ' || *terminator == '\0') break; } start = terminator; @@ -104,23 +107,23 @@ class WGLDisplayConfig { extensions = mbgl::platform::wglGetExtensionsStringARB(wglGetCurrentDC()); - if(!extensions || !StringInExtensionString(extension, extensions)) + if (!extensions || !StringInExtensionString(extension, extensions)) extensions = mbgl::platform::wglGetExtensionsStringEXT(); - if(!extensions || !StringInExtensionString(extension, extensions)) - extensions = (const char *)wgl_glGetString(GL_EXTENSIONS); + if (!extensions || !StringInExtensionString(extension, extensions)) + extensions = (const char*)wgl_glGetString(GL_EXTENSIONS); - if (!extensions) - return false; + if (!extensions) return false; return StringInExtensionString(extension, extensions); } + public: explicit WGLDisplayConfig(Key) { HDC dummyDC, previousDC; HGLRC dummyRC, previousRC; PIXELFORMATDESCRIPTOR pfd; - + CreateHelperWindow(); dummyDC = GetDC(helperWindowHandle); @@ -136,8 +139,9 @@ class WGLDisplayConfig { pfd.cDepthBits = 24; pfd.cStencilBits = 8; - // Note: we're choosing an arbitrary pixel format, since we're not using the default surface - // anyway; all rendering will be directed to framebuffers which have their own configuration. + // Note: we're choosing an arbitrary pixel format, since we're not using + // the default surface anyway; all rendering will be directed to + // framebuffers which have their own configuration. if (!SetPixelFormat(dummyDC, ChoosePixelFormat(dummyDC, &pfd), &pfd)) { Log::Error(Event::OpenGL, "Failed to set pixel format for dummy context"); throw std::runtime_error("Failed to set pixel format for dummy context"); @@ -178,7 +182,9 @@ class WGLDisplayConfig { DestroyHelperWindow(); renderingWindowClass.style = CS_OWNDC; - renderingWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, uMsg, wParam, lParam); }; + renderingWindowClass.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { + return DefWindowProc(hWnd, uMsg, wParam, lParam); + }; renderingWindowClass.lpszClassName = "WGL Rendering Window"; GetModuleHandleExA(0, NULL, &renderingWindowClass.hInstance); @@ -188,20 +194,19 @@ class WGLDisplayConfig { } } - ~WGLDisplayConfig() { - UnregisterClassA(renderingWindowClass.lpszClassName, renderingWindowClass.hInstance); - } + ~WGLDisplayConfig() { UnregisterClassA(renderingWindowClass.lpszClassName, renderingWindowClass.hInstance); } static std::shared_ptr create() { static std::weak_ptr instance; auto shared = instance.lock(); - + if (!shared) { instance = shared = std::make_shared(Key{}); } - + return shared; } + public: bool ARB_multisample = false; bool ARB_create_context = false; @@ -209,7 +214,7 @@ class WGLDisplayConfig { bool EXT_colorspace = false; bool ARB_pixel_format = false; bool ARB_ES3_compatibility = false; - WNDCLASSEXA renderingWindowClass = { sizeof(WNDCLASSEXA) }; + WNDCLASSEXA renderingWindowClass = {sizeof(WNDCLASSEXA)}; }; class WGLBackendImpl final : public HeadlessBackend::Impl { @@ -219,21 +224,23 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { HWND renderingWindowHandle = NULL; HDC renderingWindowDeviceContext = NULL; HGLRC renderingWindowRenderingContext = NULL; + private: void CreateRenderingWindow() { MSG message; - renderingWindowHandle = CreateWindowExA( - 0, - wglDisplayConfig->renderingWindowClass.lpszClassName, - "WGL Render Window", - WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - 0, 0, 1, 1, - NULL, - NULL, - wglDisplayConfig->renderingWindowClass.hInstance, - NULL - ); + renderingWindowHandle = CreateWindowExA(0, + wglDisplayConfig->renderingWindowClass.lpszClassName, + "WGL Render Window", + WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + 0, + 0, + 1, + 1, + NULL, + NULL, + wglDisplayConfig->renderingWindowClass.hInstance, + NULL); if (!renderingWindowHandle) { Log::Error(Event::OpenGL, "Failed to create helper window"); @@ -282,17 +289,29 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { renderingWindowDeviceContext = GetDC(renderingWindowHandle); } - if (!mbgl::platform::wglChoosePixelFormatARB(renderingWindowDeviceContext, std::initializer_list({ - WGL_SUPPORT_OPENGL_ARB, GL_TRUE, - WGL_DOUBLE_BUFFER_ARB, GL_TRUE, - WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, - WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, - WGL_COLOR_BITS_ARB, 24, - WGL_ALPHA_BITS_ARB, 8, - WGL_DEPTH_BITS_ARB, 24, - WGL_STENCIL_BITS_ARB, 8, - NULL - }).begin(), NULL, 1, &pixelFormat, &numFormats)) { + if (!mbgl::platform::wglChoosePixelFormatARB(renderingWindowDeviceContext, + std::initializer_list({WGL_SUPPORT_OPENGL_ARB, + GL_TRUE, + WGL_DOUBLE_BUFFER_ARB, + GL_TRUE, + WGL_ACCELERATION_ARB, + WGL_FULL_ACCELERATION_ARB, + WGL_PIXEL_TYPE_ARB, + WGL_TYPE_RGBA_ARB, + WGL_COLOR_BITS_ARB, + 24, + WGL_ALPHA_BITS_ARB, + 8, + WGL_DEPTH_BITS_ARB, + 24, + WGL_STENCIL_BITS_ARB, + 8, + NULL}) + .begin(), + NULL, + 1, + &pixelFormat, + &numFormats)) { Log::Error(Event::OpenGL, "Failed to choose pixel format for context"); throw std::runtime_error("Failed to choose pixel format for context"); } @@ -312,13 +331,17 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { } if (wglDisplayConfig->ARB_create_context) { - renderingWindowRenderingContext = mbgl::platform::wglCreateContextAttribsARB(renderingWindowDeviceContext, NULL, - std::initializer_list({ - WGL_CONTEXT_MAJOR_VERSION_ARB, 3, - WGL_CONTEXT_MINOR_VERSION_ARB, 0, - WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, - NULL - }).begin()); + renderingWindowRenderingContext = mbgl::platform::wglCreateContextAttribsARB( + renderingWindowDeviceContext, + NULL, + std::initializer_list({WGL_CONTEXT_MAJOR_VERSION_ARB, + 3, + WGL_CONTEXT_MINOR_VERSION_ARB, + 0, + WGL_CONTEXT_PROFILE_MASK_ARB, + WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, + NULL}) + .begin()); if (!renderingWindowRenderingContext) { const DWORD error = GetLastError(); @@ -326,24 +349,24 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { if (error == (0xc0070000 | ERROR_INVALID_VERSION_ARB)) { Log::Error(Event::OpenGL, "Driver does not support OpenGL ES version 2.0"); throw std::runtime_error("Driver does not support OpenGL ES version 2.0"); - } - else if (error == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) { + } else if (error == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) { Log::Error(Event::OpenGL, "Driver does not support the requested OpenGL profile"); throw std::runtime_error("Driver does not support the requested OpenGL profile"); - } - else if (error == (0xc0070000 | ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB)) { - Log::Error(Event::OpenGL, "The share context is not compatible with the requested context"); - throw std::runtime_error("The share context is not compatible with the requested context"); - } - else { + } else if (error == (0xc0070000 | ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB)) { + Log::Error(Event::OpenGL, + "The share context is not compatible with the " + "requested context"); + throw std::runtime_error( + "The share context is not compatible with the " + "requested context"); + } else { Log::Error(Event::OpenGL, "Failed to create OpenGL ES context"); throw std::runtime_error("Failed to create OpenGL ES context"); } return false; } - } - else { + } else { renderingWindowRenderingContext = wglCreateContext(renderingWindowDeviceContext); if (!renderingWindowRenderingContext) { @@ -365,13 +388,13 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { bool DestroyRenderingContext() { if (renderingWindowRenderingContext && !wglMakeCurrent(renderingWindowDeviceContext, NULL)) { Log::Error(Event::OpenGL, "Failed to make context current"); - //throw std::runtime_error("Failed to make context current"); + // throw std::runtime_error("Failed to make context current"); return false; } if (renderingWindowRenderingContext && !wglDeleteContext(renderingWindowRenderingContext)) { Log::Error(Event::OpenGL, "Failed to delete current context"); - //throw std::runtime_error("Failed to delete current context"); + // throw std::runtime_error("Failed to delete current context"); return false; } @@ -381,9 +404,7 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { } public: - WGLBackendImpl() { - auto renderingContext = GetContext(); - } + WGLBackendImpl() { auto renderingContext = GetContext(); } ~WGLBackendImpl() final { if (renderingWindowRenderingContext) { @@ -398,16 +419,17 @@ class WGLBackendImpl final : public HeadlessBackend::Impl { } void activateContext() final { - if (renderingWindowRenderingContext && !wglMakeCurrent(renderingWindowDeviceContext, renderingWindowRenderingContext)) { + if (renderingWindowRenderingContext && + !wglMakeCurrent(renderingWindowDeviceContext, renderingWindowRenderingContext)) { Log::Error(Event::OpenGL, "Switching OpenGL context failed"); - //throw std::runtime_error("Switching OpenGL context failed"); + // throw std::runtime_error("Switching OpenGL context failed"); } } void deactivateContext() final { if (renderingWindowRenderingContext && !wglMakeCurrent(NULL, NULL)) { Log::Error(Event::OpenGL, "Removing OpenGL context failed"); - //throw std::runtime_error("Removing OpenGL context failed"); + // throw std::runtime_error("Removing OpenGL context failed"); } } }; diff --git a/platform/windows/src/thread.cpp b/platform/windows/src/thread.cpp index 22405dcfcd8..9c1b597c701 100644 --- a/platform/windows/src/thread.cpp +++ b/platform/windows/src/thread.cpp @@ -20,11 +20,10 @@ void SetThreadName(DWORD dwThreadID, const char* threadName) { info.dwFlags = 0; #pragma warning(push) -#pragma warning(disable: 6320 6322) +#pragma warning(disable : 6320 6322) __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); - } - __except (EXCEPTION_EXECUTE_HANDLER){ + } __except (EXCEPTION_EXECUTE_HANDLER) { } #pragma warning(pop) } @@ -50,24 +49,22 @@ namespace platform { std::string getCurrentThreadName() { THREAD_INFO* info = GetCurrentThreadInfo(); - if (info && info->name) - { + if (info && info->name) { return std::string(info->name); } - + return std::string(); } void setCurrentThreadName(const std::string& name) { THREAD_INFO* info = GetCurrentThreadInfo(); - if (info && info->name) - { + if (info && info->name) { free(info->name); info->name = new char[name.length() + 1]; std::strcpy(info->name, name.c_str()); } - + SetThreadName(-1, name.c_str()); } diff --git a/platform/windows/src/thread_local.cpp b/platform/windows/src/thread_local.cpp index dba1f1275cd..7e0b8b9c4bf 100644 --- a/platform/windows/src/thread_local.cpp +++ b/platform/windows/src/thread_local.cpp @@ -33,8 +33,8 @@ ThreadLocalBase::ThreadLocalBase() { } ThreadLocalBase::~ThreadLocalBase() { - // ThreadLocal will not take ownership of the pointer it is managing. The pointer - // needs to be explicitly cleared before we destroy this object. + // ThreadLocal will not take ownership of the pointer it is managing. The + // pointer needs to be explicitly cleared before we destroy this object. assert(!get()); DWORD key = StorageToThreadInfo->key; diff --git a/render-test/allocation_index.cpp b/render-test/allocation_index.cpp index 144c18ddd5d..7f776076db2 100644 --- a/render-test/allocation_index.cpp +++ b/render-test/allocation_index.cpp @@ -19,7 +19,9 @@ std::mutex indexMutex; class FlagGuard { public: explicit FlagGuard(std::atomic_bool& flag_) - : flag(flag_) { flag = true; } + : flag(flag_) { + flag = true; + } ~FlagGuard() { flag = false; } private: @@ -74,7 +76,7 @@ void AllocationIndex::reset() { // static void* AllocationIndex::allocate(size_t size) { - void *ptr = std::malloc(size); + void* ptr = std::malloc(size); if (ptr && canModifyIndex()) addToIndex(size, ptr); return ptr; } diff --git a/render-test/allocation_index.hpp b/render-test/allocation_index.hpp index 71da441c1f9..35e33067826 100644 --- a/render-test/allocation_index.hpp +++ b/render-test/allocation_index.hpp @@ -20,34 +20,35 @@ class AllocationIndex { /** * @brief Same as `malloc()` + indexes the allocated data, * if indexing is active. - * - * @return void* + * + * @return void* */ static void* allocate(size_t); /** * @brief Same as `free()` + removes the corresponding data from index, * if these data are present in the index and indexing is active. - * - * @return void* + * + * @return void* */ static void deallocate(void*) noexcept; /** * @brief Returns the size (in bytes) of allocated data, currently present in the index. - * + * * @return size_t */ static size_t getAllocatedSize(); /** * @brief Returns the total amount of allocations since indexing start. - * - * @return size_t + * + * @return size_t */ static size_t getAllocationsCount(); /** - * @brief Returns the maximum size (in bytes) of the allocated data in the index, since last `reset()` call. - * - * @return size_t + * @brief Returns the maximum size (in bytes) of the allocated data in the + * index, since last `reset()` call. + * + * @return size_t */ static size_t getAllocatedSizePeak(); }; diff --git a/render-test/file_source.cpp b/render-test/file_source.cpp index 51810dc27d2..30b1f679e1f 100644 --- a/render-test/file_source.cpp +++ b/render-test/file_source.cpp @@ -16,15 +16,19 @@ std::atomic_size_t transferredSize{0}; std::atomic_bool active{false}; std::atomic_bool offline{true}; -ProxyFileSource::ProxyFileSource(std::shared_ptr defaultResourceLoader_, const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) +ProxyFileSource::ProxyFileSource(std::shared_ptr defaultResourceLoader_, + const ResourceOptions& resourceOptions_, + const ClientOptions& clientOptions_) : defaultResourceLoader(std::move(defaultResourceLoader_)), - resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) { + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) { assert(defaultResourceLoader); if (offline) { - std::shared_ptr dbfs = FileSourceManager::get()->getFileSource(FileSourceType::Database, resourceOptions_, clientOptions_); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, resourceOptions_, clientOptions_); dbfs->setProperty(READ_ONLY_MODE_KEY, true); } -} +} ProxyFileSource::~ProxyFileSource() = default; @@ -59,10 +63,9 @@ std::unique_ptr ProxyFileSource::request(const Resource& resource, return defaultResourceLoader->request(transformed, [=](Response response) { if (transformed.loadingMethod == Resource::LoadingMethod::CacheOnly && response.noContent) { if (transformed.kind == Resource::Kind::Tile && transformed.tileData) { - mbgl::Log::Info(mbgl::Event::Database, - "Resource not found in cache: " + - transformed.url + "(" + - transformed.tileData->urlTemplate + ")"); + mbgl::Log::Info( + mbgl::Event::Database, + "Resource not found in cache: " + transformed.url + "(" + transformed.tileData->urlTemplate + ")"); } else { mbgl::Log::Info(mbgl::Event::Database, "Resource not found in cache: " + transformed.url); } @@ -78,7 +81,7 @@ std::unique_ptr ProxyFileSource::request(const Resource& resource, } void ProxyFileSource::setResourceOptions(ResourceOptions options) { - resourceOptions = options; + resourceOptions = options; } ResourceOptions ProxyFileSource::getResourceOptions() { @@ -86,14 +89,13 @@ ResourceOptions ProxyFileSource::getResourceOptions() { } void ProxyFileSource::setClientOptions(ClientOptions options) { - clientOptions = options; + clientOptions = options; } ClientOptions ProxyFileSource::getClientOptions() { return clientOptions.clone(); } - // static void ProxyFileSource::setOffline(bool status) { offline = status; diff --git a/render-test/file_source.hpp b/render-test/file_source.hpp index b03b70142eb..c06d223079d 100644 --- a/render-test/file_source.hpp +++ b/render-test/file_source.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include namespace mbgl { diff --git a/render-test/manifest_parser.cpp b/render-test/manifest_parser.cpp index 27589140f33..486ac363cbb 100644 --- a/render-test/manifest_parser.cpp +++ b/render-test/manifest_parser.cpp @@ -100,15 +100,15 @@ mbgl::filesystem::path getValidPath(const std::string& manifestPath, const std:: } // namespace -std::optional ManifestParser::parseManifest(const std::string& manifestPath, - std::string testFilter) { +std::optional ManifestParser::parseManifest(const std::string& manifestPath, std::string testFilter) { Manifest manifest; const auto filePath = mbgl::filesystem::path(manifestPath); manifest.manifestPath = manifestPath.substr(0, manifestPath.find(filePath.filename())); auto contents = readJson(filePath); if (!contents.is()) { - mbgl::Log::Error(mbgl::Event::General, "Provided manifest file: " + std::string(filePath) + " is not a valid json"); + mbgl::Log::Error(mbgl::Event::General, + "Provided manifest file: " + std::string(filePath) + " is not a valid json"); return std::nullopt; } @@ -116,8 +116,8 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("result_path")) { const auto& resultPathValue = document["result_path"]; if (!resultPathValue.IsString()) { - mbgl::Log::Warning( - mbgl::Event::General, "Invalid result_path is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning(mbgl::Event::General, + "Invalid result_path is provided inside the manifest file: " + std::string(filePath)); return std::nullopt; } manifest.resultPath = (getValidPath(manifest.manifestPath, resultPathValue.GetString()) / "").string(); @@ -128,8 +128,8 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("cache_path")) { const auto& cachePathValue = document["cache_path"]; if (!cachePathValue.IsString()) { - mbgl::Log::Warning( - mbgl::Event::General, "Invalid cache_path is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning(mbgl::Event::General, + "Invalid cache_path is provided inside the manifest file: " + std::string(filePath)); return std::nullopt; } manifest.cachePath = (getValidPath(manifest.manifestPath, ".") / cachePathValue.GetString()).string(); @@ -137,7 +137,7 @@ std::optional ManifestParser::parseManifest(const std::string& manifes return std::nullopt; } } - //TODO:PP + // TODO:PP if (document.HasMember("access_token")) { const auto& apiKeyValue = document["access_token"]; if (!apiKeyValue.IsString()) { @@ -155,7 +155,9 @@ std::optional ManifestParser::parseManifest(const std::string& manifes const auto& testPathValue = document["base_test_path"]; if (!testPathValue.IsString()) { mbgl::Log::Warning(mbgl::Event::General, - "Invalid base_test_path is provided inside the manifest file: " + std::string(filePath)); + "Invalid base_test_path is provided inside the manifest " + "file: " + + std::string(filePath)); return std::nullopt; } baseTestPath = getValidPath(manifest.manifestPath, testPathValue.GetString()); @@ -167,8 +169,8 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("metric_path")) { const auto& metricPathValue = document["metric_path"]; if (!metricPathValue.IsString()) { - mbgl::Log::Warning( - mbgl::Event::General, "Invalid metric_path is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning(mbgl::Event::General, + "Invalid metric_path is provided inside the manifest file: " + std::string(filePath)); return std::nullopt; } expectedMetricPath = getValidPath(manifest.manifestPath, metricPathValue.GetString()); @@ -181,13 +183,17 @@ std::optional ManifestParser::parseManifest(const std::string& manifes const auto& expectationPathValue = document["expectation_paths"]; if (!expectationPathValue.IsArray()) { mbgl::Log::Warning(mbgl::Event::General, - "Provided expectation_paths inside the manifest file: %s is not a valid array" + std::string(filePath)); + "Provided expectation_paths inside the manifest file: %s is " + "not a valid array" + + std::string(filePath)); return std::nullopt; } for (const auto& value : expectationPathValue.GetArray()) { if (!value.IsString()) { mbgl::Log::Warning(mbgl::Event::General, - "Invalid expectation path item is provided inside the manifest file: " + std::string(filePath)); + "Invalid expectation path item is provided inside the " + "manifest file: " + + std::string(filePath)); return std::nullopt; } expectationPaths.emplace_back(getValidPath(manifest.manifestPath, value.GetString())); @@ -200,14 +206,17 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("ignore_paths")) { const auto& ignorePathValue = document["ignore_paths"]; if (!ignorePathValue.IsArray()) { - mbgl::Log::Warning(mbgl::Event::General, - "Provided ignore_paths inside the manifest file: " + std::string(filePath) + " is not a valid array"); + mbgl::Log::Warning( + mbgl::Event::General, + "Provided ignore_paths inside the manifest file: " + std::string(filePath) + " is not a valid array"); return std::nullopt; } for (const auto& value : ignorePathValue.GetArray()) { if (!value.IsString()) { mbgl::Log::Warning(mbgl::Event::General, - "Invalid ignore path item is provided inside the manifest file: " + std::string(filePath)); + "Invalid ignore path item is provided inside the manifest " + "file: " + + std::string(filePath)); return std::nullopt; } ignorePaths.emplace_back(getValidPath(manifest.manifestPath, value.GetString())); @@ -221,15 +230,17 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (document.HasMember("probes")) { const auto& probesValue = document["probes"]; if (!probesValue.IsArray()) { - mbgl::Log::Warning(mbgl::Event::General, - "Provided probes inside the manifest file: " + std::string(filePath) + "is not a valid array"); + mbgl::Log::Warning( + mbgl::Event::General, + "Provided probes inside the manifest file: " + std::string(filePath) + "is not a valid array"); return std::nullopt; } for (const auto& value : probesValue.GetArray()) { if (!value.IsString()) { mbgl::Log::Warning(mbgl::Event::General, - "Invalid probe type is provided inside the manifest file: " + - std::string(filePath)); + "Invalid probe type is provided inside the manifest " + "file: " + + std::string(filePath)); return std::nullopt; } manifest.probes.emplace(value.GetString()); @@ -239,8 +250,8 @@ std::optional ManifestParser::parseManifest(const std::string& manifes if (testFilter.empty() && document.HasMember("filter")) { const auto& filterValue = document["filter"]; if (!filterValue.IsString()) { - mbgl::Log::Warning( - mbgl::Event::General, "Invalid filter is provided inside the manifest file: " + std::string(filePath)); + mbgl::Log::Warning(mbgl::Event::General, + "Invalid filter is provided inside the manifest file: " + std::string(filePath)); return std::nullopt; } diff --git a/render-test/manifest_parser.hpp b/render-test/manifest_parser.hpp index 2fad5ce7272..14c58703a79 100644 --- a/render-test/manifest_parser.hpp +++ b/render-test/manifest_parser.hpp @@ -39,6 +39,5 @@ class Manifest { class ManifestParser { public: - static std::optional parseManifest(const std::string& manifestPath, - std::string testFilter); + static std::optional parseManifest(const std::string& manifestPath, std::string testFilter); }; diff --git a/render-test/metadata.hpp b/render-test/metadata.hpp index 07cb599042b..95b79f888e2 100644 --- a/render-test/metadata.hpp +++ b/render-test/metadata.hpp @@ -60,7 +60,9 @@ inline std::tuple checkValue(float expected, float actual, float to struct FileSizeProbe { FileSizeProbe() = default; FileSizeProbe(std::string path_, uintmax_t size_, float tolerance_) - : path(std::move(path_)), size(size_), tolerance(tolerance_) {} + : path(std::move(path_)), + size(size_), + tolerance(tolerance_) {} std::string path; uintmax_t size; @@ -69,7 +71,10 @@ struct FileSizeProbe { struct MemoryProbe { MemoryProbe() = default; - MemoryProbe(size_t peak_, size_t allocations_) : peak(peak_), allocations(allocations_), tolerance(0.0f) {} + MemoryProbe(size_t peak_, size_t allocations_) + : peak(peak_), + allocations(allocations_), + tolerance(0.0f) {} size_t peak; size_t allocations; @@ -80,7 +85,8 @@ struct MemoryProbe { } static std::tuple checkAllocations(const MemoryProbe& expected, const MemoryProbe& actual) { - return checkValue(static_cast(expected.allocations), static_cast(actual.allocations), actual.tolerance); + return checkValue( + static_cast(expected.allocations), static_cast(actual.allocations), actual.tolerance); } }; @@ -92,7 +98,9 @@ struct FpsProbe { struct NetworkProbe { NetworkProbe() = default; - NetworkProbe(size_t requests_, size_t transferred_) : requests(requests_), transferred(transferred_) {} + NetworkProbe(size_t requests_, size_t transferred_) + : requests(requests_), + transferred(transferred_) {} size_t requests; size_t transferred; @@ -101,7 +109,9 @@ struct NetworkProbe { struct GfxProbe { struct Memory { Memory() = default; - Memory(int allocated_, int peak_) : allocated(allocated_), peak(peak_) {} + Memory(int allocated_, int peak_) + : allocated(allocated_), + peak(peak_) {} int allocated; int peak; @@ -144,7 +154,7 @@ struct TestMetadata { // to prevent the unit test fail, and just verify the render result. bool ignoreProbing = false; - mbgl::Size size{ 512u, 512u }; + mbgl::Size size{512u, 512u}; float pixelRatio = 1.0f; double allowed = 0.00015; // diff std::string description; @@ -185,7 +195,6 @@ struct TestMetadata { std::string errorMessage; double difference = 0.0; - }; class TestContext { diff --git a/render-test/parser.cpp b/render-test/parser.cpp index e42f00b1ae3..4bc96b9e035 100644 --- a/render-test/parser.cpp +++ b/render-test/parser.cpp @@ -172,13 +172,13 @@ std::string toJSON(const std::vector& features, unsigned indent, JSONReply readJson(const mbgl::filesystem::path& jsonPath) { auto maybeJSON = mbgl::util::readFile(jsonPath); if (!maybeJSON) { - return { std::string("Unable to open file ") + jsonPath.string() }; + return {std::string("Unable to open file ") + jsonPath.string()}; } mbgl::JSDocument document; document.Parse<0>(*maybeJSON); if (document.HasParseError()) { - return { mbgl::formatJSONParseError(document) }; + return {mbgl::formatJSONParseError(document)}; } return {std::move(document)}; @@ -485,8 +485,8 @@ TestMetadata parseTestMetadata(const TestPaths& paths) { } else if (mapModeStr == "static") metadata.mapMode = mbgl::MapMode::Static; else { - mbgl::Log::Warning( - mbgl::Event::ParseStyle, "Unknown map mode: " + mapModeStr + ". Falling back to static mode"); + mbgl::Log::Warning(mbgl::Event::ParseStyle, + "Unknown map mode: " + mapModeStr + ". Falling back to static mode"); metadata.mapMode = mbgl::MapMode::Static; } } @@ -521,8 +521,8 @@ TestMetadata parseTestMetadata(const TestPaths& paths) { if (testValue.HasMember("description")) { assert(testValue["description"].IsString()); - metadata.description = - std::string{testValue["description"].GetString(), testValue["description"].GetStringLength()}; + metadata.description = std::string{testValue["description"].GetString(), + testValue["description"].GetStringLength()}; } // Test operations handled in runner.cpp. @@ -568,7 +568,7 @@ TestMetadata parseTestMetadata(const TestPaths& paths) { } metadata.renderTest = false; } - + if (testValue.HasMember("ignoreProbing")) { if (testValue["ignoreProbing"].IsBool()) { metadata.ignoreProbing = testValue["ignoreProbing"].GetBool(); @@ -890,8 +890,8 @@ TestOperations parseTestOperations(TestMetadata& metadata) { result.emplace_back([sourceName, json = serializeJsonValue(operationArray[2])](TestContext& ctx) { mbgl::style::conversion::Error error; - auto converted = - mbgl::style::conversion::convertJSON>(json, error, sourceName); + auto converted = mbgl::style::conversion::convertJSON>( + json, error, sourceName); if (!converted) { ctx.getMetadata().errorMessage = std::string("Unable to convert source: ") + error.message; return false; @@ -1229,7 +1229,9 @@ TestOperations parseTestOperations(TestMetadata& metadata) { mbgl::AnimationOptions animationOptions(mbgl::Milliseconds(duration * 1000)); animationOptions.minZoom = mbgl::util::min(startZoom, endZoom); - animationOptions.transitionFinishFn = [&]() { transitionFinished = true; }; + animationOptions.transitionFinishFn = [&]() { + transitionFinished = true; + }; map.flyTo(mbgl::CameraOptions().withCenter(endPos).withZoom(endZoom), animationOptions); @@ -1313,12 +1315,13 @@ std::string encodeBase64(const std::string& data) { } std::string createResultItem(const TestMetadata& metadata, bool hasFailedTests) { - const bool shouldHide = - (hasFailedTests && metadata.status == "passed") || (metadata.status.find("ignored") != std::string::npos); + const bool shouldHide = (hasFailedTests && metadata.status == "passed") || + (metadata.status.find("ignored") != std::string::npos); std::string html; html.append("

\n"); - html.append(R"(

" + metadata.status + " " + metadata.id + "

\n"); + html.append(R"(

" + metadata.status + + " " + metadata.id + "

\n"); if (!metadata.renderErrored) { if (metadata.outputsImage) { @@ -1361,7 +1364,10 @@ std::string createResultItem(const TestMetadata& metadata, bool hasFailedTests) return html; } -std::string createResultPage(const TestStatistics& stats, const std::vector& metadatas, bool shuffle, uint32_t seed) { +std::string createResultPage(const TestStatistics& stats, + const std::vector& metadatas, + bool shuffle, + uint32_t seed) { const uint32_t unsuccessful = stats.erroredTests + stats.failedTests; std::string resultsPage; diff --git a/render-test/render_test.cpp b/render-test/render_test.cpp index 0c3473b159d..77b684bab19 100644 --- a/render-test/render_test.cpp +++ b/render-test/render_test.cpp @@ -14,15 +14,15 @@ #include "parser.hpp" #include "runner.hpp" -#define ANSI_COLOR_RED "\x1b[31m" -#define ANSI_COLOR_GREEN "\x1b[32m" -#define ANSI_COLOR_YELLOW "\x1b[33m" -#define ANSI_COLOR_BLUE "\x1b[34m" -#define ANSI_COLOR_MAGENTA "\x1b[35m" -#define ANSI_COLOR_CYAN "\x1b[36m" -#define ANSI_COLOR_GRAY "\x1b[37m" +#define ANSI_COLOR_RED "\x1b[31m" +#define ANSI_COLOR_GREEN "\x1b[32m" +#define ANSI_COLOR_YELLOW "\x1b[33m" +#define ANSI_COLOR_BLUE "\x1b[34m" +#define ANSI_COLOR_MAGENTA "\x1b[35m" +#define ANSI_COLOR_CYAN "\x1b[36m" +#define ANSI_COLOR_GRAY "\x1b[37m" #define ANSI_COLOR_LIGHT_GRAY "\x1b[90m" -#define ANSI_COLOR_RESET "\x1b[0m" +#define ANSI_COLOR_RESET "\x1b[0m" #if !defined(SANITIZE) void* operator new(std::size_t sz) { @@ -105,8 +105,8 @@ ArgumentsTuple parseArguments(int argc, char** argv) { const auto shuffle = shuffleFlag ? args::get(shuffleFlag) : false; const auto online = onlineFlag ? args::get(onlineFlag) : false; const auto seed = seedValue ? args::get(seedValue) : 1u; - TestRunner::UpdateResults updateResults = - testUpdateResultsValue ? args::get(testUpdateResultsValue) : TestRunner::UpdateResults::NO; + TestRunner::UpdateResults updateResults = testUpdateResultsValue ? args::get(testUpdateResultsValue) + : TestRunner::UpdateResults::NO; return ArgumentsTuple{recycleMapFlag ? args::get(recycleMapFlag) : false, shuffle, online, @@ -174,7 +174,8 @@ int runRenderTests(int argc, char** argv, std::function testStatus) { std::string ignoreReason; const std::string ignoreName = id; - const auto it = std::find_if(ignores.cbegin(), ignores.cend(), [&ignoreName](auto pair) { return pair.first == ignoreName; }); + const auto it = std::find_if( + ignores.cbegin(), ignores.cend(), [&ignoreName](auto pair) { return pair.first == ignoreName; }); if (it != ignores.end()) { metadata.ignoredTest = shouldIgnore = true; ignoreReason = it->second; @@ -204,13 +205,15 @@ int runRenderTests(int argc, char** argv, std::function testStatus) { status = "ignored failed"; color = "#9E9E9E"; stats.ignoreFailedTests++; - printf(ANSI_COLOR_LIGHT_GRAY "* ignore %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str()); + printf( + ANSI_COLOR_LIGHT_GRAY "* ignore %s (%s)" ANSI_COLOR_RESET "\n", id.c_str(), ignoreReason.c_str()); } } else { - // Only fail the bots on render errors, this is a CI limitation that we need - // to succeed on metrics failed so the rebaseline bot can run next in the - // pipeline and collect the new baselines. The rebaseline bot will ultimately - // report the error and block the patch from being merged. + // Only fail the bots on render errors, this is a CI limitation that + // we need to succeed on metrics failed so the rebaseline bot can + // run next in the pipeline and collect the new baselines. The + // rebaseline bot will ultimately report the error and block the + // patch from being merged. if (metadata.renderErrored || metadata.renderFailed) { returnCode = 1; } @@ -247,23 +250,33 @@ int runRenderTests(int argc, char** argv, std::function testStatus) { std::string resultsHTML = createResultPage(stats, metadatas, shuffle, seed); mbgl::util::write_file(resultPath, resultsHTML); - const uint32_t count = - stats.erroredTests + stats.failedTests + stats.ignoreFailedTests + stats.ignorePassedTests + stats.passedTests; + const uint32_t count = stats.erroredTests + stats.failedTests + stats.ignoreFailedTests + stats.ignorePassedTests + + stats.passedTests; if (stats.passedTests) { - printf(ANSI_COLOR_GREEN "%u passed (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.passedTests, 100.0 * stats.passedTests / count); + printf(ANSI_COLOR_GREEN "%u passed (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.passedTests, + 100.0 * stats.passedTests / count); } if (stats.ignorePassedTests) { - printf(ANSI_COLOR_YELLOW "%u passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.ignorePassedTests, 100.0 * stats.ignorePassedTests / count); + printf(ANSI_COLOR_YELLOW "%u passed but were ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.ignorePassedTests, + 100.0 * stats.ignorePassedTests / count); } if (stats.ignoreFailedTests) { - printf(ANSI_COLOR_LIGHT_GRAY "%u ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.ignoreFailedTests, 100.0 * stats.ignoreFailedTests / count); + printf(ANSI_COLOR_LIGHT_GRAY "%u ignored (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.ignoreFailedTests, + 100.0 * stats.ignoreFailedTests / count); } if (stats.failedTests) { - printf(ANSI_COLOR_RED "%u failed (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.failedTests, 100.0 * stats.failedTests / count); + printf(ANSI_COLOR_RED "%u failed (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.failedTests, + 100.0 * stats.failedTests / count); } if (stats.erroredTests) { - printf(ANSI_COLOR_RED "%u errored (%.1lf%%)" ANSI_COLOR_RESET "\n", stats.erroredTests, 100.0 * stats.erroredTests / count); + printf(ANSI_COLOR_RED "%u errored (%.1lf%%)" ANSI_COLOR_RESET "\n", + stats.erroredTests, + 100.0 * stats.erroredTests / count); } printf("Results at: %s\n", mbgl::filesystem::canonical(resultPath).c_str()); diff --git a/render-test/runner.cpp b/render-test/runner.cpp index d07ac971186..396a1225b9a 100644 --- a/render-test/runner.cpp +++ b/render-test/runner.cpp @@ -90,7 +90,8 @@ std::string simpleDiff(const Value& result, const Value& expected) { } TestRunner::TestRunner(Manifest manifest_, UpdateResults updateResults_) - : manifest(std::move(manifest_)), updateResults(updateResults_) { + : manifest(std::move(manifest_)), + updateResults(updateResults_) { registerProxyFileSource(); } @@ -99,9 +100,10 @@ void TestRunner::registerProxyFileSource() { std::call_once(registerProxyFlag, [] { auto* fileSourceManager = mbgl::FileSourceManager::get(); - auto resourceLoaderFactory = - fileSourceManager->unRegisterFileSourceFactory(mbgl::FileSourceType::ResourceLoader); - auto factory = [defaultFactory = std::move(resourceLoaderFactory)](const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) { + auto resourceLoaderFactory = fileSourceManager->unRegisterFileSourceFactory( + mbgl::FileSourceType::ResourceLoader); + auto factory = [defaultFactory = std::move(resourceLoaderFactory)](const mbgl::ResourceOptions& resourceOptions, + const mbgl::ClientOptions& clientOptions) { assert(defaultFactory); std::shared_ptr fileSource = defaultFactory(resourceOptions, clientOptions); return std::make_unique(std::move(fileSource), resourceOptions, clientOptions); @@ -257,13 +259,12 @@ void TestRunner::checkRenderTestResults(mbgl::PremultipliedImage&& actualImage, expectedImage = mbgl::decodeImage(*maybeExpectedImage); - pixels = static_cast( - mapbox::pixelmatch(actualImage.data.get(), - expectedImage.data.get(), - expectedImage.size.width, - expectedImage.size.height, - imageDiff.data.get(), - 0.1285) // Defined in GL JS + pixels = static_cast(mapbox::pixelmatch(actualImage.data.get(), + expectedImage.data.get(), + expectedImage.size.width, + expectedImage.size.height, + imageDiff.data.get(), + 0.1285) // Defined in GL JS ); metadata.diff = mbgl::encodePNG(imageDiff); @@ -298,8 +299,8 @@ void TestRunner::checkProbingResults(TestMetadata& resultMetadata) { return; } - // Check the possible paths in reverse order, so that the default path with the test style will only be checked in - // the very end. + // Check the possible paths in reverse order, so that the default path with + // the test style will only be checked in the very end. std::vector expectedMetricsPaths; for (auto rit = expectedMetrics.rbegin(); rit != expectedMetrics.rend(); ++rit) { if (mbgl::filesystem::exists(*rit)) { @@ -308,8 +309,8 @@ void TestRunner::checkProbingResults(TestMetadata& resultMetadata) { } } - // In case no metrics.json is found, skip assigning the expectedMetrics to metadata, otherwise, take the first found - // metrics. + // In case no metrics.json is found, skip assigning the expectedMetrics to + // metadata, otherwise, take the first found metrics. for (const auto& entry : expectedMetricsPaths) { auto maybeExpectedMetrics = readExpectedMetrics(entry); if (maybeExpectedMetrics.isEmpty()) { @@ -322,8 +323,8 @@ void TestRunner::checkProbingResults(TestMetadata& resultMetadata) { } if (resultMetadata.expectedMetrics.isEmpty()) { - resultMetadata.errorMessage = - "Failed to find metric expectations for: " + resultMetadata.paths.stylePath.string(); + resultMetadata.errorMessage = "Failed to find metric expectations for: " + + resultMetadata.paths.stylePath.string(); if (updateResults == UpdateResults::REBASELINE && !resultMetadata.ignoredTest) { writeMetrics(expectedMetrics.back(), ". Created baseline for missing metrics."); } @@ -350,7 +351,9 @@ void TestRunner::checkProbingResults(TestMetadata& resultMetadata) { return; } - auto result = checkValue(static_cast(expected.second.size), static_cast(actual->second.size), actual->second.tolerance); + auto result = checkValue(static_cast(expected.second.size), + static_cast(actual->second.size), + actual->second.tolerance); if (!std::get(result)) { std::stringstream ss; ss << "File size does not match at probe \"" << expected.first << "\" for file \"" @@ -658,7 +661,8 @@ void resetContext(const TestMetadata& metadata, TestContext& ctx) { LatLng getTileCenterCoordinates(const UnwrappedTileID& tileId) { double scale = (1 << tileId.canonical.z); - Point tileCenter{(tileId.canonical.x + 0.5) * util::tileSize_D, (tileId.canonical.y + 0.5) * util::tileSize_D}; + Point tileCenter{(tileId.canonical.x + 0.5) * util::tileSize_D, + (tileId.canonical.y + 0.5) * util::tileSize_D}; return Projection::unproject(tileCenter, scale); } @@ -677,10 +681,13 @@ uint32_t getImageTileOffset(const std::set& dims, uint32_t dim, float } // namespace -TestRunner::Impl::Impl(const TestMetadata& metadata, const mbgl::ResourceOptions& resourceOptions, const mbgl::ClientOptions& clientOptions) +TestRunner::Impl::Impl(const TestMetadata& metadata, + const mbgl::ResourceOptions& resourceOptions, + const mbgl::ClientOptions& clientOptions) : observer(std::make_unique()), frontend(metadata.size, metadata.pixelRatio, swapBehavior(metadata.mapMode)), - fileSource(mbgl::FileSourceManager::get()->getFileSource(mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions)), + fileSource(mbgl::FileSourceManager::get()->getFileSource( + mbgl::FileSourceType::ResourceLoader, resourceOptions, clientOptions)), map(frontend, *observer.get(), mbgl::MapOptions() @@ -699,7 +706,8 @@ void TestRunner::run(TestMetadata& metadata) { ProxyFileSource::setTrackingActive(false); struct ContextImpl final : public TestContext { - ContextImpl(TestMetadata& metadata_) : metadata(metadata_) {} + ContextImpl(TestMetadata& metadata_) + : metadata(metadata_) {} HeadlessFrontend& getFrontend() override { assert(runnerImpl); return runnerImpl->frontend; @@ -776,8 +784,8 @@ void TestRunner::run(TestMetadata& metadata) { } auto tileScreenSize = getTileScreenPixelSize(metadata.pixelRatio); - result.image = - PremultipliedImage({uint32_t(xDims.size()) * tileScreenSize, uint32_t(yDims.size()) * tileScreenSize}); + result.image = PremultipliedImage( + {uint32_t(xDims.size()) * tileScreenSize, uint32_t(yDims.size()) * tileScreenSize}); for (const auto& tileId : tileIds) { resetContext(metadata, ctx); ctx.getFrontend().getRenderer()->collectPlacedSymbolData(true); @@ -837,11 +845,13 @@ void TestRunner::run(TestMetadata& metadata) { if (placedSymbol.intersectsTileBorder) { if (placedSymbol.textCollisionBox) { findCutOffs( - placedSymbol, *placedSymbol.textCollisionBox, placedSymbol.textPlaced, false /*isIcon*/); + placedSymbol, *placedSymbol.textCollisionBox, placedSymbol.textPlaced, false /*isIcon*/ + ); } if (placedSymbol.iconCollisionBox) { findCutOffs( - placedSymbol, *placedSymbol.iconCollisionBox, placedSymbol.iconPlaced, true /*isIcon*/); + placedSymbol, *placedSymbol.iconCollisionBox, placedSymbol.iconPlaced, true /*isIcon*/ + ); } } } diff --git a/render-test/runner.hpp b/render-test/runner.hpp index b2cb8d57f81..fd8b5d2105e 100644 --- a/render-test/runner.hpp +++ b/render-test/runner.hpp @@ -36,7 +36,13 @@ class TestRunnerMapObserver : public mbgl::MapObserver { class TestRunner { public: - enum class UpdateResults { NO, DEFAULT, PLATFORM, METRICS, REBASELINE }; + enum class UpdateResults { + NO, + DEFAULT, + PLATFORM, + METRICS, + REBASELINE + }; TestRunner(Manifest, UpdateResults); void run(TestMetadata&); diff --git a/src/mbgl/actor/mailbox.cpp b/src/mbgl/actor/mailbox.cpp index e53584efef3..4c50f74719a 100644 --- a/src/mbgl/actor/mailbox.cpp +++ b/src/mbgl/actor/mailbox.cpp @@ -8,13 +8,14 @@ namespace mbgl { Mailbox::Mailbox() = default; -Mailbox::Mailbox(Scheduler& scheduler_) : weakScheduler(scheduler_.makeWeakPtr()) {} +Mailbox::Mailbox(Scheduler& scheduler_) + : weakScheduler(scheduler_.makeWeakPtr()) {} void Mailbox::open(Scheduler& scheduler_) { assert(!weakScheduler); - // As with close(), block until neither receive() nor push() are in progress, and acquire the two - // mutexes in the same order. + // As with close(), block until neither receive() nor push() are in + // progress, and acquire the two mutexes in the same order. std::lock_guard receivingLock(receivingMutex); std::lock_guard pushingLock(pushingMutex); @@ -31,11 +32,12 @@ void Mailbox::open(Scheduler& scheduler_) { } void Mailbox::close() { - // Block until neither receive() nor push() are in progress. Two mutexes are used because receive() - // must not block send(). Of the two, the receiving mutex must be acquired first, because that is - // the order that an actor will obtain them when it self-sends a message, and consistent lock - // acquisition order prevents deadlocks. - // The receiving mutex is recursive to allow a mailbox (and thus the actor) to close itself. + // Block until neither receive() nor push() are in progress. Two mutexes are + // used because receive() must not block send(). Of the two, the receiving + // mutex must be acquired first, because that is the order that an actor + // will obtain them when it self-sends a message, and consistent lock + // acquisition order prevents deadlocks. The receiving mutex is recursive to + // allow a mailbox (and thus the actor) to close itself. std::lock_guard receivingLock(receivingMutex); std::lock_guard pushingLock(pushingMutex); @@ -99,7 +101,9 @@ void Mailbox::maybeReceive(const std::weak_ptr& mailbox) { // static std::function Mailbox::makeClosure(std::weak_ptr mailbox) { - return [mailbox = std::move(mailbox)]() { maybeReceive(mailbox); }; + return [mailbox = std::move(mailbox)]() { + maybeReceive(mailbox); + }; } } // namespace mbgl diff --git a/src/mbgl/actor/scheduler.cpp b/src/mbgl/actor/scheduler.cpp index 0e051d0273a..b6132ebc66d 100644 --- a/src/mbgl/actor/scheduler.cpp +++ b/src/mbgl/actor/scheduler.cpp @@ -68,4 +68,4 @@ std::shared_ptr Scheduler::GetSequenced() { return result; } -} //namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/algorithm/update_renderables.hpp b/src/mbgl/algorithm/update_renderables.hpp index 7fa8fee788f..dd46bcd13e9 100644 --- a/src/mbgl/algorithm/update_renderables.hpp +++ b/src/mbgl/algorithm/update_renderables.hpp @@ -38,7 +38,7 @@ void updateRenderables(GetTileFn getTile, tile = createTile(idealDataTileID); // For source types where TileJSON.bounds is set, tiles outside the // bounds are not created - if(tile == nullptr) { + if (tile == nullptr) { continue; } } @@ -75,8 +75,8 @@ void updateRenderables(GetTileFn getTile, retainTile(*tile, TileNecessity::Optional); renderTile(childDataTileID.toUnwrapped(), *tile); } else { - // At least one child tile doesn't exist, so we are going to look for - // parents as well. + // At least one child tile doesn't exist, so we are + // going to look for parents as well. covered = false; } } @@ -87,15 +87,16 @@ void updateRenderables(GetTileFn getTile, for (overscaledZ = idealDataTileID.overscaledZ - 1; overscaledZ >= zoomRange.min; --overscaledZ) { const auto parentDataTileID = idealDataTileID.scaledTo(overscaledZ); - // Request / render parent tile only if it's overscale factor is less than defined maximum. + // Request / render parent tile only if it's overscale + // factor is less than defined maximum. if (maxParentOverscaleFactor && (idealDataTileID.overscaledZ - overscaledZ) > *maxParentOverscaleFactor) { break; } if (checked.find(parentDataTileID) != checked.end()) { - // Break parent tile ascent, this route has been checked by another child - // tile before. + // Break parent tile ascent, this route has been checked + // by another child tile before. break; } else { checked.emplace(parentDataTileID); @@ -108,17 +109,19 @@ void updateRenderables(GetTileFn getTile, if (tile) { if (!parentIsLoaded) { - // We haven't completed loading the child, so we only do an optional - // (cache) request in an attempt to quickly load data that we can show. + // We haven't completed loading the child, so we + // only do an optional (cache) request in an attempt + // to quickly load data that we can show. retainTile(*tile, TileNecessity::Optional); } else { - // Now that we've checked the child and know for sure that we can't load - // it, we attempt to load the parent from the network. + // Now that we've checked the child and know for + // sure that we can't load it, we attempt to load + // the parent from the network. retainTile(*tile, TileNecessity::Required); } - // Save the current values, since they're the parent of the next iteration - // of the parent tile ascent loop. + // Save the current values, since they're the parent of + // the next iteration of the parent tile ascent loop. parentHasTriedOptional = tile->hasTriedCache(); parentIsLoaded = tile->isLoaded(); diff --git a/src/mbgl/algorithm/update_tile_masks.hpp b/src/mbgl/algorithm/update_tile_masks.hpp index 000be1606c2..fa13923c358 100644 --- a/src/mbgl/algorithm/update_tile_masks.hpp +++ b/src/mbgl/algorithm/update_tile_masks.hpp @@ -10,21 +10,27 @@ namespace mbgl { namespace algorithm { template -bool tileNeedsMask(const std::reference_wrapper& tile) { return tile.get().usedByRenderedLayers; } -template -void setTileMask(const std::reference_wrapper& tile, TileMask&& mask ) { return tile.get().setMask(std::move(mask)); } +bool tileNeedsMask(const std::reference_wrapper& tile) { + return tile.get().usedByRenderedLayers; +} +template +void setTileMask(const std::reference_wrapper& tile, TileMask&& mask) { + return tile.get().setMask(std::move(mask)); +} // Overloads for tests -template bool tileNeedsMask(const T& tile) { return tile.usedByRenderedLayers; } -template void setTileMask(T& tile, TileMask&& mask ) { return tile.setMask(std::move(mask)); } +template +bool tileNeedsMask(const T& tile) { + return tile.usedByRenderedLayers; +} +template +void setTileMask(T& tile, TileMask&& mask) { + return tile.setMask(std::move(mask)); +} template void computeTileMasks( - const CanonicalTileID& root, - const UnwrappedTileID& ref, - const Iterator begin, - const Iterator end, - TileMask& mask) { + const CanonicalTileID& root, const UnwrappedTileID& ref, const Iterator begin, const Iterator end, TileMask& mask) { // If the reference or any of its children is found in the list, we need to recurse. for (auto it = begin; it != end; ++it) { const UnwrappedTileID& id = it->first; @@ -35,7 +41,7 @@ void computeTileMasks( if (ref == id) { // The current tile is masked out, so we don't need to add them to the mask set. return; - } + } if (id.isChildOf(ref)) { // There's at least one child tile that is masked out, so recursively descend. @@ -47,17 +53,19 @@ void computeTileMasks( } // We couldn't find a child, so it's definitely a masked part. - // Compute the difference between the root tile ID and the reference tile ID, since TileMask - // elements are always relative (see below for explanation). + // Compute the difference between the root tile ID and the reference tile + // ID, since TileMask elements are always relative (see below for + // explanation). const uint8_t diffZ = ref.canonical.z - root.z; mask.emplace(diffZ, ref.canonical.x - (root.x << diffZ), ref.canonical.y - (root.y << diffZ)); } -// Updates the TileMasks for all renderable tiles. Each renderable tile has a corresponding UnwrappedTileID -// indicating where it should be rendered on the screen. A TileMask describes all regions -// within a renderable tile that are *not* covered by other renderable tiles. -// Example: Renderable tiles in our list are 2/1/3, 3/3/6, and 4/5/13. The schematic for creating the -// TileMask for 2/1/3 looks like this: +// Updates the TileMasks for all renderable tiles. Each renderable tile has a +// corresponding UnwrappedTileID indicating where it should be rendered on the +// screen. A TileMask describes all regions within a renderable tile that are +// *not* covered by other renderable tiles. Example: Renderable tiles in our +// list are 2/1/3, 3/3/6, and 4/5/13. The schematic for creating the TileMask +// for 2/1/3 looks like this: // // ┌────────┬────────┬─────────────────┐ // │ │ │#################│ @@ -77,10 +85,11 @@ void computeTileMasks( // │ │ │ // └─────────────────┴─────────────────┘ // -// The TileMask for 2/1/3 thus consists of the tiles 4/4/12, 4/5/12, 4/4/13, 3/2/7, and 3/3/7, -// but it does *not* include 4/5/13, and 3/3/6, since these are other renderable tiles. -// A TileMask always contains TileIDs *relative* to the tile it is generated for, so 2/1/3 is -// "subtracted" from these TileIDs. The final TileMask for 2/1/3 will thus be: +// The TileMask for 2/1/3 thus consists of the tiles 4/4/12, 4/5/12, 4/4/13, +// 3/2/7, and 3/3/7, but it does *not* include 4/5/13, and 3/3/6, since these +// are other renderable tiles. A TileMask always contains TileIDs *relative* to +// the tile it is generated for, so 2/1/3 is "subtracted" from these TileIDs. +// The final TileMask for 2/1/3 will thus be: // // ┌────────┬────────┬─────────────────┐ // │ │ │#################│ @@ -100,9 +109,10 @@ void computeTileMasks( // │ │ │ // └─────────────────┴─────────────────┘ // -// Only other renderable tiles that are *children* of the renderable tile we are generating the mask for will -// will be considered. For example, adding a renderable tile with TileID 4/8/13 won't affect the TileMask for -// 2/1/3, since it is not a descendant of it. +// Only other renderable tiles that are *children* of the renderable tile we are +// generating the mask for will will be considered. For example, adding a +// renderable tile with TileID 4/8/13 won't affect the TileMask for 2/1/3, since +// it is not a descendant of it. template void updateTileMasks(RenderableTilesMap& renderables) { TileMask mask; @@ -113,14 +123,15 @@ void updateTileMasks(RenderableTilesMap& renderables) { continue; } // Try to add all remaining ids as children. We sorted the tile list - // by z earlier, so all preceding items cannot be children of the current - // tile. We also compute the lower bound of the next wrap, because items of the next wrap - // can never be children of the current wrap. + // by z earlier, so all preceding items cannot be children of the + // current tile. We also compute the lower bound of the next wrap, + // because items of the next wrap can never be children of the current + // wrap. auto child_it = std::next(it); const auto children_end = std::lower_bound( - child_it, end, - UnwrappedTileID{ static_cast(id.wrap + 1), { 0, 0, 0 } }, - [](auto& a, auto& b) { return a.first < b; }); + child_it, end, UnwrappedTileID{static_cast(id.wrap + 1), {0, 0, 0}}, [](auto& a, auto& b) { + return a.first < b; + }); mask.clear(); computeTileMasks(id.canonical, id, child_it, children_end, mask); diff --git a/src/mbgl/annotation/annotation_manager.cpp b/src/mbgl/annotation/annotation_manager.cpp index b890a24c33c..1121a24eff6 100644 --- a/src/mbgl/annotation/annotation_manager.cpp +++ b/src/mbgl/annotation/annotation_manager.cpp @@ -18,15 +18,15 @@ // at compile time, so that linker (with LTO on) is able // to optimize out the unreachable code. #define CHECK_ANNOTATIONS_ENABLED_AND_RETURN_NOARG() \ -if (!LayerManager::annotationsEnabled) { \ - assert(false); \ - return; \ -} + if (!LayerManager::annotationsEnabled) { \ + assert(false); \ + return; \ + } #define CHECK_ANNOTATIONS_ENABLED_AND_RETURN(result) \ -if (!LayerManager::annotationsEnabled) { \ - assert(false); \ - return result; \ -} + if (!LayerManager::annotationsEnabled) { \ + assert(false); \ + return result; \ + } namespace mbgl { @@ -37,8 +37,7 @@ const std::string AnnotationManager::PointLayerID = "com.mapbox.annotations.poin const std::string AnnotationManager::ShapeLayerID = "com.mapbox.annotations.shape."; AnnotationManager::AnnotationManager(Style& style_) - : style(style_) { -}; + : style(style_){}; AnnotationManager::~AnnotationManager() = default; @@ -56,9 +55,7 @@ AnnotationID AnnotationManager::addAnnotation(const Annotation& annotation) { CHECK_ANNOTATIONS_ENABLED_AND_RETURN(nextID++); std::lock_guard lock(mutex); AnnotationID id = nextID++; - Annotation::visit(annotation, [&] (const auto& annotation_) { - this->add(id, annotation_); - }); + Annotation::visit(annotation, [&](const auto& annotation_) { this->add(id, annotation_); }); dirty = true; return id; } @@ -66,9 +63,7 @@ AnnotationID AnnotationManager::addAnnotation(const Annotation& annotation) { bool AnnotationManager::updateAnnotation(const AnnotationID& id, const Annotation& annotation) { CHECK_ANNOTATIONS_ENABLED_AND_RETURN(true); std::lock_guard lock(mutex); - Annotation::visit(annotation, [&] (const auto& annotation_) { - this->update(id, annotation_); - }); + Annotation::visit(annotation, [&](const auto& annotation_) { this->update(id, annotation_); }); return dirty; } @@ -86,14 +81,14 @@ void AnnotationManager::add(const AnnotationID& id, const SymbolAnnotation& anno } void AnnotationManager::add(const AnnotationID& id, const LineAnnotation& annotation) { - ShapeAnnotationImpl& impl = *shapeAnnotations.emplace(id, - std::make_unique(id, annotation)).first->second; + ShapeAnnotationImpl& impl = + *shapeAnnotations.emplace(id, std::make_unique(id, annotation)).first->second; impl.updateStyle(*style.get().impl); } void AnnotationManager::add(const AnnotationID& id, const FillAnnotation& annotation) { - ShapeAnnotationImpl& impl = *shapeAnnotations.emplace(id, - std::make_unique(id, annotation)).first->second; + ShapeAnnotationImpl& impl = + *shapeAnnotations.emplace(id, std::make_unique(id, annotation)).first->second; impl.updateStyle(*style.get().impl); } @@ -153,8 +148,7 @@ void AnnotationManager::remove(const AnnotationID& id) { } std::unique_ptr AnnotationManager::getTileData(const CanonicalTileID& tileID) { - if (symbolAnnotations.empty() && shapeAnnotations.empty()) - return nullptr; + if (symbolAnnotations.empty() && shapeAnnotations.empty()) return nullptr; auto tileData = std::make_unique(); @@ -167,11 +161,10 @@ std::unique_ptr AnnotationManager::getTileData(const Canonic // The rendering/querying logic will make sure the symbols show up in only one of the tiles tileBounds.extend(LatLng(tileBounds.south() - 0.000000001, tileBounds.west() - 0.000000001)); tileBounds.extend(LatLng(tileBounds.north() + 0.000000001, tileBounds.east() + 0.000000001)); - - symbolTree.query(boost::geometry::index::intersects(tileBounds), - boost::make_function_output_iterator([&](const auto& val){ - val->updateLayer(tileID, *pointLayer); - })); + + symbolTree.query( + boost::geometry::index::intersects(tileBounds), + boost::make_function_output_iterator([&](const auto& val) { val->updateLayer(tileID, *pointLayer); })); for (const auto& shape : shapeAnnotations) { shape.second->updateTileData(tileID, *tileData); @@ -181,8 +174,9 @@ std::unique_ptr AnnotationManager::getTileData(const Canonic } void AnnotationManager::updateStyle() { - // Create annotation source, point layer, and point bucket. We do everything via Style::Impl - // because we don't want annotation mutations to trigger Style::Impl::styleMutated to be set. + // Create annotation source, point layer, and point bucket. We do everything + // via Style::Impl because we don't want annotation mutations to trigger + // Style::Impl::styleMutated to be set. if (!style.get().impl->getSource(SourceID)) { style.get().impl->addSource(std::make_unique()); @@ -205,11 +199,12 @@ void AnnotationManager::updateStyle() { } for (const auto& image : images) { - // Call addImage even for images we may have previously added, because we must support - // addAnnotationImage being used to update an existing image. Creating a new image is - // relatively cheap, as it copies only the Immutable reference. (We can't keep track - // of which images need to be added because we don't know if the style is the same - // instance as in the last updateStyle call. If it's a new style, we need to add all + // Call addImage even for images we may have previously added, because + // we must support addAnnotationImage being used to update an existing + // image. Creating a new image is relatively cheap, as it copies only + // the Immutable reference. (We can't keep track of which images need to + // be added because we don't know if the style is the same instance as + // in the last updateStyle call. If it's a new style, we need to add all // images.) style.get().impl->addImage(std::make_unique(image.second)); } @@ -250,8 +245,8 @@ void AnnotationManager::addImage(std::unique_ptr image) { std::lock_guard lock(mutex); const std::string id = prefixedImageID(image->getID()); images.erase(id); - auto inserted = images.emplace(id, style::Image(id, image->getImage().clone(), - image->getPixelRatio(), image->isSdf())); + auto inserted = images.emplace(id, + style::Image(id, image->getImage().clone(), image->getPixelRatio(), image->isSdf())); style.get().impl->addImage(std::make_unique(inserted.first->second)); } diff --git a/src/mbgl/annotation/annotation_manager.hpp b/src/mbgl/annotation/annotation_manager.hpp index 57f27c63528..0bfe89546a1 100644 --- a/src/mbgl/annotation/annotation_manager.hpp +++ b/src/mbgl/annotation/annotation_manager.hpp @@ -72,12 +72,14 @@ class AnnotationManager : private util::noncopyable { std::mutex mutex; bool dirty = false; - + AnnotationID nextID = 0; - using SymbolAnnotationTree = boost::geometry::index::rtree, boost::geometry::index::rstar<16, 4>>; - // Unlike std::unordered_map, std::map is guaranteed to sort by AnnotationID, ensuring that older annotations are below newer annotations. - // + using SymbolAnnotationTree = boost::geometry::index::rtree, + boost::geometry::index::rstar<16, 4>>; + // Unlike std::unordered_map, std::map is guaranteed to sort by + // AnnotationID, ensuring that older annotations are below newer + // annotations. using SymbolAnnotationMap = std::map>; using ShapeAnnotationMap = std::map>; using ImageMap = std::unordered_map; diff --git a/src/mbgl/annotation/annotation_source.cpp b/src/mbgl/annotation/annotation_source.cpp index 19a33bb02ac..7c55c412b59 100644 --- a/src/mbgl/annotation/annotation_source.cpp +++ b/src/mbgl/annotation/annotation_source.cpp @@ -7,12 +7,10 @@ namespace mbgl { using namespace style; AnnotationSource::AnnotationSource() - : Source(makeMutable()) { -} + : Source(makeMutable()) {} AnnotationSource::Impl::Impl() - : Source::Impl(SourceType::Annotations, AnnotationManager::SourceID) { -} + : Source::Impl(SourceType::Annotations, AnnotationManager::SourceID) {} const AnnotationSource::Impl& AnnotationSource::impl() const { return static_cast(*baseImpl); diff --git a/src/mbgl/annotation/annotation_source.hpp b/src/mbgl/annotation/annotation_source.hpp index 3d1cd33ec3e..65b2a83e2c1 100644 --- a/src/mbgl/annotation/annotation_source.hpp +++ b/src/mbgl/annotation/annotation_source.hpp @@ -18,10 +18,8 @@ class AnnotationSource final : public style::Source { private: void loadDescription(FileSource&) final; bool supportsLayerType(const mbgl::style::LayerTypeInfo*) const override; - mapbox::base::WeakPtr makeWeakPtr() override { - return weakFactory.makeWeakPtr(); - } - mapbox::base::WeakPtrFactory weakFactory {this}; + mapbox::base::WeakPtr makeWeakPtr() override { return weakFactory.makeWeakPtr(); } + mapbox::base::WeakPtrFactory weakFactory{this}; }; class AnnotationSource::Impl : public style::Source::Impl { diff --git a/src/mbgl/annotation/annotation_tile.cpp b/src/mbgl/annotation/annotation_tile.cpp index aa910ae54ce..c52fd938208 100644 --- a/src/mbgl/annotation/annotation_tile.cpp +++ b/src/mbgl/annotation/annotation_tile.cpp @@ -7,8 +7,7 @@ namespace mbgl { -AnnotationTile::AnnotationTile(const OverscaledTileID& overscaledTileID, - const TileParameters& parameters) +AnnotationTile::AnnotationTile(const OverscaledTileID& overscaledTileID, const TileParameters& parameters) : GeometryTile(overscaledTileID, AnnotationManager::SourceID, parameters), annotationManager(parameters.annotationManager) { auto guard = annotationManager.lock(); @@ -33,8 +32,7 @@ class AnnotationTileFeatureData { : id(id_), type(type_), geometries(std::move(geometries_)), - properties(std::move(properties_)) { - } + properties(std::move(properties_)) {} AnnotationID id; FeatureType type; @@ -43,8 +41,7 @@ class AnnotationTileFeatureData { }; AnnotationTileFeature::AnnotationTileFeature(std::shared_ptr data_) - : data(std::move(data_)) { -} + : data(std::move(data_)) {} AnnotationTileFeature::~AnnotationTileFeature() = default; @@ -70,14 +67,15 @@ const GeometryCollection& AnnotationTileFeature::getGeometries() const { class AnnotationTileLayerData { public: - explicit AnnotationTileLayerData(std::string name_) : name(std::move(name_)) {} + explicit AnnotationTileLayerData(std::string name_) + : name(std::move(name_)) {} const std::string name; std::vector> features; }; -AnnotationTileLayer::AnnotationTileLayer(std::shared_ptr layer_) : layer(std::move(layer_)) { -} +AnnotationTileLayer::AnnotationTileLayer(std::shared_ptr layer_) + : layer(std::move(layer_)) {} std::size_t AnnotationTileLayer::featureCount() const { return layer->features.size(); @@ -95,9 +93,8 @@ void AnnotationTileLayer::addFeature(const AnnotationID id, FeatureType type, GeometryCollection geometries, std::unordered_map properties) { - - layer->features.emplace_back(std::make_shared( - id, type, std::move(geometries), std::move(properties))); + layer->features.emplace_back( + std::make_shared(id, type, std::move(geometries), std::move(properties))); } std::unique_ptr AnnotationTileData::clone() const { diff --git a/src/mbgl/annotation/fill_annotation_impl.cpp b/src/mbgl/annotation/fill_annotation_impl.cpp index 59b8133cf78..bc9ba63b255 100644 --- a/src/mbgl/annotation/fill_annotation_impl.cpp +++ b/src/mbgl/annotation/fill_annotation_impl.cpp @@ -9,8 +9,10 @@ using namespace style; FillAnnotationImpl::FillAnnotationImpl(AnnotationID id_, FillAnnotation annotation_) : ShapeAnnotationImpl(id_), - annotation(ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), annotation_.opacity, annotation_.color, annotation_.outlineColor) { -} + annotation(ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), + annotation_.opacity, + annotation_.color, + annotation_.outlineColor) {} void FillAnnotationImpl::updateStyle(Style::Impl& style) const { Layer* layer = style.getLayer(layerID); diff --git a/src/mbgl/annotation/line_annotation_impl.cpp b/src/mbgl/annotation/line_annotation_impl.cpp index 533a137a3df..74fb00a0475 100644 --- a/src/mbgl/annotation/line_annotation_impl.cpp +++ b/src/mbgl/annotation/line_annotation_impl.cpp @@ -9,8 +9,10 @@ using namespace style; LineAnnotationImpl::LineAnnotationImpl(AnnotationID id_, LineAnnotation annotation_) : ShapeAnnotationImpl(id_), - annotation(ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), annotation_.opacity, annotation_.width, annotation_.color) { -} + annotation(ShapeAnnotationGeometry::visit(annotation_.geometry, CloseShapeAnnotation{}), + annotation_.opacity, + annotation_.width, + annotation_.color) {} void LineAnnotationImpl::updateStyle(Style::Impl& style) const { Layer* layer = style.getLayer(layerID); diff --git a/src/mbgl/annotation/render_annotation_source.cpp b/src/mbgl/annotation/render_annotation_source.cpp index 3cd74b0258e..1333c39a11e 100644 --- a/src/mbgl/annotation/render_annotation_source.cpp +++ b/src/mbgl/annotation/render_annotation_source.cpp @@ -42,12 +42,12 @@ void RenderAnnotationSource::update(Immutable baseImpl_, [&](const OverscaledTileID& tileID) { return std::make_unique(tileID, parameters); }); } -std::unordered_map> -RenderAnnotationSource::queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const { +std::unordered_map> RenderAnnotationSource::queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const { return tilePyramid.queryRenderedFeatures(geometry, transformState, layers, options, projMatrix, {}); } @@ -55,5 +55,4 @@ std::vector RenderAnnotationSource::querySourceFeatures(const SourceQue return {}; } - } // namespace mbgl diff --git a/src/mbgl/annotation/render_annotation_source.hpp b/src/mbgl/annotation/render_annotation_source.hpp index c920d760c2c..23187b6c31e 100644 --- a/src/mbgl/annotation/render_annotation_source.hpp +++ b/src/mbgl/annotation/render_annotation_source.hpp @@ -15,15 +15,14 @@ class RenderAnnotationSource final : public RenderTileSource { bool needsRelayout, const TileParameters&) final; - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const final; - - std::vector - querySourceFeatures(const SourceQueryOptions&) const final; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const final; + + std::vector querySourceFeatures(const SourceQueryOptions&) const final; private: const AnnotationSource::Impl& impl() const; diff --git a/src/mbgl/annotation/shape_annotation_impl.cpp b/src/mbgl/annotation/shape_annotation_impl.cpp index 0da98acb84c..7981438309d 100644 --- a/src/mbgl/annotation/shape_annotation_impl.cpp +++ b/src/mbgl/annotation/shape_annotation_impl.cpp @@ -14,8 +14,7 @@ using namespace style; ShapeAnnotationImpl::ShapeAnnotationImpl(const AnnotationID id_) : id(id_), - layerID(AnnotationManager::ShapeLayerID + util::toString(id)) { -} + layerID(AnnotationManager::ShapeLayerID + util::toString(id)) {} void ShapeAnnotationImpl::updateTileData(const CanonicalTileID& tileID, AnnotationTileData& data) { static const double baseTolerance = 4; @@ -25,8 +24,8 @@ void ShapeAnnotationImpl::updateTileData(const CanonicalTileID& tileID, Annotati features.emplace_back(ShapeAnnotationGeometry::visit( geometry(), [](auto&& geom) { return Feature{std::forward(geom)}; })); mapbox::geojsonvt::Options options; - // The annotation source is currently hard coded to maxzoom 16, so we're topping out at z16 - // here as well. + // The annotation source is currently hard coded to maxzoom 16, so we're + // topping out at z16 here as well. options.maxZoom = 16; options.buffer = 255u; options.extent = util::EXTENT; @@ -35,8 +34,7 @@ void ShapeAnnotationImpl::updateTileData(const CanonicalTileID& tileID, Annotati } const auto& shapeTile = shapeTiler->getTile(tileID.z, tileID.x, tileID.y); - if (shapeTile.features.empty()) - return; + if (shapeTile.features.empty()) return; auto layer = data.addLayer(layerID); diff --git a/src/mbgl/annotation/shape_annotation_impl.hpp b/src/mbgl/annotation/shape_annotation_impl.hpp index 64007d4fa1c..b18c2ab845c 100644 --- a/src/mbgl/annotation/shape_annotation_impl.hpp +++ b/src/mbgl/annotation/shape_annotation_impl.hpp @@ -20,10 +20,10 @@ class ShapeAnnotationImpl { ShapeAnnotationImpl(AnnotationID); virtual ~ShapeAnnotationImpl() = default; - virtual void updateStyle(style::Style::Impl&) const = 0; - virtual const ShapeAnnotationGeometry& geometry() const = 0; + virtual void updateStyle(style::Style::Impl &) const = 0; + virtual const ShapeAnnotationGeometry &geometry() const = 0; - void updateTileData(const CanonicalTileID&, AnnotationTileData&); + void updateTileData(const CanonicalTileID &, AnnotationTileData &); const AnnotationID id; const std::string layerID; @@ -31,12 +31,8 @@ class ShapeAnnotationImpl { }; struct CloseShapeAnnotation { - ShapeAnnotationGeometry operator()(const mbgl::LineString &geom) const { - return geom; - } - ShapeAnnotationGeometry operator()(const mbgl::MultiLineString &geom) const { - return geom; - } + ShapeAnnotationGeometry operator()(const mbgl::LineString &geom) const { return geom; } + ShapeAnnotationGeometry operator()(const mbgl::MultiLineString &geom) const { return geom; } ShapeAnnotationGeometry operator()(const mbgl::Polygon &geom) const { mbgl::Polygon closed = geom; for (auto &ring : closed) { diff --git a/src/mbgl/annotation/symbol_annotation_impl.cpp b/src/mbgl/annotation/symbol_annotation_impl.cpp index c95eb481b5a..44ad7b4b7c2 100644 --- a/src/mbgl/annotation/symbol_annotation_impl.cpp +++ b/src/mbgl/annotation/symbol_annotation_impl.cpp @@ -7,18 +7,17 @@ namespace mbgl { SymbolAnnotationImpl::SymbolAnnotationImpl(AnnotationID id_, SymbolAnnotation annotation_) -: id(id_), - annotation(std::move(annotation_)) { -} + : id(id_), + annotation(std::move(annotation_)) {} void SymbolAnnotationImpl::updateLayer(const CanonicalTileID& tileID, AnnotationTileLayer& layer) const { std::unordered_map featureProperties; featureProperties.emplace("sprite", annotation.icon.empty() ? std::string("default_marker") : annotation.icon); - LatLng latLng { annotation.geometry.y, annotation.geometry.x }; + LatLng latLng{annotation.geometry.y, annotation.geometry.x}; TileCoordinate coordinate = TileCoordinate::fromLatLng(0, latLng); GeometryCoordinate tilePoint = TileCoordinate::toGeometryCoordinate(UnwrappedTileID(0, tileID), coordinate.p); - layer.addFeature(id, FeatureType::Point, GeometryCollection {{ {{ tilePoint }} }}, featureProperties); + layer.addFeature(id, FeatureType::Point, GeometryCollection{{{{tilePoint}}}}, featureProperties); } } // namespace mbgl diff --git a/src/mbgl/annotation/symbol_annotation_impl.hpp b/src/mbgl/annotation/symbol_annotation_impl.hpp index 928a6059574..9b26b7cff1f 100644 --- a/src/mbgl/annotation/symbol_annotation_impl.hpp +++ b/src/mbgl/annotation/symbol_annotation_impl.hpp @@ -35,30 +35,50 @@ namespace geometry { // Make Boost Geometry aware of our LatLng type namespace traits { -template<> struct tag { using type = point_tag; }; -template<> struct dimension : boost::mpl::int_<2> {}; -template<> struct coordinate_type { using type = double; }; -template<> struct coordinate_system { using type = boost::geometry::cs::cartesian; }; +template <> +struct tag { + using type = point_tag; +}; +template <> +struct dimension : boost::mpl::int_<2> {}; +template <> +struct coordinate_type { + using type = double; +}; +template <> +struct coordinate_system { + using type = boost::geometry::cs::cartesian; +}; -template<> struct access { static inline double get(mbgl::LatLng const& p) { return p.longitude(); } }; -template<> struct access { static inline double get(mbgl::LatLng const& p) { return p.latitude(); } }; +template <> +struct access { + static inline double get(mbgl::LatLng const& p) { return p.longitude(); } +}; +template <> +struct access { + static inline double get(mbgl::LatLng const& p) { return p.latitude(); } +}; -template<> struct tag { using type = box_tag; }; -template<> struct point_type { using type = mbgl::LatLng; }; +template <> +struct tag { + using type = box_tag; +}; +template <> +struct point_type { + using type = mbgl::LatLng; +}; template -struct indexed_access -{ +struct indexed_access { using ct = coordinate_type::type; static inline ct get(mbgl::LatLngBounds const& b) { return geometry::get(b.southwest()); } static inline void set(mbgl::LatLngBounds& b, ct const& value) { geometry::set(b.southwest(), value); } }; template -struct indexed_access -{ +struct indexed_access { using ct = coordinate_type::type; - static inline ct get(mbgl::LatLngBounds const& b) { return geometry::get(b.northeast()); } + static inline ct get(mbgl::LatLngBounds const& b) { return geometry::get(b.northeast()); } static inline void set(mbgl::LatLngBounds& b, ct const& value) { geometry::set(b.northeast(), value); } }; diff --git a/src/mbgl/geometry/anchor.hpp b/src/mbgl/geometry/anchor.hpp index 454d3ad0719..89cc4456a26 100644 --- a/src/mbgl/geometry/anchor.hpp +++ b/src/mbgl/geometry/anchor.hpp @@ -15,7 +15,9 @@ class Anchor { std::optional segment; Anchor(float x_, float y_, float angle_, std::optional segment_ = std::nullopt) - : point(x_, y_), angle(angle_), segment(std::move(segment_)) {} + : point(x_, y_), + angle(angle_), + segment(std::move(segment_)) {} }; using Anchors = std::vector; diff --git a/src/mbgl/geometry/debug_font_data.hpp b/src/mbgl/geometry/debug_font_data.hpp index 26c54cb4808..4ac7eaea7ea 100644 --- a/src/mbgl/geometry/debug_font_data.hpp +++ b/src/mbgl/geometry/debug_font_data.hpp @@ -3,100 +3,148 @@ #include #include -const int8_t simplex_1[] = { 5, 21, 5, 7, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2 }; -const int8_t simplex_2[] = { 4, 21, 4, 14, -1, -1, 12, 21, 12, 14 }; -const int8_t simplex_3[] = { 11, 25, 4, -7, -1, -1, 17, 25, 10, -7, -1, -1, 4, 12, 18, 12, -1, -1, 3, 6, 17, 6 }; -const int8_t simplex_4[] = { 8, 25, 8, -4, -1, -1, 12, 25, 12, -4, -1, -1, 17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3 }; -const int8_t simplex_5[] = { 21, 21, 3, 0, -1, -1, 8, 21, 10, 19, 10, 17, 9, 15, 7, 14, 5, 14, 3, 16, 3, 18, 4, 20, 6, 21, 8, 21, 10, 20, 13, 19, 16, 19, 19, 20, 21, 21, -1, -1, 17, 7, 15, 6, 14, 4, 14, 2, 16, 0, 18, 0, 20, 1, 21, 3, 21, 5, 19, 7, 17, 7 }; -const int8_t simplex_6[] = { 23, 12, 23, 13, 22, 14, 21, 14, 20, 13, 19, 11, 17, 6, 15, 3, 13, 1, 11, 0, 7, 0, 5, 1, 4, 2, 3, 4, 3, 6, 4, 8, 5, 9, 12, 13, 13, 14, 14, 16, 14, 18, 13, 20, 11, 21, 9, 20, 8, 18, 8, 16, 9, 13, 11, 10, 16, 3, 18, 1, 20, 0, 22, 0, 23, 1, 23, 2 }; -const int8_t simplex_7[] = { 5, 19, 4, 20, 5, 21, 6, 20, 6, 18, 5, 16, 4, 15 }; -const int8_t simplex_8[] = { 11, 25, 9, 23, 7, 20, 5, 16, 4, 11, 4, 7, 5, 2, 7, -2, 9, -5, 11, -7 }; -const int8_t simplex_9[] = { 3, 25, 5, 23, 7, 20, 9, 16, 10, 11, 10, 7, 9, 2, 7, -2, 5, -5, 3, -7 }; -const int8_t simplex_10[] = { 8, 21, 8, 9, -1, -1, 3, 18, 13, 12, -1, -1, 13, 18, 3, 12 }; -const int8_t simplex_11[] = { 13, 18, 13, 0, -1, -1, 4, 9, 22, 9 }; -const int8_t simplex_12[] = { 6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4 }; -const int8_t simplex_13[] = { 4, 9, 22, 9 }; -const int8_t simplex_14[] = { 5, 2, 4, 1, 5, 0, 6, 1, 5, 2 }; -const int8_t simplex_15[] = { 20, 25, 2, -7 }; -const int8_t simplex_16[] = { 9, 21, 6, 20, 4, 17, 3, 12, 3, 9, 4, 4, 6, 1, 9, 0, 11, 0, 14, 1, 16, 4, 17, 9, 17, 12, 16, 17, 14, 20, 11, 21, 9, 21 }; -const int8_t simplex_17[] = { 6, 17, 8, 18, 11, 21, 11, 0 }; -const int8_t simplex_18[] = { 4, 16, 4, 17, 5, 19, 6, 20, 8, 21, 12, 21, 14, 20, 15, 19, 16, 17, 16, 15, 15, 13, 13, 10, 3, 0, 17, 0 }; -const int8_t simplex_19[] = { 5, 21, 16, 21, 10, 13, 13, 13, 15, 12, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4 }; -const int8_t simplex_20[] = { 13, 21, 3, 7, 18, 7, -1, -1, 13, 21, 13, 0 }; -const int8_t simplex_21[] = { 15, 21, 5, 21, 4, 12, 5, 13, 8, 14, 11, 14, 14, 13, 16, 11, 17, 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4 }; -const int8_t simplex_22[] = { 16, 18, 15, 20, 12, 21, 10, 21, 7, 20, 5, 17, 4, 12, 4, 7, 5, 3, 7, 1, 10, 0, 11, 0, 14, 1, 16, 3, 17, 6, 17, 7, 16, 10, 14, 12, 11, 13, 10, 13, 7, 12, 5, 10, 4, 7 }; -const int8_t simplex_23[] = { 17, 21, 7, 0, -1, -1, 3, 21, 17, 21 }; -const int8_t simplex_24[] = { 8, 21, 5, 20, 4, 18, 4, 16, 5, 14, 7, 13, 11, 12, 14, 11, 16, 9, 17, 7, 17, 4, 16, 2, 15, 1, 12, 0, 8, 0, 5, 1, 4, 2, 3, 4, 3, 7, 4, 9, 6, 11, 9, 12, 13, 13, 15, 14, 16, 16, 16, 18, 15, 20, 12, 21, 8, 21 }; -const int8_t simplex_25[] = { 16, 14, 15, 11, 13, 9, 10, 8, 9, 8, 6, 9, 4, 11, 3, 14, 3, 15, 4, 18, 6, 20, 9, 21, 10, 21, 13, 20, 15, 18, 16, 14, 16, 9, 15, 4, 13, 1, 10, 0, 8, 0, 5, 1, 4, 3 }; -const int8_t simplex_26[] = { 5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2 }; -const int8_t simplex_27[] = { 5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4 }; -const int8_t simplex_28[] = { 20, 18, 4, 9, 20, 0 }; -const int8_t simplex_29[] = { 4, 12, 22, 12, -1, -1, 4, 6, 22, 6 }; -const int8_t simplex_30[] = { 4, 18, 20, 9, 4, 0 }; -const int8_t simplex_31[] = { 3, 16, 3, 17, 4, 19, 5, 20, 7, 21, 11, 21, 13, 20, 14, 19, 15, 17, 15, 15, 14, 13, 13, 12, 9, 10, 9, 7, -1, -1, 9, 2, 8, 1, 9, 0, 10, 1, 9, 2 }; -const int8_t simplex_32[] = { 18, 13, 17, 15, 15, 16, 12, 16, 10, 15, 9, 14, 8, 11, 8, 8, 9, 6, 11, 5, 14, 5, 16, 6, 17, 8, -1, -1, 12, 16, 10, 14, 9, 11, 9, 8, 10, 6, 11, 5, -1, -1, 18, 16, 17, 8, 17, 6, 19, 5, 21, 5, 23, 7, 24, 10, 24, 12, 23, 15, 22, 17, 20, 19, 18, 20, 15, 21, 12, 21, 9, 20, 7, 19, 5, 17, 4, 15, 3, 12, 3, 9, 4, 6, 5, 4, 7, 2, 9, 1, 12, 0, 15, 0, 18, 1, 20, 2, 21, 3, -1, -1, 19, 16, 18, 8, 18, 6, 19, 5 }; -const int8_t simplex_33[] = { 9, 21, 1, 0, -1, -1, 9, 21, 17, 0, -1, -1, 4, 7, 14, 7 }; -const int8_t simplex_34[] = { 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, -1, -1, 4, 11, 13, 11, 16, 10, 17, 9, 18, 7, 18, 4, 17, 2, 16, 1, 13, 0, 4, 0 }; -const int8_t simplex_35[] = { 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5 }; -const int8_t simplex_36[] = { 4, 21, 4, 0, -1, -1, 4, 21, 11, 21, 14, 20, 16, 18, 17, 16, 18, 13, 18, 8, 17, 5, 16, 3, 14, 1, 11, 0, 4, 0 }; -const int8_t simplex_37[] = { 4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11, -1, -1, 4, 0, 17, 0 }; -const int8_t simplex_38[] = { 4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11 }; -const int8_t simplex_39[] = { 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 18, 8, -1, -1, 13, 8, 18, 8 }; -const int8_t simplex_40[] = { 4, 21, 4, 0, -1, -1, 18, 21, 18, 0, -1, -1, 4, 11, 18, 11 }; -const int8_t simplex_41[] = { 4, 21, 4, 0 }; -const int8_t simplex_42[] = { 12, 21, 12, 5, 11, 2, 10, 1, 8, 0, 6, 0, 4, 1, 3, 2, 2, 5, 2, 7 }; -const int8_t simplex_43[] = { 4, 21, 4, 0, -1, -1, 18, 21, 4, 7, -1, -1, 9, 12, 18, 0 }; -const int8_t simplex_44[] = { 4, 21, 4, 0, -1, -1, 4, 0, 16, 0 }; -const int8_t simplex_45[] = { 4, 21, 4, 0, -1, -1, 4, 21, 12, 0, -1, -1, 20, 21, 12, 0, -1, -1, 20, 21, 20, 0 }; -const int8_t simplex_46[] = { 4, 21, 4, 0, -1, -1, 4, 21, 18, 0, -1, -1, 18, 21, 18, 0 }; -const int8_t simplex_47[] = { 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21 }; -const int8_t simplex_48[] = { 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 14, 17, 12, 16, 11, 13, 10, 4, 10 }; -const int8_t simplex_49[] = { 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, -1, -1, 12, 4, 18, -2 }; -const int8_t simplex_50[] = { 4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, 11, 4, 11, -1, -1, 11, 11, 18, 0 }; -const int8_t simplex_51[] = { 17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3 }; -const int8_t simplex_52[] = { 8, 21, 8, 0, -1, -1, 1, 21, 15, 21 }; -const int8_t simplex_53[] = { 4, 21, 4, 6, 5, 3, 7, 1, 10, 0, 12, 0, 15, 1, 17, 3, 18, 6, 18, 21 }; -const int8_t simplex_54[] = { 1, 21, 9, 0, -1, -1, 17, 21, 9, 0 }; -const int8_t simplex_55[] = { 2, 21, 7, 0, -1, -1, 12, 21, 7, 0, -1, -1, 12, 21, 17, 0, -1, -1, 22, 21, 17, 0 }; -const int8_t simplex_56[] = { 3, 21, 17, 0, -1, -1, 17, 21, 3, 0 }; -const int8_t simplex_57[] = { 1, 21, 9, 11, 9, 0, -1, -1, 17, 21, 9, 11 }; -const int8_t simplex_58[] = { 17, 21, 3, 0, -1, -1, 3, 21, 17, 21, -1, -1, 3, 0, 17, 0 }; -const int8_t simplex_59[] = { 4, 25, 4, -7, -1, -1, 5, 25, 5, -7, -1, -1, 4, 25, 11, 25, -1, -1, 4, -7, 11, -7 }; -const int8_t simplex_60[] = { 0, 21, 14, -3 }; -const int8_t simplex_61[] = { 9, 25, 9, -7, -1, -1, 10, 25, 10, -7, -1, -1, 3, 25, 10, 25, -1, -1, 3, -7, 10, -7 }; -const int8_t simplex_62[] = { 6, 15, 8, 18, 10, 15, -1, -1, 3, 12, 8, 17, 13, 12, -1, -1, 8, 17, 8, 0 }; -const int8_t simplex_63[] = { 0, -2, 16, -2 }; -const int8_t simplex_64[] = { 6, 21, 5, 20, 4, 18, 4, 16, 5, 15, 6, 16, 5, 17 }; -const int8_t simplex_65[] = { 15, 14, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_66[] = { 4, 21, 4, 0, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3 }; -const int8_t simplex_67[] = { 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_68[] = { 15, 21, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_69[] = { 3, 8, 15, 8, 15, 10, 14, 12, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_70[] = { 10, 21, 8, 21, 6, 20, 5, 17, 5, 0, -1, -1, 2, 14, 9, 14 }; -const int8_t simplex_71[] = { 15, 14, 15, -2, 14, -5, 13, -6, 11, -7, 8, -7, 6, -6, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_72[] = { 4, 21, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0 }; -const int8_t simplex_73[] = { 3, 21, 4, 20, 5, 21, 4, 22, 3, 21, -1, -1, 4, 14, 4, 0 }; -const int8_t simplex_74[] = { 5, 21, 6, 20, 7, 21, 6, 22, 5, 21, -1, -1, 6, 14, 6, -3, 5, -6, 3, -7, 1, -7 }; -const int8_t simplex_75[] = { 4, 21, 4, 0, -1, -1, 14, 14, 4, 4, -1, -1, 8, 8, 15, 0 }; -const int8_t simplex_76[] = { 4, 21, 4, 0 }; -const int8_t simplex_77[] = { 4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0, -1, -1, 15, 10, 18, 13, 20, 14, 23, 14, 25, 13, 26, 10, 26, 0 }; -const int8_t simplex_78[] = { 4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0 }; -const int8_t simplex_79[] = { 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3, 16, 6, 16, 8, 15, 11, 13, 13, 11, 14, 8, 14 }; -const int8_t simplex_80[] = { 4, 14, 4, -7, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3 }; -const int8_t simplex_81[] = { 15, 14, 15, -7, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3 }; -const int8_t simplex_82[] = { 4, 14, 4, 0, -1, -1, 4, 8, 5, 11, 7, 13, 9, 14, 12, 14 }; -const int8_t simplex_83[] = { 14, 11, 13, 13, 10, 14, 7, 14, 4, 13, 3, 11, 4, 9, 6, 8, 11, 7, 13, 6, 14, 4, 14, 3, 13, 1, 10, 0, 7, 0, 4, 1, 3, 3 }; -const int8_t simplex_84[] = { 5, 21, 5, 4, 6, 1, 8, 0, 10, 0, -1, -1, 2, 14, 9, 14 }; -const int8_t simplex_85[] = { 4, 14, 4, 4, 5, 1, 7, 0, 10, 0, 12, 1, 15, 4, -1, -1, 15, 14, 15, 0 }; -const int8_t simplex_86[] = { 2, 14, 8, 0, -1, -1, 14, 14, 8, 0 }; -const int8_t simplex_87[] = { 3, 14, 7, 0, -1, -1, 11, 14, 7, 0, -1, -1, 11, 14, 15, 0, -1, -1, 19, 14, 15, 0 }; -const int8_t simplex_88[] = { 3, 14, 14, 0, -1, -1, 14, 14, 3, 0 }; -const int8_t simplex_89[] = { 2, 14, 8, 0, -1, -1, 14, 14, 8, 0, 6, -4, 4, -6, 2, -7, 1, -7 }; -const int8_t simplex_90[] = { 14, 14, 3, 0, -1, -1, 3, 14, 14, 14, -1, -1, 3, 0, 14, 0 }; -const int8_t simplex_91[] = { 9, 25, 7, 24, 6, 23, 5, 21, 5, 19, 6, 17, 7, 16, 8, 14, 8, 12, 6, 10, -1, -1, 7, 24, 6, 22, 6, 20, 7, 18, 8, 17, 9, 15, 9, 13, 8, 11, 4, 9, 8, 7, 9, 5, 9, 3, 8, 1, 7, 0, 6, -2, 6, -4, 7, -6, -1, -1, 6, 8, 8, 6, 8, 4, 7, 2, 6, 1, 5, -1, 5, -3, 6, -5, 7, -6, 9, -7 }; -const int8_t simplex_92[] = { 4, 25, 4, -7 }; -const int8_t simplex_93[] = { 5, 25, 7, 24, 8, 23, 9, 21, 9, 19, 8, 17, 7, 16, 6, 14, 6, 12, 8, 10, -1, -1, 7, 24, 8, 22, 8, 20, 7, 18, 6, 17, 5, 15, 5, 13, 6, 11, 10, 9, 6, 7, 5, 5, 5, 3, 6, 1, 7, 0, 8, -2, 8, -4, 7, -6, -1, -1, 8, 8, 6, 6, 6, 4, 7, 2, 8, 1, 9, -1, 9, -3, 8, -5, 7, -6, 5, -7 }; -const int8_t simplex_94[] = { 3, 6, 3, 8, 4, 11, 6, 12, 8, 12, 10, 11, 14, 8, 16, 7, 18, 7, 20, 8, 21, 10, -1, -1, 3, 8, 4, 10, 6, 11, 8, 11, 10, 10, 14, 7, 16, 6, 18, 6, 20, 7, 21, 10, 21, 12 }; +const int8_t simplex_1[] = {5, 21, 5, 7, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2}; +const int8_t simplex_2[] = {4, 21, 4, 14, -1, -1, 12, 21, 12, 14}; +const int8_t simplex_3[] = {11, 25, 4, -7, -1, -1, 17, 25, 10, -7, -1, -1, 4, 12, 18, 12, -1, -1, 3, 6, 17, 6}; +const int8_t simplex_4[] = {8, 25, 8, -4, -1, -1, 12, 25, 12, -4, -1, -1, 17, 18, 15, 20, 12, 21, + 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, 13, 10, 15, 9, + 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3}; +const int8_t simplex_5[] = {21, 21, 3, 0, -1, -1, 8, 21, 10, 19, 10, 17, 9, 15, 7, 14, 5, 14, 3, 16, 3, + 18, 4, 20, 6, 21, 8, 21, 10, 20, 13, 19, 16, 19, 19, 20, 21, 21, -1, -1, 17, 7, + 15, 6, 14, 4, 14, 2, 16, 0, 18, 0, 20, 1, 21, 3, 21, 5, 19, 7, 17, 7}; +const int8_t simplex_6[] = {23, 12, 23, 13, 22, 14, 21, 14, 20, 13, 19, 11, 17, 6, 15, 3, 13, 1, 11, 0, 7, 0, 5, + 1, 4, 2, 3, 4, 3, 6, 4, 8, 5, 9, 12, 13, 13, 14, 14, 16, 14, 18, 13, 20, 11, 21, + 9, 20, 8, 18, 8, 16, 9, 13, 11, 10, 16, 3, 18, 1, 20, 0, 22, 0, 23, 1, 23, 2}; +const int8_t simplex_7[] = {5, 19, 4, 20, 5, 21, 6, 20, 6, 18, 5, 16, 4, 15}; +const int8_t simplex_8[] = {11, 25, 9, 23, 7, 20, 5, 16, 4, 11, 4, 7, 5, 2, 7, -2, 9, -5, 11, -7}; +const int8_t simplex_9[] = {3, 25, 5, 23, 7, 20, 9, 16, 10, 11, 10, 7, 9, 2, 7, -2, 5, -5, 3, -7}; +const int8_t simplex_10[] = {8, 21, 8, 9, -1, -1, 3, 18, 13, 12, -1, -1, 13, 18, 3, 12}; +const int8_t simplex_11[] = {13, 18, 13, 0, -1, -1, 4, 9, 22, 9}; +const int8_t simplex_12[] = {6, 1, 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4}; +const int8_t simplex_13[] = {4, 9, 22, 9}; +const int8_t simplex_14[] = {5, 2, 4, 1, 5, 0, 6, 1, 5, 2}; +const int8_t simplex_15[] = {20, 25, 2, -7}; +const int8_t simplex_16[] = {9, 21, 6, 20, 4, 17, 3, 12, 3, 9, 4, 4, 6, 1, 9, 0, 11, + 0, 14, 1, 16, 4, 17, 9, 17, 12, 16, 17, 14, 20, 11, 21, 9, 21}; +const int8_t simplex_17[] = {6, 17, 8, 18, 11, 21, 11, 0}; +const int8_t simplex_18[] = {4, 16, 4, 17, 5, 19, 6, 20, 8, 21, 12, 21, 14, 20, + 15, 19, 16, 17, 16, 15, 15, 13, 13, 10, 3, 0, 17, 0}; +const int8_t simplex_19[] = {5, 21, 16, 21, 10, 13, 13, 13, 15, 12, 16, 11, 17, 8, 17, + 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4}; +const int8_t simplex_20[] = {13, 21, 3, 7, 18, 7, -1, -1, 13, 21, 13, 0}; +const int8_t simplex_21[] = {15, 21, 5, 21, 4, 12, 5, 13, 8, 14, 11, 14, 14, 13, 16, 11, 17, + 8, 17, 6, 16, 3, 14, 1, 11, 0, 8, 0, 5, 1, 4, 2, 3, 4}; +const int8_t simplex_22[] = {16, 18, 15, 20, 12, 21, 10, 21, 7, 20, 5, 17, 4, 12, 4, 7, 5, 3, 7, 1, 10, 0, 11, + 0, 14, 1, 16, 3, 17, 6, 17, 7, 16, 10, 14, 12, 11, 13, 10, 13, 7, 12, 5, 10, 4, 7}; +const int8_t simplex_23[] = {17, 21, 7, 0, -1, -1, 3, 21, 17, 21}; +const int8_t simplex_24[] = {8, 21, 5, 20, 4, 18, 4, 16, 5, 14, 7, 13, 11, 12, 14, 11, 16, 9, 17, 7, + 17, 4, 16, 2, 15, 1, 12, 0, 8, 0, 5, 1, 4, 2, 3, 4, 3, 7, 4, 9, + 6, 11, 9, 12, 13, 13, 15, 14, 16, 16, 16, 18, 15, 20, 12, 21, 8, 21}; +const int8_t simplex_25[] = {16, 14, 15, 11, 13, 9, 10, 8, 9, 8, 6, 9, 4, 11, 3, 14, 3, 15, 4, 18, 6, 20, 9, + 21, 10, 21, 13, 20, 15, 18, 16, 14, 16, 9, 15, 4, 13, 1, 10, 0, 8, 0, 5, 1, 4, 3}; +const int8_t simplex_26[] = {5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 5, 2, 4, 1, 5, 0, 6, 1, 5, 2}; +const int8_t simplex_27[] = {5, 14, 4, 13, 5, 12, 6, 13, 5, 14, -1, -1, 6, 1, + 5, 0, 4, 1, 5, 2, 6, 1, 6, -1, 5, -3, 4, -4}; +const int8_t simplex_28[] = {20, 18, 4, 9, 20, 0}; +const int8_t simplex_29[] = {4, 12, 22, 12, -1, -1, 4, 6, 22, 6}; +const int8_t simplex_30[] = {4, 18, 20, 9, 4, 0}; +const int8_t simplex_31[] = {3, 16, 3, 17, 4, 19, 5, 20, 7, 21, 11, 21, 13, 20, 14, 19, 15, 17, 15, 15, + 14, 13, 13, 12, 9, 10, 9, 7, -1, -1, 9, 2, 8, 1, 9, 0, 10, 1, 9, 2}; +const int8_t simplex_32[] = {18, 13, 17, 15, 15, 16, 12, 16, 10, 15, 9, 14, 8, 11, 8, 8, 9, 6, 11, 5, 14, 5, + 16, 6, 17, 8, -1, -1, 12, 16, 10, 14, 9, 11, 9, 8, 10, 6, 11, 5, -1, -1, 18, 16, + 17, 8, 17, 6, 19, 5, 21, 5, 23, 7, 24, 10, 24, 12, 23, 15, 22, 17, 20, 19, 18, 20, + 15, 21, 12, 21, 9, 20, 7, 19, 5, 17, 4, 15, 3, 12, 3, 9, 4, 6, 5, 4, 7, 2, + 9, 1, 12, 0, 15, 0, 18, 1, 20, 2, 21, 3, -1, -1, 19, 16, 18, 8, 18, 6, 19, 5}; +const int8_t simplex_33[] = {9, 21, 1, 0, -1, -1, 9, 21, 17, 0, -1, -1, 4, 7, 14, 7}; +const int8_t simplex_34[] = {4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, 18, 15, 17, 13, 16, 12, 13, + 11, -1, -1, 4, 11, 13, 11, 16, 10, 17, 9, 18, 7, 18, 4, 17, 2, 16, 1, 13, 0, 4, 0}; +const int8_t simplex_35[] = {18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, + 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5}; +const int8_t simplex_36[] = {4, 21, 4, 0, -1, -1, 4, 21, 11, 21, 14, 20, 16, 18, 17, + 16, 18, 13, 18, 8, 17, 5, 16, 3, 14, 1, 11, 0, 4, 0}; +const int8_t simplex_37[] = {4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11, -1, -1, 4, 0, 17, 0}; +const int8_t simplex_38[] = {4, 21, 4, 0, -1, -1, 4, 21, 17, 21, -1, -1, 4, 11, 12, 11}; +const int8_t simplex_39[] = {18, 16, 17, 18, 15, 20, 13, 21, 9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, + 5, 3, 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 18, 8, -1, -1, 13, 8, 18, 8}; +const int8_t simplex_40[] = {4, 21, 4, 0, -1, -1, 18, 21, 18, 0, -1, -1, 4, 11, 18, 11}; +const int8_t simplex_41[] = {4, 21, 4, 0}; +const int8_t simplex_42[] = {12, 21, 12, 5, 11, 2, 10, 1, 8, 0, 6, 0, 4, 1, 3, 2, 2, 5, 2, 7}; +const int8_t simplex_43[] = {4, 21, 4, 0, -1, -1, 18, 21, 4, 7, -1, -1, 9, 12, 18, 0}; +const int8_t simplex_44[] = {4, 21, 4, 0, -1, -1, 4, 0, 16, 0}; +const int8_t simplex_45[] = {4, 21, 4, 0, -1, -1, 4, 21, 12, 0, -1, -1, 20, 21, 12, 0, -1, -1, 20, 21, 20, 0}; +const int8_t simplex_46[] = {4, 21, 4, 0, -1, -1, 4, 21, 18, 0, -1, -1, 18, 21, 18, 0}; +const int8_t simplex_47[] = {9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, 7, 1, 9, 0, 13, + 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, 18, 16, 17, 18, 15, 20, 13, 21, 9, 21}; +const int8_t simplex_48[] = {4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, + 19, 18, 17, 18, 14, 17, 12, 16, 11, 13, 10, 4, 10}; +const int8_t simplex_49[] = {9, 21, 7, 20, 5, 18, 4, 16, 3, 13, 3, 8, 4, 5, 5, 3, + 7, 1, 9, 0, 13, 0, 15, 1, 17, 3, 18, 5, 19, 8, 19, 13, + 18, 16, 17, 18, 15, 20, 13, 21, 9, 21, -1, -1, 12, 4, 18, -2}; +const int8_t simplex_50[] = {4, 21, 4, 0, -1, -1, 4, 21, 13, 21, 16, 20, 17, 19, 18, 17, + 18, 15, 17, 13, 16, 12, 13, 11, 4, 11, -1, -1, 11, 11, 18, 0}; +const int8_t simplex_51[] = {17, 18, 15, 20, 12, 21, 8, 21, 5, 20, 3, 18, 3, 16, 4, 14, 5, 13, 7, 12, + 13, 10, 15, 9, 16, 8, 17, 6, 17, 3, 15, 1, 12, 0, 8, 0, 5, 1, 3, 3}; +const int8_t simplex_52[] = {8, 21, 8, 0, -1, -1, 1, 21, 15, 21}; +const int8_t simplex_53[] = {4, 21, 4, 6, 5, 3, 7, 1, 10, 0, 12, 0, 15, 1, 17, 3, 18, 6, 18, 21}; +const int8_t simplex_54[] = {1, 21, 9, 0, -1, -1, 17, 21, 9, 0}; +const int8_t simplex_55[] = {2, 21, 7, 0, -1, -1, 12, 21, 7, 0, -1, -1, 12, 21, 17, 0, -1, -1, 22, 21, 17, 0}; +const int8_t simplex_56[] = {3, 21, 17, 0, -1, -1, 17, 21, 3, 0}; +const int8_t simplex_57[] = {1, 21, 9, 11, 9, 0, -1, -1, 17, 21, 9, 11}; +const int8_t simplex_58[] = {17, 21, 3, 0, -1, -1, 3, 21, 17, 21, -1, -1, 3, 0, 17, 0}; +const int8_t simplex_59[] = {4, 25, 4, -7, -1, -1, 5, 25, 5, -7, -1, -1, 4, 25, 11, 25, -1, -1, 4, -7, 11, -7}; +const int8_t simplex_60[] = {0, 21, 14, -3}; +const int8_t simplex_61[] = {9, 25, 9, -7, -1, -1, 10, 25, 10, -7, -1, -1, 3, 25, 10, 25, -1, -1, 3, -7, 10, -7}; +const int8_t simplex_62[] = {6, 15, 8, 18, 10, 15, -1, -1, 3, 12, 8, 17, 13, 12, -1, -1, 8, 17, 8, 0}; +const int8_t simplex_63[] = {0, -2, 16, -2}; +const int8_t simplex_64[] = {6, 21, 5, 20, 4, 18, 4, 16, 5, 15, 6, 16, 5, 17}; +const int8_t simplex_65[] = {15, 14, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_66[] = {4, 21, 4, 0, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, + 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3}; +const int8_t simplex_67[] = {15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, 11, 3, 8, + 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_68[] = {15, 21, 15, 0, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_69[] = {3, 8, 15, 8, 15, 10, 14, 12, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_70[] = {10, 21, 8, 21, 6, 20, 5, 17, 5, 0, -1, -1, 2, 14, 9, 14}; +const int8_t simplex_71[] = {15, 14, 15, -2, 14, -5, 13, -6, 11, -7, 8, -7, 6, -6, -1, -1, 15, 11, 13, 13, 11, 14, + 8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_72[] = {4, 21, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0}; +const int8_t simplex_73[] = {3, 21, 4, 20, 5, 21, 4, 22, 3, 21, -1, -1, 4, 14, 4, 0}; +const int8_t simplex_74[] = {5, 21, 6, 20, 7, 21, 6, 22, 5, 21, -1, -1, 6, 14, 6, -3, 5, -6, 3, -7, 1, -7}; +const int8_t simplex_75[] = {4, 21, 4, 0, -1, -1, 14, 14, 4, 4, -1, -1, 8, 8, 15, 0}; +const int8_t simplex_76[] = {4, 21, 4, 0}; +const int8_t simplex_77[] = {4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, + 15, 0, -1, -1, 15, 10, 18, 13, 20, 14, 23, 14, 25, 13, 26, 10, 26, 0}; +const int8_t simplex_78[] = {4, 14, 4, 0, -1, -1, 4, 10, 7, 13, 9, 14, 12, 14, 14, 13, 15, 10, 15, 0}; +const int8_t simplex_79[] = {8, 14, 6, 13, 4, 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, + 0, 13, 1, 15, 3, 16, 6, 16, 8, 15, 11, 13, 13, 11, 14, 8, 14}; +const int8_t simplex_80[] = {4, 14, 4, -7, -1, -1, 4, 11, 6, 13, 8, 14, 11, 14, 13, 13, 15, + 11, 16, 8, 16, 6, 15, 3, 13, 1, 11, 0, 8, 0, 6, 1, 4, 3}; +const int8_t simplex_81[] = {15, 14, 15, -7, -1, -1, 15, 11, 13, 13, 11, 14, 8, 14, 6, 13, 4, + 11, 3, 8, 3, 6, 4, 3, 6, 1, 8, 0, 11, 0, 13, 1, 15, 3}; +const int8_t simplex_82[] = {4, 14, 4, 0, -1, -1, 4, 8, 5, 11, 7, 13, 9, 14, 12, 14}; +const int8_t simplex_83[] = {14, 11, 13, 13, 10, 14, 7, 14, 4, 13, 3, 11, 4, 9, 6, 8, 11, + 7, 13, 6, 14, 4, 14, 3, 13, 1, 10, 0, 7, 0, 4, 1, 3, 3}; +const int8_t simplex_84[] = {5, 21, 5, 4, 6, 1, 8, 0, 10, 0, -1, -1, 2, 14, 9, 14}; +const int8_t simplex_85[] = {4, 14, 4, 4, 5, 1, 7, 0, 10, 0, 12, 1, 15, 4, -1, -1, 15, 14, 15, 0}; +const int8_t simplex_86[] = {2, 14, 8, 0, -1, -1, 14, 14, 8, 0}; +const int8_t simplex_87[] = {3, 14, 7, 0, -1, -1, 11, 14, 7, 0, -1, -1, 11, 14, 15, 0, -1, -1, 19, 14, 15, 0}; +const int8_t simplex_88[] = {3, 14, 14, 0, -1, -1, 14, 14, 3, 0}; +const int8_t simplex_89[] = {2, 14, 8, 0, -1, -1, 14, 14, 8, 0, 6, -4, 4, -6, 2, -7, 1, -7}; +const int8_t simplex_90[] = {14, 14, 3, 0, -1, -1, 3, 14, 14, 14, -1, -1, 3, 0, 14, 0}; +const int8_t simplex_91[] = {9, 25, 7, 24, 6, 23, 5, 21, 5, 19, 6, 17, 7, 16, 8, 14, 8, 12, 6, 10, + -1, -1, 7, 24, 6, 22, 6, 20, 7, 18, 8, 17, 9, 15, 9, 13, 8, 11, 4, 9, + 8, 7, 9, 5, 9, 3, 8, 1, 7, 0, 6, -2, 6, -4, 7, -6, -1, -1, 6, 8, + 8, 6, 8, 4, 7, 2, 6, 1, 5, -1, 5, -3, 6, -5, 7, -6, 9, -7}; +const int8_t simplex_92[] = {4, 25, 4, -7}; +const int8_t simplex_93[] = {5, 25, 7, 24, 8, 23, 9, 21, 9, 19, 8, 17, 7, 16, 6, 14, 6, 12, 8, 10, + -1, -1, 7, 24, 8, 22, 8, 20, 7, 18, 6, 17, 5, 15, 5, 13, 6, 11, 10, 9, + 6, 7, 5, 5, 5, 3, 6, 1, 7, 0, 8, -2, 8, -4, 7, -6, -1, -1, 8, 8, + 6, 6, 6, 4, 7, 2, 8, 1, 9, -1, 9, -3, 8, -5, 7, -6, 5, -7}; +const int8_t simplex_94[] = {3, 6, 3, 8, 4, 11, 6, 12, 8, 12, 10, 11, 14, 8, 16, 7, 18, 7, 20, 8, 21, 10, -1, + -1, 3, 8, 4, 10, 6, 11, 8, 11, 10, 10, 14, 7, 16, 6, 18, 6, 20, 7, 21, 10, 21, 12}; struct glyph { uint8_t width; @@ -108,99 +156,193 @@ struct glyph { // http://paulbourke.net/dataformats/hershey/ const glyph simplex[] = { - /* 32 */ { 16, 0, nullptr }, - /* 33 ! */ { 10, sizeof(simplex_1), simplex_1 }, - /* 34 " */ { 16, sizeof(simplex_2), simplex_2 }, - /* 35 # */ { 21, sizeof(simplex_3), simplex_3 }, - /* 36 $ */ { 20, sizeof(simplex_4), simplex_4 }, - /* 37 % */ { 24, sizeof(simplex_5), simplex_5 }, - /* 38 & */ { 26, sizeof(simplex_6), simplex_6 }, - /* 39 ' */ { 10, sizeof(simplex_7), simplex_7 }, - /* 40 ( */ { 14, sizeof(simplex_8), simplex_8 }, - /* 41 ) */ { 14, sizeof(simplex_9), simplex_9 }, - /* 42 * */ { 16, sizeof(simplex_10), simplex_10 }, - /* 43 + */ { 26, sizeof(simplex_11), simplex_11 }, - /* 44 , */ { 10, sizeof(simplex_12), simplex_12 }, - /* 45 - */ { 26, sizeof(simplex_13), simplex_13 }, - /* 46 . */ { 10, sizeof(simplex_14), simplex_14 }, - /* 47 / */ { 22, sizeof(simplex_15), simplex_15 }, - /* 48 0 */ { 20, sizeof(simplex_16), simplex_16 }, - /* 49 1 */ { 20, sizeof(simplex_17), simplex_17 }, - /* 50 2 */ { 20, sizeof(simplex_18), simplex_18 }, - /* 51 3 */ { 20, sizeof(simplex_19), simplex_19 }, - /* 52 4 */ { 20, sizeof(simplex_20), simplex_20 }, - /* 53 5 */ { 20, sizeof(simplex_21), simplex_21 }, - /* 54 6 */ { 20, sizeof(simplex_22), simplex_22 }, - /* 55 7 */ { 20, sizeof(simplex_23), simplex_23 }, - /* 56 8 */ { 20, sizeof(simplex_24), simplex_24 }, - /* 57 9 */ { 20, sizeof(simplex_25), simplex_25 }, - /* 58 : */ { 10, sizeof(simplex_26), simplex_26 }, - /* 59 ; */ { 10, sizeof(simplex_27), simplex_27 }, - /* 60 < */ { 24, sizeof(simplex_28), simplex_28 }, - /* 61 = */ { 26, sizeof(simplex_29), simplex_29 }, - /* 62 > */ { 24, sizeof(simplex_30), simplex_30 }, - /* 63 ? */ { 18, sizeof(simplex_31), simplex_31 }, - /* 64 @ */ { 27, sizeof(simplex_32), simplex_32 }, - /* 65 A */ { 18, sizeof(simplex_33), simplex_33 }, - /* 66 B */ { 21, sizeof(simplex_34), simplex_34 }, - /* 67 C */ { 21, sizeof(simplex_35), simplex_35 }, - /* 68 D */ { 21, sizeof(simplex_36), simplex_36 }, - /* 69 E */ { 19, sizeof(simplex_37), simplex_37 }, - /* 70 F */ { 18, sizeof(simplex_38), simplex_38 }, - /* 71 G */ { 21, sizeof(simplex_39), simplex_39 }, - /* 72 H */ { 22, sizeof(simplex_40), simplex_40 }, - /* 73 I */ { 8, sizeof(simplex_41), simplex_41 }, - /* 74 J */ { 16, sizeof(simplex_42), simplex_42 }, - /* 75 K */ { 21, sizeof(simplex_43), simplex_43 }, - /* 76 L */ { 17, sizeof(simplex_44), simplex_44 }, - /* 77 M */ { 24, sizeof(simplex_45), simplex_45 }, - /* 78 N */ { 22, sizeof(simplex_46), simplex_46 }, - /* 79 O */ { 22, sizeof(simplex_47), simplex_47 }, - /* 80 P */ { 21, sizeof(simplex_48), simplex_48 }, - /* 81 Q */ { 22, sizeof(simplex_49), simplex_49 }, - /* 82 R */ { 21, sizeof(simplex_50), simplex_50 }, - /* 83 S */ { 20, sizeof(simplex_51), simplex_51 }, - /* 84 T */ { 16, sizeof(simplex_52), simplex_52 }, - /* 85 U */ { 22, sizeof(simplex_53), simplex_53 }, - /* 86 V */ { 18, sizeof(simplex_54), simplex_54 }, - /* 87 W */ { 24, sizeof(simplex_55), simplex_55 }, - /* 88 X */ { 20, sizeof(simplex_56), simplex_56 }, - /* 89 Y */ { 18, sizeof(simplex_57), simplex_57 }, - /* 90 Z */ { 20, sizeof(simplex_58), simplex_58 }, - /* 91 [ */ { 14, sizeof(simplex_59), simplex_59 }, - /* 92 \ */ { 14, sizeof(simplex_60), simplex_60 }, - /* 93 ] */ { 14, sizeof(simplex_61), simplex_61 }, - /* 94 ^ */ { 16, sizeof(simplex_62), simplex_62 }, - /* 95 _ */ { 16, sizeof(simplex_63), simplex_63 }, - /* 96 ` */ { 10, sizeof(simplex_64), simplex_64 }, - /* 97 a */ { 19, sizeof(simplex_65), simplex_65 }, - /* 98 b */ { 19, sizeof(simplex_66), simplex_66 }, - /* 99 c */ { 18, sizeof(simplex_67), simplex_67 }, - /* 100 d */ { 19, sizeof(simplex_68), simplex_68 }, - /* 101 e */ { 18, sizeof(simplex_69), simplex_69 }, - /* 102 f */ { 12, sizeof(simplex_70), simplex_70 }, - /* 103 g */ { 19, sizeof(simplex_71), simplex_71 }, - /* 104 h */ { 19, sizeof(simplex_72), simplex_72 }, - /* 105 i */ { 8, sizeof(simplex_73), simplex_73 }, - /* 106 j */ { 10, sizeof(simplex_74), simplex_74 }, - /* 107 k */ { 17, sizeof(simplex_75), simplex_75 }, - /* 108 l */ { 8, sizeof(simplex_76), simplex_76 }, - /* 109 m */ { 30, sizeof(simplex_77), simplex_77 }, - /* 110 n */ { 19, sizeof(simplex_78), simplex_78 }, - /* 111 o */ { 19, sizeof(simplex_79), simplex_79 }, - /* 112 p */ { 19, sizeof(simplex_80), simplex_80 }, - /* 113 q */ { 19, sizeof(simplex_81), simplex_81 }, - /* 114 r */ { 13, sizeof(simplex_82), simplex_82 }, - /* 115 s */ { 17, sizeof(simplex_83), simplex_83 }, - /* 116 t */ { 12, sizeof(simplex_84), simplex_84 }, - /* 117 u */ { 19, sizeof(simplex_85), simplex_85 }, - /* 118 v */ { 16, sizeof(simplex_86), simplex_86 }, - /* 119 w */ { 22, sizeof(simplex_87), simplex_87 }, - /* 120 x */ { 17, sizeof(simplex_88), simplex_88 }, - /* 121 y */ { 16, sizeof(simplex_89), simplex_89 }, - /* 122 z */ { 17, sizeof(simplex_90), simplex_90 }, - /* 123 { */ { 14, sizeof(simplex_91), simplex_91 }, - /* 124 | */ { 8, sizeof(simplex_92), simplex_92 }, - /* 125 } */ { 14, sizeof(simplex_93), simplex_93 }, - /* 126 ~ */ { 24, sizeof(simplex_94), simplex_94 }, + /* 32 */ {16, 0, nullptr}, + /* 33 ! */ + {10, sizeof(simplex_1), simplex_1}, + /* 34 " */ + {16, sizeof(simplex_2), simplex_2}, + /* 35 # */ + {21, sizeof(simplex_3), simplex_3}, + /* 36 $ */ + {20, sizeof(simplex_4), simplex_4}, + /* 37 % */ + {24, sizeof(simplex_5), simplex_5}, + /* 38 & */ + {26, sizeof(simplex_6), simplex_6}, + /* 39 ' */ + {10, sizeof(simplex_7), simplex_7}, + /* 40 ( */ + {14, sizeof(simplex_8), simplex_8}, + /* 41 ) */ + {14, sizeof(simplex_9), simplex_9}, + /* 42 * */ + {16, sizeof(simplex_10), simplex_10}, + /* 43 + */ + {26, sizeof(simplex_11), simplex_11}, + /* 44 , */ + {10, sizeof(simplex_12), simplex_12}, + /* 45 - */ + {26, sizeof(simplex_13), simplex_13}, + /* 46 . */ + {10, sizeof(simplex_14), simplex_14}, + /* 47 / */ + {22, sizeof(simplex_15), simplex_15}, + /* 48 0 */ + {20, sizeof(simplex_16), simplex_16}, + /* 49 1 */ + {20, sizeof(simplex_17), simplex_17}, + /* 50 2 */ + {20, sizeof(simplex_18), simplex_18}, + /* 51 3 */ + {20, sizeof(simplex_19), simplex_19}, + /* 52 4 */ + {20, sizeof(simplex_20), simplex_20}, + /* 53 5 */ + {20, sizeof(simplex_21), simplex_21}, + /* 54 6 */ + {20, sizeof(simplex_22), simplex_22}, + /* 55 7 */ + {20, sizeof(simplex_23), simplex_23}, + /* 56 8 */ + {20, sizeof(simplex_24), simplex_24}, + /* 57 9 */ + {20, sizeof(simplex_25), simplex_25}, + /* 58 : */ + {10, sizeof(simplex_26), simplex_26}, + /* 59 ; */ + {10, sizeof(simplex_27), simplex_27}, + /* 60 < */ + {24, sizeof(simplex_28), simplex_28}, + /* 61 = */ + {26, sizeof(simplex_29), simplex_29}, + /* 62 > */ + {24, sizeof(simplex_30), simplex_30}, + /* 63 ? */ + {18, sizeof(simplex_31), simplex_31}, + /* 64 @ */ + {27, sizeof(simplex_32), simplex_32}, + /* 65 A */ + {18, sizeof(simplex_33), simplex_33}, + /* 66 B */ + {21, sizeof(simplex_34), simplex_34}, + /* 67 C */ + {21, sizeof(simplex_35), simplex_35}, + /* 68 D */ + {21, sizeof(simplex_36), simplex_36}, + /* 69 E */ + {19, sizeof(simplex_37), simplex_37}, + /* 70 F */ + {18, sizeof(simplex_38), simplex_38}, + /* 71 G */ + {21, sizeof(simplex_39), simplex_39}, + /* 72 H */ + {22, sizeof(simplex_40), simplex_40}, + /* 73 I */ + {8, sizeof(simplex_41), simplex_41}, + /* 74 J */ + {16, sizeof(simplex_42), simplex_42}, + /* 75 K */ + {21, sizeof(simplex_43), simplex_43}, + /* 76 L */ + {17, sizeof(simplex_44), simplex_44}, + /* 77 M */ + {24, sizeof(simplex_45), simplex_45}, + /* 78 N */ + {22, sizeof(simplex_46), simplex_46}, + /* 79 O */ + {22, sizeof(simplex_47), simplex_47}, + /* 80 P */ + {21, sizeof(simplex_48), simplex_48}, + /* 81 Q */ + {22, sizeof(simplex_49), simplex_49}, + /* 82 R */ + {21, sizeof(simplex_50), simplex_50}, + /* 83 S */ + {20, sizeof(simplex_51), simplex_51}, + /* 84 T */ + {16, sizeof(simplex_52), simplex_52}, + /* 85 U */ + {22, sizeof(simplex_53), simplex_53}, + /* 86 V */ + {18, sizeof(simplex_54), simplex_54}, + /* 87 W */ + {24, sizeof(simplex_55), simplex_55}, + /* 88 X */ + {20, sizeof(simplex_56), simplex_56}, + /* 89 Y */ + {18, sizeof(simplex_57), simplex_57}, + /* 90 Z */ + {20, sizeof(simplex_58), simplex_58}, + /* 91 [ */ + {14, sizeof(simplex_59), simplex_59}, + /* 92 \ */ + {14, sizeof(simplex_60), simplex_60}, + /* 93 ] */ + {14, sizeof(simplex_61), simplex_61}, + /* 94 ^ */ + {16, sizeof(simplex_62), simplex_62}, + /* 95 _ */ + {16, sizeof(simplex_63), simplex_63}, + /* 96 ` */ + {10, sizeof(simplex_64), simplex_64}, + /* 97 a */ + {19, sizeof(simplex_65), simplex_65}, + /* 98 b */ + {19, sizeof(simplex_66), simplex_66}, + /* 99 c */ + {18, sizeof(simplex_67), simplex_67}, + /* 100 d */ + {19, sizeof(simplex_68), simplex_68}, + /* 101 e */ + {18, sizeof(simplex_69), simplex_69}, + /* 102 f */ + {12, sizeof(simplex_70), simplex_70}, + /* 103 g */ + {19, sizeof(simplex_71), simplex_71}, + /* 104 h */ + {19, sizeof(simplex_72), simplex_72}, + /* 105 i */ + {8, sizeof(simplex_73), simplex_73}, + /* 106 j */ + {10, sizeof(simplex_74), simplex_74}, + /* 107 k */ + {17, sizeof(simplex_75), simplex_75}, + /* 108 l */ + {8, sizeof(simplex_76), simplex_76}, + /* 109 m */ + {30, sizeof(simplex_77), simplex_77}, + /* 110 n */ + {19, sizeof(simplex_78), simplex_78}, + /* 111 o */ + {19, sizeof(simplex_79), simplex_79}, + /* 112 p */ + {19, sizeof(simplex_80), simplex_80}, + /* 113 q */ + {19, sizeof(simplex_81), simplex_81}, + /* 114 r */ + {13, sizeof(simplex_82), simplex_82}, + /* 115 s */ + {17, sizeof(simplex_83), simplex_83}, + /* 116 t */ + {12, sizeof(simplex_84), simplex_84}, + /* 117 u */ + {19, sizeof(simplex_85), simplex_85}, + /* 118 v */ + {16, sizeof(simplex_86), simplex_86}, + /* 119 w */ + {22, sizeof(simplex_87), simplex_87}, + /* 120 x */ + {17, sizeof(simplex_88), simplex_88}, + /* 121 y */ + {16, sizeof(simplex_89), simplex_89}, + /* 122 z */ + {17, sizeof(simplex_90), simplex_90}, + /* 123 { */ + {14, sizeof(simplex_91), simplex_91}, + /* 124 | */ + {8, sizeof(simplex_92), simplex_92}, + /* 125 } */ + {14, sizeof(simplex_93), simplex_93}, + /* 126 ~ */ + {24, sizeof(simplex_94), simplex_94}, }; diff --git a/src/mbgl/geometry/dem_data.cpp b/src/mbgl/geometry/dem_data.cpp index 80a3289a3b3..55ea5cbd605 100644 --- a/src/mbgl/geometry/dem_data.cpp +++ b/src/mbgl/geometry/dem_data.cpp @@ -3,14 +3,13 @@ namespace mbgl { -DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encoding): - dim(_image.size.height), - // extra two pixels per row for border backfilling on either edge - stride(dim + 2), - encoding(_encoding), - image({ static_cast(stride), static_cast(stride) }) { - - if (_image.size.height != _image.size.width){ +DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encoding) + : dim(_image.size.height), + // extra two pixels per row for border backfilling on either edge + stride(dim + 2), + encoding(_encoding), + image({static_cast(stride), static_cast(stride)}) { + if (_image.size.height != _image.size.width) { throw std::runtime_error("raster-dem tiles must be square."); } @@ -21,11 +20,12 @@ DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encodin dest += stride; source += dim; } - - // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of - // pixels around the image with the data of the nearest pixel from the image. this data is eventually - // replaced when the tile's neighboring tiles are loaded and the accurate data can be backfilled using - // DEMData#backfillBorder + + // in order to avoid flashing seams between tiles, here we are initially + // populating a 1px border of pixels around the image with the data of the + // nearest pixel from the image. this data is eventually replaced when the + // tile's neighboring tiles are loaded and the accurate data can be + // backfilled using DEMData#backfillBorder auto* data = reinterpret_cast(image.data.get()); for (int32_t x = 0; x < dim; x++) { @@ -36,42 +36,47 @@ DEMData::DEMData(const PremultipliedImage& _image, Tileset::DEMEncoding _encodin // right vertical border data[rowOffset + dim + 1] = data[rowOffset + dim]; } - + // top horizontal border with corners memcpy(data, data + stride, stride * 4); // bottom horizontal border with corners memcpy(data + (dim + 1) * stride, data + dim * stride, stride * 4); } -// This function takes the DEMData from a neighboring tile and backfills the edge/corner -// data in order to create a one pixel "buffer" of image data around the tile. This is -// necessary because the hillshade formula calculates the dx/dz, dy/dz derivatives at each -// pixel of the tile by querying the 8 surrounding pixels, and if we don't have the pixel -// buffer we get seams at tile boundaries. +// This function takes the DEMData from a neighboring tile and backfills the +// edge/corner data in order to create a one pixel "buffer" of image data around +// the tile. This is necessary because the hillshade formula calculates the +// dx/dz, dy/dz derivatives at each pixel of the tile by querying the 8 +// surrounding pixels, and if we don't have the pixel buffer we get seams at +// tile boundaries. void DEMData::backfillBorder(const DEMData& borderTileData, int8_t dx, int8_t dy) { auto& o = borderTileData; // Tiles from the same source should always be of the same dimensions. assert(dim == o.dim); - // We determine the pixel range to backfill based which corner/edge `borderTileData` - // represents. For example, dx = -1, dy = -1 represents the upper left corner of the - // base tile, so we only need to backfill one pixel at coordinates (-1, -1) of the tile - // image. + // We determine the pixel range to backfill based which corner/edge + // `borderTileData` represents. For example, dx = -1, dy = -1 represents the + // upper left corner of the base tile, so we only need to backfill one pixel + // at coordinates (-1, -1) of the tile image. int32_t xMin = dx * dim; int32_t xMax = dx * dim + dim; int32_t yMin = dy * dim; int32_t yMax = dy * dim + dim; - - if (dx == -1) xMin = xMax - 1; - else if (dx == 1) xMax = xMin + 1; - - if (dy == -1) yMin = yMax - 1; - else if (dy == 1) yMax = yMin + 1; - + + if (dx == -1) + xMin = xMax - 1; + else if (dx == 1) + xMax = xMin + 1; + + if (dy == -1) + yMin = yMax - 1; + else if (dy == 1) + yMax = yMin + 1; + int32_t ox = -dx * dim; int32_t oy = -dy * dim; - + auto* dest = reinterpret_cast(image.data.get()); auto* source = reinterpret_cast(o.image.data.get()); @@ -90,9 +95,9 @@ int32_t DEMData::get(const int32_t x, const int32_t y) const { const std::array& DEMData::getUnpackVector() const { // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb - static const std::array unpackMapbox = {{ 6553.6f, 25.6f, 0.1f, 10000.0f }}; + static const std::array unpackMapbox = {{6553.6f, 25.6f, 0.1f, 10000.0f}}; // https://aws.amazon.com/public-datasets/terrain/ - static const std::array unpackTerrarium = {{ 256.0f, 1.0f, 1.0f / 256.0f, 32768.0f }}; + static const std::array unpackTerrarium = {{256.0f, 1.0f, 1.0f / 256.0f, 32768.0f}}; return encoding == Tileset::DEMEncoding::Terrarium ? unpackTerrarium : unpackMapbox; } diff --git a/src/mbgl/geometry/dem_data.hpp b/src/mbgl/geometry/dem_data.hpp index 5044fb06589..b087afb63f0 100644 --- a/src/mbgl/geometry/dem_data.hpp +++ b/src/mbgl/geometry/dem_data.hpp @@ -19,14 +19,11 @@ class DEMData { int32_t get(int32_t x, int32_t y) const; const std::array& getUnpackVector() const; - const PremultipliedImage* getImage() const { - return ℑ - } + const PremultipliedImage* getImage() const { return ℑ } const int32_t dim; const int32_t stride; - private: Tileset::DEMEncoding encoding; PremultipliedImage image; @@ -38,7 +35,6 @@ class DEMData { assert(y < dim + 1); return (y + 1) * stride + (x + 1); } - }; } // namespace mbgl diff --git a/src/mbgl/geometry/feature_index.cpp b/src/mbgl/geometry/feature_index.cpp index c64bdf8bd7b..4bd81100209 100644 --- a/src/mbgl/geometry/feature_index.cpp +++ b/src/mbgl/geometry/feature_index.cpp @@ -35,8 +35,8 @@ namespace mbgl { FeatureIndex::FeatureIndex(std::unique_ptr tileData_) : grid(util::EXTENT, util::EXTENT, util::EXTENT / 16) // 16x16 grid -> 32px cell - , tileData(std::move(tileData_)) { -} + , + tileData(std::move(tileData_)) {} void FeatureIndex::insert(const GeometryCollection& geometries, std::size_t index, @@ -45,9 +45,7 @@ void FeatureIndex::insert(const GeometryCollection& geometries, auto featureSortIndex = sortIndex++; for (const auto& ring : geometries) { auto envelope = mapbox::geometry::envelope(ring); - if (envelope.min.x < util::EXTENT && - envelope.min.y < util::EXTENT && - envelope.max.x >= 0 && + if (envelope.min.x < util::EXTENT && envelope.min.y < util::EXTENT && envelope.max.x >= 0 && envelope.max.y >= 0) { grid.insert(IndexedSubfeature(index, sourceLayerName, bucketLeaderID, featureSortIndex), {convertPoint(envelope.min), convertPoint(envelope.max)}); @@ -56,37 +54,49 @@ void FeatureIndex::insert(const GeometryCollection& geometries, } void FeatureIndex::query(std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState& transformState, - const mat4& posMatrix, const double tileSize, const double scale, - const RenderedQueryOptions& queryOptions, const UnwrappedTileID& tileID, + const GeometryCoordinates& queryGeometry, + const TransformState& transformState, + const mat4& posMatrix, + const double tileSize, + const double scale, + const RenderedQueryOptions& queryOptions, + const UnwrappedTileID& tileID, const std::unordered_map& layers, - const float additionalQueryPadding, const SourceFeatureState& sourceFeatureState) const { + const float additionalQueryPadding, + const SourceFeatureState& sourceFeatureState) const { if (!tileData) { return; } // Determine query radius const auto pixelsToTileUnits = static_cast(util::EXTENT / tileSize / scale); - const int16_t additionalPadding = std::min(util::EXTENT, static_cast(additionalQueryPadding * pixelsToTileUnits)); + const int16_t additionalPadding = std::min( + util::EXTENT, static_cast(additionalQueryPadding * pixelsToTileUnits)); // Query the grid index mapbox::geometry::box box = mapbox::geometry::envelope(queryGeometry); - std::vector features = grid.query({ convertPoint(box.min - additionalPadding), - convertPoint(box.max + additionalPadding) }); - + std::vector features = grid.query( + {convertPoint(box.min - additionalPadding), convertPoint(box.max + additionalPadding)}); std::sort(features.begin(), features.end(), [](const IndexedSubfeature& a, const IndexedSubfeature& b) { return a.sortIndex > b.sortIndex; }); size_t previousSortIndex = std::numeric_limits::max(); for (const auto& indexedFeature : features) { - // If this feature is the same as the previous feature, skip it. if (indexedFeature.sortIndex == previousSortIndex) continue; previousSortIndex = indexedFeature.sortIndex; - addFeature(result, indexedFeature, queryOptions, tileID.canonical, layers, queryGeometry, transformState, - pixelsToTileUnits, posMatrix, &sourceFeatureState); + addFeature(result, + indexedFeature, + queryOptions, + tileID.canonical, + layers, + queryGeometry, + transformState, + pixelsToTileUnits, + posMatrix, + &sourceFeatureState); } } @@ -102,41 +112,56 @@ std::unordered_map> FeatureIndex::lookupSymbol } std::vector sortedFeatures(symbolFeatures.begin(), symbolFeatures.end()); - std::sort(sortedFeatures.begin(), sortedFeatures.end(), [featureSortOrder](const IndexedSubfeature& a, const IndexedSubfeature& b) { - // Same idea as the non-symbol sort order, but symbol features may have changed their sort order - // since their corresponding IndexedSubfeature was added to the CollisionIndex - // The 'featureSortOrder' is relatively inefficient for querying but cheap to build on every bucket sort - if (featureSortOrder) { - // queryRenderedSymbols documentation says we'll return features in - // "top-to-bottom" rendering order (aka last-to-first). - // Actually there can be multiple symbol instances per feature, so - // we sort each feature based on the first matching symbol instance. - auto sortedA = std::find(featureSortOrder->begin(), featureSortOrder->end(), a.index); - auto sortedB = std::find(featureSortOrder->begin(), featureSortOrder->end(), b.index); - assert(sortedA != featureSortOrder->end()); - assert(sortedB != featureSortOrder->end()); - return sortedA > sortedB; - } else { - // Bucket hasn't been re-sorted based on angle, so use same "reverse of appearance in source data" - // logic as non-symboles - return a.sortIndex > b.sortIndex; - } - }); + std::sort(sortedFeatures.begin(), + sortedFeatures.end(), + [featureSortOrder](const IndexedSubfeature& a, const IndexedSubfeature& b) { + // Same idea as the non-symbol sort order, but symbol features may + // have changed their sort order since their corresponding + // IndexedSubfeature was added to the CollisionIndex The + // 'featureSortOrder' is relatively inefficient for querying but + // cheap to build on every bucket sort + if (featureSortOrder) { + // queryRenderedSymbols documentation says we'll return features in + // "top-to-bottom" rendering order (aka last-to-first). + // Actually there can be multiple symbol instances per feature, so + // we sort each feature based on the first matching symbol instance. + auto sortedA = std::find(featureSortOrder->begin(), featureSortOrder->end(), a.index); + auto sortedB = std::find(featureSortOrder->begin(), featureSortOrder->end(), b.index); + assert(sortedA != featureSortOrder->end()); + assert(sortedB != featureSortOrder->end()); + return sortedA > sortedB; + } else { + // Bucket hasn't been re-sorted based on angle, so use same + // "reverse of appearance in source data" logic as non-symboles + return a.sortIndex > b.sortIndex; + } + }); for (const auto& symbolFeature : sortedFeatures) { mat4 unusedMatrix; - addFeature(result, symbolFeature, queryOptions, tileID.canonical, layers, GeometryCoordinates(), {}, 0, - unusedMatrix, nullptr); + addFeature(result, + symbolFeature, + queryOptions, + tileID.canonical, + layers, + GeometryCoordinates(), + {}, + 0, + unusedMatrix, + nullptr); } return result; } void FeatureIndex::addFeature(std::unordered_map>& result, - const IndexedSubfeature& indexedFeature, const RenderedQueryOptions& options, + const IndexedSubfeature& indexedFeature, + const RenderedQueryOptions& options, const CanonicalTileID& tileID, const std::unordered_map& layers, - const GeometryCoordinates& queryGeometry, const TransformState& transformState, - const float pixelsToTileUnits, const mat4& posMatrix, + const GeometryCoordinates& queryGeometry, + const TransformState& transformState, + const float pixelsToTileUnits, + const mat4& posMatrix, const SourceFeatureState* sourceFeatureState) const { // Lazily calculated. std::unique_ptr sourceLayer; @@ -165,14 +190,16 @@ void FeatureIndex::addFeature(std::unordered_mapbaseImpl->getTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required; + bool needsCrossTileIndex = renderLayer->baseImpl->getTypeInfo()->crossTileIndex == + style::LayerTypeInfo::CrossTileIndex::Required; if (!needsCrossTileIndex && - !renderLayer->queryIntersectsFeature(queryGeometry, *geometryTileFeature, tileID.z, transformState, - pixelsToTileUnits, posMatrix, state)) { + !renderLayer->queryIntersectsFeature( + queryGeometry, *geometryTileFeature, tileID.z, transformState, pixelsToTileUnits, posMatrix, state)) { continue; } - if (options.filter && !(*options.filter)(style::expression::EvaluationContext { static_cast(tileID.z), geometryTileFeature.get() })) { + if (options.filter && !(*options.filter)(style::expression::EvaluationContext{static_cast(tileID.z), + geometryTileFeature.get()})) { continue; } @@ -184,17 +211,17 @@ void FeatureIndex::addFeature(std::unordered_map FeatureIndex::translateQueryGeometry( - const GeometryCoordinates& queryGeometry, - const std::array& translate, - const style::TranslateAnchorType anchorType, - const float bearing, - const float pixelsToTileUnits) { +std::optional FeatureIndex::translateQueryGeometry(const GeometryCoordinates& queryGeometry, + const std::array& translate, + const style::TranslateAnchorType anchorType, + const float bearing, + const float pixelsToTileUnits) { if (translate[0] == 0 && translate[1] == 0) { return {}; } - GeometryCoordinate translateVec(static_cast(translate[0] * pixelsToTileUnits), static_cast(translate[1] * pixelsToTileUnits)); + GeometryCoordinate translateVec(static_cast(translate[0] * pixelsToTileUnits), + static_cast(translate[1] * pixelsToTileUnits)); if (anchorType == style::TranslateAnchorType::Viewport) { translateVec = util::rotate(translateVec, -bearing); } diff --git a/src/mbgl/geometry/feature_index.hpp b/src/mbgl/geometry/feature_index.hpp index 7f1976910b9..8577304ac77 100644 --- a/src/mbgl/geometry/feature_index.hpp +++ b/src/mbgl/geometry/feature_index.hpp @@ -25,23 +25,20 @@ class IndexedSubfeature { public: IndexedSubfeature() = delete; IndexedSubfeature(std::size_t index_, std::string sourceLayerName_, std::string bucketName_, size_t sortIndex_) - : index(index_) - , sourceLayerName(std::move(sourceLayerName_)) - , bucketLeaderID(std::move(bucketName_)) - , sortIndex(sortIndex_) - , bucketInstanceId(0) - , collisionGroupId(0) - {} - - + : index(index_), + sourceLayerName(std::move(sourceLayerName_)), + bucketLeaderID(std::move(bucketName_)), + sortIndex(sortIndex_), + bucketInstanceId(0), + collisionGroupId(0) {} + IndexedSubfeature(const IndexedSubfeature& other, uint32_t bucketInstanceId_, uint16_t collisionGroupId_) - : index(other.index) - , sourceLayerName(other.sourceLayerName) - , bucketLeaderID(other.bucketLeaderID) - , sortIndex(other.sortIndex) - , bucketInstanceId(bucketInstanceId_) - , collisionGroupId(collisionGroupId_) - {} + : index(other.index), + sourceLayerName(other.sourceLayerName), + bucketLeaderID(other.bucketLeaderID), + sortIndex(other.sortIndex), + bucketInstanceId(bucketInstanceId_), + collisionGroupId(collisionGroupId_) {} size_t index; std::string sourceLayerName; std::string bucketLeaderID; @@ -77,8 +74,11 @@ class FeatureIndex { FeatureIndex(std::unique_ptr tileData_); const GeometryTileData* getData() { return tileData.get(); } - - void insert(const GeometryCollection&, std::size_t index, const std::string& sourceLayerName, const std::string& bucketLeaderID); + + void insert(const GeometryCollection&, + std::size_t index, + const std::string& sourceLayerName, + const std::string& bucketLeaderID); void query(std::unordered_map>& result, const GeometryCoordinates& queryGeometry, @@ -93,10 +93,10 @@ class FeatureIndex { const SourceFeatureState& sourceFeatureState) const; static std::optional translateQueryGeometry(const GeometryCoordinates& queryGeometry, - const std::array& translate, - style::TranslateAnchorType, - float bearing, - float pixelsToTileUnits); + const std::array& translate, + style::TranslateAnchorType, + float bearing, + float pixelsToTileUnits); void setBucketLayerIDs(const std::string& bucketLeaderID, const std::vector& layerIDs); diff --git a/src/mbgl/geometry/line_atlas.cpp b/src/mbgl/geometry/line_atlas.cpp index 2042195b6c2..02c2b311ca5 100644 --- a/src/mbgl/geometry/line_atlas.cpp +++ b/src/mbgl/geometry/line_atlas.cpp @@ -11,8 +11,8 @@ namespace mbgl { namespace { size_t getDashPatternHash(const std::vector& dasharray, const LinePatternCap patternCap) { - size_t key = - patternCap == LinePatternCap::Round ? std::numeric_limits::min() : std::numeric_limits::max(); + size_t key = patternCap == LinePatternCap::Round ? std::numeric_limits::min() + : std::numeric_limits::max(); for (const float part : dasharray) { util::hash_combine(key, part); } @@ -180,19 +180,22 @@ DashPatternTexture::DashPatternTexture(const std::vector& from_, // The OpenGL ES 2.0 spec, section 3.8.2 states: // - // Calling a sampler from a fragment shader will return (R,G,B,A) = (0,0,0,1) if any of the - // following conditions are true: - // […] - // - A two-dimensional sampler is called, the corresponding texture image is a - // non-power-of-two image […], and either the texture wrap mode is not CLAMP_TO_EDGE, or - // the minification filter is neither NEAREST nor LINEAR. + // Calling a sampler from a fragment shader will return (R,G,B,A) = + // (0,0,0,1) if any of the following conditions are true: […] + // - A two-dimensional sampler is called, the corresponding texture + // image is a + // non-power-of-two image […], and either the texture wrap mode is not + // CLAMP_TO_EDGE, or the minification filter is neither NEAREST nor + // LINEAR. // […] // - // This means that texture lookups won't work for NPOT textures unless they use GL_CLAMP_TO_EDGE. - // We're using GL_CLAMP_TO_EDGE for the vertical direction, but GL_REPEAT for the horizontal - // direction, which means that we need a power-of-two texture for our line dash patterns to work - // on OpenGL ES 2.0 conforming implementations. Fortunately, this just means changing the height - // from 15 to 16, and from 30 to 32, so we don't waste many pixels. + // This means that texture lookups won't work for NPOT textures unless they + // use GL_CLAMP_TO_EDGE. We're using GL_CLAMP_TO_EDGE for the vertical + // direction, but GL_REPEAT for the horizontal direction, which means that + // we need a power-of-two texture for our line dash patterns to work on + // OpenGL ES 2.0 conforming implementations. Fortunately, this just means + // changing the height from 15 to 16, and from 30 to 32, so we don't waste + // many pixels. const uint32_t textureHeight = 1 << util::ceil_log2(height); AlphaImage image({256, textureHeight}); diff --git a/src/mbgl/geometry/line_atlas.hpp b/src/mbgl/geometry/line_atlas.hpp index 942e1a84b1a..c65a9466245 100644 --- a/src/mbgl/geometry/line_atlas.hpp +++ b/src/mbgl/geometry/line_atlas.hpp @@ -38,8 +38,9 @@ class DashPatternTexture { public: DashPatternTexture(const std::vector& from, const std::vector& to, LinePatternCap); - // Uploads the texture to the GPU to be available when we need it. This is a lazy operation; - // the texture is only bound when the data is uploaded for the first time. + // Uploads the texture to the GPU to be available when we need it. This is a + // lazy operation; the texture is only bound when the data is uploaded for + // the first time. void upload(gfx::UploadPass&); // Binds the atlas texture to the GPU, and uploads data if it is out of date. diff --git a/src/mbgl/gfx/attribute.cpp b/src/mbgl/gfx/attribute.cpp index a96bd7593d1..f83eafacd81 100644 --- a/src/mbgl/gfx/attribute.cpp +++ b/src/mbgl/gfx/attribute.cpp @@ -6,7 +6,8 @@ namespace mbgl { namespace gfx { -std::optional offsetAttributeBinding(const std::optional& binding, std::size_t vertexOffset) { +std::optional offsetAttributeBinding(const std::optional& binding, + std::size_t vertexOffset) { assert(vertexOffset <= std::numeric_limits::max()); if (binding) { AttributeBinding result = *binding; diff --git a/src/mbgl/gfx/attribute.hpp b/src/mbgl/gfx/attribute.hpp index 1707e13dcb0..1f4826beba1 100644 --- a/src/mbgl/gfx/attribute.hpp +++ b/src/mbgl/gfx/attribute.hpp @@ -11,12 +11,10 @@ #include #include -#define MBGL_DEFINE_ATTRIBUTE(type_, n_, name_) \ - struct name_ { \ - using Type = ::mbgl::gfx::AttributeType; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_ATTRIBUTE(type_, n_, name_) \ + struct name_ { \ + using Type = ::mbgl::gfx::AttributeType; \ + static constexpr auto name() { return #name_; } \ } #if defined(_MSC_VER) && !defined(__clang__) @@ -28,35 +26,64 @@ namespace mbgl { namespace gfx { -template struct AttributeDataTypeOf; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; -template <> struct AttributeDataTypeOf : std::integral_constant {}; +template +struct AttributeDataTypeOf; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; +template <> +struct AttributeDataTypeOf : std::integral_constant {}; template class AttributeType { @@ -90,15 +117,11 @@ class AttributeBinding { uint32_t vertexOffset; friend bool operator==(const AttributeBinding& lhs, const AttributeBinding& rhs) { - return lhs.attribute == rhs.attribute && - lhs.vertexStride == rhs.vertexStride && - lhs.vertexBufferResource == rhs.vertexBufferResource && - lhs.vertexOffset == rhs.vertexOffset; + return lhs.attribute == rhs.attribute && lhs.vertexStride == rhs.vertexStride && + lhs.vertexBufferResource == rhs.vertexBufferResource && lhs.vertexOffset == rhs.vertexOffset; } - bool operator!=(const AttributeBinding& rhs) const { - return !(*this == rhs); - } + bool operator!=(const AttributeBinding& rhs) const { return !(*this == rhs); } }; // Attribute binding requires member offsets. The only standard way to @@ -161,9 +184,11 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 1, { - { A1::DataType, offsetof(Type, a1) }, - }}; + static constexpr const VertexDescriptor data = {sizeof(Type), + 1, + { + {A1::DataType, offsetof(Type, a1)}, + }}; }; template @@ -174,10 +199,12 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 2, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - }}; + static constexpr const VertexDescriptor data = {sizeof(Type), + 2, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + }}; }; template @@ -188,11 +215,13 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 3, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - { A3::DataType, offsetof(Type, a3) }, - }}; + static constexpr const VertexDescriptor data = {sizeof(Type), + 3, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + {A3::DataType, offsetof(Type, a3)}, + }}; }; template @@ -203,12 +232,14 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 4, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - { A3::DataType, offsetof(Type, a3) }, - { A4::DataType, offsetof(Type, a4) }, - }}; + static constexpr const VertexDescriptor data = {sizeof(Type), + 4, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + {A3::DataType, offsetof(Type, a3)}, + {A4::DataType, offsetof(Type, a4)}, + }}; }; template @@ -219,13 +250,15 @@ struct Descriptor> { using Type = VertexType; static_assert(sizeof(Type) < 256, "vertex type must be smaller than 256 bytes"); static_assert(std::is_standard_layout_v, "vertex type must use standard layout"); - static constexpr const VertexDescriptor data = { sizeof(Type), 5, { - { A1::DataType, offsetof(Type, a1) }, - { A2::DataType, offsetof(Type, a2) }, - { A3::DataType, offsetof(Type, a3) }, - { A4::DataType, offsetof(Type, a4) }, - { A5::DataType, offsetof(Type, a5) }, - }}; + static constexpr const VertexDescriptor data = {sizeof(Type), + 5, + { + {A1::DataType, offsetof(Type, a1)}, + {A2::DataType, offsetof(Type, a2)}, + {A3::DataType, offsetof(Type, a3)}, + {A4::DataType, offsetof(Type, a4)}, + {A5::DataType, offsetof(Type, a5)}, + }}; }; template @@ -259,34 +292,32 @@ AttributeBinding attributeBinding(const VertexBuffer>& }; } -std::optional offsetAttributeBinding(const std::optional& binding, std::size_t vertexOffset); +std::optional offsetAttributeBinding(const std::optional& binding, + std::size_t vertexOffset); template class AttributeBindings; template class AttributeBindings> final - : public IndexedTuple, - TypeList>...>> { - using Base = IndexedTuple, - TypeList>...>>; + : public IndexedTuple, TypeList>...>> { + using Base = IndexedTuple, TypeList>...>>; public: AttributeBindings(const VertexBuffer>>& buffer) - : Base{ attributeBinding::value>(buffer)... } { - } + : Base{attributeBinding::value>(buffer)...} {} template - AttributeBindings(Args&&... args) : Base(std::forward(args)...) { - } + AttributeBindings(Args&&... args) + : Base(std::forward(args)...) {} AttributeBindings offset(const std::size_t vertexOffset) const { - return { offsetAttributeBinding(Base::template get(), vertexOffset)... }; + return {offsetAttributeBinding(Base::template get(), vertexOffset)...}; } uint32_t activeCount() const { uint32_t result = 0; - util::ignore({ ((result += bool(Base::template get())), 0)... }); + util::ignore({((result += bool(Base::template get())), 0)...}); return result; } }; diff --git a/src/mbgl/gfx/color_mode.hpp b/src/mbgl/gfx/color_mode.hpp index 077c7771bd3..578a681a27c 100644 --- a/src/mbgl/gfx/color_mode.hpp +++ b/src/mbgl/gfx/color_mode.hpp @@ -29,15 +29,11 @@ class ColorMode { static constexpr ColorBlendFactorType dstFactor = ColorBlendFactorType::Zero; }; - using Add = LinearBlend; - using Subtract = LinearBlend; - using ReverseSubtract = LinearBlend; + using Add = LinearBlend; + using Subtract = LinearBlend; + using ReverseSubtract = LinearBlend; - using BlendFunction = variant< - Replace, - Add, - Subtract, - ReverseSubtract>; + using BlendFunction = variant; BlendFunction blendFunction; Color blendColor; @@ -51,20 +47,16 @@ class ColorMode { Mask mask; - static ColorMode disabled() { - return { Replace{}, {}, { false, false, false, false } }; - } + static ColorMode disabled() { return {Replace{}, {}, {false, false, false, false}}; } - static ColorMode unblended() { - return { Replace{}, {}, { true, true, true, true } }; - } + static ColorMode unblended() { return {Replace{}, {}, {true, true, true, true}}; } static ColorMode alphaBlended() { - return { Add{ ColorBlendFactorType::One, ColorBlendFactorType::OneMinusSrcAlpha }, {}, { true, true, true, true } }; + return {Add{ColorBlendFactorType::One, ColorBlendFactorType::OneMinusSrcAlpha}, {}, {true, true, true, true}}; } static ColorMode additive() { - return { Add{ ColorBlendFactorType::One, ColorBlendFactorType::One }, {}, { true, true, true, true } }; + return {Add{ColorBlendFactorType::One, ColorBlendFactorType::One}, {}, {true, true, true, true}}; } }; diff --git a/src/mbgl/gfx/command_encoder.hpp b/src/mbgl/gfx/command_encoder.hpp index 5692615643c..617a20b3fe6 100644 --- a/src/mbgl/gfx/command_encoder.hpp +++ b/src/mbgl/gfx/command_encoder.hpp @@ -25,9 +25,7 @@ class CommandEncoder { CommandEncoder(const CommandEncoder&) = delete; CommandEncoder& operator=(const CommandEncoder&) = delete; - DebugGroup createDebugGroup(const char* name) { - return { *this, name }; - } + DebugGroup createDebugGroup(const char* name) { return {*this, name}; } virtual std::unique_ptr createUploadPass(const char* name) = 0; virtual std::unique_ptr createRenderPass(const char* name, const RenderPassDescriptor&) = 0; diff --git a/src/mbgl/gfx/context.hpp b/src/mbgl/gfx/context.hpp index 3062ab2c6b4..71cfd0912ec 100644 --- a/src/mbgl/gfx/context.hpp +++ b/src/mbgl/gfx/context.hpp @@ -20,8 +20,7 @@ class OffscreenTexture; class Context { protected: Context(uint32_t maximumVertexBindingCount_) - : maximumVertexBindingCount(maximumVertexBindingCount_) { - } + : maximumVertexBindingCount(maximumVertexBindingCount_) {} public: static constexpr const uint32_t minimumRequiredVertexBindingCount = 8; @@ -49,28 +48,23 @@ class Context { Texture createTexture(const Size size, TexturePixelType format = TexturePixelType::RGBA, TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { - return { size, createTextureResource(size, format, type) }; + return {size, createTextureResource(size, format, type)}; } protected: - virtual std::unique_ptr - createTextureResource(Size, TexturePixelType, TextureChannelDataType) = 0; + virtual std::unique_ptr createTextureResource(Size, TexturePixelType, TextureChannelDataType) = 0; public: template - Renderbuffer - createRenderbuffer(const Size size) { - return { size, createRenderbufferResource(pixelType, size) }; + Renderbuffer createRenderbuffer(const Size size) { + return {size, createRenderbufferResource(pixelType, size)}; } protected: - virtual std::unique_ptr - createRenderbufferResource(RenderbufferPixelType, Size) = 0; + virtual std::unique_ptr createRenderbufferResource(RenderbufferPixelType, Size) = 0; public: - DrawScope createDrawScope() { - return DrawScope{ createDrawScopeResource() }; - } + DrawScope createDrawScope() { return DrawScope{createDrawScopeResource()}; } protected: virtual std::unique_ptr createDrawScopeResource() = 0; diff --git a/src/mbgl/gfx/cull_face_mode.hpp b/src/mbgl/gfx/cull_face_mode.hpp index 42920ee02ab..f71a66225d3 100644 --- a/src/mbgl/gfx/cull_face_mode.hpp +++ b/src/mbgl/gfx/cull_face_mode.hpp @@ -11,13 +11,9 @@ class CullFaceMode { CullFaceSideType side; CullFaceWindingType winding; - static CullFaceMode disabled() { - return { false, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise }; - } + static CullFaceMode disabled() { return {false, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise}; } - static CullFaceMode backCCW() { - return { true, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise }; - } + static CullFaceMode backCCW() { return {true, CullFaceSideType::Back, CullFaceWindingType::CounterClockwise}; } }; } // namespace gfx diff --git a/src/mbgl/gfx/debug_group.hpp b/src/mbgl/gfx/debug_group.hpp index e5e3630b4c1..c3265879821 100644 --- a/src/mbgl/gfx/debug_group.hpp +++ b/src/mbgl/gfx/debug_group.hpp @@ -6,11 +6,15 @@ namespace gfx { template class DebugGroup { public: - DebugGroup(T& scope_, const char* name) : scope(&scope_) { + DebugGroup(T& scope_, const char* name) + : scope(&scope_) { scope->pushDebugGroup(name); } - DebugGroup(DebugGroup&& rhs) noexcept : scope(rhs.scope) { rhs.scope = nullptr; } + DebugGroup(DebugGroup&& rhs) noexcept + : scope(rhs.scope) { + rhs.scope = nullptr; + } ~DebugGroup() { if (scope) { diff --git a/src/mbgl/gfx/depth_mode.hpp b/src/mbgl/gfx/depth_mode.hpp index 93a13be091e..4548240c999 100644 --- a/src/mbgl/gfx/depth_mode.hpp +++ b/src/mbgl/gfx/depth_mode.hpp @@ -12,9 +12,7 @@ class DepthMode { DepthMaskType mask; Range range; - static DepthMode disabled() { - return DepthMode { DepthFunctionType::Always, DepthMaskType::ReadOnly, { 0.0, 1.0 } }; - } + static DepthMode disabled() { return DepthMode{DepthFunctionType::Always, DepthMaskType::ReadOnly, {0.0, 1.0}}; } }; } // namespace gfx diff --git a/src/mbgl/gfx/draw_mode.hpp b/src/mbgl/gfx/draw_mode.hpp index e18a38903e5..850821105d3 100644 --- a/src/mbgl/gfx/draw_mode.hpp +++ b/src/mbgl/gfx/draw_mode.hpp @@ -10,68 +10,83 @@ namespace gfx { class DrawMode { protected: DrawMode(DrawModeType type_, float size_) - : type(type_), size(size_) { - } + : type(type_), + size(size_) {} public: const DrawModeType type; const float size; }; -template struct BufferGroupSizeOf; -template struct PrimitiveTypeOf; +template +struct BufferGroupSizeOf; +template +struct PrimitiveTypeOf; class Points : public DrawMode { public: - explicit Points(float pointSize_) : DrawMode(DrawModeType::Points, pointSize_) { + explicit Points(float pointSize_) + : DrawMode(DrawModeType::Points, pointSize_) { assert(size > 0); } }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; class Lines : public DrawMode { public: - explicit Lines(float lineWidth_) : DrawMode(DrawModeType::Lines, lineWidth_) { + explicit Lines(float lineWidth_) + : DrawMode(DrawModeType::Lines, lineWidth_) { assert(size > 0); } }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; // LineStrip is a form of "Line" rendering, but the element buffer // cannot be grouped into logical elements beyond a single Point. class LineStrip : public DrawMode { public: - explicit LineStrip(float lineWidth_) : DrawMode(DrawModeType::LineStrip, lineWidth_) { + explicit LineStrip(float lineWidth_) + : DrawMode(DrawModeType::LineStrip, lineWidth_) { assert(size > 0); } }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; class Triangles : public DrawMode { public: - explicit Triangles() : DrawMode(DrawModeType::Triangles, 0) { - } + explicit Triangles() + : DrawMode(DrawModeType::Triangles, 0) {} }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; // TriangleStrip is a form of "Triangle" rendering, but the element buffer // cannot be grouped into logical elements beyond a single Point. class TriangleStrip : public DrawMode { public: - explicit TriangleStrip() : DrawMode(DrawModeType::TriangleStrip, 0) { - } + explicit TriangleStrip() + : DrawMode(DrawModeType::TriangleStrip, 0) {} }; -template <> struct BufferGroupSizeOf : std::integral_constant {}; -template <> struct PrimitiveTypeOf : std::integral_constant {}; +template <> +struct BufferGroupSizeOf : std::integral_constant {}; +template <> +struct PrimitiveTypeOf : std::integral_constant {}; } // namespace gfx } // namespace mbgl diff --git a/src/mbgl/gfx/draw_scope.hpp b/src/mbgl/gfx/draw_scope.hpp index 5cdb588317b..009f733f40f 100644 --- a/src/mbgl/gfx/draw_scope.hpp +++ b/src/mbgl/gfx/draw_scope.hpp @@ -9,14 +9,15 @@ namespace gfx { class DrawScopeResource { protected: DrawScopeResource() = default; + public: virtual ~DrawScopeResource() = default; }; class DrawScope { public: - explicit DrawScope(std::unique_ptr resource_) : resource(std::move(resource_)) { - } + explicit DrawScope(std::unique_ptr resource_) + : resource(std::move(resource_)) {} template T& getResource() const { diff --git a/src/mbgl/gfx/index_buffer.hpp b/src/mbgl/gfx/index_buffer.hpp index 60f361b497e..27efc67cbfc 100644 --- a/src/mbgl/gfx/index_buffer.hpp +++ b/src/mbgl/gfx/index_buffer.hpp @@ -9,6 +9,7 @@ namespace gfx { class IndexBufferResource { protected: IndexBufferResource() = default; + public: virtual ~IndexBufferResource() = default; }; @@ -16,8 +17,8 @@ class IndexBufferResource { class IndexBuffer { public: IndexBuffer(const std::size_t elements_, std::unique_ptr&& resource_) - : elements(elements_), resource(std::move(resource_)) { - } + : elements(elements_), + resource(std::move(resource_)) {} std::size_t elements; diff --git a/src/mbgl/gfx/index_vector.hpp b/src/mbgl/gfx/index_vector.hpp index 826d43bee3a..db922b12dd0 100644 --- a/src/mbgl/gfx/index_vector.hpp +++ b/src/mbgl/gfx/index_vector.hpp @@ -16,32 +16,20 @@ class IndexVector { template void emplace_back(Args&&... args) { static_assert(sizeof...(args) == groupSize, "wrong buffer element count"); - util::ignore({ (v.emplace_back(std::forward(args)), 0)... }); + util::ignore({(v.emplace_back(std::forward(args)), 0)...}); } - std::size_t elements() const { - return v.size(); - } + std::size_t elements() const { return v.size(); } - std::size_t bytes() const { - return v.size() * sizeof(uint16_t); - } + std::size_t bytes() const { return v.size() * sizeof(uint16_t); } - bool empty() const { - return v.empty(); - } + bool empty() const { return v.empty(); } - void clear() { - v.clear(); - } + void clear() { v.clear(); } - const uint16_t* data() const { - return v.data(); - } + const uint16_t* data() const { return v.data(); } - const std::vector& vector() const { - return v; - } + const std::vector& vector() const { return v; } private: std::vector v; diff --git a/src/mbgl/gfx/offscreen_texture.hpp b/src/mbgl/gfx/offscreen_texture.hpp index d4bf5149fdf..7e83a51119d 100644 --- a/src/mbgl/gfx/offscreen_texture.hpp +++ b/src/mbgl/gfx/offscreen_texture.hpp @@ -11,8 +11,7 @@ class Texture; class OffscreenTexture : public gfx::Renderable { protected: OffscreenTexture(const Size size_, std::unique_ptr resource_) - : gfx::Renderable(size_, std::move(resource_)) { - } + : gfx::Renderable(size_, std::move(resource_)) {} public: ~OffscreenTexture() override = default; diff --git a/src/mbgl/gfx/program.hpp b/src/mbgl/gfx/program.hpp index b636bc26549..04c15603dcf 100644 --- a/src/mbgl/gfx/program.hpp +++ b/src/mbgl/gfx/program.hpp @@ -14,9 +14,12 @@ class CullFaceMode; class DrawScope; class IndexBuffer; class RenderPass; -template class UniformValues; -template class AttributeBindings; -template class TextureBindings; +template +class UniformValues; +template +class AttributeBindings; +template +class TextureBindings; template class Program { diff --git a/src/mbgl/gfx/render_pass.hpp b/src/mbgl/gfx/render_pass.hpp index 3cc377429a8..8ceb61da767 100644 --- a/src/mbgl/gfx/render_pass.hpp +++ b/src/mbgl/gfx/render_pass.hpp @@ -32,9 +32,7 @@ class RenderPass { RenderPass(const RenderPass&) = delete; RenderPass& operator=(const RenderPass&) = delete; - DebugGroup createDebugGroup(const char* name) { - return { *this, name }; - } + DebugGroup createDebugGroup(const char* name) { return {*this, name}; } }; } // namespace gfx diff --git a/src/mbgl/gfx/renderbuffer.hpp b/src/mbgl/gfx/renderbuffer.hpp index 209b7ed3f9c..bbc0c1be685 100644 --- a/src/mbgl/gfx/renderbuffer.hpp +++ b/src/mbgl/gfx/renderbuffer.hpp @@ -21,20 +21,14 @@ template class Renderbuffer final { public: Renderbuffer(const Size size_, std::unique_ptr resource_) - : size(size_), resource(std::move(resource_)) { - } + : size(size_), + resource(std::move(resource_)) {} - void setShouldClear(bool clear) { - dirty = clear; - } + void setShouldClear(bool clear) { dirty = clear; } - bool needsClearing() const { - return dirty; - } + bool needsClearing() const { return dirty; } - const Size& getSize() const { - return size; - } + const Size& getSize() const { return size; } template T& getResource() const { diff --git a/src/mbgl/gfx/renderer_backend.cpp b/src/mbgl/gfx/renderer_backend.cpp index e6fe0c0b245..b24a66a27be 100644 --- a/src/mbgl/gfx/renderer_backend.cpp +++ b/src/mbgl/gfx/renderer_backend.cpp @@ -5,15 +5,13 @@ namespace mbgl { namespace gfx { -RendererBackend::RendererBackend(const ContextMode contextMode_) : contextMode(contextMode_) { -} +RendererBackend::RendererBackend(const ContextMode contextMode_) + : contextMode(contextMode_) {} RendererBackend::~RendererBackend() = default; gfx::Context& RendererBackend::getContext() { assert(BackendScope::exists()); - std::call_once(initialized, [this] { - context = createContext(); - }); + std::call_once(initialized, [this] { context = createContext(); }); assert(context); return *context; } diff --git a/src/mbgl/gfx/shader_registry.cpp b/src/mbgl/gfx/shader_registry.cpp index 67b1fac0b4a..87aeed6ead4 100644 --- a/src/mbgl/gfx/shader_registry.cpp +++ b/src/mbgl/gfx/shader_registry.cpp @@ -6,16 +6,12 @@ namespace gfx { ShaderRegistry::ShaderRegistry() {} -bool ShaderRegistry::isShader(const std::string& shaderName) - const noexcept -{ +bool ShaderRegistry::isShader(const std::string& shaderName) const noexcept { std::shared_lock readerLock(programLock); return programs.find(shaderName) != programs.end(); } -const std::shared_ptr ShaderRegistry::getShader(const std::string& shaderName) - const noexcept -{ +const std::shared_ptr ShaderRegistry::getShader(const std::string& shaderName) const noexcept { std::shared_lock readerLock(programLock); const auto it = programs.find(shaderName); if (it == programs.end()) { @@ -25,15 +21,11 @@ const std::shared_ptr ShaderRegistry::getShader(const std::string& return it->second; } -bool ShaderRegistry::replaceShader( - std::shared_ptr&& shader) noexcept -{ +bool ShaderRegistry::replaceShader(std::shared_ptr&& shader) noexcept { return replaceShader(std::move(shader), std::string{shader->typeName()}); } -bool ShaderRegistry::replaceShader(std::shared_ptr&& shader, - const std::string& shaderName) noexcept -{ +bool ShaderRegistry::replaceShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept { std::unique_lock writerLock(programLock); if (programs.find(shaderName) == programs.end()) { return false; @@ -43,15 +35,11 @@ bool ShaderRegistry::replaceShader(std::shared_ptr&& shader, return true; } -bool ShaderRegistry::registerShader( - std::shared_ptr&& shader) noexcept -{ +bool ShaderRegistry::registerShader(std::shared_ptr&& shader) noexcept { return registerShader(std::move(shader), std::string{shader->typeName()}); } -bool ShaderRegistry::registerShader(std::shared_ptr&& shader, - const std::string& shaderName) noexcept -{ +bool ShaderRegistry::registerShader(std::shared_ptr&& shader, const std::string& shaderName) noexcept { std::unique_lock writerLock(programLock); if (programs.find(shaderName) != programs.end()) { return false; @@ -61,5 +49,5 @@ bool ShaderRegistry::registerShader(std::shared_ptr&& shader, return true; } -} // namespace gl +} // namespace gfx } // namespace mbgl diff --git a/src/mbgl/gfx/stencil_mode.hpp b/src/mbgl/gfx/stencil_mode.hpp index aec403b59bf..0ccf21faee6 100644 --- a/src/mbgl/gfx/stencil_mode.hpp +++ b/src/mbgl/gfx/stencil_mode.hpp @@ -20,24 +20,16 @@ class StencilMode { uint32_t mask; }; - using Never = SimpleTest; - using Less = MaskedTest; - using Equal = MaskedTest; - using LessEqual = MaskedTest; - using Greater = MaskedTest; - using NotEqual = MaskedTest; + using Never = SimpleTest; + using Less = MaskedTest; + using Equal = MaskedTest; + using LessEqual = MaskedTest; + using Greater = MaskedTest; + using NotEqual = MaskedTest; using GreaterEqual = MaskedTest; - using Always = SimpleTest; + using Always = SimpleTest; - using Test = variant< - Never, - Less, - Equal, - LessEqual, - Greater, - NotEqual, - GreaterEqual, - Always>; + using Test = variant; Test test; int32_t ref; @@ -48,7 +40,7 @@ class StencilMode { StencilOpType pass; static StencilMode disabled() { - return StencilMode { Always(), 0, 0, StencilOpType::Keep, StencilOpType::Keep, StencilOpType::Keep }; + return StencilMode{Always(), 0, 0, StencilOpType::Keep, StencilOpType::Keep, StencilOpType::Keep}; } }; diff --git a/src/mbgl/gfx/texture.hpp b/src/mbgl/gfx/texture.hpp index 00e94a8f6c6..851daa464f6 100644 --- a/src/mbgl/gfx/texture.hpp +++ b/src/mbgl/gfx/texture.hpp @@ -8,12 +8,10 @@ #include #include -#define MBGL_DEFINE_TEXTURE(name_) \ - struct name_ { \ - using Value = ::mbgl::gfx::TextureBinding; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_TEXTURE(name_) \ + struct name_ { \ + using Value = ::mbgl::gfx::TextureBinding; \ + static constexpr auto name() { return #name_; } \ } namespace mbgl { @@ -22,6 +20,7 @@ namespace gfx { class TextureResource { protected: TextureResource() = default; + public: virtual ~TextureResource() = default; }; @@ -29,8 +28,8 @@ class TextureResource { class Texture { public: Texture(const Size size_, std::unique_ptr&& resource_) - : size(size_), resource(std::move(resource_)) { - } + : size(size_), + resource(std::move(resource_)) {} template T& getResource() const { @@ -51,8 +50,11 @@ class TextureBinding { TextureMipMapType mipmap_ = TextureMipMapType::No, TextureWrapType wrapX_ = TextureWrapType::Clamp, TextureWrapType wrapY_ = TextureWrapType::Clamp) - : resource(&resource_), filter(filter_), mipmap(mipmap_), wrapX(wrapX_), wrapY(wrapY_) { - } + : resource(&resource_), + filter(filter_), + mipmap(mipmap_), + wrapX(wrapX_), + wrapY(wrapY_) {} TextureResource* resource; TextureFilterType filter; @@ -71,8 +73,8 @@ class TextureBindings> final public: template - TextureBindings(Args&&... args) : Base(std::forward(args)...) { - } + TextureBindings(Args&&... args) + : Base(std::forward(args)...) {} }; } // namespace gfx diff --git a/src/mbgl/gfx/uniform.hpp b/src/mbgl/gfx/uniform.hpp index f6896b91387..c69d6f0141d 100644 --- a/src/mbgl/gfx/uniform.hpp +++ b/src/mbgl/gfx/uniform.hpp @@ -5,28 +5,22 @@ #include -#define MBGL_DEFINE_UNIFORM_SCALAR(type_, name_) \ - struct name_ { \ - using Value = type_; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_UNIFORM_SCALAR(type_, name_) \ + struct name_ { \ + using Value = type_; \ + static constexpr auto name() { return #name_; } \ } -#define MBGL_DEFINE_UNIFORM_VECTOR(type_, n_, name_) \ - struct name_ { \ - using Value = std::array; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_UNIFORM_VECTOR(type_, n_, name_) \ + struct name_ { \ + using Value = std::array; \ + static constexpr auto name() { return #name_; } \ } -#define MBGL_DEFINE_UNIFORM_MATRIX(type_, n_, name_) \ - struct name_ { \ - using Value = std::array; \ - static constexpr auto name() { \ - return #name_; \ - } \ +#define MBGL_DEFINE_UNIFORM_MATRIX(type_, n_, name_) \ + struct name_ { \ + using Value = std::array; \ + static constexpr auto name() { return #name_; } \ } namespace mbgl { @@ -36,14 +30,13 @@ template class UniformValues; template -class UniformValues> final - : public IndexedTuple, TypeList> { +class UniformValues> final : public IndexedTuple, TypeList> { using Base = IndexedTuple, TypeList>; public: template - UniformValues(Args&&... args) : Base(std::forward(args)...) { - } + UniformValues(Args&&... args) + : Base(std::forward(args)...) {} }; } // namespace gfx diff --git a/src/mbgl/gfx/upload_pass.hpp b/src/mbgl/gfx/upload_pass.hpp index 4324cb57738..bbb429b8407 100644 --- a/src/mbgl/gfx/upload_pass.hpp +++ b/src/mbgl/gfx/upload_pass.hpp @@ -24,16 +24,13 @@ class UploadPass { UploadPass(const UploadPass&) = delete; UploadPass& operator=(const UploadPass&) = delete; - DebugGroup createDebugGroup(const char* name) { - return { *this, name }; - } + DebugGroup createDebugGroup(const char* name) { return {*this, name}; } public: template - VertexBuffer - createVertexBuffer(VertexVector&& v, - const BufferUsageType usage = BufferUsageType::StaticDraw) { - return { v.elements(), createVertexBufferResource(v.data(), v.bytes(), usage) }; + VertexBuffer createVertexBuffer(VertexVector&& v, + const BufferUsageType usage = BufferUsageType::StaticDraw) { + return {v.elements(), createVertexBufferResource(v.data(), v.bytes(), usage)}; } template @@ -45,7 +42,7 @@ class UploadPass { template IndexBuffer createIndexBuffer(IndexVector&& v, const BufferUsageType usage = BufferUsageType::StaticDraw) { - return { v.elements(), createIndexBufferResource(v.data(), v.bytes(), usage) }; + return {v.elements(), createIndexBufferResource(v.data(), v.bytes(), usage)}; } template @@ -58,23 +55,19 @@ class UploadPass { virtual std::unique_ptr createVertexBufferResource(const void* data, std::size_t size, BufferUsageType) = 0; - virtual void - updateVertexBufferResource(VertexBufferResource&, const void* data, std::size_t size) = 0; + virtual void updateVertexBufferResource(VertexBufferResource&, const void* data, std::size_t size) = 0; virtual std::unique_ptr createIndexBufferResource(const void* data, std::size_t size, BufferUsageType) = 0; - virtual void - updateIndexBufferResource(IndexBufferResource&, const void* data, std::size_t size) = 0; + virtual void updateIndexBufferResource(IndexBufferResource&, const void* data, std::size_t size) = 0; public: // Create a texture from an image with data. template - Texture createTexture(const Image& image, - TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { + Texture createTexture(const Image& image, TextureChannelDataType type = TextureChannelDataType::UnsignedByte) { auto format = image.channels == 4 ? TexturePixelType::RGBA : TexturePixelType::Alpha; - return { image.size, - createTextureResource(image.size, image.data.get(), format, type) }; + return {image.size, createTextureResource(image.size, image.data.get(), format, type)}; } template @@ -99,12 +92,19 @@ class UploadPass { } protected: - virtual std::unique_ptr createTextureResource( - Size, const void* data, TexturePixelType, TextureChannelDataType) = 0; - virtual void updateTextureResource(TextureResource&, Size, const void* data, - TexturePixelType, TextureChannelDataType) = 0; - virtual void updateTextureResourceSub(TextureResource&, uint16_t xOffset, uint16_t yOffset, Size, const void* data, - TexturePixelType, TextureChannelDataType) = 0; + virtual std::unique_ptr createTextureResource(Size, + const void* data, + TexturePixelType, + TextureChannelDataType) = 0; + virtual void updateTextureResource( + TextureResource&, Size, const void* data, TexturePixelType, TextureChannelDataType) = 0; + virtual void updateTextureResourceSub(TextureResource&, + uint16_t xOffset, + uint16_t yOffset, + Size, + const void* data, + TexturePixelType, + TextureChannelDataType) = 0; }; } // namespace gfx diff --git a/src/mbgl/gfx/vertex_buffer.hpp b/src/mbgl/gfx/vertex_buffer.hpp index fe98ec65052..a70fee05036 100644 --- a/src/mbgl/gfx/vertex_buffer.hpp +++ b/src/mbgl/gfx/vertex_buffer.hpp @@ -9,18 +9,20 @@ namespace gfx { class VertexBufferResource { protected: VertexBufferResource() = default; + public: virtual ~VertexBufferResource() = default; }; -// This class has a template argument that we use to specify the vertex type. It is not used by -// the implementation, but serves type checking purposes during build time. +// This class has a template argument that we use to specify the vertex type. It +// is not used by the implementation, but serves type checking purposes during +// build time. template class VertexBuffer { public: VertexBuffer(const std::size_t elements_, std::unique_ptr&& resource_) - : elements(elements_), resource(std::move(resource_)) { - } + : elements(elements_), + resource(std::move(resource_)) {} std::size_t elements; diff --git a/src/mbgl/gfx/vertex_vector.hpp b/src/mbgl/gfx/vertex_vector.hpp index 091ecb912ec..fdda3c75070 100644 --- a/src/mbgl/gfx/vertex_vector.hpp +++ b/src/mbgl/gfx/vertex_vector.hpp @@ -11,43 +11,29 @@ template class VertexVector { public: using Vertex = V; - template + template void emplace_back(Arg&& vertex) { v.emplace_back(std::forward(vertex)); } - void extend(std::size_t n, const Vertex& val) { - v.resize(v.size() + n, val); - } + void extend(std::size_t n, const Vertex& val) { v.resize(v.size() + n, val); } Vertex& at(std::size_t n) { assert(n < v.size()); return v.at(n); } - std::size_t elements() const { - return v.size(); - } + std::size_t elements() const { return v.size(); } - std::size_t bytes() const { - return v.size() * sizeof(Vertex); - } + std::size_t bytes() const { return v.size() * sizeof(Vertex); } - bool empty() const { - return v.empty(); - } + bool empty() const { return v.empty(); } - void clear() { - v.clear(); - } + void clear() { v.clear(); } - const Vertex* data() const { - return v.data(); - } + const Vertex* data() const { return v.data(); } - const std::vector& vector() const { - return v; - } + const std::vector& vector() const { return v; } private: std::vector v; diff --git a/src/mbgl/gl/attribute.hpp b/src/mbgl/gl/attribute.hpp index 88836164971..52a44d29e13 100644 --- a/src/mbgl/gl/attribute.hpp +++ b/src/mbgl/gl/attribute.hpp @@ -23,8 +23,7 @@ class AttributeLocations; template class AttributeLocations> final { private: - using Locations = - IndexedTuple, TypeList>...>>; + using Locations = IndexedTuple, TypeList>...>>; Locations locations; @@ -33,7 +32,7 @@ class AttributeLocations> final { void queryLocations(const ProgramID& id) { locations = Locations{ - queryLocation(id, concat_literals<&string_literal<'a', '_'>::value, &As::name>::value())... }; + queryLocation(id, concat_literals<&string_literal<'a', '_'>::value, &As::name>::value())...}; using TypeOfFirst = typename std::tuple_element_t<0, std::tuple>; [[maybe_unused]] auto first = locations.template get(); assert(first && first.value() == 0); @@ -42,23 +41,25 @@ class AttributeLocations> final { static constexpr const char* getFirstAttribName() { // Static assert that attribute list starts with position: we bind it on location 0. using TypeOfFirst = typename std::tuple_element_t<0, std::tuple>; - static_assert(std::is_same::value || std::is_same::value || - std::is_same::value, "Program must start with position related attribute."); + static_assert(std::is_same::value || + std::is_same::value || + std::is_same::value, + "Program must start with position related attribute."); return concat_literals<&string_literal<'a', '_'>::value, TypeOfFirst::name>::value(); } NamedAttributeLocations getNamedLocations() const { NamedAttributeLocations result; - auto maybeAddLocation = [&] (const std::string& name, const std::optional& location) { + auto maybeAddLocation = [&](const std::string& name, const std::optional& location) { if (location) { result.emplace_back(name, *location); } }; - util::ignore({ (maybeAddLocation(concat_literals<&string_literal<'a', '_'>::value, &As::name>::value(), - locations.template get()), - 0)... }); + util::ignore({(maybeAddLocation(concat_literals<&string_literal<'a', '_'>::value, &As::name>::value(), + locations.template get()), + 0)...}); return result; } @@ -67,14 +68,14 @@ class AttributeLocations> final { AttributeBindingArray result; result.resize(sizeof...(As)); - auto maybeAddBinding = [&] (const std::optional& location, - const std::optional& binding) { + auto maybeAddBinding = [&](const std::optional& location, + const std::optional& binding) { if (location) { result.at(*location) = binding; } }; - util::ignore({ (maybeAddBinding(locations.template get(), bindings.template get()), 0)... }); + util::ignore({(maybeAddBinding(locations.template get(), bindings.template get()), 0)...}); return result; } @@ -95,18 +96,18 @@ class AttributeKey> final { static uint32_t compute(const gfx::AttributeBindings>& bindings) { uint32_t value = 0; util::ignore( - { (bindings.template get() ? (void)(value |= 1 << TypeIndex::value) - : (void)0, - 0)... }); + {(bindings.template get() ? (void)(value |= 1 << TypeIndex::value) : (void)0, 0)...}); return value; } static std::string defines(const gfx::AttributeBindings>& bindings) { std::string result; - util::ignore({ (!bindings.template get() - ? (void)(result += concat_literals<&attributeDefinePrefix, &As::name, &string_literal<'\n'>::value>::value()) - : (void)0, - 0)... }); + util::ignore( + {(!bindings.template get() + ? (void)(result += + concat_literals<&attributeDefinePrefix, &As::name, &string_literal<'\n'>::value>::value()) + : (void)0, + 0)...}); return result; } }; diff --git a/src/mbgl/gl/command_encoder.cpp b/src/mbgl/gl/command_encoder.cpp index a7df14df09a..486096e7230 100644 --- a/src/mbgl/gl/command_encoder.cpp +++ b/src/mbgl/gl/command_encoder.cpp @@ -16,13 +16,12 @@ CommandEncoder::~CommandEncoder() { context.performCleanup(); } -std::unique_ptr -CommandEncoder::createUploadPass(const char* name) { +std::unique_ptr CommandEncoder::createUploadPass(const char* name) { return std::make_unique(*this, name); } -std::unique_ptr -CommandEncoder::createRenderPass(const char* name, const gfx::RenderPassDescriptor& descriptor) { +std::unique_ptr CommandEncoder::createRenderPass(const char* name, + const gfx::RenderPassDescriptor& descriptor) { return std::make_unique(*this, name, descriptor); } @@ -35,8 +34,8 @@ void CommandEncoder::pushDebugGroup(const char* name) { #ifndef NDEBUG if (auto debugging = context.getDebuggingExtension()) { if (debugging->pushDebugGroup) { - MBGL_CHECK_ERROR(debugging->pushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0, - platform::GLsizei(strlen(name)), name)); + MBGL_CHECK_ERROR( + debugging->pushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0, platform::GLsizei(strlen(name)), name)); } else if (debugging->pushGroupMarkerEXT) { MBGL_CHECK_ERROR(debugging->pushGroupMarkerEXT(platform::GLsizei(strlen(name) + 1), name)); } diff --git a/src/mbgl/gl/command_encoder.hpp b/src/mbgl/gl/command_encoder.hpp index f47aad49464..8c3e575453f 100644 --- a/src/mbgl/gl/command_encoder.hpp +++ b/src/mbgl/gl/command_encoder.hpp @@ -9,8 +9,8 @@ class Context; class CommandEncoder final : public gfx::CommandEncoder { public: - explicit CommandEncoder(gl::Context& context_) : context(context_) { - } + explicit CommandEncoder(gl::Context& context_) + : context(context_) {} ~CommandEncoder() override; diff --git a/src/mbgl/gl/context.cpp b/src/mbgl/gl/context.cpp index 6bbb433f3d4..2d3e0b06782 100644 --- a/src/mbgl/gl/context.cpp +++ b/src/mbgl/gl/context.cpp @@ -67,11 +67,8 @@ Context::~Context() noexcept { } void Context::initializeExtensions(const std::function& getProcAddress) { - if (const auto* extensions = - reinterpret_cast(MBGL_CHECK_ERROR(glGetString(GL_EXTENSIONS)))) { - - auto fn = [&]( - std::initializer_list> probes) -> ProcAddress { + if (const auto* extensions = reinterpret_cast(MBGL_CHECK_ERROR(glGetString(GL_EXTENSIONS)))) { + auto fn = [&](std::initializer_list> probes) -> ProcAddress { for (auto probe : probes) { if (strstr(extensions, probe.first) != nullptr) { if (ProcAddress ptr = getProcAddress(probe.second)) { @@ -89,8 +86,7 @@ void Context::initializeExtensions(const std::function(fn); } } @@ -102,18 +98,22 @@ void Context::enableDebugging() { } // This will enable all messages including performance hints - // MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE)); + // MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, + // GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE)); // This will only enable high and medium severity messages - MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE)); - MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE)); - MBGL_CHECK_ERROR(debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE)); + MBGL_CHECK_ERROR( + debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE)); + MBGL_CHECK_ERROR( + debugging->debugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE)); + MBGL_CHECK_ERROR(debugging->debugMessageControl( + GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE)); MBGL_CHECK_ERROR(debugging->debugMessageCallback(extension::Debugging::DebugCallback, nullptr)); } UniqueShader Context::createShader(ShaderType type, const std::initializer_list& sources) { - UniqueShader result { MBGL_CHECK_ERROR(glCreateShader(static_cast(type))), { this } }; + UniqueShader result{MBGL_CHECK_ERROR(glCreateShader(static_cast(type))), {this}}; MBGL_CHECK_ERROR(glShaderSource(result, static_cast(sources.size()), sources.begin(), nullptr)); MBGL_CHECK_ERROR(glCompileShader(result)); @@ -136,7 +136,7 @@ UniqueShader Context::createShader(ShaderType type, const std::initializer_list< } UniqueProgram Context::createProgram(ShaderID vertexShader, ShaderID fragmentShader, const char* location0AttribName) { - UniqueProgram result { MBGL_CHECK_ERROR(glCreateProgram()), { this } }; + UniqueProgram result{MBGL_CHECK_ERROR(glCreateProgram()), {this}}; MBGL_CHECK_ERROR(glAttachShader(result, vertexShader)); MBGL_CHECK_ERROR(glAttachShader(result, fragmentShader)); @@ -193,8 +193,8 @@ VertexArray Context::createVertexArray() { VertexArrayID id = 0; MBGL_CHECK_ERROR(glGenVertexArrays(1, &id)); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueVertexArray vao(std::move(id), { this }); - return { UniqueVertexArrayState(new VertexArrayState(std::move(vao)), VertexArrayStateDeleter { true })}; + UniqueVertexArray vao(std::move(id), {this}); + return {UniqueVertexArrayState(new VertexArrayState(std::move(vao)), VertexArrayStateDeleter{true})}; } UniqueFramebuffer Context::createFramebuffer() { @@ -202,29 +202,36 @@ UniqueFramebuffer Context::createFramebuffer() { MBGL_CHECK_ERROR(glGenFramebuffers(1, &id)); stats.numFrameBuffers++; // NOLINTNEXTLINE(performance-move-const-arg) - return UniqueFramebuffer{ std::move(id), { this } }; + return UniqueFramebuffer{std::move(id), {this}}; } -std::unique_ptr Context::createTextureResource( - const Size size, const gfx::TexturePixelType format, const gfx::TextureChannelDataType type) { +std::unique_ptr Context::createTextureResource(const Size size, + const gfx::TexturePixelType format, + const gfx::TextureChannelDataType type) { auto obj = createUniqueTexture(); int textureByteSize = gl::TextureResource::getStorageSize(size, format, type); stats.memTextures += textureByteSize; - std::unique_ptr resource = - std::make_unique(std::move(obj), textureByteSize); + std::unique_ptr resource = std::make_unique(std::move(obj), + textureByteSize); // Always use texture unit 0 for manipulating it. activeTextureUnit = 0; texture[0] = static_cast(*resource).texture; // Creates an empty texture with the specified size and format. - MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, Enum::sizedFor(format, type), - size.width, size.height, 0, + MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, + 0, + Enum::sizedFor(format, type), + size.width, + size.height, + 0, Enum::to(format), - Enum::to(type), nullptr)); + Enum::to(type), + nullptr)); - // We are using clamp to edge here since OpenGL ES doesn't allow GL_REPEAT on NPOT textures. - // We use those when the pixelRatio isn't a power of two, e.g. on iPhone 6 Plus. + // We are using clamp to edge here since OpenGL ES doesn't allow GL_REPEAT + // on NPOT textures. We use those when the pixelRatio isn't a power of two, + // e.g. on iPhone 6 Plus. MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); @@ -233,12 +240,12 @@ std::unique_ptr Context::createTextureResource( return resource; } -std::unique_ptr -Context::createRenderbufferResource(const gfx::RenderbufferPixelType type, const Size size) { +std::unique_ptr Context::createRenderbufferResource(const gfx::RenderbufferPixelType type, + const Size size) { RenderbufferID id = 0; MBGL_CHECK_ERROR(glGenRenderbuffers(1, &id)); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueRenderbuffer renderbuffer{ std::move(id), { this } }; + UniqueRenderbuffer renderbuffer{std::move(id), {this}}; bindRenderbuffer = renderbuffer; MBGL_CHECK_ERROR( @@ -247,18 +254,18 @@ Context::createRenderbufferResource(const gfx::RenderbufferPixelType type, const return std::make_unique(std::move(renderbuffer)); } - -std::unique_ptr Context::readFramebuffer(const Size size, const gfx::TexturePixelType format, const bool flip) { +std::unique_ptr Context::readFramebuffer(const Size size, + const gfx::TexturePixelType format, + const bool flip) { const size_t stride = size.width * (format == gfx::TexturePixelType::RGBA ? 4 : 1); auto data = std::make_unique(stride * size.height); - // When reading data from the framebuffer, make sure that we are storing the values - // tightly packed into the buffer to avoid buffer overruns. - pixelStorePack = { 1 }; + // When reading data from the framebuffer, make sure that we are storing the + // values tightly packed into the buffer to avoid buffer overruns. + pixelStorePack = {1}; - MBGL_CHECK_ERROR(glReadPixels(0, 0, size.width, size.height, - Enum::to(format), GL_UNSIGNED_BYTE, - data.get())); + MBGL_CHECK_ERROR(glReadPixels( + 0, 0, size.width, size.height, Enum::to(format), GL_UNSIGNED_BYTE, data.get())); if (flip) { auto tmp = std::make_unique(stride); @@ -279,50 +286,51 @@ void checkFramebuffer() { GLenum status = MBGL_CHECK_ERROR(glCheckFramebufferStatus(GL_FRAMEBUFFER)); if (status != GL_FRAMEBUFFER_COMPLETE) { switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - throw std::runtime_error("Couldn't create framebuffer: incomplete attachment"); - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - throw std::runtime_error("Couldn't create framebuffer: incomplete missing attachment"); + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + throw std::runtime_error("Couldn't create framebuffer: incomplete attachment"); + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + throw std::runtime_error( + "Couldn't create framebuffer: incomplete missing " + "attachment"); #ifdef GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - throw std::runtime_error("Couldn't create framebuffer: incomplete draw buffer"); + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + throw std::runtime_error("Couldn't create framebuffer: incomplete draw buffer"); #endif #ifdef GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - throw std::runtime_error("Couldn't create framebuffer: incomplete read buffer"); + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + throw std::runtime_error("Couldn't create framebuffer: incomplete read buffer"); #endif #ifdef GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - throw std::runtime_error("Couldn't create framebuffer: incomplete dimensions"); + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + throw std::runtime_error("Couldn't create framebuffer: incomplete dimensions"); #endif - case GL_FRAMEBUFFER_UNSUPPORTED: - throw std::runtime_error("Couldn't create framebuffer: unsupported"); - default: - throw std::runtime_error("Couldn't create framebuffer: other"); + case GL_FRAMEBUFFER_UNSUPPORTED: + throw std::runtime_error("Couldn't create framebuffer: unsupported"); + default: + throw std::runtime_error("Couldn't create framebuffer: other"); } } } -void bindDepthStencilRenderbuffer( - const gfx::Renderbuffer& depthStencil) { +void bindDepthStencilRenderbuffer(const gfx::Renderbuffer& depthStencil) { auto& depthStencilResource = depthStencil.getResource(); #ifdef GL_DEPTH_STENCIL_ATTACHMENT - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, depthStencilResource.renderbuffer)); + MBGL_CHECK_ERROR(glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthStencilResource.renderbuffer)); #else - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, - depthStencilResource.renderbuffer)); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, depthStencilResource.renderbuffer)); + MBGL_CHECK_ERROR(glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthStencilResource.renderbuffer)); + MBGL_CHECK_ERROR(glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthStencilResource.renderbuffer)); #endif } } // namespace -Framebuffer -Context::createFramebuffer(const gfx::Renderbuffer& color, - const gfx::Renderbuffer& depthStencil) { +Framebuffer Context::createFramebuffer( + const gfx::Renderbuffer& color, + const gfx::Renderbuffer& depthStencil) { if (color.getSize() != depthStencil.getSize()) { throw std::runtime_error("Renderbuffer size mismatch"); } @@ -330,67 +338,65 @@ Context::createFramebuffer(const gfx::Renderbuffer(); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_RENDERBUFFER, colorResource.renderbuffer)); + MBGL_CHECK_ERROR( + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorResource.renderbuffer)); bindDepthStencilRenderbuffer(depthStencil); checkFramebuffer(); - return { color.getSize(), std::move(fbo) }; + return {color.getSize(), std::move(fbo)}; } Framebuffer Context::createFramebuffer(const gfx::Renderbuffer& color) { auto fbo = createFramebuffer(); bindFramebuffer = fbo; auto& colorResource = color.getResource(); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_RENDERBUFFER, colorResource.renderbuffer)); + MBGL_CHECK_ERROR( + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorResource.renderbuffer)); checkFramebuffer(); - return { color.getSize(), std::move(fbo) }; + return {color.getSize(), std::move(fbo)}; } -Framebuffer -Context::createFramebuffer(const gfx::Texture& color, - const gfx::Renderbuffer& depthStencil) { +Framebuffer Context::createFramebuffer( + const gfx::Texture& color, const gfx::Renderbuffer& depthStencil) { if (color.size != depthStencil.getSize()) { throw std::runtime_error("Renderbuffer size mismatch"); } auto fbo = createFramebuffer(); bindFramebuffer = fbo; - MBGL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - color.getResource().texture, 0)); + MBGL_CHECK_ERROR(glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color.getResource().texture, 0)); bindDepthStencilRenderbuffer(depthStencil); checkFramebuffer(); - return { color.size, std::move(fbo) }; + return {color.size, std::move(fbo)}; } Framebuffer Context::createFramebuffer(const gfx::Texture& color) { auto fbo = createFramebuffer(); bindFramebuffer = fbo; - MBGL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - color.getResource().texture, 0)); + MBGL_CHECK_ERROR(glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color.getResource().texture, 0)); checkFramebuffer(); - return { color.size, std::move(fbo) }; + return {color.size, std::move(fbo)}; } -Framebuffer -Context::createFramebuffer(const gfx::Texture& color, - const gfx::Renderbuffer& depth) { +Framebuffer Context::createFramebuffer(const gfx::Texture& color, + const gfx::Renderbuffer& depth) { if (color.size != depth.getSize()) { throw std::runtime_error("Renderbuffer size mismatch"); } auto fbo = createFramebuffer(); bindFramebuffer = fbo; - MBGL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - color.getResource().texture, 0)); + MBGL_CHECK_ERROR(glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color.getResource().texture, 0)); auto& depthResource = depth.getResource(); - MBGL_CHECK_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, - depthResource.renderbuffer)); + MBGL_CHECK_ERROR( + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthResource.renderbuffer)); checkFramebuffer(); - return { depth.getSize(), std::move(fbo) }; + return {depth.getSize(), std::move(fbo)}; } -std::unique_ptr -Context::createOffscreenTexture(const Size size, const gfx::TextureChannelDataType type) { +std::unique_ptr Context::createOffscreenTexture(const Size size, + const gfx::TextureChannelDataType type) { return std::make_unique(*this, size, type); } @@ -432,16 +438,14 @@ void Context::setDirtyState() { pixelStorePack.setDirty(); pixelStoreUnpack.setDirty(); for (auto& tex : texture) { - tex.setDirty(); + tex.setDirty(); } vertexBuffer.setDirty(); bindVertexArray.setDirty(); globalVertexArrayState.setDirty(); } -void Context::clear(std::optional color, - std::optional depth, - std::optional stencil) { +void Context::clear(std::optional color, std::optional depth, std::optional stencil) { GLbitfield mask = 0; if (color) { @@ -481,8 +485,9 @@ void Context::setDepthMode(const gfx::DepthMode& depth) { if (depth.func == gfx::DepthFunctionType::Always && depth.mask != gfx::DepthMaskType::ReadWrite) { depthTest = false; - // Workaround for rendering errors on Adreno 2xx GPUs. Depth-related state should - // not matter when the depth test is disabled, but on these GPUs it apparently does. + // Workaround for rendering errors on Adreno 2xx GPUs. Depth-related + // state should not matter when the depth test is disabled, but on these + // GPUs it apparently does. // https://github.com/mapbox/mapbox-gl-native/issues/9164 depthFunc = depth.func; depthMask = depth.mask; @@ -501,10 +506,8 @@ void Context::setStencilMode(const gfx::StencilMode& stencil) { } else { stencilTest = true; stencilMask = stencil.mask; - stencilOp = { stencil.fail, stencil.depthFail, stencil.pass }; - apply_visitor([&] (const auto& test) { - stencilFunc = { test.func, stencil.ref, test.mask }; - }, stencil.test); + stencilOp = {stencil.fail, stencil.depthFail, stencil.pass}; + apply_visitor([&](const auto& test) { stencilFunc = {test.func, stencil.ref, test.mask}; }, stencil.test); } } @@ -514,10 +517,12 @@ void Context::setColorMode(const gfx::ColorMode& color) { } else { blend = true; blendColor = color.blendColor; - apply_visitor([&] (const auto& blendFunction) { - blendEquation = gfx::ColorBlendEquationType(blendFunction.equation); - blendFunc = { blendFunction.srcFactor, blendFunction.dstFactor }; - }, color.blendFunction); + apply_visitor( + [&](const auto& blendFunction) { + blendEquation = gfx::ColorBlendEquationType(blendFunction.equation); + blendFunc = {blendFunction.srcFactor, blendFunction.dstFactor}; + }, + color.blendFunction); } colorMask = color.mask; @@ -543,33 +548,30 @@ void Context::finish() { MBGL_CHECK_ERROR(glFinish()); } -void Context::draw(const gfx::DrawMode& drawMode, - std::size_t indexOffset, - std::size_t indexLength) { +void Context::draw(const gfx::DrawMode& drawMode, std::size_t indexOffset, std::size_t indexLength) { switch (drawMode.type) { - case gfx::DrawModeType::Points: - break; - case gfx::DrawModeType::Lines: - case gfx::DrawModeType::LineLoop: - case gfx::DrawModeType::LineStrip: - lineWidth = drawMode.size; - break; - default: - break; + case gfx::DrawModeType::Points: + break; + case gfx::DrawModeType::Lines: + case gfx::DrawModeType::LineLoop: + case gfx::DrawModeType::LineStrip: + lineWidth = drawMode.size; + break; + default: + break; } - MBGL_CHECK_ERROR(glDrawElements( - Enum::to(drawMode.type), - static_cast(indexLength), - GL_UNSIGNED_SHORT, - reinterpret_cast(sizeof(uint16_t) * indexOffset))); + MBGL_CHECK_ERROR(glDrawElements(Enum::to(drawMode.type), + static_cast(indexLength), + GL_UNSIGNED_SHORT, + reinterpret_cast(sizeof(uint16_t) * indexOffset))); stats.numDrawCalls++; } void Context::performCleanup() { - // TODO: Find a better way to unbind VAOs after we're done with them without introducing - // unnecessary bind(0)/bind(N) sequences. + // TODO: Find a better way to unbind VAOs after we're done with them without + // introducing unnecessary bind(0)/bind(N) sequences. { activeTextureUnit = 1; texture[1] = 0; @@ -635,16 +637,14 @@ void Context::performCleanup() { bindFramebuffer.setDirty(); } } - MBGL_CHECK_ERROR( - glDeleteFramebuffers(int(abandonedFramebuffers.size()), abandonedFramebuffers.data())); + MBGL_CHECK_ERROR(glDeleteFramebuffers(int(abandonedFramebuffers.size()), abandonedFramebuffers.data())); stats.numFrameBuffers -= int(abandonedFramebuffers.size()); assert(stats.numFrameBuffers >= 0); abandonedFramebuffers.clear(); } if (!abandonedRenderbuffers.empty()) { - MBGL_CHECK_ERROR(glDeleteRenderbuffers(int(abandonedRenderbuffers.size()), - abandonedRenderbuffers.data())); + MBGL_CHECK_ERROR(glDeleteRenderbuffers(int(abandonedRenderbuffers.size()), abandonedRenderbuffers.data())); abandonedRenderbuffers.clear(); } } @@ -652,8 +652,8 @@ void Context::performCleanup() { void Context::reduceMemoryUsage() { performCleanup(); - // Ensure that all pending actions are executed to ensure that they happen before the app goes - // to the background. + // Ensure that all pending actions are executed to ensure that they happen + // before the app goes to the background. MBGL_CHECK_ERROR(glFinish()); } diff --git a/src/mbgl/gl/context.hpp b/src/mbgl/gl/context.hpp index 186b2925635..0cecda77215 100644 --- a/src/mbgl/gl/context.hpp +++ b/src/mbgl/gl/context.hpp @@ -15,7 +15,6 @@ #include #include - #include #include #include @@ -62,30 +61,24 @@ class Context final : public gfx::Context { Framebuffer createFramebuffer(const gfx::Texture&, const gfx::Renderbuffer&); Framebuffer createFramebuffer(const gfx::Texture&); - Framebuffer createFramebuffer(const gfx::Texture&, - const gfx::Renderbuffer&); + Framebuffer createFramebuffer(const gfx::Texture&, const gfx::Renderbuffer&); template + : gfx::TexturePixelType::Alpha> Image readFramebuffer(const Size size, bool flip = true) { - static_assert(Image::channels == (format == gfx::TexturePixelType::RGBA ? 4 : 1), - "image format mismatch"); - return { size, readFramebuffer(size, format, flip) }; + static_assert(Image::channels == (format == gfx::TexturePixelType::RGBA ? 4 : 1), "image format mismatch"); + return {size, readFramebuffer(size, format, flip)}; } - void clear(std::optional color, - std::optional depth, - std::optional stencil); + void clear(std::optional color, std::optional depth, std::optional stencil); void setDepthMode(const gfx::DepthMode&); void setStencilMode(const gfx::StencilMode&); void setColorMode(const gfx::ColorMode&); void setCullFaceMode(const gfx::CullFaceMode&); - void draw(const gfx::DrawMode&, - std::size_t indexOffset, - std::size_t indexLength); + void draw(const gfx::DrawMode&, std::size_t indexOffset, std::size_t indexLength); void finish(); @@ -100,24 +93,16 @@ class Context final : public gfx::Context { void reset(); bool empty() const { - return pooledTextures.empty() - && abandonedPrograms.empty() - && abandonedShaders.empty() - && abandonedBuffers.empty() - && abandonedTextures.empty() - && abandonedVertexArrays.empty() - && abandonedFramebuffers.empty(); + return pooledTextures.empty() && abandonedPrograms.empty() && abandonedShaders.empty() && + abandonedBuffers.empty() && abandonedTextures.empty() && abandonedVertexArrays.empty() && + abandonedFramebuffers.empty(); } void setDirtyState(); - extension::Debugging* getDebuggingExtension() const { - return debugging.get(); - } + extension::Debugging* getDebuggingExtension() const { return debugging.get(); } - void setCleanupOnDestruction(bool cleanup) { - cleanupOnDestruction = cleanup; - } + void setCleanupOnDestruction(bool cleanup) { cleanupOnDestruction = cleanup; } private: RendererBackend& backend; @@ -136,7 +121,7 @@ class Context final : public gfx::Context { State vertexBuffer; State bindVertexArray; - VertexArrayState globalVertexArrayState { UniqueVertexArray(0, { const_cast(this) }) }; + VertexArrayState globalVertexArrayState{UniqueVertexArray(0, {const_cast(this)})}; State pixelStorePack; State pixelStoreUnpack; @@ -166,10 +151,12 @@ class Context final : public gfx::Context { std::unique_ptr createOffscreenTexture(Size, gfx::TextureChannelDataType) override; - std::unique_ptr - createTextureResource(Size, gfx::TexturePixelType, gfx::TextureChannelDataType) override; + std::unique_ptr createTextureResource(Size, + gfx::TexturePixelType, + gfx::TextureChannelDataType) override; - std::unique_ptr createRenderbufferResource(gfx::RenderbufferPixelType, Size size) override; + std::unique_ptr createRenderbufferResource(gfx::RenderbufferPixelType, + Size size) override; std::unique_ptr createDrawScopeResource() override; diff --git a/src/mbgl/gl/custom_layer.cpp b/src/mbgl/gl/custom_layer.cpp index 853b6e4008d..bb6740c3749 100644 --- a/src/mbgl/gl/custom_layer.cpp +++ b/src/mbgl/gl/custom_layer.cpp @@ -14,12 +14,10 @@ const LayerTypeInfo typeInfoCustom{"custom", LayerTypeInfo::FadingTiles::NotRequired, LayerTypeInfo::CrossTileIndex::NotRequired, LayerTypeInfo::TileKind::NotRequired}; -} // namespace +} // namespace -CustomLayer::CustomLayer(const std::string& layerID, - std::unique_ptr host) - : Layer(makeMutable(layerID, std::move(host))) { -} +CustomLayer::CustomLayer(const std::string& layerID, std::unique_ptr host) + : Layer(makeMutable(layerID, std::move(host))) {} CustomLayer::~CustomLayer() = default; @@ -39,7 +37,7 @@ std::unique_ptr CustomLayer::cloneRef(const std::string&) const { using namespace conversion; std::optional CustomLayer::setPropertyInternal(const std::string&, const Convertible&) { - return Error { "layer doesn't support this property" }; + return Error{"layer doesn't support this property"}; } StyleProperty CustomLayer::getProperty(const std::string&) const { diff --git a/src/mbgl/gl/custom_layer_factory.cpp b/src/mbgl/gl/custom_layer_factory.cpp index 616d0271e0a..f8d98b69483 100644 --- a/src/mbgl/gl/custom_layer_factory.cpp +++ b/src/mbgl/gl/custom_layer_factory.cpp @@ -9,7 +9,8 @@ const style::LayerTypeInfo* CustomLayerFactory::getTypeInfo() const noexcept { return style::CustomLayer::Impl::staticTypeInfo(); } -std::unique_ptr CustomLayerFactory::createLayer(const std::string&, const style::conversion::Convertible&) noexcept { +std::unique_ptr CustomLayerFactory::createLayer(const std::string&, + const style::conversion::Convertible&) noexcept { assert(false); return nullptr; } diff --git a/src/mbgl/gl/custom_layer_impl.cpp b/src/mbgl/gl/custom_layer_impl.cpp index 85df44bc800..8268272ae4f 100644 --- a/src/mbgl/gl/custom_layer_impl.cpp +++ b/src/mbgl/gl/custom_layer_impl.cpp @@ -3,8 +3,7 @@ namespace mbgl { namespace style { -CustomLayer::Impl::Impl(const std::string& id_, - std::unique_ptr host_) +CustomLayer::Impl::Impl(const std::string& id_, std::unique_ptr host_) : Layer::Impl(id_, std::string()) { host = std::move(host_); } @@ -13,8 +12,7 @@ bool CustomLayer::Impl::hasLayoutDifference(const Layer::Impl&) const { return false; } -void CustomLayer::Impl::stringifyLayout(rapidjson::Writer&) const { -} +void CustomLayer::Impl::stringifyLayout(rapidjson::Writer&) const {} } // namespace style } // namespace mbgl diff --git a/src/mbgl/gl/custom_layer_impl.hpp b/src/mbgl/gl/custom_layer_impl.hpp index 0c9339adf18..d0ea5f38278 100644 --- a/src/mbgl/gl/custom_layer_impl.hpp +++ b/src/mbgl/gl/custom_layer_impl.hpp @@ -14,8 +14,7 @@ namespace style { class CustomLayer::Impl : public Layer::Impl { public: - Impl(const std::string& id, - std::unique_ptr host); + Impl(const std::string& id, std::unique_ptr host); bool hasLayoutDifference(const Layer::Impl&) const override; void stringifyLayout(rapidjson::Writer&) const override; diff --git a/src/mbgl/gl/debugging_extension.cpp b/src/mbgl/gl/debugging_extension.cpp index 06bdd70d90d..e979f82b9f7 100644 --- a/src/mbgl/gl/debugging_extension.cpp +++ b/src/mbgl/gl/debugging_extension.cpp @@ -11,48 +11,94 @@ void Debugging::DebugCallback(GLenum source, GLenum severity, GLsizei /* length */, const GLchar* message, - const void* /* userParam */) { + const void* /* userParam */ +) { std::string strSource; switch (source) { - case GL_DEBUG_SOURCE_API: strSource = "DEBUG_SOURCE_API"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM: strSource = "DEBUG_SOURCE_WINDOW_SYSTEM"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER: strSource = "DEBUG_SOURCE_SHADER_COMPILER"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY: strSource = "DEBUG_SOURCE_THIRD_PARTY"; break; - case GL_DEBUG_SOURCE_APPLICATION: strSource = "DEBUG_SOURCE_APPLICATION"; break; - case GL_DEBUG_SOURCE_OTHER: strSource = "DEBUG_SOURCE_OTHER"; break; - default: strSource = "(unknown)"; break; + case GL_DEBUG_SOURCE_API: + strSource = "DEBUG_SOURCE_API"; + break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM: + strSource = "DEBUG_SOURCE_WINDOW_SYSTEM"; + break; + case GL_DEBUG_SOURCE_SHADER_COMPILER: + strSource = "DEBUG_SOURCE_SHADER_COMPILER"; + break; + case GL_DEBUG_SOURCE_THIRD_PARTY: + strSource = "DEBUG_SOURCE_THIRD_PARTY"; + break; + case GL_DEBUG_SOURCE_APPLICATION: + strSource = "DEBUG_SOURCE_APPLICATION"; + break; + case GL_DEBUG_SOURCE_OTHER: + strSource = "DEBUG_SOURCE_OTHER"; + break; + default: + strSource = "(unknown)"; + break; } std::string strType; switch (type) { - case GL_DEBUG_TYPE_ERROR: strType = "DEBUG_TYPE_ERROR"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: strType = "DEBUG_TYPE_DEPRECATED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: strType = "DEBUG_TYPE_UNDEFINED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_PERFORMANCE: strType = "DEBUG_TYPE_PERFORMANCE"; break; - case GL_DEBUG_TYPE_PORTABILITY: strType = "DEBUG_TYPE_PORTABILITY"; break; - case GL_DEBUG_TYPE_OTHER: strType = "DEBUG_TYPE_OTHER"; break; - case GL_DEBUG_TYPE_MARKER: strType = "DEBUG_TYPE_MARKER"; break; - case GL_DEBUG_TYPE_PUSH_GROUP: strType = "DEBUG_TYPE_OTHER"; break; - case GL_DEBUG_TYPE_POP_GROUP: strType = "DEBUG_TYPE_POP_GROUP"; break; - default: strSource = "(unknown)"; break; + case GL_DEBUG_TYPE_ERROR: + strType = "DEBUG_TYPE_ERROR"; + break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: + strType = "DEBUG_TYPE_DEPRECATED_BEHAVIOR"; + break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: + strType = "DEBUG_TYPE_UNDEFINED_BEHAVIOR"; + break; + case GL_DEBUG_TYPE_PERFORMANCE: + strType = "DEBUG_TYPE_PERFORMANCE"; + break; + case GL_DEBUG_TYPE_PORTABILITY: + strType = "DEBUG_TYPE_PORTABILITY"; + break; + case GL_DEBUG_TYPE_OTHER: + strType = "DEBUG_TYPE_OTHER"; + break; + case GL_DEBUG_TYPE_MARKER: + strType = "DEBUG_TYPE_MARKER"; + break; + case GL_DEBUG_TYPE_PUSH_GROUP: + strType = "DEBUG_TYPE_OTHER"; + break; + case GL_DEBUG_TYPE_POP_GROUP: + strType = "DEBUG_TYPE_POP_GROUP"; + break; + default: + strSource = "(unknown)"; + break; } std::string strSeverity; mbgl::EventSeverity evtSeverity; switch (severity) { - case GL_DEBUG_SEVERITY_HIGH: strSeverity = "DEBUG_SEVERITY_HIGH"; evtSeverity = mbgl::EventSeverity::Error; break; - case GL_DEBUG_SEVERITY_MEDIUM: strSeverity = "DEBUG_SEVERITY_MEDIUM"; evtSeverity = mbgl::EventSeverity::Warning; break; - case GL_DEBUG_SEVERITY_LOW: strSeverity = "DEBUG_SEVERITY_LOW"; evtSeverity = mbgl::EventSeverity::Info; break; - case GL_DEBUG_SEVERITY_NOTIFICATION: strSeverity = "DEBUG_SEVERITY_NOTIFICATION"; evtSeverity = mbgl::EventSeverity::Debug; break; - default: strSource = "(unknown)"; evtSeverity = mbgl::EventSeverity::Debug; break; + case GL_DEBUG_SEVERITY_HIGH: + strSeverity = "DEBUG_SEVERITY_HIGH"; + evtSeverity = mbgl::EventSeverity::Error; + break; + case GL_DEBUG_SEVERITY_MEDIUM: + strSeverity = "DEBUG_SEVERITY_MEDIUM"; + evtSeverity = mbgl::EventSeverity::Warning; + break; + case GL_DEBUG_SEVERITY_LOW: + strSeverity = "DEBUG_SEVERITY_LOW"; + evtSeverity = mbgl::EventSeverity::Info; + break; + case GL_DEBUG_SEVERITY_NOTIFICATION: + strSeverity = "DEBUG_SEVERITY_NOTIFICATION"; + evtSeverity = mbgl::EventSeverity::Debug; + break; + default: + strSource = "(unknown)"; + evtSeverity = mbgl::EventSeverity::Debug; + break; } - const std::string logMsg = "GL_" + strSource + - " GL_" + strType + - " " + std::to_string(id) + - " GL_" + strSeverity + - " - " + message; + const std::string logMsg = "GL_" + strSource + " GL_" + strType + " " + std::to_string(id) + " GL_" + strSeverity + + " - " + message; mbgl::Log::Record(evtSeverity, mbgl::Event::OpenGL, logMsg); - } } // namespace extension diff --git a/src/mbgl/gl/debugging_extension.hpp b/src/mbgl/gl/debugging_extension.hpp index 0fa5a7b424c..89b23a45ac9 100644 --- a/src/mbgl/gl/debugging_extension.hpp +++ b/src/mbgl/gl/debugging_extension.hpp @@ -3,49 +3,49 @@ #include #include -#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 #define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 -#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 -#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 -#define GL_DEBUG_SOURCE_API 0x8246 -#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 -#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 -#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 -#define GL_DEBUG_SOURCE_APPLICATION 0x824A -#define GL_DEBUG_SOURCE_OTHER 0x824B -#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_TYPE_ERROR 0x824C #define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D -#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E -#define GL_DEBUG_TYPE_PORTABILITY 0x824F -#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 -#define GL_DEBUG_TYPE_OTHER 0x8251 -#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 -#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 -#define GL_DEBUG_LOGGED_MESSAGES 0x9145 -#define GL_DEBUG_SEVERITY_HIGH 0x9146 -#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 -#define GL_DEBUG_SEVERITY_LOW 0x9148 -#define GL_DEBUG_TYPE_MARKER 0x8268 -#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 -#define GL_DEBUG_TYPE_POP_GROUP 0x826A -#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B -#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C -#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D -#define GL_BUFFER 0x82E0 -#define GL_SHADER 0x82E1 -#define GL_PROGRAM 0x82E2 -#define GL_QUERY 0x82E3 -#define GL_PROGRAM_PIPELINE 0x82E4 -#define GL_SAMPLER 0x82E6 -#define GL_MAX_LABEL_LENGTH 0x82E8 -#define GL_DEBUG_OUTPUT 0x92E0 -#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 -#define GL_DISPLAY_LIST 0x82E7 -#define GL_VERTEX_ARRAY 0x8074 -#define GL_TRANSFORM_FEEDBACK 0x8E22 -#define GL_TEXTURE 0x1702 -#define GL_RENDERBUFFER 0x8D41 -#define GL_FRAMEBUFFER 0x8D40 +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_BUFFER 0x82E0 +#define GL_SHADER 0x82E1 +#define GL_PROGRAM 0x82E2 +#define GL_QUERY 0x82E3 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_SAMPLER 0x82E6 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_DISPLAY_LIST 0x82E7 +#define GL_VERTEX_ARRAY 0x8074 +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TEXTURE 0x1702 +#define GL_RENDERBUFFER 0x8D41 +#define GL_FRAMEBUFFER 0x8D40 namespace mbgl { namespace gl { @@ -69,52 +69,39 @@ class Debugging { GLenum severity, GLsizei /* length */, const GLchar* message, - const void* /* userParam */); + const void* /* userParam */ + ); template Debugging(const Fn& loadExtension) : #ifndef NDEBUG - pushDebugGroup( - loadExtension({ { "GL_KHR_debug", "glPushDebugGroup" } })), - popDebugGroup( - loadExtension({ { "GL_KHR_debug", "glPopDebugGroup" } })), - pushGroupMarkerEXT( - loadExtension({ { "GL_EXT_debug_marker", "glPushGroupMarkerEXT" } })), - popGroupMarkerEXT( - loadExtension({ { "GL_EXT_debug_marker", "glPopGroupMarkerEXT" } })), + pushDebugGroup(loadExtension({{"GL_KHR_debug", "glPushDebugGroup"}})), + popDebugGroup(loadExtension({{"GL_KHR_debug", "glPopDebugGroup"}})), + pushGroupMarkerEXT(loadExtension({{"GL_EXT_debug_marker", "glPushGroupMarkerEXT"}})), + popGroupMarkerEXT(loadExtension({{"GL_EXT_debug_marker", "glPopGroupMarkerEXT"}})), #endif - debugMessageControl( - loadExtension({ { "GL_KHR_debug", "glDebugMessageControl" }, - { "GL_ARB_debug_output", "glDebugMessageControlARB" } })), - debugMessageCallback( - loadExtension({ { "GL_KHR_debug", "glDebugMessageCallback" }, - { "GL_ARB_debug_output", "glDebugMessageCallbackARB" } })) { + debugMessageControl(loadExtension( + {{"GL_KHR_debug", "glDebugMessageControl"}, {"GL_ARB_debug_output", "glDebugMessageControlARB"}})), + debugMessageCallback(loadExtension( + {{"GL_KHR_debug", "glDebugMessageCallback"}, {"GL_ARB_debug_output", "glDebugMessageCallbackARB"}})) { } #ifndef NDEBUG - const ExtensionFunction pushDebugGroup; + const ExtensionFunction pushDebugGroup; const ExtensionFunction popDebugGroup; - const ExtensionFunction pushGroupMarkerEXT; + const ExtensionFunction pushGroupMarkerEXT; const ExtensionFunction popGroupMarkerEXT; #endif - const ExtensionFunction debugMessageControl; + const ExtensionFunction + debugMessageControl; - const ExtensionFunction debugMessageCallback; + const ExtensionFunction debugMessageCallback; }; } // namespace extension diff --git a/src/mbgl/gl/defines.hpp b/src/mbgl/gl/defines.hpp index 5f8c748fcbd..7cc3223b246 100644 --- a/src/mbgl/gl/defines.hpp +++ b/src/mbgl/gl/defines.hpp @@ -3,84 +3,84 @@ /* OpenGL ES 2.0 */ /* ClearBufferMask */ -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 /* Boolean */ -#define GL_FALSE 0 -#define GL_TRUE 1 +#define GL_FALSE 0 +#define GL_TRUE 1 /* BeginMode */ -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 /* BlendingFactorDest */ -#define GL_ZERO 0 -#define GL_ONE 1 -#define GL_SRC_COLOR 0x0300 -#define GL_ONE_MINUS_SRC_COLOR 0x0301 -#define GL_SRC_ALPHA 0x0302 -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 -#define GL_DST_ALPHA 0x0304 -#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 /* BlendingFactorSrc */ /* GL_ZERO */ /* GL_ONE */ -#define GL_DST_COLOR 0x0306 -#define GL_ONE_MINUS_DST_COLOR 0x0307 -#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 /* GL_SRC_ALPHA */ /* GL_ONE_MINUS_SRC_ALPHA */ /* GL_DST_ALPHA */ /* GL_ONE_MINUS_DST_ALPHA */ /* BlendEquationSeparate */ -#define GL_FUNC_ADD 0x8006 -#define GL_BLEND_EQUATION 0x8009 -#define GL_BLEND_EQUATION_RGB 0x8009 /* same as BLEND_EQUATION */ -#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_FUNC_ADD 0x8006 +#define GL_BLEND_EQUATION 0x8009 +#define GL_BLEND_EQUATION_RGB 0x8009 /* same as BLEND_EQUATION */ +#define GL_BLEND_EQUATION_ALPHA 0x883D /* BlendSubtract */ -#define GL_FUNC_SUBTRACT 0x800A -#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B /* Separate Blend Functions */ -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_CONSTANT_COLOR 0x8001 -#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 -#define GL_CONSTANT_ALPHA 0x8003 -#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 -#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_BLEND_COLOR 0x8005 /* Buffer Objects */ -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_STREAM_DRAW 0x88E0 -#define GL_STATIC_DRAW 0x88E4 -#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_STREAM_DRAW 0x88E0 +#define GL_STATIC_DRAW 0x88E4 +#define GL_DYNAMIC_DRAW 0x88E8 -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 -#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 /* CullFaceMode */ -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_FRONT_AND_BACK 0x0408 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_FRONT_AND_BACK 0x0408 /* DepthFunction */ /* GL_NEVER */ @@ -93,77 +93,77 @@ /* GL_ALWAYS */ /* EnableCap */ -#define GL_TEXTURE_2D 0x0DE1 -#define GL_CULL_FACE 0x0B44 -#define GL_BLEND 0x0BE2 -#define GL_DITHER 0x0BD0 -#define GL_STENCIL_TEST 0x0B90 -#define GL_DEPTH_TEST 0x0B71 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_CULL_FACE 0x0B44 +#define GL_BLEND 0x0BE2 +#define GL_DITHER 0x0BD0 +#define GL_STENCIL_TEST 0x0B90 +#define GL_DEPTH_TEST 0x0B71 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_COVERAGE 0x80A0 /* ErrorCode */ -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_OUT_OF_MEMORY 0x0505 +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_OUT_OF_MEMORY 0x0505 /* FrontFaceDirection */ -#define GL_CW 0x0900 -#define GL_CCW 0x0901 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 /* GetPName */ -#define GL_LINE_WIDTH 0x0B21 -#define GL_ALIASED_POINT_SIZE_RANGE 0x846D -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E -#define GL_CULL_FACE_MODE 0x0B45 -#define GL_FRONT_FACE 0x0B46 -#define GL_DEPTH_RANGE 0x0B70 -#define GL_DEPTH_WRITEMASK 0x0B72 -#define GL_DEPTH_CLEAR_VALUE 0x0B73 -#define GL_DEPTH_FUNC 0x0B74 -#define GL_STENCIL_CLEAR_VALUE 0x0B91 -#define GL_STENCIL_FUNC 0x0B92 -#define GL_STENCIL_FAIL 0x0B94 -#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 -#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 -#define GL_STENCIL_REF 0x0B97 -#define GL_STENCIL_VALUE_MASK 0x0B93 -#define GL_STENCIL_WRITEMASK 0x0B98 -#define GL_STENCIL_BACK_FUNC 0x8800 -#define GL_STENCIL_BACK_FAIL 0x8801 -#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 -#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 -#define GL_STENCIL_BACK_REF 0x8CA3 -#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 -#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 -#define GL_VIEWPORT 0x0BA2 -#define GL_SCISSOR_BOX 0x0C10 +#define GL_LINE_WIDTH 0x0B21 +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VIEWPORT 0x0BA2 +#define GL_SCISSOR_BOX 0x0C10 /* GL_SCISSOR_TEST */ -#define GL_COLOR_CLEAR_VALUE 0x0C22 -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_ALIGNMENT 0x0D05 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_RED_BITS 0x0D52 -#define GL_GREEN_BITS 0x0D53 -#define GL_BLUE_BITS 0x0D54 -#define GL_ALPHA_BITS 0x0D55 -#define GL_DEPTH_BITS 0x0D56 -#define GL_STENCIL_BITS 0x0D57 -#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_ALPHA_BITS 0x0D55 +#define GL_DEPTH_BITS 0x0D56 +#define GL_STENCIL_BITS 0x0D57 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 /* GL_POLYGON_OFFSET_FILL */ -#define GL_POLYGON_OFFSET_FACTOR 0x8038 -#define GL_TEXTURE_BINDING_2D 0x8069 -#define GL_SAMPLE_BUFFERS 0x80A8 -#define GL_SAMPLES 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB /* GetTextureParameter */ /* GL_TEXTURE_MAG_FILTER */ @@ -171,561 +171,561 @@ /* GL_TEXTURE_WRAP_S */ /* GL_TEXTURE_WRAP_T */ -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 /* HintMode */ -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 /* HintTarget */ -#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_GENERATE_MIPMAP_HINT 0x8192 /* DataType */ -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_INT 0x1404 -#define GL_UNSIGNED_INT 0x1405 -#define GL_FLOAT 0x1406 -#define GL_FIXED 0x140C +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_FIXED 0x140C /* PixelFormat */ -#define GL_STENCIL_INDEX 0x1901 -#define GL_DEPTH_COMPONENT 0x1902 -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_LUMINANCE 0x1909 -#define GL_LUMINANCE_ALPHA 0x190A +#define GL_STENCIL_INDEX 0x1901 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A /* PixelType */ /* GL_UNSIGNED_BYTE */ -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 /* Shaders */ -#define GL_FRAGMENT_SHADER 0x8B30 -#define GL_VERTEX_SHADER 0x8B31 -#define GL_MAX_VERTEX_ATTRIBS 0x8869 -#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB -#define GL_MAX_VARYING_VECTORS 0x8DFC -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C -#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 -#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD -#define GL_SHADER_TYPE 0x8B4F -#define GL_DELETE_STATUS 0x8B80 -#define GL_LINK_STATUS 0x8B82 -#define GL_VALIDATE_STATUS 0x8B83 -#define GL_ATTACHED_SHADERS 0x8B85 -#define GL_ACTIVE_UNIFORMS 0x8B86 -#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 -#define GL_ACTIVE_ATTRIBUTES 0x8B89 -#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A -#define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GL_MAX_VARYING_VECTORS 0x8DFC +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GL_SHADER_TYPE 0x8B4F +#define GL_DELETE_STATUS 0x8B80 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D /* StencilFunction */ -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 /* StencilOp */ /* GL_ZERO */ -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 -#define GL_INVERT 0x150A -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +#define GL_INVERT 0x150A +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 /* StringName */ -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 /* TextureMagFilter */ -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 /* TextureMinFilter */ /* GL_NEAREST */ /* GL_LINEAR */ -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 /* TextureParameterName */ -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 /* TextureTarget */ /* GL_TEXTURE_2D */ -#define GL_TEXTURE 0x1702 - -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_TEXTURE 0x1702 + +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C /* TextureUnit */ -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF -#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 /* TextureWrapMode */ -#define GL_REPEAT 0x2901 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_MIRRORED_REPEAT 0x8370 +#define GL_REPEAT 0x2901 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_MIRRORED_REPEAT 0x8370 /* Uniform Types */ -#define GL_FLOAT_VEC2 0x8B50 -#define GL_FLOAT_VEC3 0x8B51 -#define GL_FLOAT_VEC4 0x8B52 -#define GL_INT_VEC2 0x8B53 -#define GL_INT_VEC3 0x8B54 -#define GL_INT_VEC4 0x8B55 -#define GL_BOOL 0x8B56 -#define GL_BOOL_VEC2 0x8B57 -#define GL_BOOL_VEC3 0x8B58 -#define GL_BOOL_VEC4 0x8B59 -#define GL_FLOAT_MAT2 0x8B5A -#define GL_FLOAT_MAT3 0x8B5B -#define GL_FLOAT_MAT4 0x8B5C -#define GL_SAMPLER_2D 0x8B5E -#define GL_SAMPLER_CUBE 0x8B60 +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_CUBE 0x8B60 /* Vertex Arrays */ -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F /* Read Format */ -#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A -#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B +#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B /* Shader Source */ -#define GL_COMPILE_STATUS 0x8B81 -#define GL_INFO_LOG_LENGTH 0x8B84 -#define GL_SHADER_SOURCE_LENGTH 0x8B88 -#define GL_SHADER_COMPILER 0x8DFA +#define GL_COMPILE_STATUS 0x8B81 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_SHADER_COMPILER 0x8DFA /* Shader Binary */ -#define GL_SHADER_BINARY_FORMATS 0x8DF8 -#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 /* Shader Precision-Specified Types */ -#define GL_LOW_FLOAT 0x8DF0 -#define GL_MEDIUM_FLOAT 0x8DF1 -#define GL_HIGH_FLOAT 0x8DF2 -#define GL_LOW_INT 0x8DF3 -#define GL_MEDIUM_INT 0x8DF4 -#define GL_HIGH_INT 0x8DF5 +#define GL_LOW_FLOAT 0x8DF0 +#define GL_MEDIUM_FLOAT 0x8DF1 +#define GL_HIGH_FLOAT 0x8DF2 +#define GL_LOW_INT 0x8DF3 +#define GL_MEDIUM_INT 0x8DF4 +#define GL_HIGH_INT 0x8DF5 /* Framebuffer Object. */ -#define GL_FRAMEBUFFER 0x8D40 -#define GL_RENDERBUFFER 0x8D41 - -#define GL_RGBA4 0x8056 -#define GL_RGB5_A1 0x8057 -#define GL_RGB565 0x8D62 -#define GL_DEPTH_COMPONENT16 0x81A5 -#define GL_STENCIL_INDEX8 0x8D48 - -#define GL_RENDERBUFFER_WIDTH 0x8D42 -#define GL_RENDERBUFFER_HEIGHT 0x8D43 -#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 -#define GL_RENDERBUFFER_RED_SIZE 0x8D50 -#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 -#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 -#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 -#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 -#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 - -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 - -#define GL_COLOR_ATTACHMENT0 0x8CE0 -#define GL_DEPTH_ATTACHMENT 0x8D00 -#define GL_STENCIL_ATTACHMENT 0x8D20 - -#define GL_NONE 0 - -#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 -#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 -#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 -#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 -#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD - -#define GL_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_RENDERBUFFER_BINDING 0x8CA7 -#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 - -#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 + +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGB565 0x8D62 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_STENCIL_INDEX8 0x8D48 + +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 + +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 + +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 + +#define GL_NONE 0 + +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD + +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 + +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 /* OpenGL ES 3.0 */ -#define GL_READ_BUFFER 0x0C02 -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#define GL_UNPACK_SKIP_ROWS 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS 0x0CF4 -#define GL_PACK_ROW_LENGTH 0x0D02 -#define GL_PACK_SKIP_ROWS 0x0D03 -#define GL_PACK_SKIP_PIXELS 0x0D04 -#define GL_COLOR 0x1800 -#define GL_DEPTH 0x1801 -#define GL_STENCIL 0x1802 -#define GL_RED 0x1903 -#define GL_RGB8 0x8051 -#define GL_RGBA8 0x8058 -#define GL_RGB10_A2 0x8059 -#define GL_TEXTURE_BINDING_3D 0x806A -#define GL_UNPACK_SKIP_IMAGES 0x806D -#define GL_UNPACK_IMAGE_HEIGHT 0x806E -#define GL_TEXTURE_3D 0x806F -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_MAX_3D_TEXTURE_SIZE 0x8073 -#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_TEXTURE_MIN_LOD 0x813A -#define GL_TEXTURE_MAX_LOD 0x813B -#define GL_TEXTURE_BASE_LEVEL 0x813C -#define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_MIN 0x8007 -#define GL_MAX 0x8008 -#define GL_DEPTH_COMPONENT24 0x81A6 -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D -#define GL_CURRENT_QUERY 0x8865 -#define GL_QUERY_RESULT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE 0x8867 -#define GL_BUFFER_MAPPED 0x88BC -#define GL_BUFFER_MAP_POINTER 0x88BD -#define GL_STREAM_READ 0x88E1 -#define GL_STREAM_COPY 0x88E2 -#define GL_STATIC_READ 0x88E5 -#define GL_STATIC_COPY 0x88E6 -#define GL_DYNAMIC_READ 0x88E9 -#define GL_DYNAMIC_COPY 0x88EA -#define GL_MAX_DRAW_BUFFERS 0x8824 -#define GL_DRAW_BUFFER0 0x8825 -#define GL_DRAW_BUFFER1 0x8826 -#define GL_DRAW_BUFFER2 0x8827 -#define GL_DRAW_BUFFER3 0x8828 -#define GL_DRAW_BUFFER4 0x8829 -#define GL_DRAW_BUFFER5 0x882A -#define GL_DRAW_BUFFER6 0x882B -#define GL_DRAW_BUFFER7 0x882C -#define GL_DRAW_BUFFER8 0x882D -#define GL_DRAW_BUFFER9 0x882E -#define GL_DRAW_BUFFER10 0x882F -#define GL_DRAW_BUFFER11 0x8830 -#define GL_DRAW_BUFFER12 0x8831 -#define GL_DRAW_BUFFER13 0x8832 -#define GL_DRAW_BUFFER14 0x8833 -#define GL_DRAW_BUFFER15 0x8834 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A -#define GL_SAMPLER_3D 0x8B5F -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B -#define GL_PIXEL_PACK_BUFFER 0x88EB -#define GL_PIXEL_UNPACK_BUFFER 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF -#define GL_FLOAT_MAT2x3 0x8B65 -#define GL_FLOAT_MAT2x4 0x8B66 -#define GL_FLOAT_MAT3x2 0x8B67 -#define GL_FLOAT_MAT3x4 0x8B68 -#define GL_FLOAT_MAT4x2 0x8B69 -#define GL_FLOAT_MAT4x3 0x8B6A -#define GL_SRGB 0x8C40 -#define GL_SRGB8 0x8C41 -#define GL_SRGB8_ALPHA8 0x8C43 -#define GL_COMPARE_REF_TO_TEXTURE 0x884E -#define GL_MAJOR_VERSION 0x821B -#define GL_MINOR_VERSION 0x821C -#define GL_NUM_EXTENSIONS 0x821D -#define GL_RGBA32F 0x8814 -#define GL_RGB32F 0x8815 -#define GL_RGBA16F 0x881A -#define GL_RGB16F 0x881B -#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD -#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF -#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 -#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 -#define GL_MAX_VARYING_COMPONENTS 0x8B4B -#define GL_TEXTURE_2D_ARRAY 0x8C1A -#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D -#define GL_R11F_G11F_B10F 0x8C3A -#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B -#define GL_RGB9_E5 0x8C3D -#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E -#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 -#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 -#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 -#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 -#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 -#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 -#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_READ_BUFFER 0x0C02 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_RED 0x1903 +#define GL_RGB8 0x8051 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 #define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B -#define GL_INTERLEAVED_ATTRIBS 0x8C8C -#define GL_SEPARATE_ATTRIBS 0x8C8D -#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E -#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F -#define GL_RGBA32UI 0x8D70 -#define GL_RGB32UI 0x8D71 -#define GL_RGBA16UI 0x8D76 -#define GL_RGB16UI 0x8D77 -#define GL_RGBA8UI 0x8D7C -#define GL_RGB8UI 0x8D7D -#define GL_RGBA32I 0x8D82 -#define GL_RGB32I 0x8D83 -#define GL_RGBA16I 0x8D88 -#define GL_RGB16I 0x8D89 -#define GL_RGBA8I 0x8D8E -#define GL_RGB8I 0x8D8F -#define GL_RED_INTEGER 0x8D94 -#define GL_RGB_INTEGER 0x8D98 -#define GL_RGBA_INTEGER 0x8D99 -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#define GL_UNSIGNED_INT_VEC2 0x8DC6 -#define GL_UNSIGNED_INT_VEC3 0x8DC7 -#define GL_UNSIGNED_INT_VEC4 0x8DC8 -#define GL_INT_SAMPLER_2D 0x8DCA -#define GL_INT_SAMPLER_3D 0x8DCB -#define GL_INT_SAMPLER_CUBE 0x8DCC -#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF -#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 -#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 -#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 -#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 -#define GL_BUFFER_ACCESS_FLAGS 0x911F -#define GL_BUFFER_MAP_LENGTH 0x9120 -#define GL_BUFFER_MAP_OFFSET 0x9121 -#define GL_DEPTH_COMPONENT32F 0x8CAC -#define GL_DEPTH32F_STENCIL8 0x8CAD -#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD -#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 -#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 -#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 -#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 -#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 -#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 -#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 -#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 -#define GL_FRAMEBUFFER_DEFAULT 0x8218 -#define GL_FRAMEBUFFER_UNDEFINED 0x8219 -#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A -#define GL_DEPTH_STENCIL 0x84F9 -#define GL_UNSIGNED_INT_24_8 0x84FA -#define GL_DEPTH24_STENCIL8 0x88F0 -#define GL_UNSIGNED_NORMALIZED 0x8C17 -#define GL_DRAW_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING -#define GL_READ_FRAMEBUFFER 0x8CA8 -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA -#define GL_RENDERBUFFER_SAMPLES 0x8CAB -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 -#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF -#define GL_COLOR_ATTACHMENT1 0x8CE1 -#define GL_COLOR_ATTACHMENT2 0x8CE2 -#define GL_COLOR_ATTACHMENT3 0x8CE3 -#define GL_COLOR_ATTACHMENT4 0x8CE4 -#define GL_COLOR_ATTACHMENT5 0x8CE5 -#define GL_COLOR_ATTACHMENT6 0x8CE6 -#define GL_COLOR_ATTACHMENT7 0x8CE7 -#define GL_COLOR_ATTACHMENT8 0x8CE8 -#define GL_COLOR_ATTACHMENT9 0x8CE9 -#define GL_COLOR_ATTACHMENT10 0x8CEA -#define GL_COLOR_ATTACHMENT11 0x8CEB -#define GL_COLOR_ATTACHMENT12 0x8CEC -#define GL_COLOR_ATTACHMENT13 0x8CED -#define GL_COLOR_ATTACHMENT14 0x8CEE -#define GL_COLOR_ATTACHMENT15 0x8CEF -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 -#define GL_MAX_SAMPLES 0x8D57 -#define GL_HALF_FLOAT 0x140B -#define GL_MAP_READ_BIT 0x0001 -#define GL_MAP_WRITE_BIT 0x0002 -#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 -#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 -#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 -#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 -#define GL_RG 0x8227 -#define GL_RG_INTEGER 0x8228 -#define GL_R8 0x8229 -#define GL_RG8 0x822B -#define GL_R16F 0x822D -#define GL_R32F 0x822E -#define GL_RG16F 0x822F -#define GL_RG32F 0x8230 -#define GL_R8I 0x8231 -#define GL_R8UI 0x8232 -#define GL_R16I 0x8233 -#define GL_R16UI 0x8234 -#define GL_R32I 0x8235 -#define GL_R32UI 0x8236 -#define GL_RG8I 0x8237 -#define GL_RG8UI 0x8238 -#define GL_RG16I 0x8239 -#define GL_RG16UI 0x823A -#define GL_RG32I 0x823B -#define GL_RG32UI 0x823C -#define GL_VERTEX_ARRAY_BINDING 0x85B5 -#define GL_R8_SNORM 0x8F94 -#define GL_RG8_SNORM 0x8F95 -#define GL_RGB8_SNORM 0x8F96 -#define GL_RGBA8_SNORM 0x8F97 -#define GL_SIGNED_NORMALIZED 0x8F9C -#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 -#define GL_COPY_READ_BUFFER 0x8F36 -#define GL_COPY_WRITE_BUFFER 0x8F37 -#define GL_COPY_READ_BUFFER_BINDING GL_COPY_READ_BUFFER -#define GL_COPY_WRITE_BUFFER_BINDING GL_COPY_WRITE_BUFFER -#define GL_UNIFORM_BUFFER 0x8A11 -#define GL_UNIFORM_BUFFER_BINDING 0x8A28 -#define GL_UNIFORM_BUFFER_START 0x8A29 -#define GL_UNIFORM_BUFFER_SIZE 0x8A2A -#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B -#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D -#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E -#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F -#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 -#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 -#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 -#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 -#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 -#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -#define GL_UNIFORM_TYPE 0x8A37 -#define GL_UNIFORM_SIZE 0x8A38 -#define GL_UNIFORM_NAME_LENGTH 0x8A39 -#define GL_UNIFORM_BLOCK_INDEX 0x8A3A -#define GL_UNIFORM_OFFSET 0x8A3B -#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E -#define GL_UNIFORM_BLOCK_BINDING 0x8A3F -#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 -#define GL_INVALID_INDEX 0xFFFFFFFFu -#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 -#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 -#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 -#define GL_OBJECT_TYPE 0x9112 -#define GL_SYNC_CONDITION 0x9113 -#define GL_SYNC_STATUS 0x9114 -#define GL_SYNC_FLAGS 0x9115 -#define GL_SYNC_FENCE 0x9116 -#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 -#define GL_UNSIGNALED 0x9118 -#define GL_SIGNALED 0x9119 -#define GL_ALREADY_SIGNALED 0x911A -#define GL_TIMEOUT_EXPIRED 0x911B -#define GL_CONDITION_SATISFIED 0x911C -#define GL_WAIT_FAILED 0x911D -#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 -#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE -#define GL_ANY_SAMPLES_PASSED 0x8C2F -#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A -#define GL_SAMPLER_BINDING 0x8919 -#define GL_RGB10_A2UI 0x906F -#define GL_TEXTURE_SWIZZLE_R 0x8E42 -#define GL_TEXTURE_SWIZZLE_G 0x8E43 -#define GL_TEXTURE_SWIZZLE_B 0x8E44 -#define GL_TEXTURE_SWIZZLE_A 0x8E45 -#define GL_GREEN 0x1904 -#define GL_BLUE 0x1905 -#define GL_INT_2_10_10_10_REV 0x8D9F -#define GL_TRANSFORM_FEEDBACK 0x8E22 -#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 -#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 -#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 -#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 -#define GL_PROGRAM_BINARY_LENGTH 0x8741 -#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE -#define GL_PROGRAM_BINARY_FORMATS 0x87FF -#define GL_COMPRESSED_R11_EAC 0x9270 -#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 -#define GL_COMPRESSED_RG11_EAC 0x9272 -#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 -#define GL_COMPRESSED_RGB8_ETC2 0x9274 -#define GL_COMPRESSED_SRGB8_ETC2 0x9275 -#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 -#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 -#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 -#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F -#define GL_MAX_ELEMENT_INDEX 0x8D6B -#define GL_NUM_SAMPLE_COUNTS 0x9380 -#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_DRAW_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_RG8 0x822B +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_COPY_READ_BUFFER_BINDING GL_COPY_READ_BUFFER +#define GL_COPY_WRITE_BUFFER_BINDING GL_COPY_WRITE_BUFFER +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFFu +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_INT_2_10_10_10_REV 0x8D9F +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 +#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#define GL_COMPRESSED_R11_EAC 0x9270 +#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 +#define GL_COMPRESSED_RG11_EAC 0x9272 +#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 +#define GL_COMPRESSED_RGB8_ETC2 0x9274 +#define GL_COMPRESSED_SRGB8_ETC2 0x9275 +#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 +#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 +#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +#define GL_MAX_ELEMENT_INDEX 0x8D6B +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF /* OpenGL ES Extensions */ -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE diff --git a/src/mbgl/gl/draw_scope_resource.hpp b/src/mbgl/gl/draw_scope_resource.hpp index 4c446cd4fe7..298aaf29bbd 100644 --- a/src/mbgl/gl/draw_scope_resource.hpp +++ b/src/mbgl/gl/draw_scope_resource.hpp @@ -8,8 +8,8 @@ namespace gl { class DrawScopeResource : public gfx::DrawScopeResource { public: - DrawScopeResource(VertexArray&& vertexArray_) : vertexArray(std::move(vertexArray_)) { - } + DrawScopeResource(VertexArray&& vertexArray_) + : vertexArray(std::move(vertexArray_)) {} VertexArray vertexArray; }; diff --git a/src/mbgl/gl/enum.cpp b/src/mbgl/gl/enum.cpp index 899fb496cc4..060435e288c 100644 --- a/src/mbgl/gl/enum.cpp +++ b/src/mbgl/gl/enum.cpp @@ -8,13 +8,20 @@ namespace gl { template <> platform::GLenum Enum::to(const gfx::DrawModeType value) { switch (value) { - case gfx::DrawModeType::Points: return GL_POINTS; - case gfx::DrawModeType::Lines: return GL_LINES; - case gfx::DrawModeType::LineLoop: return GL_LINE_LOOP; - case gfx::DrawModeType::LineStrip: return GL_LINE_STRIP; - case gfx::DrawModeType::Triangles: return GL_TRIANGLES; - case gfx::DrawModeType::TriangleStrip: return GL_TRIANGLE_STRIP; - case gfx::DrawModeType::TriangleFan: return GL_TRIANGLE_FAN; + case gfx::DrawModeType::Points: + return GL_POINTS; + case gfx::DrawModeType::Lines: + return GL_LINES; + case gfx::DrawModeType::LineLoop: + return GL_LINE_LOOP; + case gfx::DrawModeType::LineStrip: + return GL_LINE_STRIP; + case gfx::DrawModeType::Triangles: + return GL_TRIANGLES; + case gfx::DrawModeType::TriangleStrip: + return GL_TRIANGLE_STRIP; + case gfx::DrawModeType::TriangleFan: + return GL_TRIANGLE_FAN; } return GL_INVALID_ENUM; } @@ -22,9 +29,12 @@ platform::GLenum Enum::to(const gfx::DrawModeType value) { template <> gfx::ColorBlendEquationType Enum::from(const platform::GLint value) { switch (value) { - case GL_FUNC_ADD: return gfx::ColorBlendEquationType::Add; - case GL_FUNC_SUBTRACT: return gfx::ColorBlendEquationType::Subtract; - case GL_FUNC_REVERSE_SUBTRACT: return gfx::ColorBlendEquationType::ReverseSubtract; + case GL_FUNC_ADD: + return gfx::ColorBlendEquationType::Add; + case GL_FUNC_SUBTRACT: + return gfx::ColorBlendEquationType::Subtract; + case GL_FUNC_REVERSE_SUBTRACT: + return gfx::ColorBlendEquationType::ReverseSubtract; } return {}; } @@ -32,9 +42,12 @@ gfx::ColorBlendEquationType Enum::from(const platfo template <> platform::GLenum Enum::to(const gfx::ColorBlendEquationType value) { switch (value) { - case gfx::ColorBlendEquationType::Add: return GL_FUNC_ADD; - case gfx::ColorBlendEquationType::Subtract: return GL_FUNC_SUBTRACT; - case gfx::ColorBlendEquationType::ReverseSubtract: return GL_FUNC_REVERSE_SUBTRACT; + case gfx::ColorBlendEquationType::Add: + return GL_FUNC_ADD; + case gfx::ColorBlendEquationType::Subtract: + return GL_FUNC_SUBTRACT; + case gfx::ColorBlendEquationType::ReverseSubtract: + return GL_FUNC_REVERSE_SUBTRACT; } return GL_INVALID_ENUM; } @@ -42,21 +55,36 @@ platform::GLenum Enum::to(const gfx::ColorBlendEqua template <> gfx::ColorBlendFactorType Enum::from(const platform::GLint value) { switch (value) { - case GL_ZERO: return gfx::ColorBlendFactorType::Zero; - case GL_ONE: return gfx::ColorBlendFactorType::One; - case GL_SRC_COLOR: return gfx::ColorBlendFactorType::SrcColor; - case GL_ONE_MINUS_SRC_COLOR: return gfx::ColorBlendFactorType::OneMinusSrcColor; - case GL_DST_COLOR: return gfx::ColorBlendFactorType::DstColor; - case GL_ONE_MINUS_DST_COLOR: return gfx::ColorBlendFactorType::OneMinusDstColor; - case GL_SRC_ALPHA: return gfx::ColorBlendFactorType::SrcAlpha; - case GL_ONE_MINUS_SRC_ALPHA: return gfx::ColorBlendFactorType::OneMinusSrcAlpha; - case GL_DST_ALPHA: return gfx::ColorBlendFactorType::DstAlpha; - case GL_ONE_MINUS_DST_ALPHA: return gfx::ColorBlendFactorType::OneMinusDstAlpha; - case GL_CONSTANT_COLOR: return gfx::ColorBlendFactorType::ConstantColor; - case GL_ONE_MINUS_CONSTANT_COLOR: return gfx::ColorBlendFactorType::OneMinusConstantColor; - case GL_CONSTANT_ALPHA: return gfx::ColorBlendFactorType::ConstantAlpha; - case GL_ONE_MINUS_CONSTANT_ALPHA: return gfx::ColorBlendFactorType::OneMinusConstantAlpha; - case GL_SRC_ALPHA_SATURATE: return gfx::ColorBlendFactorType::SrcAlphaSaturate; + case GL_ZERO: + return gfx::ColorBlendFactorType::Zero; + case GL_ONE: + return gfx::ColorBlendFactorType::One; + case GL_SRC_COLOR: + return gfx::ColorBlendFactorType::SrcColor; + case GL_ONE_MINUS_SRC_COLOR: + return gfx::ColorBlendFactorType::OneMinusSrcColor; + case GL_DST_COLOR: + return gfx::ColorBlendFactorType::DstColor; + case GL_ONE_MINUS_DST_COLOR: + return gfx::ColorBlendFactorType::OneMinusDstColor; + case GL_SRC_ALPHA: + return gfx::ColorBlendFactorType::SrcAlpha; + case GL_ONE_MINUS_SRC_ALPHA: + return gfx::ColorBlendFactorType::OneMinusSrcAlpha; + case GL_DST_ALPHA: + return gfx::ColorBlendFactorType::DstAlpha; + case GL_ONE_MINUS_DST_ALPHA: + return gfx::ColorBlendFactorType::OneMinusDstAlpha; + case GL_CONSTANT_COLOR: + return gfx::ColorBlendFactorType::ConstantColor; + case GL_ONE_MINUS_CONSTANT_COLOR: + return gfx::ColorBlendFactorType::OneMinusConstantColor; + case GL_CONSTANT_ALPHA: + return gfx::ColorBlendFactorType::ConstantAlpha; + case GL_ONE_MINUS_CONSTANT_ALPHA: + return gfx::ColorBlendFactorType::OneMinusConstantAlpha; + case GL_SRC_ALPHA_SATURATE: + return gfx::ColorBlendFactorType::SrcAlphaSaturate; } return {}; } @@ -64,21 +92,36 @@ gfx::ColorBlendFactorType Enum::from(const platform:: template <> platform::GLenum Enum::to(const gfx::ColorBlendFactorType value) { switch (value) { - case gfx::ColorBlendFactorType::Zero: return GL_ZERO; - case gfx::ColorBlendFactorType::One: return GL_ONE; - case gfx::ColorBlendFactorType::SrcColor: return GL_SRC_COLOR; - case gfx::ColorBlendFactorType::OneMinusSrcColor: return GL_ONE_MINUS_SRC_COLOR; - case gfx::ColorBlendFactorType::DstColor: return GL_DST_COLOR; - case gfx::ColorBlendFactorType::OneMinusDstColor: return GL_ONE_MINUS_DST_COLOR; - case gfx::ColorBlendFactorType::SrcAlpha: return GL_SRC_ALPHA; - case gfx::ColorBlendFactorType::OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; - case gfx::ColorBlendFactorType::DstAlpha: return GL_DST_ALPHA; - case gfx::ColorBlendFactorType::OneMinusDstAlpha: return GL_ONE_MINUS_DST_ALPHA; - case gfx::ColorBlendFactorType::ConstantColor: return GL_CONSTANT_COLOR; - case gfx::ColorBlendFactorType::OneMinusConstantColor: return GL_ONE_MINUS_CONSTANT_COLOR; - case gfx::ColorBlendFactorType::ConstantAlpha: return GL_CONSTANT_ALPHA; - case gfx::ColorBlendFactorType::OneMinusConstantAlpha: return GL_ONE_MINUS_CONSTANT_ALPHA; - case gfx::ColorBlendFactorType::SrcAlphaSaturate: return GL_SRC_ALPHA_SATURATE; + case gfx::ColorBlendFactorType::Zero: + return GL_ZERO; + case gfx::ColorBlendFactorType::One: + return GL_ONE; + case gfx::ColorBlendFactorType::SrcColor: + return GL_SRC_COLOR; + case gfx::ColorBlendFactorType::OneMinusSrcColor: + return GL_ONE_MINUS_SRC_COLOR; + case gfx::ColorBlendFactorType::DstColor: + return GL_DST_COLOR; + case gfx::ColorBlendFactorType::OneMinusDstColor: + return GL_ONE_MINUS_DST_COLOR; + case gfx::ColorBlendFactorType::SrcAlpha: + return GL_SRC_ALPHA; + case gfx::ColorBlendFactorType::OneMinusSrcAlpha: + return GL_ONE_MINUS_SRC_ALPHA; + case gfx::ColorBlendFactorType::DstAlpha: + return GL_DST_ALPHA; + case gfx::ColorBlendFactorType::OneMinusDstAlpha: + return GL_ONE_MINUS_DST_ALPHA; + case gfx::ColorBlendFactorType::ConstantColor: + return GL_CONSTANT_COLOR; + case gfx::ColorBlendFactorType::OneMinusConstantColor: + return GL_ONE_MINUS_CONSTANT_COLOR; + case gfx::ColorBlendFactorType::ConstantAlpha: + return GL_CONSTANT_ALPHA; + case gfx::ColorBlendFactorType::OneMinusConstantAlpha: + return GL_ONE_MINUS_CONSTANT_ALPHA; + case gfx::ColorBlendFactorType::SrcAlphaSaturate: + return GL_SRC_ALPHA_SATURATE; } return GL_INVALID_ENUM; } @@ -86,14 +129,22 @@ platform::GLenum Enum::to(const gfx::ColorBlendFactor template <> gfx::DepthFunctionType Enum::from(const platform::GLint value) { switch (value) { - case GL_NEVER: return gfx::DepthFunctionType::Never; - case GL_LESS: return gfx::DepthFunctionType::Less; - case GL_EQUAL: return gfx::DepthFunctionType::Equal; - case GL_LEQUAL: return gfx::DepthFunctionType::LessEqual; - case GL_GREATER: return gfx::DepthFunctionType::Greater; - case GL_NOTEQUAL: return gfx::DepthFunctionType::NotEqual; - case GL_GEQUAL: return gfx::DepthFunctionType::GreaterEqual; - case GL_ALWAYS: return gfx::DepthFunctionType::Always; + case GL_NEVER: + return gfx::DepthFunctionType::Never; + case GL_LESS: + return gfx::DepthFunctionType::Less; + case GL_EQUAL: + return gfx::DepthFunctionType::Equal; + case GL_LEQUAL: + return gfx::DepthFunctionType::LessEqual; + case GL_GREATER: + return gfx::DepthFunctionType::Greater; + case GL_NOTEQUAL: + return gfx::DepthFunctionType::NotEqual; + case GL_GEQUAL: + return gfx::DepthFunctionType::GreaterEqual; + case GL_ALWAYS: + return gfx::DepthFunctionType::Always; } return {}; } @@ -101,14 +152,22 @@ gfx::DepthFunctionType Enum::from(const platform::GLint template <> platform::GLenum Enum::to(const gfx::DepthFunctionType value) { switch (value) { - case gfx::DepthFunctionType::Never: return GL_NEVER; - case gfx::DepthFunctionType::Less: return GL_LESS; - case gfx::DepthFunctionType::Equal: return GL_EQUAL; - case gfx::DepthFunctionType::LessEqual: return GL_LEQUAL; - case gfx::DepthFunctionType::Greater: return GL_GREATER; - case gfx::DepthFunctionType::NotEqual: return GL_NOTEQUAL; - case gfx::DepthFunctionType::GreaterEqual: return GL_GEQUAL; - case gfx::DepthFunctionType::Always: return GL_ALWAYS; + case gfx::DepthFunctionType::Never: + return GL_NEVER; + case gfx::DepthFunctionType::Less: + return GL_LESS; + case gfx::DepthFunctionType::Equal: + return GL_EQUAL; + case gfx::DepthFunctionType::LessEqual: + return GL_LEQUAL; + case gfx::DepthFunctionType::Greater: + return GL_GREATER; + case gfx::DepthFunctionType::NotEqual: + return GL_NOTEQUAL; + case gfx::DepthFunctionType::GreaterEqual: + return GL_GEQUAL; + case gfx::DepthFunctionType::Always: + return GL_ALWAYS; } return GL_INVALID_ENUM; } @@ -126,14 +185,22 @@ platform::GLboolean Enum::to(const gfx::DepthMaskType value) template <> gfx::StencilFunctionType Enum::from(const platform::GLint value) { switch (value) { - case GL_NEVER: return gfx::StencilFunctionType::Never; - case GL_LESS: return gfx::StencilFunctionType::Less; - case GL_EQUAL: return gfx::StencilFunctionType::Equal; - case GL_LEQUAL: return gfx::StencilFunctionType::LessEqual; - case GL_GREATER: return gfx::StencilFunctionType::Greater; - case GL_NOTEQUAL: return gfx::StencilFunctionType::NotEqual; - case GL_GEQUAL: return gfx::StencilFunctionType::GreaterEqual; - case GL_ALWAYS: return gfx::StencilFunctionType::Always; + case GL_NEVER: + return gfx::StencilFunctionType::Never; + case GL_LESS: + return gfx::StencilFunctionType::Less; + case GL_EQUAL: + return gfx::StencilFunctionType::Equal; + case GL_LEQUAL: + return gfx::StencilFunctionType::LessEqual; + case GL_GREATER: + return gfx::StencilFunctionType::Greater; + case GL_NOTEQUAL: + return gfx::StencilFunctionType::NotEqual; + case GL_GEQUAL: + return gfx::StencilFunctionType::GreaterEqual; + case GL_ALWAYS: + return gfx::StencilFunctionType::Always; } return {}; } @@ -141,14 +208,22 @@ gfx::StencilFunctionType Enum::from(const platform::GL template <> platform::GLenum Enum::to(const gfx::StencilFunctionType value) { switch (value) { - case gfx::StencilFunctionType::Never: return GL_NEVER; - case gfx::StencilFunctionType::Less: return GL_LESS; - case gfx::StencilFunctionType::Equal: return GL_EQUAL; - case gfx::StencilFunctionType::LessEqual: return GL_LEQUAL; - case gfx::StencilFunctionType::Greater: return GL_GREATER; - case gfx::StencilFunctionType::NotEqual: return GL_NOTEQUAL; - case gfx::StencilFunctionType::GreaterEqual: return GL_GEQUAL; - case gfx::StencilFunctionType::Always: return GL_ALWAYS; + case gfx::StencilFunctionType::Never: + return GL_NEVER; + case gfx::StencilFunctionType::Less: + return GL_LESS; + case gfx::StencilFunctionType::Equal: + return GL_EQUAL; + case gfx::StencilFunctionType::LessEqual: + return GL_LEQUAL; + case gfx::StencilFunctionType::Greater: + return GL_GREATER; + case gfx::StencilFunctionType::NotEqual: + return GL_NOTEQUAL; + case gfx::StencilFunctionType::GreaterEqual: + return GL_GEQUAL; + case gfx::StencilFunctionType::Always: + return GL_ALWAYS; } return GL_INVALID_ENUM; } @@ -156,14 +231,22 @@ platform::GLenum Enum::to(const gfx::StencilFunctionTy template <> gfx::StencilOpType Enum::from(const platform::GLint value) { switch (value) { - case GL_KEEP: return gfx::StencilOpType::Keep; - case GL_ZERO: return gfx::StencilOpType::Zero; - case GL_REPLACE: return gfx::StencilOpType::Replace; - case GL_INCR: return gfx::StencilOpType::Increment; - case GL_INCR_WRAP: return gfx::StencilOpType::IncrementWrap; - case GL_DECR: return gfx::StencilOpType::Decrement; - case GL_DECR_WRAP: return gfx::StencilOpType::DecrementWrap; - case GL_INVERT: return gfx::StencilOpType::Invert; + case GL_KEEP: + return gfx::StencilOpType::Keep; + case GL_ZERO: + return gfx::StencilOpType::Zero; + case GL_REPLACE: + return gfx::StencilOpType::Replace; + case GL_INCR: + return gfx::StencilOpType::Increment; + case GL_INCR_WRAP: + return gfx::StencilOpType::IncrementWrap; + case GL_DECR: + return gfx::StencilOpType::Decrement; + case GL_DECR_WRAP: + return gfx::StencilOpType::DecrementWrap; + case GL_INVERT: + return gfx::StencilOpType::Invert; } return {}; } @@ -171,14 +254,22 @@ gfx::StencilOpType Enum::from(const platform::GLint value) { template <> platform::GLenum Enum::to(const gfx::StencilOpType value) { switch (value) { - case gfx::StencilOpType::Keep: return GL_KEEP; - case gfx::StencilOpType::Zero: return GL_ZERO; - case gfx::StencilOpType::Replace: return GL_REPLACE; - case gfx::StencilOpType::Increment: return GL_INCR; - case gfx::StencilOpType::IncrementWrap: return GL_INCR_WRAP; - case gfx::StencilOpType::Decrement: return GL_DECR; - case gfx::StencilOpType::DecrementWrap: return GL_DECR_WRAP; - case gfx::StencilOpType::Invert: return GL_INVERT; + case gfx::StencilOpType::Keep: + return GL_KEEP; + case gfx::StencilOpType::Zero: + return GL_ZERO; + case gfx::StencilOpType::Replace: + return GL_REPLACE; + case gfx::StencilOpType::Increment: + return GL_INCR; + case gfx::StencilOpType::IncrementWrap: + return GL_INCR_WRAP; + case gfx::StencilOpType::Decrement: + return GL_DECR; + case gfx::StencilOpType::DecrementWrap: + return GL_DECR_WRAP; + case gfx::StencilOpType::Invert: + return GL_INVERT; } return GL_INVALID_ENUM; } @@ -186,9 +277,12 @@ platform::GLenum Enum::to(const gfx::StencilOpType value) { template <> gfx::CullFaceSideType Enum::from(const platform::GLint value) { switch (value) { - case GL_FRONT: return gfx::CullFaceSideType::Front; - case GL_BACK: return gfx::CullFaceSideType::Back; - case GL_FRONT_AND_BACK: return gfx::CullFaceSideType::FrontAndBack; + case GL_FRONT: + return gfx::CullFaceSideType::Front; + case GL_BACK: + return gfx::CullFaceSideType::Back; + case GL_FRONT_AND_BACK: + return gfx::CullFaceSideType::FrontAndBack; } return {}; } @@ -196,9 +290,12 @@ gfx::CullFaceSideType Enum::from(const platform::GLint va template <> platform::GLenum Enum::to(const gfx::CullFaceSideType value) { switch (value) { - case gfx::CullFaceSideType::Front: return GL_FRONT; - case gfx::CullFaceSideType::Back: return GL_BACK; - case gfx::CullFaceSideType::FrontAndBack: return GL_FRONT_AND_BACK; + case gfx::CullFaceSideType::Front: + return GL_FRONT; + case gfx::CullFaceSideType::Back: + return GL_BACK; + case gfx::CullFaceSideType::FrontAndBack: + return GL_FRONT_AND_BACK; } return GL_INVALID_ENUM; } @@ -206,8 +303,10 @@ platform::GLenum Enum::to(const gfx::CullFaceSideType val template <> gfx::CullFaceWindingType Enum::from(const platform::GLint value) { switch (value) { - case GL_CW: return gfx::CullFaceWindingType::Clockwise; - case GL_CCW: return gfx::CullFaceWindingType::CounterClockwise; + case GL_CW: + return gfx::CullFaceWindingType::Clockwise; + case GL_CCW: + return gfx::CullFaceWindingType::CounterClockwise; } return {}; } @@ -215,8 +314,10 @@ gfx::CullFaceWindingType Enum::from(const platform::GL template <> platform::GLenum Enum::to(const gfx::CullFaceWindingType value) { switch (value) { - case gfx::CullFaceWindingType::Clockwise: return GL_CW; - case gfx::CullFaceWindingType::CounterClockwise: return GL_CCW; + case gfx::CullFaceWindingType::Clockwise: + return GL_CW; + case gfx::CullFaceWindingType::CounterClockwise: + return GL_CCW; } return GL_INVALID_ENUM; } @@ -224,9 +325,12 @@ platform::GLenum Enum::to(const gfx::CullFaceWindingTy template <> gfx::BufferUsageType Enum::from(const platform::GLint value) { switch (value) { - case GL_STREAM_DRAW: return gfx::BufferUsageType::StreamDraw; - case GL_STATIC_DRAW: return gfx::BufferUsageType::StaticDraw; - case GL_DYNAMIC_DRAW: return gfx::BufferUsageType::DynamicDraw; + case GL_STREAM_DRAW: + return gfx::BufferUsageType::StreamDraw; + case GL_STATIC_DRAW: + return gfx::BufferUsageType::StaticDraw; + case GL_DYNAMIC_DRAW: + return gfx::BufferUsageType::DynamicDraw; } return {}; } @@ -234,9 +338,12 @@ gfx::BufferUsageType Enum::from(const platform::GLint valu template <> platform::GLenum Enum::to(const gfx::BufferUsageType value) { switch (value) { - case gfx::BufferUsageType::StreamDraw: return GL_STREAM_DRAW; - case gfx::BufferUsageType::StaticDraw: return GL_STATIC_DRAW; - case gfx::BufferUsageType::DynamicDraw: return GL_DYNAMIC_DRAW; + case gfx::BufferUsageType::StreamDraw: + return GL_STREAM_DRAW; + case gfx::BufferUsageType::StaticDraw: + return GL_STATIC_DRAW; + case gfx::BufferUsageType::DynamicDraw: + return GL_DYNAMIC_DRAW; } return GL_INVALID_ENUM; } @@ -244,11 +351,16 @@ platform::GLenum Enum::to(const gfx::BufferUsageType value template <> gfx::TexturePixelType Enum::from(const platform::GLint value) { switch (value) { - case GL_RGBA: return gfx::TexturePixelType::RGBA; - case GL_ALPHA: return gfx::TexturePixelType::Alpha; - case GL_STENCIL_INDEX: return gfx::TexturePixelType::Stencil; - case GL_DEPTH_COMPONENT: return gfx::TexturePixelType::Depth; - case GL_LUMINANCE: return gfx::TexturePixelType::Luminance; + case GL_RGBA: + return gfx::TexturePixelType::RGBA; + case GL_ALPHA: + return gfx::TexturePixelType::Alpha; + case GL_STENCIL_INDEX: + return gfx::TexturePixelType::Stencil; + case GL_DEPTH_COMPONENT: + return gfx::TexturePixelType::Depth; + case GL_LUMINANCE: + return gfx::TexturePixelType::Luminance; } return {}; } @@ -256,19 +368,24 @@ gfx::TexturePixelType Enum::from(const platform::GLint va template <> platform::GLenum Enum::to(const gfx::TexturePixelType value) { switch (value) { - case gfx::TexturePixelType::RGBA: return GL_RGBA; - case gfx::TexturePixelType::Alpha: return GL_ALPHA; - case gfx::TexturePixelType::Stencil: return GL_STENCIL_INDEX; - case gfx::TexturePixelType::Depth: return GL_DEPTH_COMPONENT; - case gfx::TexturePixelType::Luminance: return GL_LUMINANCE; + case gfx::TexturePixelType::RGBA: + return GL_RGBA; + case gfx::TexturePixelType::Alpha: + return GL_ALPHA; + case gfx::TexturePixelType::Stencil: + return GL_STENCIL_INDEX; + case gfx::TexturePixelType::Depth: + return GL_DEPTH_COMPONENT; + case gfx::TexturePixelType::Luminance: + return GL_LUMINANCE; } return GL_INVALID_ENUM; } -template <> template<> +template <> +template <> platform::GLenum Enum::sizedFor<>(const gfx::TexturePixelType value, - gfx::TextureChannelDataType type) -{ + gfx::TextureChannelDataType type) { switch (type) { case gfx::TextureChannelDataType::UnsignedByte: { return Enum::to(value); @@ -277,7 +394,8 @@ platform::GLenum Enum::sizedFor<>(const gfx::TexturePixel switch (value) { case gfx::TexturePixelType::RGBA: return GL_RGBA16F; - default: break; + default: + break; } } } @@ -288,8 +406,10 @@ platform::GLenum Enum::sizedFor<>(const gfx::TexturePixel template <> gfx::TextureChannelDataType Enum::from(const platform::GLint value) { switch (value) { - case GL_UNSIGNED_BYTE: return gfx::TextureChannelDataType::UnsignedByte; - case GL_HALF_FLOAT: return gfx::TextureChannelDataType::HalfFloat; + case GL_UNSIGNED_BYTE: + return gfx::TextureChannelDataType::UnsignedByte; + case GL_HALF_FLOAT: + return gfx::TextureChannelDataType::HalfFloat; } return {}; } @@ -297,8 +417,10 @@ gfx::TextureChannelDataType Enum::from(const platfo template <> platform::GLenum Enum::to(const gfx::TextureChannelDataType value) { switch (value) { - case gfx::TextureChannelDataType::UnsignedByte: return GL_UNSIGNED_BYTE; - case gfx::TextureChannelDataType::HalfFloat: return GL_HALF_FLOAT; + case gfx::TextureChannelDataType::UnsignedByte: + return GL_UNSIGNED_BYTE; + case gfx::TextureChannelDataType::HalfFloat: + return GL_HALF_FLOAT; } return GL_INVALID_ENUM; } @@ -306,9 +428,12 @@ platform::GLenum Enum::to(const gfx::TextureChannel template <> gfx::RenderbufferPixelType Enum::from(const platform::GLint value) { switch (value) { - case GL_RGBA8: return gfx::RenderbufferPixelType::RGBA; - case GL_DEPTH_COMPONENT16: return gfx::RenderbufferPixelType::Depth; - case GL_DEPTH24_STENCIL8: return gfx::RenderbufferPixelType::DepthStencil; + case GL_RGBA8: + return gfx::RenderbufferPixelType::RGBA; + case GL_DEPTH_COMPONENT16: + return gfx::RenderbufferPixelType::Depth; + case GL_DEPTH24_STENCIL8: + return gfx::RenderbufferPixelType::DepthStencil; } return {}; } @@ -316,9 +441,12 @@ gfx::RenderbufferPixelType Enum::from(const platform template <> platform::GLenum Enum::to(const gfx::RenderbufferPixelType value) { switch (value) { - case gfx::RenderbufferPixelType::RGBA: return GL_RGBA8; - case gfx::RenderbufferPixelType::Depth: return GL_DEPTH_COMPONENT16; - case gfx::RenderbufferPixelType::DepthStencil: return GL_DEPTH24_STENCIL8; + case gfx::RenderbufferPixelType::RGBA: + return GL_RGBA8; + case gfx::RenderbufferPixelType::Depth: + return GL_DEPTH_COMPONENT16; + case gfx::RenderbufferPixelType::DepthStencil: + return GL_DEPTH24_STENCIL8; } return GL_INVALID_ENUM; } diff --git a/src/mbgl/gl/enum.hpp b/src/mbgl/gl/enum.hpp index d4ef3eea3e4..f662fd8516b 100644 --- a/src/mbgl/gl/enum.hpp +++ b/src/mbgl/gl/enum.hpp @@ -10,13 +10,15 @@ namespace gl { template class Enum { public: - using InType = std::conditional_t, bool>, platform::GLboolean, platform::GLint>; - using OutType = std::conditional_t, bool>, platform::GLboolean, platform::GLenum>; + using InType = + std::conditional_t, bool>, platform::GLboolean, platform::GLint>; + using OutType = + std::conditional_t, bool>, platform::GLboolean, platform::GLenum>; static T from(InType); static OutType to(T); - template + template static OutType sizedFor(T, U type); }; diff --git a/src/mbgl/gl/extension.hpp b/src/mbgl/gl/extension.hpp index 8710314ef2c..9186fab7285 100644 --- a/src/mbgl/gl/extension.hpp +++ b/src/mbgl/gl/extension.hpp @@ -15,16 +15,12 @@ class ExtensionFunction; template class ExtensionFunction { public: - ExtensionFunction(const ProcAddress ptr_) : ptr(ptr_) { - } + ExtensionFunction(const ProcAddress ptr_) + : ptr(ptr_) {} - explicit operator bool() const { - return ptr; - } + explicit operator bool() const { return ptr; } - R operator()(Args... args) const { - return (*reinterpret_cast(ptr))(std::forward(args)...); - } + R operator()(Args... args) const { return (*reinterpret_cast(ptr))(std::forward(args)...); } private: const ProcAddress ptr; diff --git a/src/mbgl/gl/index_buffer_resource.hpp b/src/mbgl/gl/index_buffer_resource.hpp index 10d9bfc8014..f3f42d3efc4 100644 --- a/src/mbgl/gl/index_buffer_resource.hpp +++ b/src/mbgl/gl/index_buffer_resource.hpp @@ -8,7 +8,9 @@ namespace gl { class IndexBufferResource : public gfx::IndexBufferResource { public: - IndexBufferResource(UniqueBuffer&& buffer_, int byteSize_) : buffer(std::move(buffer_)), byteSize(byteSize_) {} + IndexBufferResource(UniqueBuffer&& buffer_, int byteSize_) + : buffer(std::move(buffer_)), + byteSize(byteSize_) {} ~IndexBufferResource() noexcept override; UniqueBuffer buffer; diff --git a/src/mbgl/gl/offscreen_texture.cpp b/src/mbgl/gl/offscreen_texture.cpp index ab9e72a5378..0382eac6c7b 100644 --- a/src/mbgl/gl/offscreen_texture.cpp +++ b/src/mbgl/gl/offscreen_texture.cpp @@ -8,10 +8,10 @@ namespace gl { class OffscreenTextureResource final : public gl::RenderableResource { public: - OffscreenTextureResource(gl::Context& context_, - const Size size_, - const gfx::TextureChannelDataType type_) - : context(context_), size(size_), type(type_) { + OffscreenTextureResource(gl::Context& context_, const Size size_, const gfx::TextureChannelDataType type_) + : context(context_), + size(size_), + type(type_) { assert(!size.isEmpty()); } @@ -28,7 +28,7 @@ class OffscreenTextureResource final : public gl::RenderableResource { context.activeTextureUnit = 0; context.scissorTest = false; - context.viewport = { 0, 0, size }; + context.viewport = {0, 0, size}; } PremultipliedImage readStillImage() { @@ -50,11 +50,8 @@ class OffscreenTextureResource final : public gl::RenderableResource { std::optional framebuffer; }; -OffscreenTexture::OffscreenTexture(gl::Context& context, - const Size size_, - const gfx::TextureChannelDataType type) - : gfx::OffscreenTexture(size, std::make_unique(context, size_, type)) { -} +OffscreenTexture::OffscreenTexture(gl::Context& context, const Size size_, const gfx::TextureChannelDataType type) + : gfx::OffscreenTexture(size, std::make_unique(context, size_, type)) {} bool OffscreenTexture::isRenderable() { try { diff --git a/src/mbgl/gl/program.hpp b/src/mbgl/gl/program.hpp index c601652498d..0e6f0ab9ac6 100644 --- a/src/mbgl/gl/program.hpp +++ b/src/mbgl/gl/program.hpp @@ -31,8 +31,7 @@ class Program final : public gfx::Program { using TextureList = typename Name::TextureList; Program(ProgramParameters programParameters_) - : programParameters(std::move(programParameters_)) { - } + : programParameters(std::move(programParameters_)) {} const ProgramParameters programParameters; @@ -41,36 +40,32 @@ class Program final : public gfx::Program { Instance(Context& context, const std::initializer_list& vertexSource, const std::initializer_list& fragmentSource) - : program(context.createProgram( - context.createShader(ShaderType::Vertex, vertexSource), - context.createShader(ShaderType::Fragment, fragmentSource), - attributeLocations.getFirstAttribName())) { + : program(context.createProgram(context.createShader(ShaderType::Vertex, vertexSource), + context.createShader(ShaderType::Fragment, fragmentSource), + attributeLocations.getFirstAttribName())) { attributeLocations.queryLocations(program); uniformStates.queryLocations(program); // Texture units are specified via uniforms as well, so we need query their locations textureStates.queryLocations(program); } - static std::unique_ptr - createInstance(gl::Context& context, - const ProgramParameters& programParameters, - const std::string& additionalDefines) { + static std::unique_ptr createInstance(gl::Context& context, + const ProgramParameters& programParameters, + const std::string& additionalDefines) { // Compile the shader std::initializer_list vertexSource = { "#version 300 es\n", programParameters.getDefines().c_str(), additionalDefines.c_str(), shaders::ShaderSource::vertex, - programParameters.vertexSource(gfx::Backend::Type::OpenGL).c_str() - }; + programParameters.vertexSource(gfx::Backend::Type::OpenGL).c_str()}; std::initializer_list fragmentSource = { "#version 300 es\n", programParameters.getDefines().c_str(), additionalDefines.c_str(), shaders::ShaderSource::fragment, - programParameters.fragmentSource(gfx::Backend::Type::OpenGL).c_str() - }; + programParameters.fragmentSource(gfx::Backend::Type::OpenGL).c_str()}; return std::make_unique(context, vertexSource, fragmentSource); } @@ -106,12 +101,12 @@ class Program final : public gfx::Program { auto it = instances.find(key); if (it == instances.end()) { try { - it = instances.emplace(key, - Instance::createInstance( - context, - programParameters, - gl::AttributeKey::defines(attributeBindings) - )).first; + it = instances + .emplace(key, + Instance::createInstance(context, + programParameters, + gl::AttributeKey::defines(attributeBindings))) + .first; } catch (const std::runtime_error& e) { Log::Error(Event::OpenGL, e.what()); return; @@ -126,13 +121,9 @@ class Program final : public gfx::Program { instance.textureStates.bind(context, textureBindings); auto& vertexArray = drawScope.getResource().vertexArray; - vertexArray.bind(context, - indexBuffer, - instance.attributeLocations.toBindingArray(attributeBindings)); + vertexArray.bind(context, indexBuffer, instance.attributeLocations.toBindingArray(attributeBindings)); - context.draw(drawMode, - indexOffset, - indexLength); + context.draw(drawMode, indexOffset, indexLength); } private: diff --git a/src/mbgl/gl/render_custom_layer.cpp b/src/mbgl/gl/render_custom_layer.cpp index 91df5537a84..e90af6bd6b4 100644 --- a/src/mbgl/gl/render_custom_layer.cpp +++ b/src/mbgl/gl/render_custom_layer.cpp @@ -56,12 +56,11 @@ void RenderCustomLayer::markContextDestroyed() { contextDestroyed = true; } -void RenderCustomLayer::prepare(const LayerPrepareParameters&) { -} +void RenderCustomLayer::prepare(const LayerPrepareParameters&) {} void RenderCustomLayer::render(PaintParameters& paintParameters) { if (host != impl(baseImpl).host) { - //If the context changed, deinitialize the previous one before initializing the new one. + // If the context changed, deinitialize the previous one before initializing the new one. if (host && !contextDestroyed) { MBGL_CHECK_ERROR(host->deinitialize()); } @@ -96,8 +95,8 @@ void RenderCustomLayer::render(PaintParameters& paintParameters) { MBGL_CHECK_ERROR(host->render(parameters)); - // Reset the view back to our original one, just in case the CustomLayer changed - // the viewport or Framebuffer. + // Reset the view back to our original one, just in case the CustomLayer + // changed the viewport or Framebuffer. paintParameters.backend.getDefaultRenderable().getResource().bind(); glContext.setDirtyState(); } diff --git a/src/mbgl/gl/render_pass.cpp b/src/mbgl/gl/render_pass.cpp index b327f7954fd..9d0ffeb10fc 100644 --- a/src/mbgl/gl/render_pass.cpp +++ b/src/mbgl/gl/render_pass.cpp @@ -9,11 +9,11 @@ namespace gl { RenderPass::RenderPass(gl::CommandEncoder& commandEncoder_, const char* name, const gfx::RenderPassDescriptor& descriptor) - : commandEncoder(commandEncoder_), debugGroup(commandEncoder.createDebugGroup(name)) { + : commandEncoder(commandEncoder_), + debugGroup(commandEncoder.createDebugGroup(name)) { descriptor.renderable.getResource().bind(); const auto clearDebugGroup(commandEncoder.createDebugGroup("clear")); - commandEncoder.context.clear(descriptor.clearColor, descriptor.clearDepth, - descriptor.clearStencil); + commandEncoder.context.clear(descriptor.clearColor, descriptor.clearDepth, descriptor.clearStencil); } void RenderPass::pushDebugGroup(const char* name) { diff --git a/src/mbgl/gl/renderbuffer_resource.hpp b/src/mbgl/gl/renderbuffer_resource.hpp index 9a318cbd48a..dc701a480a9 100644 --- a/src/mbgl/gl/renderbuffer_resource.hpp +++ b/src/mbgl/gl/renderbuffer_resource.hpp @@ -9,8 +9,7 @@ namespace gl { class RenderbufferResource final : public gfx::RenderbufferResource { public: explicit RenderbufferResource(UniqueRenderbuffer renderbuffer_) - : renderbuffer(std::move(renderbuffer_)) { - } + : renderbuffer(std::move(renderbuffer_)) {} ~RenderbufferResource() noexcept override = default; diff --git a/src/mbgl/gl/renderer_backend.cpp b/src/mbgl/gl/renderer_backend.cpp index 1f52ce06a9b..6a2bf2fb237 100644 --- a/src/mbgl/gl/renderer_backend.cpp +++ b/src/mbgl/gl/renderer_backend.cpp @@ -9,14 +9,12 @@ namespace mbgl { namespace gl { RendererBackend::RendererBackend(const gfx::ContextMode contextMode_) - : gfx::RendererBackend(contextMode_) { -} + : gfx::RendererBackend(contextMode_) {} std::unique_ptr RendererBackend::createContext() { auto result = std::make_unique(*this); result->enableDebugging(); - result->initializeExtensions( - std::bind(&RendererBackend::getExtensionFunctionPointer, this, std::placeholders::_1)); + result->initializeExtensions(std::bind(&RendererBackend::getExtensionFunctionPointer, this, std::placeholders::_1)); return result; } @@ -32,7 +30,7 @@ void RendererBackend::assumeFramebufferBinding(const gl::FramebufferID fbo) { } void RendererBackend::assumeViewport(int32_t x, int32_t y, const Size& size) { - getContext().viewport.setCurrentValue({ x, y, size }); + getContext().viewport.setCurrentValue({x, y, size}); assert(gl::value::Viewport::Get() == getContext().viewport.getCurrentValue()); } @@ -53,7 +51,7 @@ void RendererBackend::setFramebufferBinding(const gl::FramebufferID fbo) { } void RendererBackend::setViewport(int32_t x, int32_t y, const Size& size) { - getContext().viewport = { x, y, size }; + getContext().viewport = {x, y, size}; assert(gl::value::Viewport::Get() == getContext().viewport.getCurrentValue()); } diff --git a/src/mbgl/gl/state.hpp b/src/mbgl/gl/state.hpp index 77effb17810..3809da0369b 100644 --- a/src/mbgl/gl/state.hpp +++ b/src/mbgl/gl/state.hpp @@ -5,8 +5,8 @@ namespace mbgl { namespace gl { -// Wraps a piece of OpenGL state and remember its value to avoid redundant state calls. -// Wrapped types need to implement to the Value class interface: +// Wraps a piece of OpenGL state and remember its value to avoid redundant state +// calls. Wrapped types need to implement to the Value class interface: // // class Value { // using Type = ...; @@ -17,8 +17,8 @@ namespace gl { template class State { public: - State(Args&&... args) : params(std::forward_as_tuple(::std::forward(args)...)) { - } + State(Args&&... args) + : params(std::forward_as_tuple(::std::forward(args)...)) {} State& operator=(const typename T::Type& value) { if (*this != value) { @@ -29,13 +29,9 @@ class State { return *this; } - bool operator==(const typename T::Type& value) const { - return !(*this != value); - } + bool operator==(const typename T::Type& value) const { return !(*this != value); } - bool operator!=(const typename T::Type& value) const { - return dirty || currentValue != value; - } + bool operator!=(const typename T::Type& value) const { return dirty || currentValue != value; } void setCurrentValue(const typename T::Type& value) { dirty = false; @@ -44,17 +40,11 @@ class State { // Mark the state as dirty. This means that the next time we are assigning a value to this // piece of OpenGL state will always result in an actual OpenGL call. - void setDirty() { - dirty = true; - } + void setDirty() { dirty = true; } - typename T::Type getCurrentValue() const { - return currentValue; - } + typename T::Type getCurrentValue() const { return currentValue; } - bool isDirty() const { - return dirty; - } + bool isDirty() const { return dirty; } private: template diff --git a/src/mbgl/gl/texture.cpp b/src/mbgl/gl/texture.cpp index ef4d0836772..41557ce089a 100644 --- a/src/mbgl/gl/texture.cpp +++ b/src/mbgl/gl/texture.cpp @@ -10,41 +10,42 @@ using namespace platform; void bindTexture(gl::Context& context, const uint8_t unit, const gfx::TextureBinding& binding) { auto& resource = static_cast(*binding.resource); - if (binding.filter != resource.filter || binding.mipmap != resource.mipmap || - binding.wrapX != resource.wrapX || binding.wrapY != resource.wrapY) { + if (binding.filter != resource.filter || binding.mipmap != resource.mipmap || binding.wrapX != resource.wrapX || + binding.wrapY != resource.wrapY) { context.activeTextureUnit = unit; context.texture[unit] = resource.texture; if (binding.filter != resource.filter || binding.mipmap != resource.mipmap) { MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + GL_TEXTURE_2D, + GL_TEXTURE_MIN_FILTER, binding.filter == gfx::TextureFilterType::Linear - ? (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_LINEAR_MIPMAP_NEAREST - : GL_LINEAR) - : (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_NEAREST_MIPMAP_NEAREST - : GL_NEAREST))); - MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, - binding.filter == gfx::TextureFilterType::Linear ? GL_LINEAR : GL_NEAREST)); + ? (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR) + : (binding.mipmap == gfx::TextureMipMapType::Yes ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST))); + MBGL_CHECK_ERROR( + glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_MAG_FILTER, + binding.filter == gfx::TextureFilterType::Linear ? GL_LINEAR : GL_NEAREST)); resource.filter = binding.filter; resource.mipmap = binding.mipmap; } if (binding.wrapX != resource.wrapX) { - - MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, - binding.wrapX == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT)); + MBGL_CHECK_ERROR( + glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_WRAP_S, + binding.wrapX == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT)); resource.wrapX = binding.wrapX; } if (binding.wrapY != resource.wrapY) { - MBGL_CHECK_ERROR(glTexParameteri( - GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, - binding.wrapY == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT)); + MBGL_CHECK_ERROR( + glTexParameteri(GL_TEXTURE_2D, + GL_TEXTURE_WRAP_T, + binding.wrapY == gfx::TextureWrapType::Clamp ? GL_CLAMP_TO_EDGE : GL_REPEAT)); resource.wrapY = binding.wrapY; } } else if (context.texture[unit] != resource.texture) { - // We are checking first to avoid setting the active texture without a subsequent - // texture bind. + // We are checking first to avoid setting the active texture without a + // subsequent texture bind. context.activeTextureUnit = unit; context.texture[unit] = resource.texture; } diff --git a/src/mbgl/gl/texture.hpp b/src/mbgl/gl/texture.hpp index 74a314d2a7b..f6cecc397fd 100644 --- a/src/mbgl/gl/texture.hpp +++ b/src/mbgl/gl/texture.hpp @@ -21,27 +21,25 @@ class TextureStates; template class TextureStates> { private: - using State = - IndexedTuple, TypeList>...>>; + using State = IndexedTuple, TypeList>...>>; State state; public: void queryLocations(const ProgramID& id) { - state = State{ gl::uniformLocation(id, - concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value())... }; + state = State{ + gl::uniformLocation(id, concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value())...}; } NamedUniformLocations getNamedLocations() const { - return NamedUniformLocations{ { concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value(), - state.template get().location }... }; + return NamedUniformLocations{{concat_literals<&string_literal<'u', '_'>::value, &Ts::name>::value(), + state.template get().location}...}; } void bind(gl::Context& context, const gfx::TextureBindings>& bindings) { - util::ignore( - { (state.template get() = TypeIndex::value, - gl::bindTexture(context, TypeIndex::value, bindings.template get()), - 0)... }); + util::ignore({(state.template get() = TypeIndex::value, + gl::bindTexture(context, TypeIndex::value, bindings.template get()), + 0)...}); } }; diff --git a/src/mbgl/gl/texture_resource.hpp b/src/mbgl/gl/texture_resource.hpp index e2162beb8a5..100beadb6cc 100644 --- a/src/mbgl/gl/texture_resource.hpp +++ b/src/mbgl/gl/texture_resource.hpp @@ -8,7 +8,9 @@ namespace gl { class TextureResource : public gfx::TextureResource { public: - TextureResource(UniqueTexture&& texture_, int byteSize_) : texture(std::move(texture_)), byteSize(byteSize_) {} + TextureResource(UniqueTexture&& texture_, int byteSize_) + : texture(std::move(texture_)), + byteSize(byteSize_) {} ~TextureResource() noexcept override; static int getStorageSize(const Size& size, gfx::TexturePixelType format, gfx::TextureChannelDataType type); diff --git a/src/mbgl/gl/types.hpp b/src/mbgl/gl/types.hpp index e679d7646b1..0ff5094af90 100644 --- a/src/mbgl/gl/types.hpp +++ b/src/mbgl/gl/types.hpp @@ -15,14 +15,14 @@ using VertexArrayID = uint32_t; using FramebufferID = uint32_t; using RenderbufferID = uint32_t; -// OpenGL does not formally define a type for attribute locations, but most APIs use -// GLuint. The exception is glGetAttribLocation, which returns GLint so that -1 can -// be used as an error indicator. +// OpenGL does not formally define a type for attribute locations, but most APIs +// use GLuint. The exception is glGetAttribLocation, which returns GLint so that +// -1 can be used as an error indicator. using AttributeLocation = uint32_t; -// OpenGL does not formally define a type for uniform locations, but all APIs use GLint. -// The value -1 is special, typically used as a placeholder for an unused uniform and -// "silently ignored". +// OpenGL does not formally define a type for uniform locations, but all APIs +// use GLint. The value -1 is special, typically used as a placeholder for an +// unused uniform and "silently ignored". using UniformLocation = int32_t; enum class ShaderType : uint32_t { diff --git a/src/mbgl/gl/uniform.cpp b/src/mbgl/gl/uniform.cpp index b4750cc8510..648905150c3 100644 --- a/src/mbgl/gl/uniform.cpp +++ b/src/mbgl/gl/uniform.cpp @@ -61,7 +61,6 @@ void bindUniform>(UniformLocation location, const std::ar MBGL_CHECK_ERROR(glUniformMatrix4fv(location, 1, GL_FALSE, util::convert(t).data())); } - template <> void bindUniform(UniformLocation location, const bool& t) { return bindUniform(location, int32_t(t)); @@ -79,12 +78,12 @@ void bindUniform(UniformLocation location, const uint8_t& t) { template <> void bindUniform(UniformLocation location, const Color& t) { - bindUniform(location, std::array {{ t.r, t.g, t.b, t.a }}); + bindUniform(location, std::array{{t.r, t.g, t.b, t.a}}); } template <> void bindUniform(UniformLocation location, const Size& t) { - bindUniform(location, util::convert(std::array {{ t.width, t.height }})); + bindUniform(location, util::convert(std::array{{t.width, t.height}})); } template <> @@ -119,9 +118,8 @@ ActiveUniforms activeUniforms(ProgramID id) { GLenum type; for (GLint index = 0; index < count; index++) { MBGL_CHECK_ERROR(glGetActiveUniform(id, index, maxLength, &length, &size, &type, name.get())); - active.emplace( - std::string{ name.get(), static_cast(length) }, - ActiveUniform{ static_cast(size), static_cast(type) }); + active.emplace(std::string{name.get(), static_cast(length)}, + ActiveUniform{static_cast(size), static_cast(type)}); } return active; @@ -159,19 +157,15 @@ bool verifyUniform>(const ActiveUniform& uniform) { template <> bool verifyUniform(const ActiveUniform& uniform) { - assert(uniform.size == 1 && - (uniform.type == UniformDataType::Bool || - uniform.type == UniformDataType::Int || - uniform.type == UniformDataType::Float)); + assert(uniform.size == 1 && (uniform.type == UniformDataType::Bool || uniform.type == UniformDataType::Int || + uniform.type == UniformDataType::Float)); return true; } template <> bool verifyUniform(const ActiveUniform& uniform) { - assert(uniform.size == 1 && - (uniform.type == UniformDataType::Int || - uniform.type == UniformDataType::Float || - uniform.type == UniformDataType::Sampler2D)); + assert(uniform.size == 1 && (uniform.type == UniformDataType::Int || uniform.type == UniformDataType::Float || + uniform.type == UniformDataType::Sampler2D)); return true; } @@ -190,16 +184,14 @@ bool verifyUniform(const ActiveUniform& uniform) { template <> bool verifyUniform>(const ActiveUniform& uniform) { assert(uniform.size == 1 && - (uniform.type == UniformDataType::IntVec2 || - uniform.type == UniformDataType::FloatVec2)); + (uniform.type == UniformDataType::IntVec2 || uniform.type == UniformDataType::FloatVec2)); return true; } template <> bool verifyUniform>(const ActiveUniform& uniform) { assert(uniform.size == 1 && - (uniform.type == UniformDataType::IntVec4 || - uniform.type == UniformDataType::FloatVec4)); + (uniform.type == UniformDataType::IntVec4 || uniform.type == UniformDataType::FloatVec4)); return true; } diff --git a/src/mbgl/gl/uniform.hpp b/src/mbgl/gl/uniform.hpp index f26bafd77b2..28c643ec694 100644 --- a/src/mbgl/gl/uniform.hpp +++ b/src/mbgl/gl/uniform.hpp @@ -38,7 +38,8 @@ ActiveUniforms activeUniforms(ProgramID); template class UniformState { public: - UniformState(UniformLocation location_ = -1) : location(location_) {} + UniformState(UniformLocation location_ = -1) + : location(location_) {} UniformState& operator=(const Value& value) { if (location >= 0 && (!current || *current != value)) { @@ -74,22 +75,26 @@ class UniformStates> final { const auto active = gl::activeUniforms(id); util::ignore( - { // Some shader programs have uniforms declared, but not used, so they're not active. - // Therefore, we'll only verify them when they are indeed active. - (active.find(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value()) != active.end() - ? verifyUniform(active.at(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value())) - : false)... }); + {// Some shader programs have uniforms declared, but not used, so + // they're not active. Therefore, we'll only verify them when they + // are indeed active. + (active.find(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value()) != active.end() + ? verifyUniform( + active.at(concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value())) + : false)...}); #endif - state = State{ gl::uniformLocation(id, concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value())... }; + state = State{ + gl::uniformLocation(id, concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value())...}; } NamedUniformLocations getNamedLocations() const { - return NamedUniformLocations{ { concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value(), state.template get().location }... }; + return NamedUniformLocations{{concat_literals<&string_literal<'u', '_'>::value, &Us::name>::value(), + state.template get().location}...}; } void bind(const gfx::UniformValues>& values) { - util::ignore({ (state.template get() = values.template get(), 0)... }); + util::ignore({(state.template get() = values.template get(), 0)...}); } }; diff --git a/src/mbgl/gl/upload_pass.cpp b/src/mbgl/gl/upload_pass.cpp index 8615bfbc25a..6a366cd6537 100644 --- a/src/mbgl/gl/upload_pass.cpp +++ b/src/mbgl/gl/upload_pass.cpp @@ -13,70 +13,65 @@ namespace gl { using namespace platform; UploadPass::UploadPass(gl::CommandEncoder& commandEncoder_, const char* name) - : commandEncoder(commandEncoder_), debugGroup(commandEncoder.createDebugGroup(name)) { -} + : commandEncoder(commandEncoder_), + debugGroup(commandEncoder.createDebugGroup(name)) {} -std::unique_ptr UploadPass::createVertexBufferResource( - const void* data, std::size_t size, const gfx::BufferUsageType usage) { +std::unique_ptr UploadPass::createVertexBufferResource(const void* data, + std::size_t size, + const gfx::BufferUsageType usage) { BufferID id = 0; MBGL_CHECK_ERROR(glGenBuffers(1, &id)); commandEncoder.context.renderingStats().numBuffers++; commandEncoder.context.renderingStats().memVertexBuffers += static_cast(size); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueBuffer result{ std::move(id), { commandEncoder.context } }; + UniqueBuffer result{std::move(id), {commandEncoder.context}}; commandEncoder.context.vertexBuffer = result; - MBGL_CHECK_ERROR( - glBufferData(GL_ARRAY_BUFFER, size, data, Enum::to(usage))); + MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, size, data, Enum::to(usage))); return std::make_unique(std::move(result), static_cast(size)); } -void UploadPass::updateVertexBufferResource(gfx::VertexBufferResource& resource, - const void* data, - std::size_t size) { +void UploadPass::updateVertexBufferResource(gfx::VertexBufferResource& resource, const void* data, std::size_t size) { commandEncoder.context.vertexBuffer = static_cast(resource).buffer; MBGL_CHECK_ERROR(glBufferSubData(GL_ARRAY_BUFFER, 0, size, data)); } -std::unique_ptr UploadPass::createIndexBufferResource( - const void* data, std::size_t size, const gfx::BufferUsageType usage) { +std::unique_ptr UploadPass::createIndexBufferResource(const void* data, + std::size_t size, + const gfx::BufferUsageType usage) { BufferID id = 0; MBGL_CHECK_ERROR(glGenBuffers(1, &id)); commandEncoder.context.renderingStats().numBuffers++; commandEncoder.context.renderingStats().memIndexBuffers += static_cast(size); // NOLINTNEXTLINE(performance-move-const-arg) - UniqueBuffer result{ std::move(id), { commandEncoder.context } }; + UniqueBuffer result{std::move(id), {commandEncoder.context}}; commandEncoder.context.bindVertexArray = 0; commandEncoder.context.globalVertexArrayState.indexBuffer = result; - MBGL_CHECK_ERROR( - glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, Enum::to(usage))); + MBGL_CHECK_ERROR(glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, Enum::to(usage))); return std::make_unique(std::move(result), static_cast(size)); } -void UploadPass::updateIndexBufferResource(gfx::IndexBufferResource& resource, - const void* data, - std::size_t size) { - // Be sure to unbind any existing vertex array object before binding the index buffer - // so that we don't mess up another VAO +void UploadPass::updateIndexBufferResource(gfx::IndexBufferResource& resource, const void* data, std::size_t size) { + // Be sure to unbind any existing vertex array object before binding the + // index buffer so that we don't mess up another VAO commandEncoder.context.bindVertexArray = 0; - commandEncoder.context.globalVertexArrayState.indexBuffer = - static_cast(resource).buffer; + commandEncoder.context.globalVertexArrayState.indexBuffer = static_cast(resource).buffer; MBGL_CHECK_ERROR(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, size, data)); } -std::unique_ptr -UploadPass::createTextureResource(const Size size, - const void* data, - gfx::TexturePixelType format, - gfx::TextureChannelDataType type) { +std::unique_ptr UploadPass::createTextureResource(const Size size, + const void* data, + gfx::TexturePixelType format, + gfx::TextureChannelDataType type) { auto obj = commandEncoder.context.createUniqueTexture(); int textureByteSize = gl::TextureResource::getStorageSize(size, format, type); commandEncoder.context.renderingStats().memTextures += textureByteSize; - std::unique_ptr resource = - std::make_unique(std::move(obj), textureByteSize); - commandEncoder.context.pixelStoreUnpack = { 1 }; + std::unique_ptr resource = std::make_unique(std::move(obj), + textureByteSize); + commandEncoder.context.pixelStoreUnpack = {1}; updateTextureResource(*resource, size, data, format, type); - // We are using clamp to edge here since OpenGL ES doesn't allow GL_REPEAT on NPOT textures. - // We use those when the pixelRatio isn't a power of two, e.g. on iPhone 6 Plus. + // We are using clamp to edge here since OpenGL ES doesn't allow GL_REPEAT + // on NPOT textures. We use those when the pixelRatio isn't a power of two, + // e.g. on iPhone 6 Plus. MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); @@ -92,10 +87,15 @@ void UploadPass::updateTextureResource(gfx::TextureResource& resource, // Always use texture unit 0 for manipulating it. commandEncoder.context.activeTextureUnit = 0; commandEncoder.context.texture[0] = static_cast(resource).texture; - MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, Enum::to(format), - size.width, size.height, 0, + MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, + 0, + Enum::to(format), + size.width, + size.height, + 0, Enum::to(format), - Enum::to(type), data)); + Enum::to(type), + data)); } void UploadPass::updateTextureResourceSub(gfx::TextureResource& resource, @@ -108,9 +108,15 @@ void UploadPass::updateTextureResourceSub(gfx::TextureResource& resource, // Always use texture unit 0 for manipulating it. commandEncoder.context.activeTextureUnit = 0; commandEncoder.context.texture[0] = static_cast(resource).texture; - MBGL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, size.width, size.height, + MBGL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, + 0, + xOffset, + yOffset, + size.width, + size.height, Enum::to(format), - Enum::to(type), data)); + Enum::to(type), + data)); } void UploadPass::pushDebugGroup(const char* name) { diff --git a/src/mbgl/gl/upload_pass.hpp b/src/mbgl/gl/upload_pass.hpp index 692652a8239..841ddc892d2 100644 --- a/src/mbgl/gl/upload_pass.hpp +++ b/src/mbgl/gl/upload_pass.hpp @@ -33,8 +33,12 @@ class UploadPass final : public gfx::UploadPass { void updateIndexBufferResource(gfx::IndexBufferResource&, const void* data, std::size_t size) override; public: - std::unique_ptr createTextureResource(Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType) override; - void updateTextureResource(gfx::TextureResource&, Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType) override; + std::unique_ptr createTextureResource(Size, + const void* data, + gfx::TexturePixelType, + gfx::TextureChannelDataType) override; + void updateTextureResource( + gfx::TextureResource&, Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType) override; void updateTextureResourceSub(gfx::TextureResource&, uint16_t xOffset, uint16_t yOffset, diff --git a/src/mbgl/gl/value.cpp b/src/mbgl/gl/value.cpp index b19bbd020de..6370ba38ab5 100644 --- a/src/mbgl/gl/value.cpp +++ b/src/mbgl/gl/value.cpp @@ -22,7 +22,7 @@ ClearDepth::Type ClearDepth::Get() { return clearDepth; } -const ClearColor::Type ClearColor::Default { 0, 0, 0, 0 }; +const ClearColor::Type ClearColor::Default{0, 0, 0, 0}; void ClearColor::Set(const Type& value) { MBGL_CHECK_ERROR(glClearColor(value.r, value.g, value.b, value.a)); @@ -31,7 +31,7 @@ void ClearColor::Set(const Type& value) { ClearColor::Type ClearColor::Get() { GLfloat clearColor[4]; MBGL_CHECK_ERROR(glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor)); - return { clearColor[0], clearColor[1], clearColor[2], clearColor[3] }; + return {clearColor[0], clearColor[1], clearColor[2], clearColor[3]}; } const constexpr ClearStencil::Type ClearStencil::Default; @@ -79,8 +79,10 @@ void ColorMask::Set(const Type& value) { ColorMask::Type ColorMask::Get() { GLboolean bools[4]; MBGL_CHECK_ERROR(glGetBooleanv(GL_COLOR_WRITEMASK, bools)); - return { static_cast(bools[0]), static_cast(bools[1]), static_cast(bools[2]), - static_cast(bools[3]) }; + return {static_cast(bools[0]), + static_cast(bools[1]), + static_cast(bools[2]), + static_cast(bools[3])}; } const constexpr StencilFunc::Type StencilFunc::Default; @@ -96,7 +98,7 @@ StencilFunc::Type StencilFunc::Get() { MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_FUNC, &func)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_REF, &ref)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_VALUE_MASK, &mask)); - return { Enum::from(func), ref, static_cast(mask) }; + return {Enum::from(func), ref, static_cast(mask)}; } const constexpr StencilTest::Type StencilTest::Default; @@ -126,9 +128,9 @@ StencilOp::Type StencilOp::Get() { MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_FAIL, &sfail)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &dpfail)); MBGL_CHECK_ERROR(glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &dppass)); - return { Enum::from(sfail), - Enum::from(dpfail), - Enum::from(dppass) }; + return {Enum::from(sfail), + Enum::from(dpfail), + Enum::from(dppass)}; } const constexpr DepthRange::Type DepthRange::Default; @@ -140,7 +142,7 @@ void DepthRange::Set(const Type& value) { DepthRange::Type DepthRange::Get() { GLfloat floats[2]; MBGL_CHECK_ERROR(glGetFloatv(GL_DEPTH_RANGE, floats)); - return { floats[0], floats[1] }; + return {floats[0], floats[1]}; } const constexpr DepthTest::Type DepthTest::Default; @@ -203,11 +205,10 @@ BlendFunc::Type BlendFunc::Get() { GLint dfactor; MBGL_CHECK_ERROR(glGetIntegerv(GL_BLEND_SRC_ALPHA, &sfactor)); MBGL_CHECK_ERROR(glGetIntegerv(GL_BLEND_DST_ALPHA, &dfactor)); - return { Enum::from(sfactor), - Enum::from(dfactor) }; + return {Enum::from(sfactor), Enum::from(dfactor)}; } -const BlendColor::Type BlendColor::Default { 0, 0, 0, 0 }; +const BlendColor::Type BlendColor::Default{0, 0, 0, 0}; void BlendColor::Set(const Type& value) { MBGL_CHECK_ERROR(glBlendColor(value.r, value.g, value.b, value.a)); @@ -216,7 +217,7 @@ void BlendColor::Set(const Type& value) { BlendColor::Type BlendColor::Get() { GLfloat floats[4]; MBGL_CHECK_ERROR(glGetFloatv(GL_BLEND_COLOR, floats)); - return { floats[0], floats[1], floats[2], floats[3] }; + return {floats[0], floats[1], floats[2], floats[3]}; } const constexpr Program::Type Program::Default; @@ -264,8 +265,9 @@ void Viewport::Set(const Type& value) { Viewport::Type Viewport::Get() { GLint viewport[4]; MBGL_CHECK_ERROR(glGetIntegerv(GL_VIEWPORT, viewport)); - return { static_cast(viewport[0]), static_cast(viewport[1]), - { static_cast(viewport[2]), static_cast(viewport[3]) } }; + return {static_cast(viewport[0]), + static_cast(viewport[1]), + {static_cast(viewport[2]), static_cast(viewport[3])}}; } const constexpr ScissorTest::Type ScissorTest::Default; @@ -388,7 +390,7 @@ BindVertexArray::Type BindVertexArray::Get() { return binding; } -const VertexAttribute::Type VertexAttribute::Default {}; +const VertexAttribute::Type VertexAttribute::Default{}; namespace { @@ -477,7 +479,7 @@ GLint components(const gfx::AttributeDataType type) { #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4312) // reinterpret_cast different size +#pragma warning(disable : 4312) // reinterpret_cast different size #endif void VertexAttribute::Set(const Type& binding, Context& context, AttributeLocation location) { @@ -503,8 +505,7 @@ void VertexAttribute::Set(const Type& binding, Context& context, AttributeLocati const constexpr PixelStorePack::Type PixelStorePack::Default; void PixelStorePack::Set(const Type& value) { - assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || - value.alignment == 8); + assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || value.alignment == 8); MBGL_CHECK_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, value.alignment)); } @@ -517,8 +518,7 @@ PixelStorePack::Type PixelStorePack::Get() { const constexpr PixelStoreUnpack::Type PixelStoreUnpack::Default; void PixelStoreUnpack::Set(const Type& value) { - assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || - value.alignment == 8); + assert(value.alignment == 1 || value.alignment == 2 || value.alignment == 4 || value.alignment == 8); MBGL_CHECK_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, value.alignment)); } diff --git a/src/mbgl/gl/value.hpp b/src/mbgl/gl/value.hpp index d45b2d5a250..feda4410c6e 100644 --- a/src/mbgl/gl/value.hpp +++ b/src/mbgl/gl/value.hpp @@ -55,7 +55,7 @@ struct DepthMask { struct ColorMask { using Type = gfx::ColorMode::Mask; - static const constexpr Type Default = { true, true, true, true }; + static const constexpr Type Default = {true, true, true, true}; static void Set(const Type&); static Type Get(); }; @@ -66,7 +66,7 @@ struct StencilFunc { int32_t ref; uint32_t mask; }; - static const constexpr Type Default = { gfx::StencilMode::Always::func, 0, ~0u }; + static const constexpr Type Default = {gfx::StencilMode::Always::func, 0, ~0u}; static void Set(const Type&); static Type Get(); }; @@ -88,7 +88,8 @@ struct StencilOp { gfx::StencilOpType dpfail; gfx::StencilOpType dppass; }; - static const constexpr Type Default = { gfx::StencilOpType::Keep, gfx::StencilOpType::Keep, gfx::StencilOpType::Keep }; + static const constexpr Type Default = { + gfx::StencilOpType::Keep, gfx::StencilOpType::Keep, gfx::StencilOpType::Keep}; static void Set(const Type&); static Type Get(); }; @@ -99,7 +100,7 @@ constexpr bool operator!=(const StencilOp::Type& a, const StencilOp::Type& b) { struct DepthRange { using Type = Range; - static const constexpr Type Default = { 0, 1 }; + static const constexpr Type Default = {0, 1}; static void Set(const Type&); static Type Get(); }; @@ -137,7 +138,7 @@ struct BlendFunc { gfx::ColorBlendFactorType sfactor; gfx::ColorBlendFactorType dfactor; }; - static const constexpr Type Default = { gfx::ColorBlendFactorType::One, gfx::ColorBlendFactorType::Zero }; + static const constexpr Type Default = {gfx::ColorBlendFactorType::One, gfx::ColorBlendFactorType::Zero}; static void Set(const Type&); static Type Get(); }; @@ -180,7 +181,7 @@ struct Viewport { int32_t y; Size size; }; - static const constexpr Type Default = { 0, 0, { 0, 0 } }; + static const constexpr Type Default = {0, 0, {0, 0}}; static void Set(const Type&); static Type Get(); }; @@ -271,14 +272,14 @@ struct VertexAttribute { struct PixelStorePack { using Type = PixelStorageType; - static const constexpr Type Default = { 4 }; + static const constexpr Type Default = {4}; static void Set(const Type&); static Type Get(); }; struct PixelStoreUnpack { using Type = PixelStorageType; - static const constexpr Type Default = { 4 }; + static const constexpr Type Default = {4}; static void Set(const Type&); static Type Get(); }; diff --git a/src/mbgl/gl/vertex_array.cpp b/src/mbgl/gl/vertex_array.cpp index 168080a050a..4705b8bb20b 100644 --- a/src/mbgl/gl/vertex_array.cpp +++ b/src/mbgl/gl/vertex_array.cpp @@ -5,9 +5,7 @@ namespace mbgl { namespace gl { -void VertexArray::bind(Context& context, - const gfx::IndexBuffer& indexBuffer, - const AttributeBindingArray& bindings) { +void VertexArray::bind(Context& context, const gfx::IndexBuffer& indexBuffer, const AttributeBindingArray& bindings) { context.bindVertexArray = state->vertexArray; state->indexBuffer = indexBuffer.getResource().buffer; diff --git a/src/mbgl/gl/vertex_array.hpp b/src/mbgl/gl/vertex_array.hpp index 70413050b26..8ad6742de79 100644 --- a/src/mbgl/gl/vertex_array.hpp +++ b/src/mbgl/gl/vertex_array.hpp @@ -21,8 +21,7 @@ class Context; class VertexArrayState { public: VertexArrayState(UniqueVertexArray vertexArray_) - : vertexArray(std::move(vertexArray_)) { - } + : vertexArray(std::move(vertexArray_)) {} void setDirty() { indexBuffer.setDirty(); @@ -58,8 +57,7 @@ using UniqueVertexArrayState = std::unique_ptr BackgroundLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr BackgroundLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value) noexcept { (void)value; return std::unique_ptr(new style::BackgroundLayer(id)); } diff --git a/src/mbgl/layermanager/circle_layer_factory.cpp b/src/mbgl/layermanager/circle_layer_factory.cpp index 1e51b4f5b82..b32fb13177c 100644 --- a/src/mbgl/layermanager/circle_layer_factory.cpp +++ b/src/mbgl/layermanager/circle_layer_factory.cpp @@ -12,7 +12,8 @@ const style::LayerTypeInfo* CircleLayerFactory::getTypeInfo() const noexcept { return style::CircleLayer::Impl::staticTypeInfo(); } -std::unique_ptr CircleLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr CircleLayerFactory::createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept { auto const source = getSource(value); if (!source) { return nullptr; diff --git a/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp b/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp index 234ba894746..8c78f630c32 100644 --- a/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp +++ b/src/mbgl/layermanager/fill_extrusion_layer_factory.cpp @@ -11,7 +11,8 @@ const style::LayerTypeInfo* FillExtrusionLayerFactory::getTypeInfo() const noexc return style::FillExtrusionLayer::Impl::staticTypeInfo(); } -std::unique_ptr FillExtrusionLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr FillExtrusionLayerFactory::createLayer( + const std::string& id, const style::conversion::Convertible& value) noexcept { auto const source = getSource(value); if (!source) { return nullptr; @@ -20,9 +21,10 @@ std::unique_ptr FillExtrusionLayerFactory::createLayer(const std:: return std::unique_ptr(new style::FillExtrusionLayer(id, *source)); } -std::unique_ptr FillExtrusionLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr layer, - const std::vector>& group) noexcept { +std::unique_ptr FillExtrusionLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr layer, + const std::vector>& group) noexcept { using namespace style; using LayoutType = PatternLayout; return std::make_unique(parameters.bucketParameters, group, std::move(layer), parameters); diff --git a/src/mbgl/layermanager/fill_layer_factory.cpp b/src/mbgl/layermanager/fill_layer_factory.cpp index 441dbb79127..5690c2d34c7 100644 --- a/src/mbgl/layermanager/fill_layer_factory.cpp +++ b/src/mbgl/layermanager/fill_layer_factory.cpp @@ -11,7 +11,8 @@ const style::LayerTypeInfo* FillLayerFactory::getTypeInfo() const noexcept { return style::FillLayer::Impl::staticTypeInfo(); } -std::unique_ptr FillLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr FillLayerFactory::createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept { std::optional source = getSource(value); if (!source) { return nullptr; @@ -20,10 +21,10 @@ std::unique_ptr FillLayerFactory::createLayer(const std::string& i return std::unique_ptr(new style::FillLayer(id, *source)); } -std::unique_ptr -FillLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr layer, - const std::vector>& group) noexcept { +std::unique_ptr FillLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr layer, + const std::vector>& group) noexcept { using namespace style; using LayoutTypeUnsorted = PatternLayout; using LayoutTypeSorted = diff --git a/src/mbgl/layermanager/heatmap_layer_factory.cpp b/src/mbgl/layermanager/heatmap_layer_factory.cpp index 636afd5fdc5..17bbd71fc1b 100644 --- a/src/mbgl/layermanager/heatmap_layer_factory.cpp +++ b/src/mbgl/layermanager/heatmap_layer_factory.cpp @@ -11,7 +11,8 @@ const style::LayerTypeInfo* HeatmapLayerFactory::getTypeInfo() const noexcept { return style::HeatmapLayer::Impl::staticTypeInfo(); } -std::unique_ptr HeatmapLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr HeatmapLayerFactory::createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept { auto const source = getSource(value); if (!source) { return nullptr; @@ -20,7 +21,8 @@ std::unique_ptr HeatmapLayerFactory::createLayer(const std::string return std::unique_ptr(new style::HeatmapLayer(id, *source)); } -std::unique_ptr HeatmapLayerFactory::createBucket(const BucketParameters& parameters, const std::vector>& layers) noexcept { +std::unique_ptr HeatmapLayerFactory::createBucket( + const BucketParameters& parameters, const std::vector>& layers) noexcept { return std::make_unique(parameters, layers); } diff --git a/src/mbgl/layermanager/hillshade_layer_factory.cpp b/src/mbgl/layermanager/hillshade_layer_factory.cpp index 4e1d78a69c5..af257d1c9ee 100644 --- a/src/mbgl/layermanager/hillshade_layer_factory.cpp +++ b/src/mbgl/layermanager/hillshade_layer_factory.cpp @@ -10,7 +10,8 @@ const style::LayerTypeInfo* HillshadeLayerFactory::getTypeInfo() const noexcept return style::HillshadeLayer::Impl::staticTypeInfo(); } -std::unique_ptr HillshadeLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr HillshadeLayerFactory::createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept { auto const source = getSource(value); if (!source) { return nullptr; diff --git a/src/mbgl/layermanager/layer_factory.cpp b/src/mbgl/layermanager/layer_factory.cpp index 80f9e08d42e..8c20f590732 100644 --- a/src/mbgl/layermanager/layer_factory.cpp +++ b/src/mbgl/layermanager/layer_factory.cpp @@ -25,7 +25,8 @@ std::optional LayerFactory::getSource(const style::conversion::Conv return source; } -std::unique_ptr LayerFactory::createBucket(const BucketParameters&, const std::vector>&) noexcept { +std::unique_ptr LayerFactory::createBucket(const BucketParameters&, + const std::vector>&) noexcept { assert(false); return nullptr; } diff --git a/src/mbgl/layermanager/layer_manager.cpp b/src/mbgl/layermanager/layer_manager.cpp index 377d3acce40..26c0e741350 100644 --- a/src/mbgl/layermanager/layer_manager.cpp +++ b/src/mbgl/layermanager/layer_manager.cpp @@ -11,9 +11,10 @@ namespace mbgl { -std::unique_ptr LayerManager::createLayer( - const std::string& type, const std::string& id, - const style::conversion::Convertible& value, style::conversion::Error& error) noexcept { +std::unique_ptr LayerManager::createLayer(const std::string& type, + const std::string& id, + const style::conversion::Convertible& value, + style::conversion::Error& error) noexcept { LayerFactory* factory = getFactory(type); if (factory) { auto layer = factory->createLayer(id, value); @@ -28,8 +29,8 @@ std::unique_ptr LayerManager::createLayer( return nullptr; } -std::unique_ptr LayerManager::createBucket(const BucketParameters& parameters, - const std::vector>& layers) noexcept { +std::unique_ptr LayerManager::createBucket( + const BucketParameters& parameters, const std::vector>& layers) noexcept { assert(!layers.empty()); assert(parameters.layerType->layout == style::LayerTypeInfo::Layout::NotRequired); LayerFactory* factory = getFactory(parameters.layerType); @@ -37,9 +38,10 @@ std::unique_ptr LayerManager::createBucket(const BucketParameters& param return factory->createBucket(parameters, layers); } -std::unique_ptr LayerManager::createLayout(const LayoutParameters& parameters, - std::unique_ptr tileLayer, - const std::vector>& layers) noexcept { +std::unique_ptr LayerManager::createLayout( + const LayoutParameters& parameters, + std::unique_ptr tileLayer, + const std::vector>& layers) noexcept { assert(!layers.empty()); assert(parameters.bucketParameters.layerType->layout == style::LayerTypeInfo::Layout::Required); LayerFactory* factory = getFactory(parameters.bucketParameters.layerType); diff --git a/src/mbgl/layermanager/line_layer_factory.cpp b/src/mbgl/layermanager/line_layer_factory.cpp index cdffb2661d4..2ff372a4ae7 100644 --- a/src/mbgl/layermanager/line_layer_factory.cpp +++ b/src/mbgl/layermanager/line_layer_factory.cpp @@ -11,7 +11,8 @@ const style::LayerTypeInfo* LineLayerFactory::getTypeInfo() const noexcept { return style::LineLayer::Impl::staticTypeInfo(); } -std::unique_ptr LineLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr LineLayerFactory::createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept { auto const source = getSource(value); if (!source) { return nullptr; @@ -19,9 +20,10 @@ std::unique_ptr LineLayerFactory::createLayer(const std::string& i return std::unique_ptr(new style::LineLayer(id, *source)); } -std::unique_ptr LineLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr layer, - const std::vector>& group) noexcept { +std::unique_ptr LineLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr layer, + const std::vector>& group) noexcept { using namespace style; using LayoutTypeUnsorted = PatternLayout; using LayoutTypeSorted = diff --git a/src/mbgl/layermanager/raster_layer_factory.cpp b/src/mbgl/layermanager/raster_layer_factory.cpp index dcc1f817e17..05fc9fd66c7 100644 --- a/src/mbgl/layermanager/raster_layer_factory.cpp +++ b/src/mbgl/layermanager/raster_layer_factory.cpp @@ -10,7 +10,8 @@ const style::LayerTypeInfo* RasterLayerFactory::getTypeInfo() const noexcept { return style::RasterLayer::Impl::staticTypeInfo(); } -std::unique_ptr RasterLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr RasterLayerFactory::createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept { auto const source = getSource(value); if (!source) { return nullptr; diff --git a/src/mbgl/layermanager/symbol_layer_factory.cpp b/src/mbgl/layermanager/symbol_layer_factory.cpp index d307def5df4..465341fb678 100644 --- a/src/mbgl/layermanager/symbol_layer_factory.cpp +++ b/src/mbgl/layermanager/symbol_layer_factory.cpp @@ -11,7 +11,8 @@ const style::LayerTypeInfo* SymbolLayerFactory::getTypeInfo() const noexcept { return style::SymbolLayer::Impl::staticTypeInfo(); } -std::unique_ptr SymbolLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { +std::unique_ptr SymbolLayerFactory::createLayer(const std::string& id, + const style::conversion::Convertible& value) noexcept { std::optional source = getSource(value); if (!source) { return nullptr; @@ -19,9 +20,10 @@ std::unique_ptr SymbolLayerFactory::createLayer(const std::string& return std::unique_ptr(new style::SymbolLayer(id, *source)); } -std::unique_ptr SymbolLayerFactory::createLayout(const LayoutParameters& parameters, - std::unique_ptr tileLayer, - const std::vector>& group) noexcept { +std::unique_ptr SymbolLayerFactory::createLayout( + const LayoutParameters& parameters, + std::unique_ptr tileLayer, + const std::vector>& group) noexcept { return std::make_unique(parameters.bucketParameters, group, std::move(tileLayer), parameters); } diff --git a/src/mbgl/layout/circle_layout.hpp b/src/mbgl/layout/circle_layout.hpp index 620e04542cd..5968a80e6e9 100644 --- a/src/mbgl/layout/circle_layout.hpp +++ b/src/mbgl/layout/circle_layout.hpp @@ -13,7 +13,9 @@ class CircleLayout final : public Layout { CircleLayout(const BucketParameters& parameters, const std::vector>& group, std::unique_ptr sourceLayer_) - : sourceLayer(std::move(sourceLayer_)), zoom(parameters.tileID.overscaledZ), mode(parameters.mode) { + : sourceLayer(std::move(sourceLayer_)), + zoom(parameters.tileID.overscaledZ), + mode(parameters.mode) { assert(!group.empty()); auto leaderLayerProperties = staticImmutableCast(group.front()); const auto& unevaluatedLayout = leaderLayerProperties->layerImpl().layout; diff --git a/src/mbgl/layout/clip_lines.cpp b/src/mbgl/layout/clip_lines.cpp index 022c296e190..2b7d99db6a2 100644 --- a/src/mbgl/layout/clip_lines.cpp +++ b/src/mbgl/layout/clip_lines.cpp @@ -5,15 +5,12 @@ namespace mbgl { namespace util { -GeometryCollection clipLines(const GeometryCollection &lines, - const int16_t x1, const int16_t y1, const int16_t x2, const int16_t y2) { - +GeometryCollection clipLines( + const GeometryCollection& lines, const int16_t x1, const int16_t y1, const int16_t x2, const int16_t y2) { GeometryCollection clippedLines; for (auto& line : lines) { - - if (line.empty()) - continue; + if (line.empty()) continue; auto end = line.end() - 1; for (auto it = line.begin(); it != end; it++) { diff --git a/src/mbgl/layout/layout.hpp b/src/mbgl/layout/layout.hpp index aaa4d4b8e1f..c6593b00f2f 100644 --- a/src/mbgl/layout/layout.hpp +++ b/src/mbgl/layout/layout.hpp @@ -26,10 +26,8 @@ class Layout { virtual void prepareSymbols(const GlyphMap&, const GlyphPositions&, const ImageMap&, const ImagePositions&){}; - virtual bool hasSymbolInstances() const { - return true; - }; - + virtual bool hasSymbolInstances() const { return true; }; + virtual bool hasDependencies() const = 0; }; diff --git a/src/mbgl/layout/merge_lines.cpp b/src/mbgl/layout/merge_lines.cpp index 616a8a3ff56..ba7e90a6c08 100644 --- a/src/mbgl/layout/merge_lines.cpp +++ b/src/mbgl/layout/merge_lines.cpp @@ -13,13 +13,11 @@ size_t mergeFromRight(std::vector& features, Index::iterator left, size_t rightKey, GeometryCollection& geom) { - const size_t index = left->second; rightIndex.erase(left); rightIndex[rightKey] = index; features[index].geometry[0].pop_back(); - features[index].geometry[0].insert( - features[index].geometry[0].end(), geom[0].begin(), geom[0].end()); + features[index].geometry[0].insert(features[index].geometry[0].end(), geom[0].begin(), geom[0].end()); geom[0].clear(); return index; } @@ -29,13 +27,11 @@ size_t mergeFromLeft(std::vector& features, Index::iterator right, size_t leftKey, GeometryCollection& geom) { - const size_t index = right->second; leftIndex.erase(right); leftIndex[leftKey] = index; geom[0].pop_back(); - geom[0].insert( - geom[0].end(), features[index].geometry[0].begin(), features[index].geometry[0].end()); + geom[0].insert(geom[0].end(), features[index].geometry[0].begin(), features[index].geometry[0].end()); features[index].geometry[0].clear(); std::swap(features[index].geometry[0], geom[0]); return index; @@ -56,8 +52,9 @@ void mergeLines(std::vector& features) { if (!feature.formattedText || geometry.empty() || geometry[0].empty()) { continue; } - - // TODO: Key should include formatting options (see https://github.com/mapbox/mapbox-gl-js/issues/3645) + + // TODO: Key should include formatting options (see + // https://github.com/mapbox/mapbox-gl-js/issues/3645) const size_t leftKey = getKey(feature.formattedText->rawText(), geometry[0].front()); const size_t rightKey = getKey(feature.formattedText->rawText(), geometry[0].back()); @@ -66,8 +63,8 @@ void mergeLines(std::vector& features) { const auto right = leftIndex.find(rightKey); if (left != rightIndex.end() && right != leftIndex.end() && left->second != right->second) { - // found lines with the same text adjacent to both ends of the current line, merge all - // three + // found lines with the same text adjacent to both ends of the + // current line, merge all three size_t j = mergeFromLeft(features, leftIndex, right, leftKey, geometry); size_t i = mergeFromRight(features, rightIndex, left, rightKey, features[j].geometry); diff --git a/src/mbgl/layout/pattern_layout.hpp b/src/mbgl/layout/pattern_layout.hpp index b2bcd1b3194..8b73f3f34e5 100644 --- a/src/mbgl/layout/pattern_layout.hpp +++ b/src/mbgl/layout/pattern_layout.hpp @@ -18,13 +18,16 @@ class PatternDependency { using PatternLayerMap = std::map; -class PatternFeature { +class PatternFeature { public: PatternFeature(std::size_t i_, std::unique_ptr feature_, PatternLayerMap patterns_, float sortKey_ = 0.0f) - : i(i_), feature(std::move(feature_)), patterns(std::move(patterns_)), sortKey(sortKey_) {} + : i(i_), + feature(std::move(feature_)), + patterns(std::move(patterns_)), + sortKey(sortKey_) {} friend bool operator<(const PatternFeature& lhs, const PatternFeature& rhs) { return lhs.sortKey < rhs.sortKey; } @@ -95,8 +98,8 @@ class PatternLayout : public Layout { const auto& evaluated = style::getEvaluated(layerProperties); const auto& patternProperty = evaluated.template get(); const auto constantPattern = patternProperty.constantOr(Faded{"", ""}); - // determine if layer group has any layers that use *-pattern property and add - // constant pattern dependencies. + // determine if layer group has any layers that use *-pattern + // property and add constant pattern dependencies. if (!patternProperty.isConstant()) { hasPattern = true; } else if (!constantPattern.to.id().empty()) { @@ -124,8 +127,9 @@ class PatternLayout : public Layout { const auto paint = static_cast(*it->second).evaluated; const auto& patternProperty = paint.template get(); if (!patternProperty.isConstant()) { - // For layers with non-data-constant pattern properties, evaluate their expression and add - // the patterns to the dependency vector + // For layers with non-data-constant pattern + // properties, evaluate their expression and add the + // patterns to the dependency vector const auto min = patternProperty.evaluate(*feature, zoom - 1, layoutParameters.availableImages, @@ -171,7 +175,7 @@ class PatternLayout : public Layout { const bool /*showCollisionBoxes*/, const CanonicalTileID& canonical) override { auto bucket = std::make_shared(layout, layerPropertiesMap, zoom, overscaling); - for (auto & patternFeature : features) { + for (auto& patternFeature : features) { const auto i = patternFeature.i; std::unique_ptr feature = std::move(patternFeature.feature); const PatternLayerMap& patterns = patternFeature.patterns; @@ -182,7 +186,7 @@ class PatternLayout : public Layout { } if (bucket->hasData()) { for (const auto& pair : layerPropertiesMap) { - renderData.emplace(pair.first, LayerRenderData {bucket, pair.second}); + renderData.emplace(pair.first, LayerRenderData{bucket, pair.second}); } } }; diff --git a/src/mbgl/layout/symbol_feature.hpp b/src/mbgl/layout/symbol_feature.hpp index e1000500419..85756a9ce5e 100644 --- a/src/mbgl/layout/symbol_feature.hpp +++ b/src/mbgl/layout/symbol_feature.hpp @@ -23,9 +23,7 @@ class SymbolFeature : public GeometryTileFeature { FeatureIdentifier getID() const override { return feature->getID(); }; const GeometryCollection& getGeometries() const override { return feature->getGeometries(); } - friend bool operator < (const SymbolFeature& lhs, const SymbolFeature& rhs) { - return lhs.sortKey < rhs.sortKey; - } + friend bool operator<(const SymbolFeature& lhs, const SymbolFeature& rhs) { return lhs.sortKey < rhs.sortKey; } std::unique_ptr feature; GeometryCollection geometry; diff --git a/src/mbgl/layout/symbol_instance.cpp b/src/mbgl/layout/symbol_instance.cpp index 2175859200a..9b48b0de2f2 100644 --- a/src/mbgl/layout/symbol_instance.cpp +++ b/src/mbgl/layout/symbol_instance.cpp @@ -40,14 +40,14 @@ SymbolInstanceSharedData::SymbolInstanceSharedData(GeometryCoordinates line_, } bool singleLineInitialized = false; - const auto initHorizontalGlyphQuads = [&] (SymbolQuads& quads, const Shaping& shaping) { + const auto initHorizontalGlyphQuads = [&](SymbolQuads& quads, const Shaping& shaping) { if (!shapedTextOrientations.singleLine) { quads = getGlyphQuads(shaping, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement); return; } if (!singleLineInitialized) { - rightJustifiedGlyphQuads = - getGlyphQuads(shaping, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement); + rightJustifiedGlyphQuads = getGlyphQuads( + shaping, textOffset, layout, textPlacement, imageMap, allowVerticalPlacement); singleLineInitialized = true; } }; @@ -71,7 +71,8 @@ SymbolInstanceSharedData::SymbolInstanceSharedData(GeometryCoordinates line_, } bool SymbolInstanceSharedData::empty() const { - return rightJustifiedGlyphQuads.empty() && centerJustifiedGlyphQuads.empty() && leftJustifiedGlyphQuads.empty() && verticalGlyphQuads.empty(); + return rightJustifiedGlyphQuads.empty() && centerJustifiedGlyphQuads.empty() && leftJustifiedGlyphQuads.empty() && + verticalGlyphQuads.empty(); } SymbolInstance::SymbolInstance(Anchor& anchor_, @@ -95,33 +96,52 @@ SymbolInstance::SymbolInstance(Anchor& anchor_, const float textRotation, const std::array& variableTextOffset_, bool allowVerticalPlacement, - const SymbolContent iconType) : - sharedData(std::move(sharedData_)), - anchor(anchor_), - symbolContent(iconType), - // Create the collision features that will be used to check whether this symbol instance can be placed - // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature - textCollisionFeature(sharedData->line, anchor, getAnyShaping(shapedTextOrientations), textBoxScale_, textPadding, textPlacement, indexedFeature, overscaling, textRotation), - iconCollisionFeature(sharedData->line, anchor, shapedIcon, iconBoxScale, iconPadding, indexedFeature, iconRotation), - writingModes(WritingModeType::None), - layoutFeatureIndex(layoutFeatureIndex_), - dataFeatureIndex(dataFeatureIndex_), - textOffset(textOffset_), - iconOffset(iconOffset_), - key(std::move(key_)), - textBoxScale(textBoxScale_), - variableTextOffset(variableTextOffset_), - singleLine(shapedTextOrientations.singleLine) { + const SymbolContent iconType) + : sharedData(std::move(sharedData_)), + anchor(anchor_), + symbolContent(iconType), + // Create the collision features that will be used to check whether this + // symbol instance can be placed As a collision approximation, we can use + // either the vertical or any of the horizontal versions of the feature + textCollisionFeature(sharedData->line, + anchor, + getAnyShaping(shapedTextOrientations), + textBoxScale_, + textPadding, + textPlacement, + indexedFeature, + overscaling, + textRotation), + iconCollisionFeature( + sharedData->line, anchor, shapedIcon, iconBoxScale, iconPadding, indexedFeature, iconRotation), + writingModes(WritingModeType::None), + layoutFeatureIndex(layoutFeatureIndex_), + dataFeatureIndex(dataFeatureIndex_), + textOffset(textOffset_), + iconOffset(iconOffset_), + key(std::move(key_)), + textBoxScale(textBoxScale_), + variableTextOffset(variableTextOffset_), + singleLine(shapedTextOrientations.singleLine) { // 'hasText' depends on finding at least one glyph in the shaping that's also in the GlyphPositionMap - if(!sharedData->empty()) symbolContent |= SymbolContent::Text; + if (!sharedData->empty()) symbolContent |= SymbolContent::Text; if (allowVerticalPlacement && shapedTextOrientations.vertical) { const float verticalPointLabelAngle = 90.0f; - verticalTextCollisionFeature = CollisionFeature(line(), anchor, shapedTextOrientations.vertical, textBoxScale_, textPadding, textPlacement, indexedFeature, overscaling, textRotation + verticalPointLabelAngle); + verticalTextCollisionFeature = CollisionFeature(line(), + anchor, + shapedTextOrientations.vertical, + textBoxScale_, + textPadding, + textPlacement, + indexedFeature, + overscaling, + textRotation + verticalPointLabelAngle); if (verticallyShapedIcon) { verticalIconCollisionFeature = CollisionFeature(sharedData->line, anchor, verticallyShapedIcon, - iconBoxScale, iconPadding, + iconBoxScale, + iconPadding, indexedFeature, iconRotation + verticalPointLabelAngle); } @@ -175,11 +195,11 @@ const std::optional& SymbolInstance::iconQuads() const { bool SymbolInstance::hasText() const { return static_cast(symbolContent & SymbolContent::Text); } - + bool SymbolInstance::hasIcon() const { return static_cast(symbolContent & SymbolContent::IconRGBA) || hasSdfIcon(); } - + bool SymbolInstance::hasSdfIcon() const { return static_cast(symbolContent & SymbolContent::IconSDF); } diff --git a/src/mbgl/layout/symbol_instance.hpp b/src/mbgl/layout/symbol_instance.hpp index ea109fc4c61..066db8a64c5 100644 --- a/src/mbgl/layout/symbol_instance.hpp +++ b/src/mbgl/layout/symbol_instance.hpp @@ -15,13 +15,18 @@ struct ShapedTextOrientations { Shaping horizontal; Shaping vertical; // The following are used with variable text placement on. - Shaping& right = horizontal; + Shaping& right = horizontal; Shaping center; Shaping left; bool singleLine = false; }; -enum class SymbolContent : uint8_t { None = 0, Text = 1 << 0, IconRGBA = 1 << 1, IconSDF = 1 << 2 }; +enum class SymbolContent : uint8_t { + None = 0, + Text = 1 << 0, + IconRGBA = 1 << 1, + IconSDF = 1 << 2 +}; struct SymbolInstanceSharedData { SymbolInstanceSharedData(GeometryCoordinates line, diff --git a/src/mbgl/layout/symbol_layout.cpp b/src/mbgl/layout/symbol_layout.cpp index a83787b1351..1d159760973 100644 --- a/src/mbgl/layout/symbol_layout.cpp +++ b/src/mbgl/layout/symbol_layout.cpp @@ -23,10 +23,8 @@ using namespace style; template static bool has(const style::SymbolLayoutProperties::PossiblyEvaluated& layout) { - return layout.get().match( - [] (const typename Property::Type& t) { return !t.empty(); }, - [] (const auto&) { return true; } - ); + return layout.get().match([](const typename Property::Type& t) { return !t.empty(); }, + [](const auto&) { return true; }); } namespace { @@ -47,8 +45,10 @@ inline const SymbolLayerProperties& toSymbolLayerProperties(const Immutable(*layer); } -inline Immutable createLayout(const SymbolLayoutProperties::Unevaluated& unevaluated, float zoom) { - auto layout = makeMutable(unevaluated.evaluate(PropertyEvaluationParameters(zoom))); +inline Immutable createLayout( + const SymbolLayoutProperties::Unevaluated& unevaluated, float zoom) { + auto layout = makeMutable( + unevaluated.evaluate(PropertyEvaluationParameters(zoom))); if (layout->get() == AlignmentType::Auto) { if (layout->get() != SymbolPlacementType::Point) { @@ -109,19 +109,18 @@ SymbolLayout::SymbolLayout(const BucketParameters& parameters, const bool hasSymbolSortKey = !leader.layout.get().isUndefined(); const auto symbolZOrder = layout->get(); sortFeaturesByKey = symbolZOrder != SymbolZOrderType::ViewportY && hasSymbolSortKey; - const bool zOrderByViewportY = symbolZOrder == SymbolZOrderType::ViewportY || (symbolZOrder == SymbolZOrderType::Auto && !sortFeaturesByKey); + const bool zOrderByViewportY = symbolZOrder == SymbolZOrderType::ViewportY || + (symbolZOrder == SymbolZOrderType::Auto && !sortFeaturesByKey); sortFeaturesByY = zOrderByViewportY && (layout->get() || layout->get() || - layout->get() || layout->get()); + layout->get() || layout->get()); if (layout->get() == SymbolPlacementType::Point) { auto modes = layout->get(); // Remove duplicates and preserve order. std::set seen; - auto end = std::remove_if(modes.begin(), - modes.end(), - [&seen, this](const auto& placementMode) { - allowVerticalPlacement = allowVerticalPlacement || placementMode == style::TextWritingModeType::Vertical; - return !seen.insert(placementMode).second; - }); + auto end = std::remove_if(modes.begin(), modes.end(), [&seen, this](const auto& placementMode) { + allowVerticalPlacement = allowVerticalPlacement || placementMode == style::TextWritingModeType::Vertical; + return !seen.insert(placementMode).second; + }); modes.erase(end, modes.end()); placementModes = std::move(modes); } @@ -148,7 +147,7 @@ SymbolLayout::SymbolLayout(const BucketParameters& parameters, FontStack baseFontStack = layout->evaluate(zoom, ft, canonicalID); ft.formattedText = TaggedString(); - for (const auto & section : formatted.sections) { + for (const auto& section : formatted.sections) { if (!section.image) { std::string u8string = section.text; if (textTransform == TextTransformType::Uppercase) { @@ -167,9 +166,9 @@ SymbolLayout::SymbolLayout(const BucketParameters& parameters, } } - const bool canVerticalizeText = layout->get() == AlignmentType::Map - && layout->get() != SymbolPlacementType::Point - && ft.formattedText->allowsVerticalWritingMode(); + const bool canVerticalizeText = layout->get() == AlignmentType::Map && + layout->get() != SymbolPlacementType::Point && + ft.formattedText->allowsVerticalWritingMode(); // Loop through all characters of this text and collect unique codepoints. for (std::size_t j = 0; j < ft.formattedText->length(); j++) { @@ -227,8 +226,8 @@ namespace { // (see "yOffset" in shaping.js) const float baselineOffset = 7.0f; -// We don't care which shaping we get because this is used for collision purposes -// and all the justifications have the same collision box. +// We don't care which shaping we get because this is used for collision +// purposes and all the justifications have the same collision box. const Shaping& getDefaultHorizontalShaping(const ShapedTextOrientations& shapedTextOrientations) { if (shapedTextOrientations.right) return shapedTextOrientations.right; if (shapedTextOrientations.center) return shapedTextOrientations.center; @@ -237,17 +236,20 @@ const Shaping& getDefaultHorizontalShaping(const ShapedTextOrientations& shapedT } Shaping& shapingForTextJustifyType(ShapedTextOrientations& shapedTextOrientations, style::TextJustifyType type) { - switch(type) { - case style::TextJustifyType::Right: return shapedTextOrientations.right; - case style::TextJustifyType::Left: return shapedTextOrientations.left; - case style::TextJustifyType::Center: return shapedTextOrientations.center; - default: - assert(false); - return shapedTextOrientations.horizontal; + switch (type) { + case style::TextJustifyType::Right: + return shapedTextOrientations.right; + case style::TextJustifyType::Left: + return shapedTextOrientations.left; + case style::TextJustifyType::Center: + return shapedTextOrientations.center; + default: + assert(false); + return shapedTextOrientations.horizontal; } } -std::array evaluateRadialOffset(style::SymbolAnchorType anchor, float radialOffset) { +std::array evaluateRadialOffset(style::SymbolAnchorType anchor, float radialOffset) { std::array result{{0.0f, 0.0f}}; if (radialOffset < 0.0f) radialOffset = 0.0f; // Ignore negative offset. // solve for r where r^2 + r^2 = radialOffset^2 @@ -255,41 +257,41 @@ std::array evaluateRadialOffset(style::SymbolAnchorType anchor, float const float hypotenuse = radialOffset / sqrt2; switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::TopLeft: - result[1] = hypotenuse - baselineOffset; - break; - case SymbolAnchorType::BottomRight: - case SymbolAnchorType::BottomLeft: - result[1] = -hypotenuse + baselineOffset; - break; - case SymbolAnchorType::Bottom: - result[1] = -radialOffset + baselineOffset; - break; - case SymbolAnchorType::Top: - result[1] = radialOffset - baselineOffset; - break; - default: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::TopLeft: + result[1] = hypotenuse - baselineOffset; + break; + case SymbolAnchorType::BottomRight: + case SymbolAnchorType::BottomLeft: + result[1] = -hypotenuse + baselineOffset; + break; + case SymbolAnchorType::Bottom: + result[1] = -radialOffset + baselineOffset; + break; + case SymbolAnchorType::Top: + result[1] = radialOffset - baselineOffset; + break; + default: + break; } switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::BottomRight: - result[0] = -hypotenuse; - break; - case SymbolAnchorType::TopLeft: - case SymbolAnchorType::BottomLeft: - result[0] = hypotenuse; - break; - case SymbolAnchorType::Left: - result[0] = radialOffset; - break; - case SymbolAnchorType::Right: - result[0] = -radialOffset; - break; - default: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::BottomRight: + result[0] = -hypotenuse; + break; + case SymbolAnchorType::TopLeft: + case SymbolAnchorType::BottomLeft: + result[0] = hypotenuse; + break; + case SymbolAnchorType::Left: + result[0] = radialOffset; + break; + case SymbolAnchorType::Right: + result[0] = -radialOffset; + break; + default: + break; } return result; @@ -307,37 +309,37 @@ std::array SymbolLayout::evaluateVariableOffset(style::SymbolAnchorTyp offset[1] = std::abs(offset[1]); switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::TopLeft: - case SymbolAnchorType::Top: - result[1] = offset[1] - baselineOffset; - break; - case SymbolAnchorType::BottomRight: - case SymbolAnchorType::BottomLeft: - case SymbolAnchorType::Bottom: - result[1] = -offset[1] + baselineOffset; - break; - case SymbolAnchorType::Center: - case SymbolAnchorType::Left: - case SymbolAnchorType::Right: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::TopLeft: + case SymbolAnchorType::Top: + result[1] = offset[1] - baselineOffset; + break; + case SymbolAnchorType::BottomRight: + case SymbolAnchorType::BottomLeft: + case SymbolAnchorType::Bottom: + result[1] = -offset[1] + baselineOffset; + break; + case SymbolAnchorType::Center: + case SymbolAnchorType::Left: + case SymbolAnchorType::Right: + break; } switch (anchor) { - case SymbolAnchorType::TopRight: - case SymbolAnchorType::BottomRight: - case SymbolAnchorType::Right: - result[0] = -offset[0]; - break; - case SymbolAnchorType::TopLeft: - case SymbolAnchorType::BottomLeft: - case SymbolAnchorType::Left: - result[0] = offset[0]; - break; - case SymbolAnchorType::Center: - case SymbolAnchorType::Top: - case SymbolAnchorType::Bottom: - break; + case SymbolAnchorType::TopRight: + case SymbolAnchorType::BottomRight: + case SymbolAnchorType::Right: + result[0] = -offset[0]; + break; + case SymbolAnchorType::TopLeft: + case SymbolAnchorType::BottomLeft: + case SymbolAnchorType::Left: + result[0] = offset[0]; + break; + case SymbolAnchorType::Center: + case SymbolAnchorType::Top: + case SymbolAnchorType::Bottom: + break; } return result; @@ -393,36 +395,43 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, return result; }; - const std::vector variableTextAnchor = - layout->evaluate(zoom, feature, canonicalID); + const std::vector variableTextAnchor = layout->evaluate( + zoom, feature, canonicalID); const SymbolAnchorType textAnchor = layout->evaluate(zoom, feature, canonicalID); if (variableTextAnchor.empty()) { - // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector - // is calculated at placement time instead of layout time + // Layers with variable anchors use the `text-radial-offset` + // property and the [x, y] offset vector is calculated at + // placement time instead of layout time const float radialOffset = layout->evaluate(zoom, feature, canonicalID); if (radialOffset > 0.0f) { - // The style spec says don't use `text-offset` and `text-radial-offset` together - // but doesn't actually specify what happens if you use both. We go with the radial offset. + // The style spec says don't use `text-offset` and + // `text-radial-offset` together but doesn't actually + // specify what happens if you use both. We go with the + // radial offset. textOffset = evaluateRadialOffset(textAnchor, radialOffset * util::ONE_EM); } else { textOffset = {{layout->evaluate(zoom, feature, canonicalID)[0] * util::ONE_EM, layout->evaluate(zoom, feature, canonicalID)[1] * util::ONE_EM}}; } } - TextJustifyType textJustify = - textAlongLine ? TextJustifyType::Center : layout->evaluate(zoom, feature, canonicalID); + TextJustifyType textJustify = textAlongLine ? TextJustifyType::Center + : layout->evaluate(zoom, feature, canonicalID); const auto addVerticalShapingForPointLabelIfNeeded = [&] { if (allowVerticalPlacement && feature.formattedText->allowsVerticalWritingMode()) { feature.formattedText->verticalizePunctuation(); - // Vertical POI label placement is meant to be used for scripts that support vertical - // writing mode, thus, default style::TextJustifyType::Left justification is used. If Latin - // scripts would need to be supported, this should take into account other justifications. - shapedTextOrientations.vertical = applyShaping(*feature.formattedText, WritingModeType::Vertical, textAnchor, style::TextJustifyType::Left); + // Vertical POI label placement is meant to be used for + // scripts that support vertical writing mode, thus, default + // style::TextJustifyType::Left justification is used. If + // Latin scripts would need to be supported, this should + // take into account other justifications. + shapedTextOrientations.vertical = applyShaping( + *feature.formattedText, WritingModeType::Vertical, textAnchor, style::TextJustifyType::Left); } }; - // If this layer uses text-variable-anchor, generate shapings for all justification possibilities. + // If this layer uses text-variable-anchor, generate shapings for + // all justification possibilities. if (!textAlongLine && !variableTextAnchor.empty()) { std::vector justifications; if (textJustify != TextJustifyType::Auto) { @@ -432,14 +441,16 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, justifications.push_back(getAnchorJustification(anchor)); } } - for (TextJustifyType justification: justifications) { + for (TextJustifyType justification : justifications) { Shaping& shapingForJustification = shapingForTextJustifyType(shapedTextOrientations, justification); if (shapingForJustification) { continue; } - // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply - // the offsets for the anchor in the placement step. - Shaping shaping = applyShaping(*feature.formattedText, WritingModeType::Horizontal, SymbolAnchorType::Center, justification); + // If using text-variable-anchor for the layer, we use a + // center anchor for all shapings and apply the offsets for + // the anchor in the placement step. + Shaping shaping = applyShaping( + *feature.formattedText, WritingModeType::Horizontal, SymbolAnchorType::Center, justification); if (shaping) { shapingForJustification = std::move(shaping); if (shapingForJustification.positionedLines.size() == 1u) { @@ -457,7 +468,8 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, } // Horizontal point or line label. - Shaping shaping = applyShaping(*feature.formattedText, WritingModeType::Horizontal, textAnchor, textJustify); + Shaping shaping = applyShaping( + *feature.formattedText, WritingModeType::Horizontal, textAnchor, textJustify); if (shaping) { shapedTextOrientations.horizontal = std::move(shaping); } @@ -468,7 +480,8 @@ void SymbolLayout::prepareSymbols(const GlyphMap& glyphMap, // Verticalized line label. if (textAlongLine && feature.formattedText->allowsVerticalWritingMode()) { feature.formattedText->verticalizePunctuation(); - shapedTextOrientations.vertical = applyShaping(*feature.formattedText, WritingModeType::Vertical, textAnchor, textJustify); + shapedTextOrientations.vertical = applyShaping( + *feature.formattedText, WritingModeType::Vertical, textAnchor, textJustify); } } } @@ -643,19 +656,25 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, if (layout->get() == SymbolPlacementType::Line) { auto clippedLines = util::clipLines(feature.geometry, 0, 0, util::EXTENT, util::EXTENT); for (auto& line : clippedLines) { - Anchors anchors = getAnchors(line, - symbolSpacing, - textMaxAngle, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).left, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).right, - (shapedIcon ? shapedIcon->left() : 0), - (shapedIcon ? shapedIcon->right() : 0), - glyphSize, - textMaxBoxScale, - overscaling); + Anchors anchors = getAnchors( + line, + symbolSpacing, + textMaxAngle, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .left, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .right, + (shapedIcon ? shapedIcon->left() : 0), + (shapedIcon ? shapedIcon->right() : 0), + glyphSize, + textMaxBoxScale, + overscaling); auto sharedData = createSymbolInstanceSharedData(std::move(line)); for (auto& anchor : anchors) { - if (!feature.formattedText || !anchorIsTooClose(feature.formattedText->rawText(), textRepeatDistance, anchor)) { + if (!feature.formattedText || + !anchorIsTooClose(feature.formattedText->rawText(), textRepeatDistance, anchor)) { addSymbolInstance(anchor, sharedData); } } @@ -665,14 +684,19 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, // "lines" with only one point are ignored as in clipLines for (const auto& line : feature.geometry) { if (line.size() > 1) { - std::optional anchor = getCenterAnchor(line, - textMaxAngle, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).left, - (shapedTextOrientations.vertical ? shapedTextOrientations.vertical : getDefaultHorizontalShaping(shapedTextOrientations)).right, - (shapedIcon ? shapedIcon->left() : 0), - (shapedIcon ? shapedIcon->right() : 0), - glyphSize, - textMaxBoxScale); + std::optional anchor = getCenterAnchor( + line, + textMaxAngle, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .left, + (shapedTextOrientations.vertical ? shapedTextOrientations.vertical + : getDefaultHorizontalShaping(shapedTextOrientations)) + .right, + (shapedIcon ? shapedIcon->left() : 0), + (shapedIcon ? shapedIcon->right() : 0), + glyphSize, + textMaxBoxScale); if (anchor) { addSymbolInstance(*anchor, createSymbolInstanceSharedData(line)); } @@ -699,13 +723,15 @@ void SymbolLayout::addFeature(const std::size_t layoutFeatureIndex, // Skip invalid LineStrings. if (line.empty()) continue; - Anchor anchor(static_cast(line[0].x), static_cast(line[0].y), 0.0f, static_cast(minScale)); + Anchor anchor( + static_cast(line[0].x), static_cast(line[0].y), 0.0f, static_cast(minScale)); addSymbolInstance(anchor, createSymbolInstanceSharedData(line)); } } else if (type == FeatureType::Point) { for (const auto& points : feature.geometry) { for (const auto& point : points) { - Anchor anchor(static_cast(point.x), static_cast(point.y), 0.0f, static_cast(minScale)); + Anchor anchor( + static_cast(point.x), static_cast(point.y), 0.0f, static_cast(minScale)); addSymbolInstance(anchor, createSymbolInstanceSharedData({point})); } } @@ -727,8 +753,9 @@ bool SymbolLayout::anchorIsTooClose(const std::u16string& text, const float repe return false; } -// Analog of `addToLineVertexArray` in JS. This version doesn't need to build up a line array like the -// JS version does, but it uses the same logic to calculate tile distances. +// Analog of `addToLineVertexArray` in JS. This version doesn't need to build up +// a line array like the JS version does, but it uses the same logic to +// calculate tile distances. std::vector SymbolLayout::calculateTileDistances(const GeometryCoordinates& line, const Anchor& anchor) { std::vector tileDistances(line.size()); if (anchor.segment) { @@ -775,7 +802,7 @@ void SymbolLayout::createBucket(const ImagePositions&, std::move(placementModes), iconsInText); - for (SymbolInstance &symbolInstance : bucket->symbolInstances) { + for (SymbolInstance& symbolInstance : bucket->symbolInstances) { const bool hasText = symbolInstance.hasText(); const bool hasIcon = symbolInstance.hasIcon(); const bool singleLine = symbolInstance.singleLine; @@ -784,8 +811,9 @@ void SymbolLayout::createBucket(const ImagePositions&, // Insert final placement into collision tree and add glyphs/icons to buffers - // Process icon first, so that text symbols would have reference to iconIndex which - // is used when dynamic vertices for icon-text-fit image have to be updated. + // Process icon first, so that text symbols would have reference to + // iconIndex which is used when dynamic vertices for icon-text-fit image + // have to be updated. if (hasIcon) { const Range sizeData = bucket->iconSizeBinder->getVertexSizeData(feature); auto& iconBuffer = symbolInstance.hasSdfIcon() ? bucket->sdfIcon : bucket->icon; @@ -800,9 +828,11 @@ void SymbolLayout::createBucket(const ImagePositions&, std::vector()); index = iconBuffer.placedSymbols.size() - 1; PlacedSymbol& iconSymbol = iconBuffer.placedSymbols.back(); - iconSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) ? static_cast(M_PI_2) : 0.0f; - iconSymbol.vertexStartIndex = - addSymbols(iconBuffer, sizeData, iconQuads, symbolInstance.anchor, iconSymbol, feature.sortKey); + iconSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) + ? static_cast(M_PI_2) + : 0.0f; + iconSymbol.vertexStartIndex = addSymbols( + iconBuffer, sizeData, iconQuads, symbolInstance.anchor, iconSymbol, feature.sortKey); }; placeIcon(*symbolInstance.iconQuads(), symbolInstance.placedIconIndex, WritingModeType::None); @@ -885,7 +915,7 @@ void SymbolLayout::createBucket(const ImagePositions&, if (showCollisionBoxes) { addToDebugBuffers(*bucket); } - if (bucket->hasData()){ + if (bucket->hasData()) { for (const auto& pair : layerPaintProperties) { if (!firstLoad) { bucket->justReloaded = true; @@ -916,7 +946,8 @@ std::size_t SymbolLayout::addSymbolGlyphQuads(SymbolBucket& bucket, std::optional lastAddedSection) { const Range sizeData = bucket.textSizeBinder->getVertexSizeData(feature); const bool hasFormatSectionOverrides = bucket.hasFormatSectionOverrides(); - const auto& placedIconIndex = writingMode == WritingModeType::Vertical ? symbolInstance.placedVerticalIconIndex : symbolInstance.placedIconIndex; + const auto& placedIconIndex = writingMode == WritingModeType::Vertical ? symbolInstance.placedVerticalIconIndex + : symbolInstance.placedIconIndex; bucket.text.placedSymbols.emplace_back(symbolInstance.anchor.point, symbolInstance.anchor.segment.value_or(0u), sizeData.min, @@ -928,7 +959,9 @@ std::size_t SymbolLayout::addSymbolGlyphQuads(SymbolBucket& bucket, placedIconIndex); placedIndex = bucket.text.placedSymbols.size() - 1; PlacedSymbol& placedSymbol = bucket.text.placedSymbols.back(); - placedSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) ? static_cast(M_PI_2) : 0.0f; + placedSymbol.angle = (allowVerticalPlacement && writingMode == WritingModeType::Vertical) + ? static_cast(M_PI_2) + : 0.0f; bool firstSymbol = true; for (const auto& symbolQuad : glyphQuads) { @@ -938,7 +971,8 @@ std::size_t SymbolLayout::addSymbolGlyphQuads(SymbolBucket& bucket, } lastAddedSection = symbolQuad.sectionIndex; } - size_t index = addSymbol(bucket.text, sizeData, symbolQuad, symbolInstance.anchor, placedSymbol, feature.sortKey); + size_t index = addSymbol( + bucket.text, sizeData, symbolQuad, symbolInstance.anchor, placedSymbol, feature.sortKey); if (firstSymbol) { placedSymbol.vertexStartIndex = index; firstSymbol = false; @@ -956,11 +990,11 @@ size_t SymbolLayout::addSymbol(SymbolBucket::Buffer& buffer, float sortKey) { constexpr const uint16_t vertexLength = 4; - const auto &tl = symbol.tl; - const auto &tr = symbol.tr; - const auto &bl = symbol.bl; - const auto &br = symbol.br; - const auto &tex = symbol.tex; + const auto& tl = symbol.tl; + const auto& tr = symbol.tr; + const auto& bl = symbol.bl; + const auto& br = symbol.br; + const auto& tex = symbol.tex; const auto& pixelOffsetTL = symbol.pixelOffsetTL; const auto& pixelOffsetBR = symbol.pixelOffsetBR; const auto& minFontScale = symbol.minFontScale; @@ -1015,8 +1049,9 @@ size_t SymbolLayout::addSymbol(SymbolBucket::Buffer& buffer, pixelOffsetBR, minFontScale)); - // Dynamic/Opacity vertices are initialized so that the vertex count always agrees with - // the layout vertex buffer, but they will always be updated before rendering happens + // Dynamic/Opacity vertices are initialized so that the vertex count always + // agrees with the layout vertex buffer, but they will always be updated + // before rendering happens auto dynamicVertex = SymbolSDFIconProgram::dynamicLayoutVertex(labelAnchor.point, 0); buffer.dynamicVertices.emplace_back(dynamicVertex); buffer.dynamicVertices.emplace_back(dynamicVertex); @@ -1060,7 +1095,6 @@ size_t SymbolLayout::addSymbols(SymbolBucket::Buffer& buffer, } void SymbolLayout::addToDebugBuffers(SymbolBucket& bucket) { - if (!hasSymbolInstances()) { return; } @@ -1068,10 +1102,12 @@ void SymbolLayout::addToDebugBuffers(SymbolBucket& bucket) { for (const SymbolInstance& symbolInstance : symbolInstances) { auto populateCollisionBox = [&](const auto& feature, bool isText) { SymbolBucket::CollisionBuffer& collisionBuffer = - feature.alongLine ? (isText ? static_cast(bucket.getOrCreateTextCollisionCircleBuffer()) - : static_cast(bucket.getOrCreateIconCollisionCircleBuffer())) - : (isText ? static_cast(bucket.getOrCreateTextCollisionBox()) - : static_cast(bucket.getOrCreateIconCollisionBox())); + feature.alongLine + ? (isText + ? static_cast(bucket.getOrCreateTextCollisionCircleBuffer()) + : static_cast(bucket.getOrCreateIconCollisionCircleBuffer())) + : (isText ? static_cast(bucket.getOrCreateTextCollisionBox()) + : static_cast(bucket.getOrCreateIconCollisionBox())); for (const CollisionBox& box : feature.boxes) { auto& anchor = box.anchor; @@ -1084,24 +1120,31 @@ void SymbolLayout::addToDebugBuffers(SymbolBucket& bucket) { static constexpr std::size_t vertexLength = 4; const std::size_t indexLength = feature.alongLine ? 6 : 8; - if (collisionBuffer.segments.empty() || collisionBuffer.segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { + if (collisionBuffer.segments.empty() || collisionBuffer.segments.back().vertexLength + vertexLength > + std::numeric_limits::max()) { collisionBuffer.segments.emplace_back( collisionBuffer.vertices.elements(), - feature.alongLine - ? (isText ? bucket.textCollisionCircle->triangles.elements() : bucket.iconCollisionCircle->triangles.elements()) - : (isText ? bucket.textCollisionBox->lines.elements() : bucket.iconCollisionBox->lines.elements())); + feature.alongLine ? (isText ? bucket.textCollisionCircle->triangles.elements() + : bucket.iconCollisionCircle->triangles.elements()) + : (isText ? bucket.textCollisionBox->lines.elements() + : bucket.iconCollisionBox->lines.elements())); } auto& segment = collisionBuffer.segments.back(); auto index = static_cast(segment.vertexLength); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tl)); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tr)); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, br)); - collisionBuffer.vertices.emplace_back(CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, bl)); - - // Dynamic vertices are initialized so that the vertex count always agrees with - // the layout vertex buffer, but they will always be updated before rendering happens + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tl)); + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, tr)); + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, br)); + collisionBuffer.vertices.emplace_back( + CollisionBoxProgram::layoutVertex(anchor, symbolInstance.anchor.point, bl)); + + // Dynamic vertices are initialized so that the vertex count + // always agrees with the layout vertex buffer, but they will + // always be updated before rendering happens auto dynamicVertex = CollisionBoxProgram::dynamicVertex(false, false, {}); collisionBuffer.dynamicVertices.emplace_back(dynamicVertex); collisionBuffer.dynamicVertices.emplace_back(dynamicVertex); diff --git a/src/mbgl/layout/symbol_layout.hpp b/src/mbgl/layout/symbol_layout.hpp index 12234fba829..706acf748f8 100644 --- a/src/mbgl/layout/symbol_layout.hpp +++ b/src/mbgl/layout/symbol_layout.hpp @@ -55,9 +55,10 @@ class SymbolLayout final : public Layout { static constexpr float INVALID_OFFSET_VALUE = std::numeric_limits::max(); /** * @brief Calculates variable text offset. - * + * * @param anchor text anchor - * @param textOffset Either `text-offset` or [ `text-radial-offset`, INVALID_OFFSET_VALUE ] + * @param textOffset Either `text-offset` or [ `text-radial-offset`, + * INVALID_OFFSET_VALUE ] * @return std::array offset along x- and y- axis correspondingly. */ static std::array evaluateVariableOffset(style::SymbolAnchorType anchor, std::array textOffset); @@ -110,8 +111,8 @@ class SymbolLayout final : public Layout { std::size_t sectionIndex, const CanonicalTileID& canonical); - // Stores the layer so that we can hold on to GeometryTileFeature instances in SymbolFeature, - // which may reference data from this object. + // Stores the layer so that we can hold on to GeometryTileFeature instances + // in SymbolFeature, which may reference data from this object. const std::unique_ptr sourceLayer; const float overscaling; const float zoom; @@ -135,7 +136,9 @@ class SymbolLayout final : public Layout { Immutable layout; std::vector features; - BiDi bidi; // Consider moving this up to geometry tile worker to reduce reinstantiation costs; use of BiDi/ubiditransform object must be constrained to one thread + BiDi bidi; // Consider moving this up to geometry tile worker to reduce + // reinstantiation costs; use of BiDi/ubiditransform object must + // be constrained to one thread }; } // namespace mbgl diff --git a/src/mbgl/layout/symbol_projection.cpp b/src/mbgl/layout/symbol_projection.cpp index 674b0ca966e..c8b6816f7b2 100644 --- a/src/mbgl/layout/symbol_projection.cpp +++ b/src/mbgl/layout/symbol_projection.cpp @@ -7,418 +7,516 @@ namespace mbgl { - /* - * # Overview of coordinate spaces - * - * ## Tile coordinate spaces - * Each label has an anchor. Some labels have corresponding line geometries. - * The points for both anchors and lines are stored in tile units. Each tile has it's own - * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. - * - * ## GL coordinate space - * At the end of everything, the vertex shader needs to produce a position in GL coordinate space, - * which is (-1, 1) at the top left and (1, -1) in the bottom right. - * - * ## Map pixel coordinate spaces - * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is - * whatever counts as 1 pixel at the current zoom. - * This space is used for pitch-alignment=map, rotation-alignment=map - * - * ## Rotated map pixel coordinate spaces - * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. - * This space is used for pitch-alignment=map, rotation-alignment=viewport - * - * ## Viewport pixel coordinate space - * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner - * of the canvas. This space is used for pitch-alignment=viewport - * - * - * # Vertex projection - * It goes roughly like this: - * 1. project the anchor and line from tile units into the correct label coordinate space - * - map pixel space pitch-alignment=map rotation-alignment=map - * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport - * - viewport pixel space pitch-alignment=viewport rotation-alignment=* - * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. - * 3. add the glyph's corner offset to the point from step 3 - * 4. convert from the label coordinate space to gl coordinates - * - * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). - * This is what `u_label_plane_matrix` is used for. - * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. - * This is what `updateLineLabels(...)` in JS, `reprojectLineLabels()` in gl-native, does. - * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. - * - * Steps 3 and 4 are done in the shaders for all labels. - */ - - /* - * Returns a matrix for converting from tile units to the correct label coordinate space. - */ - mat4 getLabelPlaneMatrix(const mat4& posMatrix, const bool pitchWithMap, const bool rotateWithMap, const TransformState& state, const float pixelsToTileUnits) { - mat4 m; - matrix::identity(m); - if (pitchWithMap) { - matrix::scale(m, m, 1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1); - if (!rotateWithMap) { - matrix::rotate_z(m, m, state.getBearing()); - } - } else { - matrix::scale(m, m, state.getSize().width / 2.0, -(state.getSize().height / 2.0), 1.0); - matrix::translate(m, m, 1, -1, 0); - matrix::multiply(m, m, posMatrix); +/* + * # Overview of coordinate spaces + * + * ## Tile coordinate spaces + * Each label has an anchor. Some labels have corresponding line geometries. + * The points for both anchors and lines are stored in tile units. Each tile has + * it's own coordinate space going from (0, 0) at the top left to (EXTENT, + * EXTENT) at the bottom right. + * + * ## GL coordinate space + * At the end of everything, the vertex shader needs to produce a position in GL + * coordinate space, which is (-1, 1) at the top left and (1, -1) in the bottom + * right. + * + * ## Map pixel coordinate spaces + * Each tile has a pixel coordinate space. It's just the tile units scaled so + * that one unit is whatever counts as 1 pixel at the current zoom. This space + * is used for pitch-alignment=map, rotation-alignment=map + * + * ## Rotated map pixel coordinate spaces + * Like the above, but rotated so axis of the space are aligned with the + * viewport instead of the tile. This space is used for pitch-alignment=map, + * rotation-alignment=viewport + * + * ## Viewport pixel coordinate space + * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at + * the bottom right corner of the canvas. This space is used for + * pitch-alignment=viewport + * + * + * # Vertex projection + * It goes roughly like this: + * 1. project the anchor and line from tile units into the correct label + * coordinate space + * - map pixel space pitch-alignment=map rotation-alignment=map + * - rotated map pixel space pitch-alignment=map + * rotation-alignment=viewport + * - viewport pixel space pitch-alignment=viewport + * rotation-alignment=* + * 2. if the label follows a line, find the point along the line that is the + * correct distance from the anchor. + * 3. add the glyph's corner offset to the point from step 3 + * 4. convert from the label coordinate space to gl coordinates + * + * For horizontal labels we want to do step 1 in the shader for performance + * reasons (no cpu work). This is what `u_label_plane_matrix` is used for. For + * labels aligned with lines we have to steps 1 and 2 on the cpu since we need + * access to the line geometry. This is what `updateLineLabels(...)` in JS, + * `reprojectLineLabels()` in gl-native, does. Since the conversion is handled + * on the cpu we just set `u_label_plane_matrix` to an identity matrix. + * + * Steps 3 and 4 are done in the shaders for all labels. + */ + +/* + * Returns a matrix for converting from tile units to the correct label coordinate space. + */ +mat4 getLabelPlaneMatrix(const mat4& posMatrix, + const bool pitchWithMap, + const bool rotateWithMap, + const TransformState& state, + const float pixelsToTileUnits) { + mat4 m; + matrix::identity(m); + if (pitchWithMap) { + matrix::scale(m, m, 1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1); + if (!rotateWithMap) { + matrix::rotate_z(m, m, state.getBearing()); } - return m; + } else { + matrix::scale(m, m, state.getSize().width / 2.0, -(state.getSize().height / 2.0), 1.0); + matrix::translate(m, m, 1, -1, 0); + matrix::multiply(m, m, posMatrix); } - - /* - * Returns a matrix for converting from the correct label coordinate space to gl coords. - */ - mat4 getGlCoordMatrix(const mat4& posMatrix, const bool pitchWithMap, const bool rotateWithMap, const TransformState& state, const float pixelsToTileUnits) { - mat4 m; - matrix::identity(m); - if (pitchWithMap) { - matrix::multiply(m, m, posMatrix); - matrix::scale(m, m, pixelsToTileUnits, pixelsToTileUnits, 1); - if (!rotateWithMap) { - matrix::rotate_z(m, m, -state.getBearing()); - } - } else { - matrix::scale(m, m, 1, -1, 1); - matrix::translate(m, m, -1, -1, 0); - matrix::scale(m, m, 2.0 / state.getSize().width, 2.0 / state.getSize().height, 1.0); + return m; +} + +/* + * Returns a matrix for converting from the correct label coordinate space to gl coords. + */ +mat4 getGlCoordMatrix(const mat4& posMatrix, + const bool pitchWithMap, + const bool rotateWithMap, + const TransformState& state, + const float pixelsToTileUnits) { + mat4 m; + matrix::identity(m); + if (pitchWithMap) { + matrix::multiply(m, m, posMatrix); + matrix::scale(m, m, pixelsToTileUnits, pixelsToTileUnits, 1); + if (!rotateWithMap) { + matrix::rotate_z(m, m, -state.getBearing()); } - return m; - } - - PointAndCameraDistance project(const Point& point, const mat4& matrix) { - vec4 pos = {{ point.x, point.y, 0, 1 }}; - matrix::transformMat4(pos, pos, matrix); - return {{ static_cast(pos[0] / pos[3]), static_cast(pos[1] / pos[3]) }, static_cast(pos[3]) }; + } else { + matrix::scale(m, m, 1, -1, 1); + matrix::translate(m, m, -1, -1, 0); + matrix::scale(m, m, 2.0 / state.getSize().width, 2.0 / state.getSize().height, 1.0); } - - float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol) { - if (zoomEvaluatedSize.isFeatureConstant) { - return zoomEvaluatedSize.size; + return m; +} + +PointAndCameraDistance project(const Point& point, const mat4& matrix) { + vec4 pos = {{point.x, point.y, 0, 1}}; + matrix::transformMat4(pos, pos, matrix); + return {{static_cast(pos[0] / pos[3]), static_cast(pos[1] / pos[3])}, static_cast(pos[3])}; +} + +float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol) { + if (zoomEvaluatedSize.isFeatureConstant) { + return zoomEvaluatedSize.size; + } else { + if (zoomEvaluatedSize.isZoomConstant) { + return placedSymbol.lowerSize; } else { - if (zoomEvaluatedSize.isZoomConstant) { - return placedSymbol.lowerSize; - } else { - return placedSymbol.lowerSize + zoomEvaluatedSize.sizeT * (placedSymbol.upperSize - placedSymbol.lowerSize); - } + return placedSymbol.lowerSize + zoomEvaluatedSize.sizeT * (placedSymbol.upperSize - placedSymbol.lowerSize); } } - - bool isVisible(const vec4& anchorPos, const std::array& clippingBuffer) { - const double x = anchorPos[0] / anchorPos[3]; - const double y = anchorPos[1] / anchorPos[3]; - const bool inPaddedViewport = ( - x >= -clippingBuffer[0] && - x <= clippingBuffer[0] && - y >= -clippingBuffer[1] && - y <= clippingBuffer[1]); - return inPaddedViewport; +} + +bool isVisible(const vec4& anchorPos, const std::array& clippingBuffer) { + const double x = anchorPos[0] / anchorPos[3]; + const double y = anchorPos[1] / anchorPos[3]; + const bool inPaddedViewport = (x >= -clippingBuffer[0] && x <= clippingBuffer[0] && y >= -clippingBuffer[1] && + y <= clippingBuffer[1]); + return inPaddedViewport; +} + +void addDynamicAttributes(const Point& anchorPoint, + const float angle, + gfx::VertexVector>& dynamicVertexArray) { + auto dynamicVertex = SymbolSDFIconProgram::dynamicLayoutVertex(anchorPoint, angle); + dynamicVertexArray.emplace_back(dynamicVertex); + dynamicVertexArray.emplace_back(dynamicVertex); + dynamicVertexArray.emplace_back(dynamicVertex); + dynamicVertexArray.emplace_back(dynamicVertex); +} + +void hideGlyphs(size_t numGlyphs, gfx::VertexVector>& dynamicVertexArray) { + const Point offscreenPoint = {-INFINITY, -INFINITY}; + for (size_t i = 0; i < numGlyphs; i++) { + addDynamicAttributes(offscreenPoint, 0, dynamicVertexArray); } - - void addDynamicAttributes(const Point& anchorPoint, const float angle, - gfx::VertexVector>& dynamicVertexArray) { - auto dynamicVertex = SymbolSDFIconProgram::dynamicLayoutVertex(anchorPoint, angle); - dynamicVertexArray.emplace_back(dynamicVertex); - dynamicVertexArray.emplace_back(dynamicVertex); - dynamicVertexArray.emplace_back(dynamicVertex); - dynamicVertexArray.emplace_back(dynamicVertex); +} + +enum PlacementResult { + OK, + NotEnoughRoom, + NeedsFlipping, + UseVertical +}; + +Point projectTruncatedLineSegment(const Point& previousTilePoint, + const Point& currentTilePoint, + const Point& previousProjectedPoint, + const float minimumLength, + const mat4& projectionMatrix) { + // We are assuming "previousTilePoint" won't project to a point within one + // unit of the camera plane If it did, that would mean our label extended + // all the way out from within the viewport to a (very distant) point near + // the plane of the camera. We wouldn't be able to render the label anyway + // once it crossed the plane of the camera. + const Point projectedUnitVertex = + project(previousTilePoint + util::unit(previousTilePoint - currentTilePoint), projectionMatrix).first; + const Point projectedUnitSegment = previousProjectedPoint - projectedUnitVertex; + + return previousProjectedPoint + (projectedUnitSegment * (minimumLength / util::mag(projectedUnitSegment))); +} + +std::optional placeGlyphAlongLine(const float offsetX, + const float lineOffsetX, + const float lineOffsetY, + const bool flip, + const Point& projectedAnchorPoint, + const Point& tileAnchorPoint, + const uint16_t anchorSegment, + const GeometryCoordinates& line, + const std::vector& tileDistances, + const mat4& labelPlaneMatrix, + const bool returnTileDistance) { + const float combinedOffsetX = flip ? offsetX - lineOffsetX : offsetX + lineOffsetX; + + int16_t dir = combinedOffsetX > 0 ? 1 : -1; + + float angle = 0.0; + if (flip) { + // The label needs to be flipped to keep text upright. + // Iterate in the reverse direction. + dir *= -1; + angle = static_cast(M_PI); } - void hideGlyphs(size_t numGlyphs, gfx::VertexVector>& dynamicVertexArray) { - const Point offscreenPoint = { -INFINITY, -INFINITY }; - for (size_t i = 0; i < numGlyphs; i++) { - addDynamicAttributes(offscreenPoint, 0, dynamicVertexArray); - } - } - - enum PlacementResult { - OK, - NotEnoughRoom, - NeedsFlipping, - UseVertical - }; - - Point projectTruncatedLineSegment(const Point& previousTilePoint, const Point& currentTilePoint, const Point& previousProjectedPoint, const float minimumLength, const mat4& projectionMatrix) { - // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane - // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) - // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the - // plane of the camera. - const Point projectedUnitVertex = project(previousTilePoint + util::unit(previousTilePoint - currentTilePoint), projectionMatrix).first; - const Point projectedUnitSegment = previousProjectedPoint - projectedUnitVertex; - - return previousProjectedPoint + (projectedUnitSegment * (minimumLength / util::mag(projectedUnitSegment))); - } + if (dir < 0) angle += static_cast(M_PI); - std::optional placeGlyphAlongLine(const float offsetX, const float lineOffsetX, const float lineOffsetY, const bool flip, - const Point& projectedAnchorPoint, const Point& tileAnchorPoint, const uint16_t anchorSegment, const GeometryCoordinates& line, const std::vector& tileDistances, const mat4& labelPlaneMatrix, const bool returnTileDistance) { + int32_t currentIndex = dir > 0 ? anchorSegment : anchorSegment + 1; - const float combinedOffsetX = flip ? - offsetX - lineOffsetX : - offsetX + lineOffsetX; + const int32_t initialIndex = currentIndex; + Point current = projectedAnchorPoint; + Point prev = projectedAnchorPoint; + float distanceToPrev = 0.0; + float currentSegmentDistance = 0.0; + const float absOffsetX = std::abs(combinedOffsetX); - int16_t dir = combinedOffsetX > 0 ? 1 : -1; + while (distanceToPrev + currentSegmentDistance <= absOffsetX) { + currentIndex += dir; - float angle = 0.0; - if (flip) { - // The label needs to be flipped to keep text upright. - // Iterate in the reverse direction. - dir *= -1; - angle = static_cast(M_PI); + // offset does not fit on the projected line + if (currentIndex < 0 || currentIndex >= static_cast(line.size())) { + return {}; } - if (dir < 0) angle += static_cast(M_PI); - - int32_t currentIndex = dir > 0 ? anchorSegment : anchorSegment + 1; - - const int32_t initialIndex = currentIndex; - Point current = projectedAnchorPoint; - Point prev = projectedAnchorPoint; - float distanceToPrev = 0.0; - float currentSegmentDistance = 0.0; - const float absOffsetX = std::abs(combinedOffsetX); - - while (distanceToPrev + currentSegmentDistance <= absOffsetX) { - currentIndex += dir; - - // offset does not fit on the projected line - if (currentIndex < 0 || currentIndex >= static_cast(line.size())) { - return {}; - } - - prev = current; - PointAndCameraDistance projection = project(convertPoint(line.at(currentIndex)), labelPlaneMatrix); - if (projection.second > 0) { - current = projection.first; - } else { - // The vertex is behind the plane of the camera, so we can't project it - // Instead, we'll create a vertex along the line that's far enough to include the glyph - const Point previousTilePoint = distanceToPrev == 0 ? - tileAnchorPoint : - convertPoint(line.at(currentIndex - dir)); - const Point currentTilePoint = convertPoint(line.at(currentIndex)); - current = projectTruncatedLineSegment(previousTilePoint, currentTilePoint, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix); - } - - distanceToPrev += currentSegmentDistance; - currentSegmentDistance = util::dist(prev, current); + prev = current; + PointAndCameraDistance projection = project(convertPoint(line.at(currentIndex)), labelPlaneMatrix); + if (projection.second > 0) { + current = projection.first; + } else { + // The vertex is behind the plane of the camera, so we can't project it + // Instead, we'll create a vertex along the line that's far enough to include the glyph + const Point previousTilePoint = distanceToPrev == 0 + ? tileAnchorPoint + : convertPoint(line.at(currentIndex - dir)); + const Point currentTilePoint = convertPoint(line.at(currentIndex)); + current = projectTruncatedLineSegment( + previousTilePoint, currentTilePoint, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix); } - // The point is on the current segment. Interpolate to find it. - const float segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance; - const Point prevToCurrent = current - prev; - Point p = (prevToCurrent * segmentInterpolationT) + prev; - - // offset the point from the line to text-offset and icon-offset - p += util::perp(prevToCurrent) * static_cast(lineOffsetY * dir / util::mag(prevToCurrent)); - - const float segmentAngle = angle + std::atan2(current.y - prev.y, current.x - prev.x); - - return {{ - p, - segmentAngle, - returnTileDistance ? - TileDistance( - (currentIndex - dir) == initialIndex ? 0 : tileDistances[currentIndex - dir], - absOffsetX - distanceToPrev - ) : - std::optional() - }}; + distanceToPrev += currentSegmentDistance; + currentSegmentDistance = util::dist(prev, current); } - - std::optional> placeFirstAndLastGlyph(const float fontScale, - const float lineOffsetX, - const float lineOffsetY, - const bool flip, - const Point& anchorPoint, - const Point& tileAnchorPoint, - const PlacedSymbol& symbol, - const mat4& labelPlaneMatrix, - const bool returnTileDistance) { - if (symbol.glyphOffsets.empty()) { - assert(false); - return {}; - } - - const float firstGlyphOffset = symbol.glyphOffsets.front(); - const float lastGlyphOffset = symbol.glyphOffsets.back();; - - std::optional firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, static_cast(symbol.segment), symbol.line, symbol.tileDistances, labelPlaneMatrix, returnTileDistance); - if (!firstPlacedGlyph) return {}; - - std::optional lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, static_cast(symbol.segment), symbol.line, symbol.tileDistances, labelPlaneMatrix, returnTileDistance); - if (!lastPlacedGlyph) return {}; - return std::make_pair(*firstPlacedGlyph, *lastPlacedGlyph); + // The point is on the current segment. Interpolate to find it. + const float segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance; + const Point prevToCurrent = current - prev; + Point p = (prevToCurrent * segmentInterpolationT) + prev; + + // offset the point from the line to text-offset and icon-offset + p += util::perp(prevToCurrent) * static_cast(lineOffsetY * dir / util::mag(prevToCurrent)); + + const float segmentAngle = angle + std::atan2(current.y - prev.y, current.x - prev.x); + + return {{p, + segmentAngle, + returnTileDistance + ? TileDistance((currentIndex - dir) == initialIndex ? 0 : tileDistances[currentIndex - dir], + absOffsetX - distanceToPrev) + : std::optional()}}; +} + +std::optional> placeFirstAndLastGlyph(const float fontScale, + const float lineOffsetX, + const float lineOffsetY, + const bool flip, + const Point& anchorPoint, + const Point& tileAnchorPoint, + const PlacedSymbol& symbol, + const mat4& labelPlaneMatrix, + const bool returnTileDistance) { + if (symbol.glyphOffsets.empty()) { + assert(false); + return {}; } - - std::optional requiresOrientationChange(const WritingModeType writingModes, const Point& firstPoint, const Point& lastPoint, const float aspectRatio) { - if (writingModes == (WritingModeType::Horizontal | WritingModeType::Vertical)) { - // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate - // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal - // and vertical versions can have slightly different projections which could lead to angles where both or - // neither showed. - auto rise = std::abs(lastPoint.y - firstPoint.y); - auto run = std::abs(lastPoint.x - firstPoint.x) * aspectRatio; - if (rise > run) { - return PlacementResult::UseVertical; - } - } - if ((writingModes == WritingModeType::Vertical) ? - (firstPoint.y < lastPoint.y) : - (firstPoint.x > lastPoint.x)) { - // Includes "horizontalOnly" case for labels without vertical glyphs - return PlacementResult::NeedsFlipping; + const float firstGlyphOffset = symbol.glyphOffsets.front(); + const float lastGlyphOffset = symbol.glyphOffsets.back(); + ; + + std::optional firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, + lineOffsetX, + lineOffsetY, + flip, + anchorPoint, + tileAnchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + returnTileDistance); + if (!firstPlacedGlyph) return {}; + + std::optional lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, + lineOffsetX, + lineOffsetY, + flip, + anchorPoint, + tileAnchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + returnTileDistance); + if (!lastPlacedGlyph) return {}; + + return std::make_pair(*firstPlacedGlyph, *lastPlacedGlyph); +} + +std::optional requiresOrientationChange(const WritingModeType writingModes, + const Point& firstPoint, + const Point& lastPoint, + const float aspectRatio) { + if (writingModes == (WritingModeType::Horizontal | WritingModeType::Vertical)) { + // On top of choosing whether to flip, choose whether to render this + // version of the glyphs or the alternate vertical glyphs. We can't just + // filter out vertical glyphs in the horizontal range because the + // horizontal and vertical versions can have slightly different + // projections which could lead to angles where both or neither showed. + auto rise = std::abs(lastPoint.y - firstPoint.y); + auto run = std::abs(lastPoint.x - firstPoint.x) * aspectRatio; + if (rise > run) { + return PlacementResult::UseVertical; } - return {}; } - PlacementResult placeGlyphsAlongLine(const PlacedSymbol& symbol, - const float fontSize, - const bool flip, - const bool keepUpright, - const mat4& posMatrix, - const mat4& labelPlaneMatrix, - const mat4& glCoordMatrix, - gfx::VertexVector>& dynamicVertexArray, - const Point& projectedAnchorPoint, - const float aspectRatio) { - const float fontScale = fontSize / util::ONE_EM; - const float lineOffsetX = symbol.lineOffset[0] * fontScale; - const float lineOffsetY = symbol.lineOffset[1] * fontScale; - - std::vector placedGlyphs; - if (symbol.glyphOffsets.size() > 1) { - - const std::optional> firstAndLastGlyph = - placeFirstAndLastGlyph(fontScale, lineOffsetX, lineOffsetY, flip, projectedAnchorPoint, symbol.anchorPoint, symbol, labelPlaneMatrix, false); - if (!firstAndLastGlyph) { - return PlacementResult::NotEnoughRoom; - } + if ((writingModes == WritingModeType::Vertical) ? (firstPoint.y < lastPoint.y) : (firstPoint.x > lastPoint.x)) { + // Includes "horizontalOnly" case for labels without vertical glyphs + return PlacementResult::NeedsFlipping; + } + return {}; +} + +PlacementResult placeGlyphsAlongLine(const PlacedSymbol& symbol, + const float fontSize, + const bool flip, + const bool keepUpright, + const mat4& posMatrix, + const mat4& labelPlaneMatrix, + const mat4& glCoordMatrix, + gfx::VertexVector>& dynamicVertexArray, + const Point& projectedAnchorPoint, + const float aspectRatio) { + const float fontScale = fontSize / util::ONE_EM; + const float lineOffsetX = symbol.lineOffset[0] * fontScale; + const float lineOffsetY = symbol.lineOffset[1] * fontScale; + + std::vector placedGlyphs; + if (symbol.glyphOffsets.size() > 1) { + const std::optional> firstAndLastGlyph = placeFirstAndLastGlyph( + fontScale, + lineOffsetX, + lineOffsetY, + flip, + projectedAnchorPoint, + symbol.anchorPoint, + symbol, + labelPlaneMatrix, + false); + if (!firstAndLastGlyph) { + return PlacementResult::NotEnoughRoom; + } - const Point firstPoint = project(firstAndLastGlyph->first.point, glCoordMatrix).first; - const Point lastPoint = project(firstAndLastGlyph->second.point, glCoordMatrix).first; + const Point firstPoint = project(firstAndLastGlyph->first.point, glCoordMatrix).first; + const Point lastPoint = project(firstAndLastGlyph->second.point, glCoordMatrix).first; - if (keepUpright && !flip) { - auto orientationChange = requiresOrientationChange(symbol.writingModes, firstPoint, lastPoint, aspectRatio); - if (orientationChange) { - return *orientationChange; - } + if (keepUpright && !flip) { + auto orientationChange = requiresOrientationChange(symbol.writingModes, firstPoint, lastPoint, aspectRatio); + if (orientationChange) { + return *orientationChange; } + } - placedGlyphs.push_back(firstAndLastGlyph->first); - for (size_t glyphIndex = 1; glyphIndex < symbol.glyphOffsets.size() - 1; glyphIndex++) { - const float glyphOffsetX = symbol.glyphOffsets[glyphIndex]; - // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed - auto placedGlyph = placeGlyphAlongLine(glyphOffsetX * fontScale, lineOffsetX, lineOffsetY, flip, projectedAnchorPoint, symbol.anchorPoint, static_cast(symbol.segment), symbol.line, symbol.tileDistances, labelPlaneMatrix, false); - if (placedGlyph) { - placedGlyphs.push_back(*placedGlyph); - } else { - placedGlyphs.emplace_back(Point{-INFINITY, -INFINITY}, 0.0f, std::nullopt); - } + placedGlyphs.push_back(firstAndLastGlyph->first); + for (size_t glyphIndex = 1; glyphIndex < symbol.glyphOffsets.size() - 1; glyphIndex++) { + const float glyphOffsetX = symbol.glyphOffsets[glyphIndex]; + // Since first and last glyph fit on the line, we're sure that the + // rest of the glyphs can be placed + auto placedGlyph = placeGlyphAlongLine(glyphOffsetX * fontScale, + lineOffsetX, + lineOffsetY, + flip, + projectedAnchorPoint, + symbol.anchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + false); + if (placedGlyph) { + placedGlyphs.push_back(*placedGlyph); + } else { + placedGlyphs.emplace_back(Point{-INFINITY, -INFINITY}, 0.0f, std::nullopt); } - placedGlyphs.push_back(firstAndLastGlyph->second); - } else if (symbol.glyphOffsets.size() == 1) { - // Only a single glyph to place - // So, determine whether to flip based on projected angle of the line segment it's on - if (keepUpright && !flip) { - const Point a = project(symbol.anchorPoint, posMatrix).first; - const Point tileSegmentEnd = convertPoint(symbol.line.at(symbol.segment + 1)); - const PointAndCameraDistance projectedVertex = project(tileSegmentEnd, posMatrix); - // We know the anchor will be in the viewport, but the end of the line segment may be - // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) - // point on the segment. - const Point b = (projectedVertex.second > 0) ? - projectedVertex.first : - projectTruncatedLineSegment(symbol.anchorPoint,tileSegmentEnd, a, 1, posMatrix); - - auto orientationChange = requiresOrientationChange(symbol.writingModes, a, b, aspectRatio); - if (orientationChange) { - return *orientationChange; - } + } + placedGlyphs.push_back(firstAndLastGlyph->second); + } else if (symbol.glyphOffsets.size() == 1) { + // Only a single glyph to place + // So, determine whether to flip based on projected angle of the line segment it's on + if (keepUpright && !flip) { + const Point a = project(symbol.anchorPoint, posMatrix).first; + const Point tileSegmentEnd = convertPoint(symbol.line.at(symbol.segment + 1)); + const PointAndCameraDistance projectedVertex = project(tileSegmentEnd, posMatrix); + // We know the anchor will be in the viewport, but the end of the + // line segment may be behind the plane of the camera, in which case + // we can use a point at any arbitrary (closer) point on the + // segment. + const Point b = (projectedVertex.second > 0) + ? projectedVertex.first + : projectTruncatedLineSegment( + symbol.anchorPoint, tileSegmentEnd, a, 1, posMatrix); + + auto orientationChange = requiresOrientationChange(symbol.writingModes, a, b, aspectRatio); + if (orientationChange) { + return *orientationChange; } - const float glyphOffsetX = symbol.glyphOffsets.front(); - std::optional singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetX, lineOffsetX, lineOffsetY, flip, projectedAnchorPoint, symbol.anchorPoint, static_cast(symbol.segment), - symbol.line, symbol.tileDistances, labelPlaneMatrix, false); - if (!singleGlyph) - return PlacementResult::NotEnoughRoom; - - placedGlyphs.push_back(*singleGlyph); } + const float glyphOffsetX = symbol.glyphOffsets.front(); + std::optional singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetX, + lineOffsetX, + lineOffsetY, + flip, + projectedAnchorPoint, + symbol.anchorPoint, + static_cast(symbol.segment), + symbol.line, + symbol.tileDistances, + labelPlaneMatrix, + false); + if (!singleGlyph) return PlacementResult::NotEnoughRoom; + + placedGlyphs.push_back(*singleGlyph); + } - // The number of placedGlyphs must equal the number of glyphOffsets, which must correspond to the number of glyph vertices - // There may be 0 glyphs here, if a label consists entirely of glyphs that have 0x0 dimensions - for (auto& placedGlyph : placedGlyphs) { - addDynamicAttributes(placedGlyph.point, placedGlyph.angle, dynamicVertexArray); - } - - return PlacementResult::OK; + // The number of placedGlyphs must equal the number of glyphOffsets, which + // must correspond to the number of glyph vertices There may be 0 glyphs + // here, if a label consists entirely of glyphs that have 0x0 dimensions + for (auto& placedGlyph : placedGlyphs) { + addDynamicAttributes(placedGlyph.point, placedGlyph.angle, dynamicVertexArray); } + return PlacementResult::OK; +} - void reprojectLineLabels(gfx::VertexVector>& dynamicVertexArray, const std::vector& placedSymbols, - const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, bool keepUpright, - const RenderTile& tile, const SymbolSizeBinder& sizeBinder, const TransformState& state) { +void reprojectLineLabels(gfx::VertexVector>& dynamicVertexArray, + const std::vector& placedSymbols, + const mat4& posMatrix, + bool pitchWithMap, + bool rotateWithMap, + bool keepUpright, + const RenderTile& tile, + const SymbolSizeBinder& sizeBinder, + const TransformState& state) { + const ZoomEvaluatedSize partiallyEvaluatedSize = sizeBinder.evaluateForZoom(static_cast(state.getZoom())); - const ZoomEvaluatedSize partiallyEvaluatedSize = sizeBinder.evaluateForZoom(static_cast(state.getZoom())); + const std::array clippingBuffer = { + {256.0 / state.getSize().width * 2.0 + 1.0, 256.0 / state.getSize().height * 2.0 + 1.0}}; - const std::array clippingBuffer = {{ 256.0 / state.getSize().width * 2.0 + 1.0, 256.0 / state.getSize().height * 2.0 + 1.0 }}; + const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())); - const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())); + const mat4 labelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - const mat4 labelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, - rotateWithMap, state, pixelsToTileUnits); - - const mat4 glCoordMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - - dynamicVertexArray.clear(); - - bool useVertical = false; + const mat4 glCoordMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - for (auto& placedSymbol : placedSymbols) { - // Don't do calculations for vertical glyphs unless the previous symbol was horizontal - // and we determined that vertical glyphs were necessary. - // Also don't do calculations for symbols that are collided and fully faded out - if (placedSymbol.hidden || (placedSymbol.writingModes == WritingModeType::Vertical && !useVertical)) { - hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); - continue; - } - // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart - useVertical = false; - - vec4 anchorPos = {{ placedSymbol.anchorPoint.x, placedSymbol.anchorPoint.y, 0, 1 }}; - matrix::transformMat4(anchorPos, anchorPos, posMatrix); - - // Don't bother calculating the correct point for invisible labels. - if (!isVisible(anchorPos, clippingBuffer)) { - hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); - continue; - } + dynamicVertexArray.clear(); - const auto cameraToAnchorDistance = static_cast(anchorPos[3]); - const float perspectiveRatio = 0.5f + 0.5f * (cameraToAnchorDistance / state.getCameraToCenterDistance()); + bool useVertical = false; - const float fontSize = evaluateSizeForFeature(partiallyEvaluatedSize, placedSymbol); - const float pitchScaledFontSize = pitchWithMap ? - fontSize * perspectiveRatio : - fontSize / perspectiveRatio; + for (auto& placedSymbol : placedSymbols) { + // Don't do calculations for vertical glyphs unless the previous symbol + // was horizontal and we determined that vertical glyphs were necessary. + // Also don't do calculations for symbols that are collided and fully + // faded out + if (placedSymbol.hidden || (placedSymbol.writingModes == WritingModeType::Vertical && !useVertical)) { + hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); + continue; + } + // Awkward... but we're counting on the paired "vertical" symbol coming + // immediately after its horizontal counterpart + useVertical = false; - const Point anchorPoint = project(placedSymbol.anchorPoint, labelPlaneMatrix).first; + vec4 anchorPos = {{placedSymbol.anchorPoint.x, placedSymbol.anchorPoint.y, 0, 1}}; + matrix::transformMat4(anchorPos, anchorPos, posMatrix); - PlacementResult placeUnflipped = placeGlyphsAlongLine(placedSymbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, dynamicVertexArray, anchorPoint, state.getSize().aspectRatio()); - - useVertical = placeUnflipped == PlacementResult::UseVertical; + // Don't bother calculating the correct point for invisible labels. + if (!isVisible(anchorPos, clippingBuffer)) { + hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); + continue; + } - if (placeUnflipped == PlacementResult::NotEnoughRoom || useVertical || - (placeUnflipped == PlacementResult::NeedsFlipping && - placeGlyphsAlongLine(placedSymbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, dynamicVertexArray, anchorPoint, state.getSize().aspectRatio()) == PlacementResult::NotEnoughRoom)) { - hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); - } + const auto cameraToAnchorDistance = static_cast(anchorPos[3]); + const float perspectiveRatio = 0.5f + 0.5f * (cameraToAnchorDistance / state.getCameraToCenterDistance()); + + const float fontSize = evaluateSizeForFeature(partiallyEvaluatedSize, placedSymbol); + const float pitchScaledFontSize = pitchWithMap ? fontSize * perspectiveRatio : fontSize / perspectiveRatio; + + const Point anchorPoint = project(placedSymbol.anchorPoint, labelPlaneMatrix).first; + + PlacementResult placeUnflipped = placeGlyphsAlongLine(placedSymbol, + pitchScaledFontSize, + false /*unflipped*/, + keepUpright, + posMatrix, + labelPlaneMatrix, + glCoordMatrix, + dynamicVertexArray, + anchorPoint, + state.getSize().aspectRatio()); + + useVertical = placeUnflipped == PlacementResult::UseVertical; + + if (placeUnflipped == PlacementResult::NotEnoughRoom || useVertical || + (placeUnflipped == PlacementResult::NeedsFlipping && + placeGlyphsAlongLine(placedSymbol, + pitchScaledFontSize, + true /*flipped*/, + keepUpright, + posMatrix, + labelPlaneMatrix, + glCoordMatrix, + dynamicVertexArray, + anchorPoint, + state.getSize().aspectRatio()) == PlacementResult::NotEnoughRoom)) { + hideGlyphs(placedSymbol.glyphOffsets.size(), dynamicVertexArray); } } +} } // end namespace mbgl diff --git a/src/mbgl/layout/symbol_projection.hpp b/src/mbgl/layout/symbol_projection.hpp index afd5fd5a060..6cfade3da9b 100644 --- a/src/mbgl/layout/symbol_projection.hpp +++ b/src/mbgl/layout/symbol_projection.hpp @@ -6,69 +6,72 @@ namespace mbgl { - class TransformState; - class RenderTile; - class SymbolSizeBinder; - class PlacedSymbol; - namespace style { - class SymbolPropertyValues; - } // end namespace style - - struct TileDistance { - TileDistance(float prevTileDistance_, float lastSegmentViewportDistance_) - : prevTileDistance(prevTileDistance_), lastSegmentViewportDistance(lastSegmentViewportDistance_) - {} - float prevTileDistance; - float lastSegmentViewportDistance; - }; - - struct PlacedGlyph { - PlacedGlyph() = default; +class TransformState; +class RenderTile; +class SymbolSizeBinder; +class PlacedSymbol; +namespace style { +class SymbolPropertyValues; +} // end namespace style - PlacedGlyph(Point point_, float angle_, std::optional tileDistance_) - : point(point_), angle(angle_), tileDistance(std::move(tileDistance_)) - {} - PlacedGlyph(PlacedGlyph&& other) noexcept - : point(other.point), angle(other.angle), tileDistance(std::move(other.tileDistance)) {} - PlacedGlyph(const PlacedGlyph& other) = default; - Point point; - float angle; - std::optional tileDistance; - }; +struct TileDistance { + TileDistance(float prevTileDistance_, float lastSegmentViewportDistance_) + : prevTileDistance(prevTileDistance_), + lastSegmentViewportDistance(lastSegmentViewportDistance_) {} + float prevTileDistance; + float lastSegmentViewportDistance; +}; - float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol); - mat4 getLabelPlaneMatrix(const mat4& posMatrix, - bool pitchWithMap, - bool rotateWithMap, - const TransformState& state, - float pixelsToTileUnits); - mat4 getGlCoordMatrix(const mat4& posMatrix, - bool pitchWithMap, - bool rotateWithMap, - const TransformState& state, - float pixelsToTileUnits); +struct PlacedGlyph { + PlacedGlyph() = default; - using PointAndCameraDistance = std::pair,float>; - PointAndCameraDistance project(const Point& point, const mat4& matrix); + PlacedGlyph(Point point_, float angle_, std::optional tileDistance_) + : point(point_), + angle(angle_), + tileDistance(std::move(tileDistance_)) {} + PlacedGlyph(PlacedGlyph&& other) noexcept + : point(other.point), + angle(other.angle), + tileDistance(std::move(other.tileDistance)) {} + PlacedGlyph(const PlacedGlyph& other) = default; + Point point; + float angle; + std::optional tileDistance; +}; - void reprojectLineLabels(gfx::VertexVector>&, const std::vector&, - const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, bool keepUpright, - const RenderTile&, const SymbolSizeBinder& sizeBinder, const TransformState&); +float evaluateSizeForFeature(const ZoomEvaluatedSize& zoomEvaluatedSize, const PlacedSymbol& placedSymbol); +mat4 getLabelPlaneMatrix( + const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, const TransformState& state, float pixelsToTileUnits); +mat4 getGlCoordMatrix( + const mat4& posMatrix, bool pitchWithMap, bool rotateWithMap, const TransformState& state, float pixelsToTileUnits); - std::optional> placeFirstAndLastGlyph(float fontScale, - float lineOffsetX, - float lineOffsetY, - bool flip, - const Point& anchorPoint, - const Point& tileAnchorPoint, - const PlacedSymbol& symbol, - const mat4& labelPlaneMatrix, - bool returnTileDistance); +using PointAndCameraDistance = std::pair, float>; +PointAndCameraDistance project(const Point& point, const mat4& matrix); - void hideGlyphs(std::size_t numGlyphs, - gfx::VertexVector>& dynamicVertexArray); - void addDynamicAttributes(const Point& anchorPoint, - float angle, - gfx::VertexVector>& dynamicVertexArray); +void reprojectLineLabels(gfx::VertexVector>&, + const std::vector&, + const mat4& posMatrix, + bool pitchWithMap, + bool rotateWithMap, + bool keepUpright, + const RenderTile&, + const SymbolSizeBinder& sizeBinder, + const TransformState&); + +std::optional> placeFirstAndLastGlyph(float fontScale, + float lineOffsetX, + float lineOffsetY, + bool flip, + const Point& anchorPoint, + const Point& tileAnchorPoint, + const PlacedSymbol& symbol, + const mat4& labelPlaneMatrix, + bool returnTileDistance); + +void hideGlyphs(std::size_t numGlyphs, + gfx::VertexVector>& dynamicVertexArray); +void addDynamicAttributes(const Point& anchorPoint, + float angle, + gfx::VertexVector>& dynamicVertexArray); } // end namespace mbgl diff --git a/src/mbgl/map/map.cpp b/src/mbgl/map/map.cpp index 7bc201a1683..d4e05534ba1 100644 --- a/src/mbgl/map/map.cpp +++ b/src/mbgl/map/map.cpp @@ -32,15 +32,16 @@ Map::Map(RendererFrontend& frontend, const MapOptions& mapOptions, const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) - : impl(std::make_unique( - frontend, - observer, - FileSourceManager::get() - ? std::shared_ptr(FileSourceManager::get()->getFileSource(ResourceLoader, resourceOptions, clientOptions)) - : nullptr, - mapOptions)) {} + : impl(std::make_unique(frontend, + observer, + FileSourceManager::get() + ? std::shared_ptr(FileSourceManager::get()->getFileSource( + ResourceLoader, resourceOptions, clientOptions)) + : nullptr, + mapOptions)) {} -Map::Map(std::unique_ptr impl_) : impl(std::move(impl_)) {} +Map::Map(std::unique_ptr impl_) + : impl(std::move(impl_)) {} Map::~Map() = default; @@ -187,7 +188,9 @@ CameraOptions Map::cameraForLatLngBounds(const LatLngBounds& bounds, pitch); } -CameraOptions cameraForLatLngs(const std::vector& latLngs, const Transform& transform, const EdgeInsets& padding) { +CameraOptions cameraForLatLngs(const std::vector& latLngs, + const Transform& transform, + const EdgeInsets& padding) { if (latLngs.empty()) { return {}; } @@ -217,9 +220,13 @@ CameraOptions cameraForLatLngs(const std::vector& latLngs, const Transfo double zoom = transform.getZoom(); if (minScale > 0) { - zoom = util::clamp(zoom + util::log2(minScale), transform.getState().getMinZoom(), transform.getState().getMaxZoom()); + zoom = util::clamp( + zoom + util::log2(minScale), transform.getState().getMinZoom(), transform.getState().getMaxZoom()); } else { - Log::Error(Event::General, "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater than map's height or width."); + Log::Error(Event::General, + "Unable to calculate appropriate zoom level for bounds. Vertical " + "or horizontal padding is greater " + "than map's height or width."); } // Calculate the center point of a virtual bounds that is extended in all directions by padding. @@ -256,21 +263,18 @@ CameraOptions Map::cameraForGeometry(const Geometry& geometry, const std::optional& bearing, const std::optional& pitch) const { std::vector latLngs; - forEachPoint(geometry, [&](const Point& pt) { - latLngs.emplace_back(pt.y, pt.x); - }); + forEachPoint(geometry, [&](const Point& pt) { latLngs.emplace_back(pt.y, pt.x); }); return cameraForLatLngs(latLngs, padding, bearing, pitch); } LatLngBounds Map::latLngBoundsForCamera(const CameraOptions& camera) const { - Transform shallow { impl->transform.getState() }; + Transform shallow{impl->transform.getState()}; Size size = shallow.getState().getSize(); shallow.jumpTo(camera); return LatLngBounds::hull( shallow.screenCoordinateToLatLng({}), - shallow.screenCoordinateToLatLng({ static_cast(size.width), static_cast(size.height) }) - ); + shallow.screenCoordinateToLatLng({static_cast(size.width), static_cast(size.height)})); } LatLngBounds Map::latLngBoundsForCameraUnwrapped(const CameraOptions& camera) const { @@ -282,7 +286,8 @@ LatLngBounds Map::latLngBoundsForCameraUnwrapped(const CameraOptions& camera) co LatLng se = shallow.screenCoordinateToLatLng({static_cast(size.width), static_cast(size.height)}); LatLng ne = shallow.screenCoordinateToLatLng({static_cast(size.width), 0.0}); LatLng sw = shallow.screenCoordinateToLatLng({0.0, static_cast(size.height)}); - LatLng center = shallow.screenCoordinateToLatLng({static_cast(size.width) / 2, static_cast(size.height) / 2}); + LatLng center = shallow.screenCoordinateToLatLng( + {static_cast(size.width) / 2, static_cast(size.height) / 2}); nw.unwrapForShortestPath(center); se.unwrapForShortestPath(center); ne.unwrapForShortestPath(center); @@ -375,13 +380,13 @@ void Map::setViewportMode(mbgl::ViewportMode mode) { MapOptions Map::getMapOptions() const { return std::move(MapOptions() - .withMapMode(impl->mode) - .withConstrainMode(impl->transform.getConstrainMode()) - .withViewportMode(impl->transform.getViewportMode()) - .withCrossSourceCollisions(impl->crossSourceCollisions) - .withNorthOrientation(impl->transform.getNorthOrientation()) - .withSize(impl->transform.getState().getSize()) - .withPixelRatio(impl->pixelRatio)); + .withMapMode(impl->mode) + .withConstrainMode(impl->transform.getConstrainMode()) + .withViewportMode(impl->transform.getViewportMode()) + .withCrossSourceCollisions(impl->crossSourceCollisions) + .withNorthOrientation(impl->transform.getNorthOrientation()) + .withSize(impl->transform.getState().getSize()) + .withPixelRatio(impl->pixelRatio)); } // MARK: - Projection mode @@ -503,9 +508,13 @@ bool Map::isFullyLoaded() const { } void Map::dumpDebugLogs() const { - Log::Info(Event::General, "--------------------------------------------------------------------------------"); + Log::Info(Event::General, + "----------------------------------------------------------------------" + "----------"); impl->style->impl->dumpDebugLogs(); - Log::Info(Event::General, "--------------------------------------------------------------------------------"); + Log::Info(Event::General, + "----------------------------------------------------------------------" + "----------"); } void Map::setFreeCameraOptions(const FreeCameraOptions& camera) { diff --git a/src/mbgl/map/map_impl.hpp b/src/mbgl/map/map_impl.hpp index 1705de7abf7..6a8043616df 100644 --- a/src/mbgl/map/map_impl.hpp +++ b/src/mbgl/map/map_impl.hpp @@ -24,8 +24,7 @@ class ShaderRegistry; struct StillImageRequest { StillImageRequest(Map::StillImageCallback&& callback_) - : callback(std::move(callback_)) { - } + : callback(std::move(callback_)) {} Map::StillImageCallback callback; }; @@ -65,7 +64,7 @@ class Map::Impl final : public style::Observer, public RendererObserver { const float pixelRatio; const bool crossSourceCollisions; - MapDebugOptions debugOptions { MapDebugOptions::NoDebug }; + MapDebugOptions debugOptions{MapDebugOptions::NoDebug}; std::shared_ptr fileSource; diff --git a/src/mbgl/map/map_options.cpp b/src/mbgl/map/map_options.cpp index 4cebb6adabb..656d09a6506 100644 --- a/src/mbgl/map/map_options.cpp +++ b/src/mbgl/map/map_options.cpp @@ -9,12 +9,13 @@ class MapOptions::Impl { ViewportMode viewportMode = ViewportMode::Default; NorthOrientation orientation = NorthOrientation::Upwards; bool crossSourceCollisions = true; - Size size = { 64, 64 }; + Size size = {64, 64}; float pixelRatio = 1.0; }; // These requires the complete type of Impl. -MapOptions::MapOptions() : impl_(std::make_unique()) {} +MapOptions::MapOptions() + : impl_(std::make_unique()) {} MapOptions::~MapOptions() = default; MapOptions::MapOptions(MapOptions&&) noexcept = default; @@ -81,4 +82,4 @@ float MapOptions::pixelRatio() const { return impl_->pixelRatio; } -} // namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/map/map_projection.cpp b/src/mbgl/map/map_projection.cpp index 9c2eda4dd39..b0566e68ac6 100644 --- a/src/mbgl/map/map_projection.cpp +++ b/src/mbgl/map/map_projection.cpp @@ -30,11 +30,10 @@ CameraOptions MapProjection::getCamera() const { return transform->getCameraOptions(std::nullopt); } -void MapProjection::setVisibleCoordinates(const std::vector& latLngs, - const EdgeInsets& padding) { +void MapProjection::setVisibleCoordinates(const std::vector& latLngs, const EdgeInsets& padding) { transform->jumpTo(mbgl::cameraForLatLngs(latLngs, *transform, padding) - .withBearing(util::rad2deg(-transform->getBearing())) - .withPitch(util::rad2deg(transform->getPitch()))); + .withBearing(util::rad2deg(-transform->getBearing())) + .withPitch(util::rad2deg(transform->getPitch()))); } } // namespace mbgl diff --git a/src/mbgl/map/transform.cpp b/src/mbgl/map/transform.cpp index fe853e0d77c..93ac496cc1c 100644 --- a/src/mbgl/map/transform.cpp +++ b/src/mbgl/map/transform.cpp @@ -18,9 +18,9 @@ namespace mbgl { -/** Converts the given angle (in radians) to be numerically close to the anchor angle, allowing it to be interpolated properly without sudden jumps. */ -static double _normalizeAngle(double angle, double anchorAngle) -{ +/** Converts the given angle (in radians) to be numerically close to the anchor + * angle, allowing it to be interpolated properly without sudden jumps. */ +static double _normalizeAngle(double angle, double anchorAngle) { if (std::isnan(angle) || std::isnan(anchorAngle)) { return 0; } @@ -38,11 +38,9 @@ static double _normalizeAngle(double angle, double anchorAngle) return angle; } -Transform::Transform(MapObserver& observer_, - ConstrainMode constrainMode, - ViewportMode viewportMode) - : observer(observer_), state(constrainMode, viewportMode) { -} +Transform::Transform(MapObserver& observer_, ConstrainMode constrainMode, ViewportMode viewportMode) + : observer(observer_), + state(constrainMode, viewportMode) {} // MARK: - Map View @@ -109,9 +107,10 @@ void Transform::easeTo(const CameraOptions& camera, const AnimationOptions& anim if (state.getLatLngBounds() == LatLngBounds()) { if (isGestureInProgress()) { - // If gesture in progress, we transfer the wrap rounds from the end longitude into - // start, so the "scroll effect" of rounding the world is the same while assuring the - // end longitude remains wrapped. + // If gesture in progress, we transfer the wrap rounds from the end + // longitude into start, so the "scroll effect" of rounding the + // world is the same while assuring the end longitude remains + // wrapped. const double wrap = unwrappedLatLng.longitude() - latLng.longitude(); startLatLng = LatLng(startLatLng.latitude(), startLatLng.longitude() - wrap); } else { @@ -260,19 +259,16 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima Assumes an angular field of view of 2 arctan ½ ≈ 53°. */ auto w = [=](double s) { - return (isClose ? std::exp((w1 < w0 ? -1 : 1) * rho * s) - : (std::cosh(r0) / std::cosh(r0 + rho * s))); + return (isClose ? std::exp((w1 < w0 ? -1 : 1) * rho * s) : (std::cosh(r0) / std::cosh(r0 + rho * s))); }; /// u(s): Returns the distance along the flight path as projected onto the /// ground plane, measured in pixels from the world image origin at the /// initial scale. auto u = [=](double s) { - return (isClose ? 0. - : (w0 * (std::cosh(r0) * std::tanh(r0 + rho * s) - std::sinh(r0)) / rho2 / u1)); + return (isClose ? 0. : (w0 * (std::cosh(r0) * std::tanh(r0 + rho * s) - std::sinh(r0)) / rho2 / u1)); }; /// S: Total length of the flight path, measured in ρ-screenfuls. - double S = (isClose ? (std::abs(std::log(w1 / w0)) / rho) - : ((r1 - r0) / rho)); + double S = (isClose ? (std::abs(std::log(w1 / w0)) / rho) : ((r1 - r0) / rho)); Duration duration; if (animation.duration) { @@ -311,8 +307,8 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima // Calculate the current point and zoom level along the flight path. Point framePoint = util::interpolate(startPoint, endPoint, us); - double frameZoom = - linearZoomInterpolation ? util::interpolate(startZoom, zoom, k) : startZoom + state.scaleZoom(1 / w(s)); + double frameZoom = linearZoomInterpolation ? util::interpolate(startZoom, zoom, k) + : startZoom + state.scaleZoom(1 / w(s)); // Zoom can be NaN if size is empty. if (std::isnan(frameZoom)) { @@ -346,8 +342,8 @@ void Transform::flyTo(const CameraOptions& camera, const AnimationOptions& anima void Transform::moveBy(const ScreenCoordinate& offset, const AnimationOptions& animation) { ScreenCoordinate centerOffset = {offset.x, offset.y}; - ScreenCoordinate pointOnScreen = - state.getEdgeInsets().getCenter(state.getSize().width, state.getSize().height) - centerOffset; + ScreenCoordinate pointOnScreen = state.getEdgeInsets().getCenter(state.getSize().width, state.getSize().height) - + centerOffset; // Use unwrapped LatLng to carry information about moveBy direction. easeTo(CameraOptions().withCenter(screenCoordinateToLatLng(pointOnScreen, LatLng::Unwrapped)), animation); } @@ -386,7 +382,7 @@ void Transform::setMinPitch(const double minPitch) { if (util::deg2rad(minPitch) < util::PITCH_MIN) { Log::Warning(Event::General, "Trying to set minimum pitch below the limit (" + std::to_string(util::rad2deg(util::PITCH_MIN)) + - " degrees), the value will be clamped."); + " degrees), the value will be clamped."); } state.setMinPitch(util::deg2rad(minPitch)); } @@ -396,7 +392,7 @@ void Transform::setMaxPitch(const double maxPitch) { if (util::deg2rad(maxPitch) > util::PITCH_MAX) { Log::Warning(Event::General, "Trying to set maximum pitch above the limit (" + std::to_string(util::rad2deg(util::PITCH_MAX)) + - " degrees), the value will be clamped."); + " degrees), the value will be clamped."); } state.setMaxPitch(util::deg2rad(maxPitch)); } @@ -410,8 +406,8 @@ void Transform::rotateBy(const ScreenCoordinate& first, const ScreenCoordinate offset = first - center; const double distance = std::sqrt(std::pow(2, offset.x) + std::pow(2, offset.y)); - // If the first click was too close to the center, move the center of rotation by 200 pixels - // in the direction of the click. + // If the first click was too close to the center, move the center of + // rotation by 200 pixels in the direction of the click. if (distance < 200) { const double heightOffset = -200; const double rotateBearing = std::atan2(offset.y, offset.x); @@ -568,15 +564,15 @@ bool Transform::inTransition() const { } void Transform::updateTransitions(const TimePoint& now) { - // Use a temporary function to ensure that the transitionFrameFn lambda is // called only once per update. - // This addresses the symptoms of https://github.com/mapbox/mapbox-gl-native/issues/11180 - // where setting a shape source to nil (or similar) in the `onCameraIsChanging` - // observer function causes `Map::Impl::onUpdate()` to be called which - // in turn calls this function (before the current iteration has completed), - // leading to an infinite loop. See https://github.com/mapbox/mapbox-gl-native/issues/5833 + // This addresses the symptoms of + // https://github.com/mapbox/mapbox-gl-native/issues/11180 where setting a + // shape source to nil (or similar) in the `onCameraIsChanging` observer + // function causes `Map::Impl::onUpdate()` to be called which in turn calls + // this function (before the current iteration has completed), leading to an + // infinite loop. See https://github.com/mapbox/mapbox-gl-native/issues/5833 // for a similar, related, issue. // // By temporarily nulling the `transitionFrameFn` (and then restoring it @@ -601,9 +597,9 @@ void Transform::updateTransitions(const TimePoint& now) { finish(); } } else if (!transitionFrameFn) { - // We have to check `transitionFrameFn` is nil here, since a new transition - // may have been triggered in a user callback (from the transition call - // above) + // We have to check `transitionFrameFn` is nil here, since a new + // transition may have been triggered in a user callback (from the + // transition call above) transitionFrameFn = std::move(transition); } } @@ -640,15 +636,19 @@ double Transform::getMaxPitchForEdgeInsets(const EdgeInsets& insets) const { const auto height = state.getSize().height; assert(height); - // For details, see description at https://github.com/mapbox/mapbox-gl-native/pull/15195 - // The definition of half of TransformState::fov with no inset, is: fov = arctan((height / 2) / (height * 1.5)). - // We use half of fov, as it is field of view above perspective center. - // With inset, this angle changes and tangentOfFovAboveCenterAngle = (h/2 + centerOffsetY) / (height * 1.5). - // 1.03 is a bit extra added to prevent parallel ground to viewport clipping plane. + // For details, see description at + // https://github.com/mapbox/mapbox-gl-native/pull/15195 The definition of + // half of TransformState::fov with no inset, is: fov = arctan((height / 2) + // / (height * 1.5)). We use half of fov, as it is field of view above + // perspective center. With inset, this angle changes and + // tangentOfFovAboveCenterAngle = (h/2 + centerOffsetY) / (height + // * 1.5). 1.03 is a bit extra added to prevent parallel ground to viewport + // clipping plane. const double tangentOfFovAboveCenterAngle = 1.03 * (height / 2.0 + centerOffsetY) / (1.5 * height); const double fovAboveCenter = std::atan(tangentOfFovAboveCenterAngle); return M_PI * 0.5 - fovAboveCenter; - // e.g. Maximum pitch of 60 degrees is when perspective center's offset from the top is 84% of screen height. + // e.g. Maximum pitch of 60 degrees is when perspective center's offset from + // the top is 84% of screen height. } FreeCameraOptions Transform::getFreeCameraOptions() const { diff --git a/src/mbgl/map/transform.hpp b/src/mbgl/map/transform.hpp index a1458bf8ccf..eac0e8fb99d 100644 --- a/src/mbgl/map/transform.hpp +++ b/src/mbgl/map/transform.hpp @@ -22,7 +22,9 @@ class Transform : private util::noncopyable { ConstrainMode = ConstrainMode::HeightOnly, ViewportMode = ViewportMode::Default); - Transform(const TransformState &state_) : observer(MapObserver::nullObserver()), state(state_) {} + Transform(const TransformState& state_) + : observer(MapObserver::nullObserver()), + state(state_) {} // Map view void resize(Size size); @@ -126,7 +128,7 @@ class Transform : private util::noncopyable { const Duration&); // We don't want to show horizon: limit max pitch based on edge insets. - double getMaxPitchForEdgeInsets(const EdgeInsets &insets) const; + double getMaxPitchForEdgeInsets(const EdgeInsets& insets) const; TimePoint transitionStart; Duration transitionDuration; diff --git a/src/mbgl/map/transform_state.cpp b/src/mbgl/map/transform_state.cpp index f8ebacbe1b1..4d33c89dd20 100644 --- a/src/mbgl/map/transform_state.cpp +++ b/src/mbgl/map/transform_state.cpp @@ -22,7 +22,7 @@ constexpr double kEpsilon = 1e-9; double roundForAccuracy(double x) { double round_x = std::round(x); double diff = std::abs(round_x - x); - if (diff < kEpsilon && diff > 0 ){ + if (diff < kEpsilon && diff > 0) { return round_x; } else { return x; @@ -31,7 +31,9 @@ double roundForAccuracy(double x) { } // namespace TransformState::TransformState(ConstrainMode constrainMode_, ViewportMode viewportMode_) - : bounds(LatLngBounds()), constrainMode(constrainMode_), viewportMode(viewportMode_) {} + : bounds(LatLngBounds()), + constrainMode(constrainMode_), + viewportMode(viewportMode_) {} void TransformState::setProperties(const TransformStateProperties& properties) { if (properties.x) { @@ -126,8 +128,8 @@ void TransformState::getProjMatrix(mat4& projMatrix, uint16_t nearZ, bool aligne updateCameraState(); mat4 worldToCamera = camera.getWorldToCamera(scale, viewportMode == ViewportMode::FlippedY); - mat4 cameraToClip = - camera.getCameraToClipPerspective(getFieldOfView(), static_cast(size.width) / size.height, nearZ, farZ); + mat4 cameraToClip = camera.getCameraToClipPerspective( + getFieldOfView(), static_cast(size.width) / size.height, nearZ, farZ); // Move the center of perspective to center of specified edgeInsets. // Values are in range [-1, 1] where the upper and lower range values @@ -156,12 +158,14 @@ void TransformState::getProjMatrix(mat4& projMatrix, uint16_t nearZ, bool aligne projMatrix[9] = ySkew * pixelsPerMeter; } - // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles. - // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional - // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension - // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle - // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that - // it is always <= 0.5 pixels. + // Make a second projection matrix that is aligned to a pixel grid for + // rendering raster tiles. We're rounding the (floating point) x/y values to + // achieve to avoid rendering raster images to fractional coordinates. + // Additionally, we adjust by half a pixel in either direction in case that + // viewport dimension is an odd integer to preserve rendering to the pixel + // grid. We're rotating this shift based on the angle of the transformation + // so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift + // so that it is always <= 0.5 pixels. if (aligned) { const double worldSize = Projection::worldSize(scale); @@ -187,10 +191,11 @@ void TransformState::updateCameraState() const { const double worldSize = Projection::worldSize(scale); const double cameraToCenterDistance = getCameraToCenterDistance(); - // x & y tracks the center of the map in pixels. However as rendering is done in pixel coordinates the rendering - // origo is actually in the middle of the map (0.5 * worldSize). x&y positions have to be negated because it defines - // position of the map, not the camera. Moving map 10 units left has the same effect as moving camera 10 units to - // the right. + // x & y tracks the center of the map in pixels. However as rendering is + // done in pixel coordinates the rendering origo is actually in the middle + // of the map (0.5 * worldSize). x&y positions have to be negated because it + // defines position of the map, not the camera. Moving map 10 units left has + // the same effect as moving camera 10 units to the right. const double dx = 0.5 * worldSize - x; const double dy = 0.5 * worldSize - y; @@ -506,7 +511,9 @@ void TransformState::setMinPitch(const double pitch_) { if (pitch_ <= maxPitch) { minPitch = util::clamp(pitch_, util::PITCH_MIN, maxPitch); } else { - Log::Warning(Event::General, "Trying to set minimum pitch to larger than maximum pitch, no changes made."); + Log::Warning(Event::General, + "Trying to set minimum pitch to larger than maximum pitch, no " + "changes made."); } } @@ -518,7 +525,9 @@ void TransformState::setMaxPitch(const double pitch_) { if (pitch_ >= minPitch) { maxPitch = util::clamp(pitch_, minPitch, util::PITCH_MAX); } else { - Log::Warning(Event::General, "Trying to set maximum pitch to smaller than minimum pitch, no changes made."); + Log::Warning(Event::General, + "Trying to set maximum pitch to smaller than minimum pitch, no " + "changes made."); } } @@ -812,10 +821,10 @@ float TransformState::maxPitchScaleFactor() const { if (size.isEmpty()) { return {}; } - auto latLng = screenCoordinateToLatLng({ 0, static_cast(getSize().height) }); + auto latLng = screenCoordinateToLatLng({0, static_cast(getSize().height)}); Point pt = Projection::project(latLng, scale) / util::tileSize_D; - vec4 p = {{ pt.x, pt.y, 0, 1 }}; + vec4 p = {{pt.x, pt.y, 0, 1}}; vec4 topPoint; matrix::transformMat4(topPoint, p, getCoordMatrix()); return static_cast(topPoint[3]) / getCameraToCenterDistance(); diff --git a/src/mbgl/map/transform_state.hpp b/src/mbgl/map/transform_state.hpp index c4fe5cc2faf..28384eb0ba5 100644 --- a/src/mbgl/map/transform_state.hpp +++ b/src/mbgl/map/transform_state.hpp @@ -276,8 +276,8 @@ class TransformState { double scale = 1; // This fov value is somewhat arbitrary. The altitude of the camera used // to be defined as 1.5 screen heights above the ground, which was an - // arbitrary choice. This is the fov equivalent to that value calculated with: - // `fov = 2 * arctan((height / 2) / (height * 1.5))` + // arbitrary choice. This is the fov equivalent to that value calculated + // with: `fov = 2 * arctan((height / 2) / (height * 1.5))` double fov = 0.6435011087932844; double pitch = 0.0; double xSkew = 0.0; diff --git a/src/mbgl/math/log2.cpp b/src/mbgl/math/log2.cpp index 222e67dbd71..c54dd13d3f7 100644 --- a/src/mbgl/math/log2.cpp +++ b/src/mbgl/math/log2.cpp @@ -5,9 +5,12 @@ namespace util { // From http://stackoverflow.com/questions/3272424/compute-fast-log-base-2-ceiling uint32_t ceil_log2(uint64_t x) { - static const uint64_t t[6] = {0xFFFFFFFF00000000, 0x00000000FFFF0000, - 0x000000000000FF00, 0x00000000000000F0, - 0x000000000000000C, 0x0000000000000002}; + static const uint64_t t[6] = {0xFFFFFFFF00000000, + 0x00000000FFFF0000, + 0x000000000000FF00, + 0x00000000000000F0, + 0x000000000000000C, + 0x0000000000000002}; uint32_t y = (((x & (x - 1)) == 0) ? 0 : 1); uint32_t j = 32; diff --git a/src/mbgl/platform/gl_functions.cpp b/src/mbgl/platform/gl_functions.cpp index 1ffbd47b486..b9178cf5296 100644 --- a/src/mbgl/platform/gl_functions.cpp +++ b/src/mbgl/platform/gl_functions.cpp @@ -9,10 +9,11 @@ namespace platform { #ifndef NDEBUG void glCheckError(const char* cmd, const char* file, int line) { if (GLenum err = glGetError()) { - Log::Warning(Event::OpenGL, "Error" + std::to_string(err) + ": " + cmd + " - " + file + ":" + std::to_string(line)); + Log::Warning(Event::OpenGL, + "Error" + std::to_string(err) + ": " + cmd + " - " + file + ":" + std::to_string(line)); } } #endif -} // namespace platform -} // namespace mbgl +} // namespace platform +} // namespace mbgl diff --git a/src/mbgl/platform/settings.cpp b/src/mbgl/platform/settings.cpp index 10c8d109c6c..17fc1285608 100644 --- a/src/mbgl/platform/settings.cpp +++ b/src/mbgl/platform/settings.cpp @@ -21,7 +21,8 @@ class Settings::Impl { std::mutex mutex; }; -Settings::Settings() : impl(std::make_unique()) {} +Settings::Settings() + : impl(std::make_unique()) {} Settings& Settings::getInstance() noexcept { static Settings instance; diff --git a/src/mbgl/programs/attributes.hpp b/src/mbgl/programs/attributes.hpp index 09d5eca8091..b6df1c145d6 100644 --- a/src/mbgl/programs/attributes.hpp +++ b/src/mbgl/programs/attributes.hpp @@ -16,7 +16,7 @@ MBGL_DEFINE_ATTRIBUTE(int16_t, 4, pixeloffset); MBGL_DEFINE_ATTRIBUTE(int16_t, 2, label_pos); MBGL_DEFINE_ATTRIBUTE(int16_t, 2, anchor_pos); MBGL_DEFINE_ATTRIBUTE(uint16_t, 2, texture_pos); -MBGL_DEFINE_ATTRIBUTE(int16_t, 4, normal_ed); +MBGL_DEFINE_ATTRIBUTE(int16_t, 4, normal_ed); MBGL_DEFINE_ATTRIBUTE(float, 1, fade_opacity); MBGL_DEFINE_ATTRIBUTE(uint8_t, 2, placed); MBGL_DEFINE_ATTRIBUTE(uint16_t, 3, size); @@ -26,9 +26,7 @@ MBGL_DEFINE_ATTRIBUTE(float, 2, shift); template struct data { using Type = gfx::AttributeType; - static constexpr auto name() { - return "data"; - } + static constexpr auto name() { return "data"; } }; // Paint attributes diff --git a/src/mbgl/programs/background_program.cpp b/src/mbgl/programs/background_program.cpp index 25e351260ab..cb1d71df767 100644 --- a/src/mbgl/programs/background_program.cpp +++ b/src/mbgl/programs/background_program.cpp @@ -10,35 +10,39 @@ using namespace style; static_assert(sizeof(BackgroundLayoutVertex) == 4, "expected BackgroundLayoutVertex size"); -BackgroundPatternProgram::LayoutUniformValues -BackgroundPatternProgram::layoutUniformValues(mat4 matrix, - float opacity, - Size atlasSize, - const ImagePosition& a, - const ImagePosition& b, - const CrossfadeParameters& fading, - const UnwrappedTileID& tileID, - const TransformState& state) { - int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); - int32_t pixelX = static_cast(tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); +BackgroundPatternProgram::LayoutUniformValues BackgroundPatternProgram::layoutUniformValues( + mat4 matrix, + float opacity, + Size atlasSize, + const ImagePosition& a, + const ImagePosition& b, + const CrossfadeParameters& fading, + const UnwrappedTileID& tileID, + const TransformState& state) { + int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * + state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); + int32_t pixelX = static_cast(tileSizeAtNearestZoom * + (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); int32_t pixelY = tileSizeAtNearestZoom * tileID.canonical.y; return { - uniforms::matrix::Value( matrix ), - uniforms::opacity::Value( opacity ), - uniforms::texsize::Value( atlasSize ), - uniforms::pattern_tl_a::Value( a.tl() ), - uniforms::pattern_br_a::Value( a.br() ), - uniforms::pattern_tl_b::Value( b.tl() ), - uniforms::pattern_br_b::Value( b.br() ), - uniforms::pattern_size_a::Value( a.displaySize() ), - uniforms::pattern_size_b::Value( b.displaySize() ), - uniforms::scale_a::Value( fading.fromScale ), - uniforms::scale_b::Value( fading.toScale ), - uniforms::mix::Value( fading.t ), - uniforms::pixel_coord_upper::Value( std::array {{ static_cast(pixelX >> 16), static_cast(pixelY >> 16) }}), - uniforms::pixel_coord_lower::Value( std::array {{ static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}}), - uniforms::tile_units_to_pixels::Value( 1.0f / tileID.pixelsToTileUnits(1.0f, state.getIntegerZoom()) ), + uniforms::matrix::Value(matrix), + uniforms::opacity::Value(opacity), + uniforms::texsize::Value(atlasSize), + uniforms::pattern_tl_a::Value(a.tl()), + uniforms::pattern_br_a::Value(a.br()), + uniforms::pattern_tl_b::Value(b.tl()), + uniforms::pattern_br_b::Value(b.br()), + uniforms::pattern_size_a::Value(a.displaySize()), + uniforms::pattern_size_b::Value(b.displaySize()), + uniforms::scale_a::Value(fading.fromScale), + uniforms::scale_b::Value(fading.toScale), + uniforms::mix::Value(fading.t), + uniforms::pixel_coord_upper::Value( + std::array{{static_cast(pixelX >> 16), static_cast(pixelY >> 16)}}), + uniforms::pixel_coord_lower::Value( + std::array{{static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}}), + uniforms::tile_units_to_pixels::Value(1.0f / tileID.pixelsToTileUnits(1.0f, state.getIntegerZoom())), }; } diff --git a/src/mbgl/programs/background_program.hpp b/src/mbgl/programs/background_program.hpp index beb2c2a0d8c..205d8cad96c 100644 --- a/src/mbgl/programs/background_program.hpp +++ b/src/mbgl/programs/background_program.hpp @@ -13,65 +13,53 @@ namespace mbgl { class ImagePosition; class UnwrappedTileID; class TransformState; -template class Faded; +template +class Faded; using BackgroundLayoutAttributes = PositionOnlyLayoutAttributes; -using BackgroundUniforms = TypeList< - uniforms::matrix, - uniforms::color, - uniforms::opacity>; +using BackgroundUniforms = TypeList; -using BackgroundPatternUniforms = TypeList< - uniforms::matrix, - uniforms::opacity, - uniforms::texsize, - uniforms::pattern_tl_a, - uniforms::pattern_br_a, - uniforms::pattern_tl_b, - uniforms::pattern_br_b, - uniforms::pattern_size_a, - uniforms::pattern_size_b, - uniforms::scale_a, - uniforms::scale_b, - uniforms::mix, - uniforms::pixel_coord_upper, - uniforms::pixel_coord_lower, - uniforms::tile_units_to_pixels>; +using BackgroundPatternUniforms = TypeList; -class BackgroundProgram final : public Program< - BackgroundProgram, - shaders::BuiltIn::BackgroundProgram, - gfx::PrimitiveType::Triangle, - BackgroundLayoutAttributes, - BackgroundUniforms, - TypeList<>, - style::Properties<>> -{ +class BackgroundProgram final : public Program, + style::Properties<>> { public: static constexpr std::string_view Name{"BackgroundProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; -class BackgroundPatternProgram final : public Program< - BackgroundPatternProgram, - shaders::BuiltIn::BackgroundPatternProgram, - gfx::PrimitiveType::Triangle, - BackgroundLayoutAttributes, - BackgroundPatternUniforms, - TypeList< - textures::image>, - style::Properties<>> -{ +class BackgroundPatternProgram final : public Program, + style::Properties<>> { public: static constexpr std::string_view Name{"BackgroundPatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; diff --git a/src/mbgl/programs/circle_program.hpp b/src/mbgl/programs/circle_program.hpp index 73d5064c654..bb93c6c8fe4 100644 --- a/src/mbgl/programs/circle_program.hpp +++ b/src/mbgl/programs/circle_program.hpp @@ -12,27 +12,21 @@ namespace uniforms { MBGL_DEFINE_UNIFORM_SCALAR(bool, scale_with_map); } // namespace uniforms -class CircleProgram final : public Program< - CircleProgram, - shaders::BuiltIn::CircleProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos>, - TypeList< - uniforms::matrix, - uniforms::scale_with_map, - uniforms::extrude_scale, - uniforms::device_pixel_ratio, - uniforms::camera_to_center_distance, - uniforms::pitch_with_map>, - TypeList<>, - style::CirclePaintProperties> -{ +class CircleProgram final : public Program, + TypeList, + TypeList<>, + style::CirclePaintProperties> { public: static constexpr std::string_view Name{"CircleProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -43,12 +37,8 @@ class CircleProgram final : public Program< * @param {number} ey extrude normal */ static LayoutVertex vertex(Point p, float ex, float ey) { - return LayoutVertex { - {{ - static_cast((p.x * 2) + ((ex + 1) / 2)), - static_cast((p.y * 2) + ((ey + 1) / 2)) - }} - }; + return LayoutVertex{ + {{static_cast((p.x * 2) + ((ex + 1) / 2)), static_cast((p.y * 2) + ((ey + 1) / 2))}}}; } }; diff --git a/src/mbgl/programs/clipping_mask_program.cpp b/src/mbgl/programs/clipping_mask_program.cpp index aca76050371..0e433806312 100644 --- a/src/mbgl/programs/clipping_mask_program.cpp +++ b/src/mbgl/programs/clipping_mask_program.cpp @@ -1,5 +1,3 @@ #include -namespace mbgl { - -} // namespace mbgl +namespace mbgl {} // namespace mbgl diff --git a/src/mbgl/programs/clipping_mask_program.hpp b/src/mbgl/programs/clipping_mask_program.hpp index 97a14aec296..210fb94efda 100644 --- a/src/mbgl/programs/clipping_mask_program.hpp +++ b/src/mbgl/programs/clipping_mask_program.hpp @@ -7,21 +7,16 @@ namespace mbgl { -class ClippingMaskProgram final : public Program< - ClippingMaskProgram, - shaders::BuiltIn::ClippingMaskProgram, - gfx::PrimitiveType::Triangle, - PositionOnlyLayoutAttributes, - TypeList< - uniforms::matrix>, - TypeList<>, - style::Properties<>> -{ +class ClippingMaskProgram final : public Program, + TypeList<>, + style::Properties<>> { public: static constexpr std::string_view Name{"ClippingMaskProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; diff --git a/src/mbgl/programs/collision_box_program.hpp b/src/mbgl/programs/collision_box_program.hpp index 2b913f06023..cb402a01e17 100644 --- a/src/mbgl/programs/collision_box_program.hpp +++ b/src/mbgl/programs/collision_box_program.hpp @@ -10,58 +10,35 @@ namespace mbgl { -using CollisionBoxLayoutAttributes = TypeList< - attributes::pos, - attributes::anchor_pos, - attributes::extrude>; +using CollisionBoxLayoutAttributes = TypeList; using CollisionBoxDynamicAttributes = TypeList; -class CollisionBoxProgram final : public Program< - CollisionBoxProgram, - shaders::BuiltIn::CollisionBoxProgram, - gfx::PrimitiveType::Line, - TypeListConcat, - TypeList< - uniforms::matrix, - uniforms::extrude_scale, - uniforms::camera_to_center_distance>, - TypeList<>, - style::Properties<>> -{ +class CollisionBoxProgram final + : public Program, + TypeList, + TypeList<>, + style::Properties<>> { public: static constexpr std::string_view Name{"CollisionBoxProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static gfx::Vertex layoutVertex(Point a, Point anchor, Point o) { - return { - {{ - static_cast(a.x), - static_cast(a.y) - }}, - {{ - static_cast(anchor.x), - static_cast(anchor.y) - }}, - {{ - static_cast(::round(o.x)), - static_cast(::round(o.y)) - }} - }; + return {{{static_cast(a.x), static_cast(a.y)}}, + {{static_cast(anchor.x), static_cast(anchor.y)}}, + {{static_cast(::round(o.x)), static_cast(::round(o.y))}}}; } static gfx::Vertex dynamicVertex(bool placed, bool notUsed, Point shift) { - return { - {{ static_cast(placed), static_cast(notUsed) }}, - {{ shift.x, shift.y }} - }; + return {{{static_cast(placed), static_cast(notUsed)}}, {{shift.x, shift.y}}}; } - template + template void draw(gfx::Context& context, gfx::RenderPass& renderPass, const DrawMode& drawMode, @@ -79,12 +56,13 @@ class CollisionBoxProgram final : public Program< const TextureBindings& textureBindings, float currentZoom, const std::string& layerID) { - UniformValues uniformValues = layoutUniformValues - .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); + UniformValues uniformValues = layoutUniformValues.concat( + paintPropertyBinders.uniformValues(currentZoom, currentProperties)); - AttributeBindings allAttributeBindings = gfx::AttributeBindings(layoutVertexBuffer) - .concat(gfx::AttributeBindings(dynamicVertexBuffer)) - .concat(paintPropertyBinders.attributeBindings(currentProperties)); + AttributeBindings allAttributeBindings = + gfx::AttributeBindings(layoutVertexBuffer) + .concat(gfx::AttributeBindings(dynamicVertexBuffer)) + .concat(paintPropertyBinders.attributeBindings(currentProperties)); assert(layoutVertexBuffer.elements == dynamicVertexBuffer.elements); @@ -113,43 +91,27 @@ class CollisionBoxProgram final : public Program< } }; - -class CollisionCircleProgram final : public Program< - CollisionCircleProgram, - shaders::BuiltIn::CollisionCircleProgram, - gfx::PrimitiveType::Triangle, - TypeListConcat, - TypeList< - uniforms::matrix, - uniforms::extrude_scale, - uniforms::overscale_factor, - uniforms::camera_to_center_distance>, - TypeList<>, - style::Properties<>> -{ +class CollisionCircleProgram final + : public Program, + TypeList, + TypeList<>, + style::Properties<>> { public: static constexpr std::string_view Name{"CollisionCircleProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static gfx::Vertex vertex(Point a, Point anchor, Point o) { - return { - {{ - static_cast(a.x), - static_cast(a.y) - }}, - {{ - static_cast(anchor.x), - static_cast(anchor.y) - }}, - {{ - static_cast(::round(o.x)), - static_cast(::round(o.y)) - }} - }; + return {{{static_cast(a.x), static_cast(a.y)}}, + {{static_cast(anchor.x), static_cast(anchor.y)}}, + {{static_cast(::round(o.x)), static_cast(::round(o.y))}}}; } template @@ -170,12 +132,13 @@ class CollisionCircleProgram final : public Program< const TextureBindings& textureBindings, float currentZoom, const std::string& layerID) { - UniformValues uniformValues = layoutUniformValues - .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); + UniformValues uniformValues = layoutUniformValues.concat( + paintPropertyBinders.uniformValues(currentZoom, currentProperties)); - AttributeBindings allAttributeBindings = gfx::AttributeBindings(layoutVertexBuffer) - .concat(gfx::AttributeBindings(dynamicVertexBuffer)) - .concat(paintPropertyBinders.attributeBindings(currentProperties)); + AttributeBindings allAttributeBindings = + gfx::AttributeBindings(layoutVertexBuffer) + .concat(gfx::AttributeBindings(dynamicVertexBuffer)) + .concat(paintPropertyBinders.attributeBindings(currentProperties)); for (auto& segment : segments) { auto drawScopeIt = segment.drawScopes.find(layerID); diff --git a/src/mbgl/programs/debug_program.cpp b/src/mbgl/programs/debug_program.cpp index 3396e748724..5ef4dc378ae 100644 --- a/src/mbgl/programs/debug_program.cpp +++ b/src/mbgl/programs/debug_program.cpp @@ -1,5 +1,3 @@ #include -namespace mbgl { - -} // namespace mbgl +namespace mbgl {} // namespace mbgl diff --git a/src/mbgl/programs/debug_program.hpp b/src/mbgl/programs/debug_program.hpp index 68c1c5d12ce..fe0843798a9 100644 --- a/src/mbgl/programs/debug_program.hpp +++ b/src/mbgl/programs/debug_program.hpp @@ -11,20 +11,16 @@ namespace mbgl { namespace uniforms { MBGL_DEFINE_UNIFORM_SCALAR(float, overlay_scale); } -class DebugProgram final : public Program< - DebugProgram, - shaders::BuiltIn::DebugProgram, - gfx::PrimitiveType::Line, - TypeList, - TypeList, - TypeList, - style::Properties<>> -{ +class DebugProgram final : public Program, + TypeList, + TypeList, + style::Properties<>> { public: static constexpr std::string_view Name{"DebugProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; diff --git a/src/mbgl/programs/fill_extrusion_program.cpp b/src/mbgl/programs/fill_extrusion_program.cpp index e1bffa3ed70..c50319855b2 100644 --- a/src/mbgl/programs/fill_extrusion_program.cpp +++ b/src/mbgl/programs/fill_extrusion_program.cpp @@ -13,7 +13,7 @@ static_assert(sizeof(FillExtrusionLayoutVertex) == 12, "expected FillExtrusionLa std::array lightColor(const EvaluatedLight& light) { const auto color = light.get(); - return {{ color.r, color.g, color.b }}; + return {{color.r, color.g, color.b}}; } std::array lightPosition(const EvaluatedLight& light, const TransformState& state) { @@ -31,48 +31,51 @@ float lightIntensity(const EvaluatedLight& light) { return light.get(); } -FillExtrusionProgram::LayoutUniformValues FillExtrusionProgram::layoutUniformValues( - mat4 matrix, const TransformState& state, const float opacity, const EvaluatedLight& light, const float verticalGradient) { - return { - uniforms::matrix::Value( matrix ), - uniforms::opacity::Value( opacity ), - uniforms::lightcolor::Value( lightColor(light) ), - uniforms::lightpos::Value( lightPosition(light, state) ), - uniforms::lightintensity::Value( lightIntensity(light) ), - uniforms::vertical_gradient::Value( verticalGradient ) - }; +FillExtrusionProgram::LayoutUniformValues FillExtrusionProgram::layoutUniformValues(mat4 matrix, + const TransformState& state, + const float opacity, + const EvaluatedLight& light, + const float verticalGradient) { + return {uniforms::matrix::Value(matrix), + uniforms::opacity::Value(opacity), + uniforms::lightcolor::Value(lightColor(light)), + uniforms::lightpos::Value(lightPosition(light, state)), + uniforms::lightintensity::Value(lightIntensity(light)), + uniforms::vertical_gradient::Value(verticalGradient)}; } -FillExtrusionPatternProgram::LayoutUniformValues -FillExtrusionPatternProgram::layoutUniformValues(mat4 matrix, - Size atlasSize, - const CrossfadeParameters& crossfade, - const UnwrappedTileID& tileID, - const TransformState& state, - const float opacity, - const float heightFactor, - const float pixelRatio, - const EvaluatedLight& light, - const float verticalGradient) { +FillExtrusionPatternProgram::LayoutUniformValues FillExtrusionPatternProgram::layoutUniformValues( + mat4 matrix, + Size atlasSize, + const CrossfadeParameters& crossfade, + const UnwrappedTileID& tileID, + const TransformState& state, + const float opacity, + const float heightFactor, + const float pixelRatio, + const EvaluatedLight& light, + const float verticalGradient) { const auto tileRatio = 1 / tileID.pixelsToTileUnits(1, state.getIntegerZoom()); - int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); - int32_t pixelX = static_cast(tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); + int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * + state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); + int32_t pixelX = static_cast(tileSizeAtNearestZoom * + (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); int32_t pixelY = tileSizeAtNearestZoom * tileID.canonical.y; - return { - uniforms::matrix::Value( matrix ), - uniforms::opacity::Value( opacity ), - uniforms::scale::Value( {{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}} ), - uniforms::texsize::Value( atlasSize ), - uniforms::fade::Value( crossfade.t ), - uniforms::pixel_coord_upper::Value( std::array{{ static_cast(pixelX >> 16), static_cast(pixelY >> 16) }} ), - uniforms::pixel_coord_lower::Value( std::array{{ static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF) }} ), - uniforms::height_factor::Value( heightFactor ), - uniforms::lightcolor::Value( lightColor(light) ), - uniforms::lightpos::Value( lightPosition(light, state) ), - uniforms::lightintensity::Value( lightIntensity(light) ), - uniforms::vertical_gradient::Value( verticalGradient ) - }; + return {uniforms::matrix::Value(matrix), + uniforms::opacity::Value(opacity), + uniforms::scale::Value({{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}}), + uniforms::texsize::Value(atlasSize), + uniforms::fade::Value(crossfade.t), + uniforms::pixel_coord_upper::Value( + std::array{{static_cast(pixelX >> 16), static_cast(pixelY >> 16)}}), + uniforms::pixel_coord_lower::Value( + std::array{{static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}}), + uniforms::height_factor::Value(heightFactor), + uniforms::lightcolor::Value(lightColor(light)), + uniforms::lightpos::Value(lightPosition(light, state)), + uniforms::lightintensity::Value(lightIntensity(light)), + uniforms::vertical_gradient::Value(verticalGradient)}; } } // namespace mbgl diff --git a/src/mbgl/programs/fill_extrusion_program.hpp b/src/mbgl/programs/fill_extrusion_program.hpp index 82d24c0ac74..ee072631d28 100644 --- a/src/mbgl/programs/fill_extrusion_program.hpp +++ b/src/mbgl/programs/fill_extrusion_program.hpp @@ -18,98 +18,80 @@ namespace mbgl { class ImagePosition; class UnwrappedTileID; class TransformState; -template class Faded; +template +class Faded; namespace uniforms { MBGL_DEFINE_UNIFORM_VECTOR(float, 3, lightpos); MBGL_DEFINE_UNIFORM_VECTOR(float, 3, lightcolor); -MBGL_DEFINE_UNIFORM_SCALAR(float, lightintensity); -MBGL_DEFINE_UNIFORM_SCALAR(float, vertical_gradient); -MBGL_DEFINE_UNIFORM_SCALAR(float, height_factor); +MBGL_DEFINE_UNIFORM_SCALAR(float, lightintensity); +MBGL_DEFINE_UNIFORM_SCALAR(float, vertical_gradient); +MBGL_DEFINE_UNIFORM_SCALAR(float, height_factor); } // namespace uniforms -using FillExtrusionLayoutAttributes = TypeList< - attributes::pos, - attributes::normal_ed>; - -using FillExtrusionUniforms = TypeList< - uniforms::matrix, - uniforms::opacity, - uniforms::lightcolor, - uniforms::lightpos, - uniforms::lightintensity, - uniforms::vertical_gradient>; - -using FillExtrusionPatternUniforms = TypeList< - uniforms::matrix, - uniforms::opacity, - uniforms::scale, - uniforms::texsize, - uniforms::fade, - uniforms::pixel_coord_upper, - uniforms::pixel_coord_lower, - uniforms::height_factor, - uniforms::lightcolor, - uniforms::lightpos, - uniforms::lightintensity, - uniforms::vertical_gradient>; - -class FillExtrusionProgram final : public Program< - FillExtrusionProgram, - shaders::BuiltIn::FillExtrusionProgram, - gfx::PrimitiveType::Triangle, - FillExtrusionLayoutAttributes, - FillExtrusionUniforms, - TypeList<>, - style::FillExtrusionPaintProperties> -{ +using FillExtrusionLayoutAttributes = TypeList; + +using FillExtrusionUniforms = TypeList; + +using FillExtrusionPatternUniforms = TypeList; + +class FillExtrusionProgram final : public Program, + style::FillExtrusionPaintProperties> { public: static constexpr std::string_view Name{"FillExtrusionProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, double nx, double ny, double nz, unsigned short t, uint16_t e) { const auto factor = pow(2, 13); - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - // Multiply normal vector components by 2^14 to pack them into integers - // We pack a bool (`t`) into the x component indicating whether it is an upper or lower vertex - static_cast(floor(nx * factor) * 2 + t), - static_cast(ny * factor * 2), - static_cast(nz * factor * 2), - // The edgedistance attribute is used for wrapping fill_extrusion patterns - static_cast(e) - }} - }; + return LayoutVertex{{{p.x, p.y}}, + {{// Multiply normal vector components by 2^14 to pack them into + // integers We pack a bool (`t`) into the x component indicating + // whether it is an upper or lower vertex + static_cast(floor(nx * factor) * 2 + t), + static_cast(ny * factor * 2), + static_cast(nz * factor * 2), + // The edgedistance attribute is used for wrapping fill_extrusion patterns + static_cast(e)}}}; } static LayoutUniformValues layoutUniformValues( mat4, const TransformState&, float opacity, const EvaluatedLight&, float verticalGradient); }; -class FillExtrusionPatternProgram final : public Program< - FillExtrusionPatternProgram, - shaders::BuiltIn::FillExtrusionPatternProgram, - gfx::PrimitiveType::Triangle, - FillExtrusionLayoutAttributes, - FillExtrusionPatternUniforms, - TypeList< - textures::image>, - style::FillExtrusionPaintProperties> -{ +class FillExtrusionPatternProgram final : public Program, + style::FillExtrusionPaintProperties> { public: static constexpr std::string_view Name{"FillExtrusionPatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; diff --git a/src/mbgl/programs/fill_program.cpp b/src/mbgl/programs/fill_program.cpp index 51fb376cb7e..a6578e12a4d 100644 --- a/src/mbgl/programs/fill_program.cpp +++ b/src/mbgl/programs/fill_program.cpp @@ -10,28 +10,29 @@ using namespace style; static_assert(sizeof(FillLayoutVertex) == 4, "expected FillLayoutVertex size"); -FillPatternProgram::LayoutUniformValues -FillPatternProgram::layoutUniformValues(mat4 matrix, - Size framebufferSize, - Size atlasSize, - const CrossfadeParameters& crossfade, - const UnwrappedTileID& tileID, - const TransformState& state, - const float pixelRatio) { +FillPatternProgram::LayoutUniformValues FillPatternProgram::layoutUniformValues(mat4 matrix, + Size framebufferSize, + Size atlasSize, + const CrossfadeParameters& crossfade, + const UnwrappedTileID& tileID, + const TransformState& state, + const float pixelRatio) { const auto tileRatio = 1 / tileID.pixelsToTileUnits(1, state.getIntegerZoom()); - int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); - int32_t pixelX = static_cast(tileSizeAtNearestZoom * (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); + int32_t tileSizeAtNearestZoom = static_cast(util::tileSize_D * + state.zoomScale(state.getIntegerZoom() - tileID.canonical.z)); + int32_t pixelX = static_cast(tileSizeAtNearestZoom * + (tileID.canonical.x + tileID.wrap * state.zoomScale(tileID.canonical.z))); int32_t pixelY = tileSizeAtNearestZoom * tileID.canonical.y; - return { - uniforms::matrix::Value( matrix ), - uniforms::world::Value( framebufferSize ), - uniforms::texsize::Value( atlasSize ), - uniforms::scale::Value({ {pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale} } ), - uniforms::fade::Value( crossfade.t ), - uniforms::pixel_coord_upper::Value( std::array {{ static_cast(pixelX >> 16), static_cast(pixelY >> 16) }}), - uniforms::pixel_coord_lower::Value( std::array {{ static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF) }} ) - }; + return {uniforms::matrix::Value(matrix), + uniforms::world::Value(framebufferSize), + uniforms::texsize::Value(atlasSize), + uniforms::scale::Value({{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}}), + uniforms::fade::Value(crossfade.t), + uniforms::pixel_coord_upper::Value( + std::array{{static_cast(pixelX >> 16), static_cast(pixelY >> 16)}}), + uniforms::pixel_coord_lower::Value( + std::array{{static_cast(pixelX & 0xFFFF), static_cast(pixelY & 0xFFFF)}})}; } } // namespace mbgl diff --git a/src/mbgl/programs/fill_program.hpp b/src/mbgl/programs/fill_program.hpp index 0064b533dab..aee0e15c1fc 100644 --- a/src/mbgl/programs/fill_program.hpp +++ b/src/mbgl/programs/fill_program.hpp @@ -16,65 +16,47 @@ namespace mbgl { class ImagePosition; class UnwrappedTileID; class TransformState; -template class Faded; +template +class Faded; using FillLayoutAttributes = PositionOnlyLayoutAttributes; -using FillUniforms = TypeList< - uniforms::matrix, - uniforms::world>; - -using FillPatternUniforms = TypeList< - uniforms::matrix, - uniforms::world, - uniforms::texsize, - uniforms::scale, - uniforms::fade, - uniforms::pixel_coord_upper, - uniforms::pixel_coord_lower>; - -class FillProgram final : public Program< - FillProgram, - shaders::BuiltIn::FillProgram, - gfx::PrimitiveType::Triangle, - FillLayoutAttributes, - FillUniforms, - TypeList<>, - style::FillPaintProperties> -{ +using FillUniforms = TypeList; + +using FillPatternUniforms = TypeList; + +class FillProgram final : public Program, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutVertex layoutVertex(Point p) { - return LayoutVertex { - {{ - p.x, - p.y - }} - }; - } + static LayoutVertex layoutVertex(Point p) { return LayoutVertex{{{p.x, p.y}}}; } }; -class FillPatternProgram final : public Program< - FillPatternProgram, - shaders::BuiltIn::FillPatternProgram, - gfx::PrimitiveType::Triangle, - FillLayoutAttributes, - FillPatternUniforms, - TypeList< - textures::image>, - style::FillPaintProperties> -{ +class FillPatternProgram final : public Program, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillPatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -87,39 +69,30 @@ class FillPatternProgram final : public Program< float pixelRatio); }; -class FillOutlineProgram final : public Program< - FillOutlineProgram, - shaders::BuiltIn::FillOutlineProgram, - gfx::PrimitiveType::Line, - FillLayoutAttributes, - FillUniforms, - TypeList<>, - style::FillPaintProperties> -{ +class FillOutlineProgram final : public Program, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillOutlineProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; -class FillOutlinePatternProgram final : public Program< - FillOutlinePatternProgram, - shaders::BuiltIn::FillOutlinePatternProgram, - gfx::PrimitiveType::Line, - FillLayoutAttributes, - FillPatternUniforms, - TypeList< - textures::image>, - style::FillPaintProperties> -{ +class FillOutlinePatternProgram final : public Program, + style::FillPaintProperties> { public: static constexpr std::string_view Name{"FillOutlinePatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; }; diff --git a/src/mbgl/programs/heatmap_program.hpp b/src/mbgl/programs/heatmap_program.hpp index 805a663298f..6404e9c9437 100644 --- a/src/mbgl/programs/heatmap_program.hpp +++ b/src/mbgl/programs/heatmap_program.hpp @@ -13,24 +13,17 @@ namespace uniforms { MBGL_DEFINE_UNIFORM_SCALAR(float, intensity); } // namespace uniforms -class HeatmapProgram final : public Program< - HeatmapProgram, - shaders::BuiltIn::HeatmapProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos>, - TypeList< - uniforms::intensity, - uniforms::matrix, - uniforms::heatmap::extrude_scale>, - TypeList<>, - style::HeatmapPaintProperties> -{ +class HeatmapProgram final + : public Program, + TypeList, + TypeList<>, + style::HeatmapPaintProperties> { public: static constexpr std::string_view Name{"HeatmapProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -41,12 +34,8 @@ class HeatmapProgram final : public Program< * @param {number} ey extrude normal */ static LayoutVertex vertex(Point p, float ex, float ey) { - return LayoutVertex { - {{ - static_cast((p.x * 2) + ((ex + 1) / 2)), - static_cast((p.y * 2) + ((ey + 1) / 2)) - }} - }; + return LayoutVertex{ + {{static_cast((p.x * 2) + ((ex + 1) / 2)), static_cast((p.y * 2) + ((ey + 1) / 2))}}}; } }; diff --git a/src/mbgl/programs/heatmap_texture_program.hpp b/src/mbgl/programs/heatmap_texture_program.hpp index e3c55d17593..9bce2240f7b 100644 --- a/src/mbgl/programs/heatmap_texture_program.hpp +++ b/src/mbgl/programs/heatmap_texture_program.hpp @@ -9,35 +9,20 @@ namespace mbgl { -class HeatmapTextureProgram final : public Program< - HeatmapTextureProgram, - shaders::BuiltIn::HeatmapTextureProgram, - gfx::PrimitiveType::Triangle, - TypeList, - TypeList< - uniforms::matrix, - uniforms::world, - uniforms::opacity>, - TypeList< - textures::image, - textures::color_ramp>, - style::Properties<>> { +class HeatmapTextureProgram final : public Program, + TypeList, + TypeList, + style::Properties<>> { public: static constexpr std::string_view Name{"HeatmapTextureProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutVertex layoutVertex(Point p) { - return LayoutVertex{ - {{ - p.x, - p.y - }} - }; - } + static LayoutVertex layoutVertex(Point p) { return LayoutVertex{{{p.x, p.y}}}; } }; using HeatmapTextureLayoutVertex = HeatmapTextureProgram::LayoutVertex; diff --git a/src/mbgl/programs/hillshade_prepare_program.hpp b/src/mbgl/programs/hillshade_prepare_program.hpp index beb39088753..ef9d8aa4270 100644 --- a/src/mbgl/programs/hillshade_prepare_program.hpp +++ b/src/mbgl/programs/hillshade_prepare_program.hpp @@ -14,41 +14,23 @@ MBGL_DEFINE_UNIFORM_SCALAR(float, maxzoom); MBGL_DEFINE_UNIFORM_VECTOR(float, 4, unpack); } // namespace uniforms -class HillshadePrepareProgram final : public Program< - HillshadePrepareProgram, - shaders::BuiltIn::HillshadePrepareProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos, - attributes::texture_pos>, - TypeList< - uniforms::matrix, - uniforms::dimension, - uniforms::zoom, - uniforms::maxzoom, - uniforms::unpack>, - TypeList< - textures::image>, - style::Properties<>> { +class HillshadePrepareProgram final + : public Program< + HillshadePrepareProgram, + shaders::BuiltIn::HillshadePrepareProgram, + gfx::PrimitiveType::Triangle, + TypeList, + TypeList, + TypeList, + style::Properties<>> { public: static constexpr std::string_view Name{"HillshadePrepareProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, Point t) { - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - t.x, - t.y - }} - }; + return LayoutVertex{{{p.x, p.y}}, {{t.x, t.y}}}; } }; diff --git a/src/mbgl/programs/hillshade_program.hpp b/src/mbgl/programs/hillshade_program.hpp index 5b4de3d3597..f888196366a 100644 --- a/src/mbgl/programs/hillshade_program.hpp +++ b/src/mbgl/programs/hillshade_program.hpp @@ -18,42 +18,26 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, light); MBGL_DEFINE_UNIFORM_VECTOR(float, 2, latrange); } // namespace uniforms -class HillshadeProgram final : public Program< - HillshadeProgram, - shaders::BuiltIn::HillshadeProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos, - attributes::texture_pos>, - TypeList< - uniforms::matrix, - uniforms::highlight, - uniforms::shadow, - uniforms::accent, - uniforms::light, - uniforms::latrange>, - TypeList< - textures::image>, - style::HillshadePaintProperties>{ +class HillshadeProgram final : public Program, + TypeList, + TypeList, + style::HillshadePaintProperties> { public: static constexpr std::string_view Name{"HillshadeProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, Point t) { - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - t.x, - t.y - }} - }; + return LayoutVertex{{{p.x, p.y}}, {{t.x, t.y}}}; } }; diff --git a/src/mbgl/programs/line_program.cpp b/src/mbgl/programs/line_program.cpp index a72e4765f74..17c7467864c 100644 --- a/src/mbgl/programs/line_program.cpp +++ b/src/mbgl/programs/line_program.cpp @@ -12,64 +12,48 @@ using namespace style; static_assert(sizeof(LineLayoutVertex) == 8, "expected LineLayoutVertex size"); -template +template Values makeValues(const style::LinePaintProperties::PossiblyEvaluated& properties, const RenderTile& tile, const TransformState& state, const std::array& pixelsToGLUnits, const float pixelRatio, Args&&... args) { - - return Values { - uniforms::matrix::Value( - tile.translatedMatrix(properties.get(), - properties.get(), - state) - ), - uniforms::ratio::Value( 1.0f / tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())) ), - uniforms::units_to_pixels::Value({ {1.0f / pixelsToGLUnits[0], 1.0f / pixelsToGLUnits[1]} }), - uniforms::device_pixel_ratio::Value( pixelRatio ), - std::forward(args)... - }; + return Values{uniforms::matrix::Value(tile.translatedMatrix( + properties.get(), properties.get(), state)), + uniforms::ratio::Value(1.0f / tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom()))), + uniforms::units_to_pixels::Value({{1.0f / pixelsToGLUnits[0], 1.0f / pixelsToGLUnits[1]}}), + uniforms::device_pixel_ratio::Value(pixelRatio), + std::forward(args)...}; } -LineProgram::LayoutUniformValues -LineProgram::layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated& properties, - const RenderTile& tile, - const TransformState& state, - const std::array& pixelsToGLUnits, - const float pixelRatio) { - return makeValues( - properties, - tile, - state, - pixelsToGLUnits, - pixelRatio - ); +LineProgram::LayoutUniformValues LineProgram::layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated& properties, + const RenderTile& tile, + const TransformState& state, + const std::array& pixelsToGLUnits, + const float pixelRatio) { + return makeValues(properties, tile, state, pixelsToGLUnits, pixelRatio); } -LineSDFProgram::LayoutUniformValues -LineSDFProgram::layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated& properties, - float pixelRatio, - const RenderTile& tile, - const TransformState& state, - const std::array& pixelsToGLUnits, - const LinePatternPos& posA, - const LinePatternPos& posB, - const CrossfadeParameters& crossfade, - float atlasWidth) { +LineSDFProgram::LayoutUniformValues LineSDFProgram::layoutUniformValues( + const style::LinePaintProperties::PossiblyEvaluated& properties, + float pixelRatio, + const RenderTile& tile, + const TransformState& state, + const std::array& pixelsToGLUnits, + const LinePatternPos& posA, + const LinePatternPos& posB, + const CrossfadeParameters& crossfade, + float atlasWidth) { const float widthA = posA.width * crossfade.fromScale; const float widthB = posB.width * crossfade.toScale; - std::array scaleA {{ - 1.0f / tile.id.pixelsToTileUnits(widthA, state.getIntegerZoom()), - -posA.height / 2.0f - }}; + std::array scaleA{ + {1.0f / tile.id.pixelsToTileUnits(widthA, state.getIntegerZoom()), -posA.height / 2.0f}}; - std::array scaleB {{ - 1.0f / tile.id.pixelsToTileUnits(widthB, state.getIntegerZoom()), - -posB.height / 2.0f - }}; + std::array scaleB{ + {1.0f / tile.id.pixelsToTileUnits(widthB, state.getIntegerZoom()), -posB.height / 2.0f}}; return makeValues( properties, @@ -77,13 +61,12 @@ LineSDFProgram::layoutUniformValues(const style::LinePaintProperties::PossiblyEv state, pixelsToGLUnits, pixelRatio, - uniforms::patternscale_a::Value( scaleA ), - uniforms::patternscale_b::Value( scaleB ), - uniforms::tex_y_a::Value( posA.y ), - uniforms::tex_y_b::Value( posB.y ), - uniforms::mix::Value( crossfade.t ), - uniforms::sdfgamma::Value( atlasWidth / (std::min(widthA, widthB) * 256.0f * pixelRatio) / 2.0f ) - ); + uniforms::patternscale_a::Value(scaleA), + uniforms::patternscale_b::Value(scaleB), + uniforms::tex_y_a::Value(posA.y), + uniforms::tex_y_b::Value(posB.y), + uniforms::mix::Value(crossfade.t), + uniforms::sdfgamma::Value(atlasWidth / (std::min(widthA, widthB) * 256.0f * pixelRatio) / 2.0f)); } LinePatternProgram::LayoutUniformValues LinePatternProgram::layoutUniformValues( @@ -94,7 +77,6 @@ LinePatternProgram::LayoutUniformValues LinePatternProgram::layoutUniformValues( const float pixelRatio, const Size atlasSize, const CrossfadeParameters& crossfade) { - const auto tileRatio = 1 / tile.id.pixelsToTileUnits(1, state.getIntegerZoom()); return makeValues( @@ -103,10 +85,9 @@ LinePatternProgram::LayoutUniformValues LinePatternProgram::layoutUniformValues( state, pixelsToGLUnits, pixelRatio, - uniforms::scale::Value ({ {pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale} }), - uniforms::texsize::Value( atlasSize ), - uniforms::fade::Value( crossfade.t ) - ); + uniforms::scale::Value({{pixelRatio, tileRatio, crossfade.fromScale, crossfade.toScale}}), + uniforms::texsize::Value(atlasSize), + uniforms::fade::Value(crossfade.t)); } LineGradientProgram::LayoutUniformValues LineGradientProgram::layoutUniformValues( @@ -115,13 +96,7 @@ LineGradientProgram::LayoutUniformValues LineGradientProgram::layoutUniformValue const TransformState& state, const std::array& pixelsToGLUnits, const float pixelRatio) { - return makeValues( - properties, - tile, - state, - pixelsToGLUnits, - pixelRatio - ); + return makeValues(properties, tile, state, pixelsToGLUnits, pixelRatio); } } // namespace mbgl diff --git a/src/mbgl/programs/line_program.hpp b/src/mbgl/programs/line_program.hpp index 59b550de850..198cac40ece 100644 --- a/src/mbgl/programs/line_program.hpp +++ b/src/mbgl/programs/line_program.hpp @@ -26,28 +26,20 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, patternscale_b); MBGL_DEFINE_UNIFORM_VECTOR(float, 2, units_to_pixels); } // namespace uniforms -using LineLayoutAttributes = TypeList< - attributes::pos_normal, - attributes::data>; - -class LineProgram final : public Program< - LineProgram, - shaders::BuiltIn::LineProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio>, - TypeList<>, - style::LinePaintProperties> -{ +using LineLayoutAttributes = TypeList>; + +class LineProgram final + : public Program< + LineProgram, + shaders::BuiltIn::LineProgram, + gfx::PrimitiveType::Triangle, + LineLayoutAttributes, + TypeList, + TypeList<>, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LineProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -58,39 +50,36 @@ class LineProgram final : public Program< * @param up whether the line normal points up or down * @param dir direction of the line cap (-1/0/1) */ - static LayoutVertex layoutVertex(Point p, Point e, bool round, bool up, int8_t dir, int32_t linesofar = 0) { - return LayoutVertex { - {{ - static_cast((p.x * 2) | (round ? 1 : 0)), - static_cast((p.y * 2) | (up ? 1 : 0)) - }}, - {{ - // add 128 to store a byte in an unsigned byte - static_cast(::round(extrudeScale * e.x) + 128), - static_cast(::round(extrudeScale * e.y) + 128), - - // Encode the -1/0/1 direction value into the first two bits of .z of a_data. - // Combine it with the lower 6 bits of `linesofar` (shifted by 2 bites to make - // room for the direction value). The upper 8 bits of `linesofar` are placed in - // the `w` component. `linesofar` is scaled down by `LINE_DISTANCE_SCALE` so that - // we can store longer distances while sacrificing precision. - - // Encode the -1/0/1 direction value into .zw coordinates of a_data, which is normally covered - // by linesofar, so we need to merge them. - // The z component's first bit, as well as the sign bit is reserved for the direction, - // so we need to shift the linesofar. - static_cast(((dir == 0 ? 0 : (dir < 0 ? -1 : 1 )) + 1) | ((linesofar & 0x3F) << 2)), - static_cast(linesofar >> 6) - }} - }; + static LayoutVertex layoutVertex( + Point p, Point e, bool round, bool up, int8_t dir, int32_t linesofar = 0) { + return LayoutVertex{ + {{static_cast((p.x * 2) | (round ? 1 : 0)), static_cast((p.y * 2) | (up ? 1 : 0))}}, + {{// add 128 to store a byte in an unsigned byte + static_cast(::round(extrudeScale * e.x) + 128), + static_cast(::round(extrudeScale * e.y) + 128), + + // Encode the -1/0/1 direction value into the first two bits of .z + // of a_data. Combine it with the lower 6 bits of `linesofar` + // (shifted by 2 bites to make room for the direction value). The + // upper 8 bits of `linesofar` are placed in the `w` component. + // `linesofar` is scaled down by `LINE_DISTANCE_SCALE` so that we + // can store longer distances while sacrificing precision. + + // Encode the -1/0/1 direction value into .zw coordinates of + // a_data, which is normally covered by linesofar, so we need to + // merge them. The z component's first bit, as well as the sign + // bit is reserved for the direction, so we need to shift the + // linesofar. + static_cast(((dir == 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofar & 0x3F) << 2)), + static_cast(linesofar >> 6)}}}; } /* * Scale the extrusion vector so that the normal length is this value. * Contains the "texture" normals (-1..1). This is distinct from the extrude * normals for line joins, because the x-value remains 0 for the texture - * normal array, while the extrude normal actually moves the vertex to create - * the acute/bevelled line join. + * normal array, while the extrude normal actually moves the vertex to + * create the acute/bevelled line join. */ static const int8_t extrudeScale = 63; @@ -101,28 +90,22 @@ class LineProgram final : public Program< float pixelRatio); }; -class LinePatternProgram final : public Program< - LinePatternProgram, - shaders::BuiltIn::LinePatternProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio, - uniforms::scale, - uniforms::texsize, - uniforms::fade>, - TypeList< - textures::image>, - style::LinePaintProperties> -{ +class LinePatternProgram final : public Program, + TypeList, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LinePatternProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; @@ -135,65 +118,51 @@ class LinePatternProgram final : public Program< const CrossfadeParameters& crossfade); }; -class LineSDFProgram final : public Program< - LineSDFProgram, - shaders::BuiltIn::LineSDFProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio, - uniforms::patternscale_a, - uniforms::patternscale_b, - uniforms::tex_y_a, - uniforms::tex_y_b, - uniforms::mix, - uniforms::sdfgamma>, - TypeList< - textures::image>, - style::LinePaintProperties> -{ +class LineSDFProgram final : public Program, + TypeList, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LineSDFProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; - static LayoutUniformValues - layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated&, - float pixelRatio, - const RenderTile&, - const TransformState&, - const std::array& pixelsToGLUnits, - const LinePatternPos& posA, - const LinePatternPos& posB, - const CrossfadeParameters& crossfade, - float atlasWidth); + static LayoutUniformValues layoutUniformValues(const style::LinePaintProperties::PossiblyEvaluated&, + float pixelRatio, + const RenderTile&, + const TransformState&, + const std::array& pixelsToGLUnits, + const LinePatternPos& posA, + const LinePatternPos& posB, + const CrossfadeParameters& crossfade, + float atlasWidth); }; -class LineGradientProgram final : public Program< - LineGradientProgram, - shaders::BuiltIn::LineGradientProgram, - gfx::PrimitiveType::Triangle, - LineLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::ratio, - uniforms::units_to_pixels, - uniforms::device_pixel_ratio>, - TypeList< - textures::image>, - style::LinePaintProperties> -{ +class LineGradientProgram final + : public Program< + LineGradientProgram, + shaders::BuiltIn::LineGradientProgram, + gfx::PrimitiveType::Triangle, + LineLayoutAttributes, + TypeList, + TypeList, + style::LinePaintProperties> { public: static constexpr std::string_view Name{"LineGradientProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; diff --git a/src/mbgl/programs/program.hpp b/src/mbgl/programs/program.hpp index 1e312f1bf8c..ceb94c5962a 100644 --- a/src/mbgl/programs/program.hpp +++ b/src/mbgl/programs/program.hpp @@ -56,12 +56,10 @@ class Program : public gfx::Shader { switch (gfx::Backend::GetType()) { #ifdef MBGL_RENDER_BACKEND_OPENGL case gfx::Backend::Type::OpenGL: { - program = std::make_unique>(programParameters - .withDefaultSource({ - gfx::Backend::Type::OpenGL, - shaders::ShaderSource::vertex, - shaders::ShaderSource::fragment - })); + program = std::make_unique>(programParameters.withDefaultSource( + {gfx::Backend::Type::OpenGL, + shaders::ShaderSource::vertex, + shaders::ShaderSource::fragment})); break; } #endif @@ -71,13 +69,11 @@ class Program : public gfx::Shader { } } - static UniformValues computeAllUniformValues( - const LayoutUniformValues& layoutUniformValues, - const Binders& paintPropertyBinders, - const typename PaintProperties::PossiblyEvaluated& currentProperties, - float currentZoom) { - return layoutUniformValues - .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); + static UniformValues computeAllUniformValues(const LayoutUniformValues& layoutUniformValues, + const Binders& paintPropertyBinders, + const typename PaintProperties::PossiblyEvaluated& currentProperties, + float currentZoom) { + return layoutUniformValues.concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); } static AttributeBindings computeAllAttributeBindings( @@ -160,21 +156,20 @@ class Program : public gfx::Shader { drawScopeIt = segment.drawScopes.emplace(layerID, context.createDrawScope()).first; } - program->draw( - context, - renderPass, - drawMode, - depthMode, - stencilMode, - colorMode, - cullFaceMode, - uniformValues, - drawScopeIt->second, - allAttributeBindings.offset(segment.vertexOffset), - textureBindings, - indexBuffer, - segment.indexOffset, - segment.indexLength); + program->draw(context, + renderPass, + drawMode, + depthMode, + stencilMode, + colorMode, + cullFaceMode, + uniformValues, + drawScopeIt->second, + allAttributeBindings.offset(segment.vertexOffset), + textureBindings, + indexBuffer, + segment.indexOffset, + segment.indexLength); } } }; diff --git a/src/mbgl/programs/program_parameters.cpp b/src/mbgl/programs/program_parameters.cpp index 28f10ecca4d..7ff1cc3bcc9 100644 --- a/src/mbgl/programs/program_parameters.cpp +++ b/src/mbgl/programs/program_parameters.cpp @@ -5,40 +5,32 @@ namespace mbgl { -ProgramParameters::ProgramParameters(const float pixelRatio, - const bool overdraw) +ProgramParameters::ProgramParameters(const float pixelRatio, const bool overdraw) : defines([&] { - std::string result; - result.reserve(32); - result += "#define DEVICE_PIXEL_RATIO "; - result += util::toString(pixelRatio, true); - result += '\n'; - if (overdraw) { - result += "#define OVERDRAW_INSPECTOR\n"; - } - return result; - }()) -{} + std::string result; + result.reserve(32); + result += "#define DEVICE_PIXEL_RATIO "; + result += util::toString(pixelRatio, true); + result += '\n'; + if (overdraw) { + result += "#define OVERDRAW_INSPECTOR\n"; + } + return result; + }()) {} -ProgramParameters ProgramParameters::withShaderSource( - const ProgramSource &source) const noexcept -{ +ProgramParameters ProgramParameters::withShaderSource(const ProgramSource& source) const noexcept { assert(gfx::Backend::Type::TYPE_MAX != source.backend); ProgramParameters params = *this; - params.userSources[static_cast(source.backend)] - = source; + params.userSources[static_cast(source.backend)] = source; return params; } -ProgramParameters ProgramParameters::withDefaultSource( - const ProgramSource &source) const noexcept -{ +ProgramParameters ProgramParameters::withDefaultSource(const ProgramSource& source) const noexcept { assert(gfx::Backend::Type::TYPE_MAX != source.backend); ProgramParameters params = *this; - params.defaultSources[static_cast(source.backend)] - = source; + params.defaultSources[static_cast(source.backend)] = source; return params; } @@ -46,8 +38,7 @@ const std::string& ProgramParameters::getDefines() const { return defines; } -const std::string& -ProgramParameters::vertexSource(gfx::Backend::Type backend) const { +const std::string& ProgramParameters::vertexSource(gfx::Backend::Type backend) const { assert(gfx::Backend::Type::TYPE_MAX != backend); if (userSources[static_cast(backend)].vertex.length() > 0) { @@ -59,8 +50,7 @@ ProgramParameters::vertexSource(gfx::Backend::Type backend) const { } } -const std::string& -ProgramParameters::fragmentSource(gfx::Backend::Type backend) const { +const std::string& ProgramParameters::fragmentSource(gfx::Backend::Type backend) const { assert(gfx::Backend::Type::TYPE_MAX != backend); if (userSources[static_cast(backend)].fragment.length() > 0) { diff --git a/src/mbgl/programs/program_parameters.hpp b/src/mbgl/programs/program_parameters.hpp index 01c40766b44..3bd165132a5 100644 --- a/src/mbgl/programs/program_parameters.hpp +++ b/src/mbgl/programs/program_parameters.hpp @@ -9,61 +9,59 @@ namespace mbgl { class ProgramParameters { - public: - struct ProgramSource { - gfx::Backend::Type backend{gfx::Backend::Type::TYPE_MAX}; - std::string vertex; - std::string fragment; +public: + struct ProgramSource { + gfx::Backend::Type backend{gfx::Backend::Type::TYPE_MAX}; + std::string vertex; + std::string fragment; - ProgramSource() = default; + ProgramSource() = default; - /// @brief Construct a new ProgramSource object - /// @param forBackend The provided source code is intended for use with the give - /// rendering backend. - /// @param vertex_ The vertex shader source code, or empty string if not provided. - /// @param fragment_ The fragment shader source code, or empty string if not provided. - ProgramSource(gfx::Backend::Type forBackend, const std::string& vertex_, - const std::string& fragment_) - : backend(forBackend), vertex(vertex_), fragment(fragment_) - { - assert(gfx::Backend::Type::TYPE_MAX != forBackend); - } - }; + /// @brief Construct a new ProgramSource object + /// @param forBackend The provided source code is intended for use with the give + /// rendering backend. + /// @param vertex_ The vertex shader source code, or empty string if not provided. + /// @param fragment_ The fragment shader source code, or empty string if not provided. + ProgramSource(gfx::Backend::Type forBackend, const std::string& vertex_, const std::string& fragment_) + : backend(forBackend), + vertex(vertex_), + fragment(fragment_) { + assert(gfx::Backend::Type::TYPE_MAX != forBackend); + } + }; - ProgramParameters(float pixelRatio, bool overdraw); - - /// @brief Provide custom shader code which overrides any default source present - /// @param source ProgramSource - /// @return Mutated ProgramParameters - ProgramParameters withShaderSource(const ProgramSource& source) const noexcept; + ProgramParameters(float pixelRatio, bool overdraw); - /// @brief Provide default shader source - /// @param source ProgramSource - /// @return Mutated ProgramParameters - ProgramParameters withDefaultSource(const ProgramSource& source) const noexcept; + /// @brief Provide custom shader code which overrides any default source present + /// @param source ProgramSource + /// @return Mutated ProgramParameters + ProgramParameters withShaderSource(const ProgramSource& source) const noexcept; - /// @brief Get a list of built-in shader preprocessor defines - /// @return Shader source string - /// @todo With the addition of future backends, defines should also be backend-aware - const std::string& getDefines() const; + /// @brief Provide default shader source + /// @param source ProgramSource + /// @return Mutated ProgramParameters + ProgramParameters withDefaultSource(const ProgramSource& source) const noexcept; - /// @brief Get source code for the vertex shader compatible with the requested backend - /// @param backend Backend type - /// @return Shader source string - const std::string& vertexSource(gfx::Backend::Type backend) const; + /// @brief Get a list of built-in shader preprocessor defines + /// @return Shader source string + /// @todo With the addition of future backends, defines should also be backend-aware + const std::string& getDefines() const; - /// @brief Get source code for the fragment shader compatible with the requested backend - /// @param backend Backend type - /// @return Shader source string - const std::string& fragmentSource(gfx::Backend::Type backend) const; + /// @brief Get source code for the vertex shader compatible with the requested backend + /// @param backend Backend type + /// @return Shader source string + const std::string& vertexSource(gfx::Backend::Type backend) const; - private: - std::string defines; + /// @brief Get source code for the fragment shader compatible with the requested backend + /// @param backend Backend type + /// @return Shader source string + const std::string& fragmentSource(gfx::Backend::Type backend) const; - std::array(gfx::Backend::Type::TYPE_MAX)> - defaultSources; - std::array(gfx::Backend::Type::TYPE_MAX)> - userSources; +private: + std::string defines; + + std::array(gfx::Backend::Type::TYPE_MAX)> defaultSources; + std::array(gfx::Backend::Type::TYPE_MAX)> userSources; }; } // namespace mbgl diff --git a/src/mbgl/programs/programs.cpp b/src/mbgl/programs/programs.cpp index 8d2035cdcc8..a6cb91ed63a 100644 --- a/src/mbgl/programs/programs.cpp +++ b/src/mbgl/programs/programs.cpp @@ -24,57 +24,51 @@ Programs::~Programs() = default; /// @tparam ...T Type list parameter pack /// @param registry A shader registry instance /// programParameters_ ProgramParameters used to initialize each instance -template -void registerTypes(gfx::ShaderRegistry& registry, - const ProgramParameters& programParameters_) -{ +template +void registerTypes(gfx::ShaderRegistry& registry, const ProgramParameters& programParameters_) { /// The following fold expression will create a shared_ptr for every type /// in the parameter pack and register it with the shader registry. /// Registration calls are wrapped in a lambda that throws on registration /// failure, we shouldn't expect registration to faill unless the shader /// registry instance provided already has conflicting programs present. - ( [](bool expr) { - if (!expr) { - throw std::runtime_error( - "Failed to register " + - std::string(T::Name) + - " with shader registry!"); - } - }( registry.registerShader( - std::make_shared(programParameters_))), ... ); + ( + [](bool expr) { + if (!expr) { + throw std::runtime_error("Failed to register " + std::string(T::Name) + " with shader registry!"); + } + }(registry.registerShader(std::make_shared(programParameters_))), + ...); } void Programs::registerWith(gfx::ShaderRegistry& registry) { /// The following types will be registered - registerTypes< - BackgroundProgram, - BackgroundPatternProgram, - RasterProgram, - HeatmapProgram, - HeatmapTextureProgram, - HillshadeProgram, - HillshadePrepareProgram, - FillProgram, - FillPatternProgram, - FillOutlineProgram, - FillOutlinePatternProgram, - FillExtrusionProgram, - FillExtrusionPatternProgram, - CircleProgram, - LineProgram, - LineGradientProgram, - LineSDFProgram, - LinePatternProgram, - SymbolIconProgram, - SymbolSDFIconProgram, - SymbolSDFTextProgram, - SymbolTextAndIconProgram, - CollisionBoxProgram, - CollisionCircleProgram, - DebugProgram, - ClippingMaskProgram - >(registry, programParameters); + registerTypes(registry, programParameters); } } // namespace mbgl diff --git a/src/mbgl/programs/raster_program.hpp b/src/mbgl/programs/raster_program.hpp index 434fe57a8e0..491ad3f8354 100644 --- a/src/mbgl/programs/raster_program.hpp +++ b/src/mbgl/programs/raster_program.hpp @@ -21,49 +21,31 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 3, spin_weights); MBGL_DEFINE_UNIFORM_VECTOR(float, 2, tl_parent); } // namespace uniforms -class RasterProgram final : public Program< - RasterProgram, - shaders::BuiltIn::RasterProgram, - gfx::PrimitiveType::Triangle, - TypeList< - attributes::pos, - attributes::texture_pos>, - TypeList< - uniforms::matrix, - uniforms::opacity, - uniforms::fade_t, - uniforms::brightness_low, - uniforms::brightness_high, - uniforms::saturation_factor, - uniforms::contrast_factor, - uniforms::spin_weights, - uniforms::buffer_scale, - uniforms::scale_parent, - uniforms::tl_parent>, - TypeList< - textures::image0, - textures::image1>, - style::RasterPaintProperties> -{ +class RasterProgram final : public Program, + TypeList, + TypeList, + style::RasterPaintProperties> { public: static constexpr std::string_view Name{"RasterProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using Program::Program; static LayoutVertex layoutVertex(Point p, Point t) { - return LayoutVertex { - {{ - p.x, - p.y - }}, - {{ - t.x, - t.y - }} - }; + return LayoutVertex{{{p.x, p.y}}, {{t.x, t.y}}}; } }; diff --git a/src/mbgl/programs/segment.hpp b/src/mbgl/programs/segment.hpp index c263511f501..d5410623d6a 100644 --- a/src/mbgl/programs/segment.hpp +++ b/src/mbgl/programs/segment.hpp @@ -37,8 +37,8 @@ class Segment { std::size_t indexLength; // One DrawScope per layer ID. This minimizes rebinding in cases where - // several layers share buckets but have different sets of active attributes. - // This can happen: + // several layers share buckets but have different sets of active + // attributes. This can happen: // * when two layers have the same layout properties, but differing // data-driven paint properties // * when two fill layers have the same layout properties, but one diff --git a/src/mbgl/programs/symbol_program.cpp b/src/mbgl/programs/symbol_program.cpp index 76c266f039c..52037f8c01c 100644 --- a/src/mbgl/programs/symbol_program.cpp +++ b/src/mbgl/programs/symbol_program.cpp @@ -14,16 +14,16 @@ using namespace style; static_assert(sizeof(SymbolLayoutVertex) == 24, "expected SymbolLayoutVertex size"); std::unique_ptr SymbolSizeBinder::create(const float tileZoom, - const style::PropertyValue& sizeProperty, - const float defaultValue) { + const style::PropertyValue& sizeProperty, + const float defaultValue) { return sizeProperty.match( - [&] (const Undefined& value) -> std::unique_ptr { + [&](const Undefined& value) -> std::unique_ptr { return std::make_unique(tileZoom, value, defaultValue); }, - [&] (float value) -> std::unique_ptr { + [&](float value) -> std::unique_ptr { return std::make_unique(tileZoom, value, defaultValue); }, - [&] (const style::PropertyExpression& expression) -> std::unique_ptr { + [&](const style::PropertyExpression& expression) -> std::unique_ptr { if (expression.isFeatureConstant()) { return std::make_unique(tileZoom, expression, defaultValue); } else if (expression.isZoomConstant()) { @@ -31,11 +31,10 @@ std::unique_ptr SymbolSizeBinder::create(const float tileZoom, } else { return std::make_unique(tileZoom, expression, defaultValue); } - } - ); + }); } -template +template Values makeValues(const bool isText, const bool hasVariablePacement, const style::SymbolPropertyValues& values, @@ -51,10 +50,8 @@ Values makeValues(const bool isText, if (values.pitchAlignment == AlignmentType::Map) { extrudeScale.fill(tile.id.pixelsToTileUnits(1.f, static_cast(state.getZoom()))); } else { - extrudeScale = {{ - pixelsToGLUnits[0] * state.getCameraToCenterDistance(), - pixelsToGLUnits[1] * state.getCameraToCenterDistance() - }}; + extrudeScale = {{pixelsToGLUnits[0] * state.getCameraToCenterDistance(), + pixelsToGLUnits[1] * state.getCameraToCenterDistance()}}; } const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.f, static_cast(state.getZoom())); @@ -68,8 +65,9 @@ Values makeValues(const bool isText, mat4 labelPlaneMatrix; if (alongLine || hasVariablePacement) { - // For labels that follow lines the first part of the projection is handled on the cpu. - // Pass an identity matrix because no transformation needs to be done in the vertex shader. + // For labels that follow lines the first part of the projection is + // handled on the cpu. Pass an identity matrix because no transformation + // needs to be done in the vertex shader. matrix::identity(labelPlaneMatrix); } else { labelPlaneMatrix = getLabelPlaneMatrix(tile.matrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); @@ -77,68 +75,52 @@ Values makeValues(const bool isText, mat4 glCoordMatrix = getGlCoordMatrix(tile.matrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); - return Values { - uniforms::matrix::Value( tile.translatedMatrix(values.translate, - values.translateAnchor, - state) ), - uniforms::label_plane_matrix::Value(labelPlaneMatrix), - uniforms::coord_matrix::Value( tile.translateVtxMatrix(glCoordMatrix, - values.translate, - values.translateAnchor, - state, - true) ), - uniforms::extrude_scale::Value( extrudeScale ), - uniforms::texsize::Value( texsize ), - uniforms::fade_change::Value( symbolFadeChange ), - uniforms::is_text::Value( isText ), - uniforms::camera_to_center_distance::Value( state.getCameraToCenterDistance() ), - uniforms::pitch::Value( state.getPitch() ), - uniforms::pitch_with_map::Value( pitchWithMap ), - uniforms::rotate_symbol::Value( rotateInShader ), - uniforms::aspect_ratio::Value( state.getSize().aspectRatio() ), - std::forward(args)... - }; + return Values{uniforms::matrix::Value(tile.translatedMatrix(values.translate, values.translateAnchor, state)), + uniforms::label_plane_matrix::Value(labelPlaneMatrix), + uniforms::coord_matrix::Value( + tile.translateVtxMatrix(glCoordMatrix, values.translate, values.translateAnchor, state, true)), + uniforms::extrude_scale::Value(extrudeScale), + uniforms::texsize::Value(texsize), + uniforms::fade_change::Value(symbolFadeChange), + uniforms::is_text::Value(isText), + uniforms::camera_to_center_distance::Value(state.getCameraToCenterDistance()), + uniforms::pitch::Value(state.getPitch()), + uniforms::pitch_with_map::Value(pitchWithMap), + uniforms::rotate_symbol::Value(rotateInShader), + uniforms::aspect_ratio::Value(state.getSize().aspectRatio()), + std::forward(args)...}; } -SymbolIconProgram::LayoutUniformValues -SymbolIconProgram::layoutUniformValues(const bool isText, - const bool hasVariablePacement, - const style::SymbolPropertyValues& values, - const Size& texsize, - const std::array& pixelsToGLUnits, - const bool alongLine, - const RenderTile& tile, - const TransformState& state, - const float symbolFadeChange) { +SymbolIconProgram::LayoutUniformValues SymbolIconProgram::layoutUniformValues( + const bool isText, + const bool hasVariablePacement, + const style::SymbolPropertyValues& values, + const Size& texsize, + const std::array& pixelsToGLUnits, + const bool alongLine, + const RenderTile& tile, + const TransformState& state, + const float symbolFadeChange) { return makeValues( - isText, - hasVariablePacement, - values, - texsize, - pixelsToGLUnits, - alongLine, - tile, - state, - symbolFadeChange - ); + isText, hasVariablePacement, values, texsize, pixelsToGLUnits, alongLine, tile, state, symbolFadeChange); } template typename SymbolSDFProgram::LayoutUniformValues SymbolSDFProgram::layoutUniformValues(const bool isText, - const bool hasVariablePacement, - const style::SymbolPropertyValues& values, - const Size& texsize, - const std::array& pixelsToGLUnits, - const float pixelRatio, - const bool alongLine, - const RenderTile& tile, - const TransformState& state, - const float symbolFadeChange, - const SymbolSDFPart part) { + const bool hasVariablePacement, + const style::SymbolPropertyValues& values, + const Size& texsize, + const std::array& pixelsToGLUnits, + const float pixelRatio, + const bool alongLine, + const RenderTile& tile, + const TransformState& state, + const float symbolFadeChange, + const SymbolSDFPart part) { const float gammaScale = (values.pitchAlignment == AlignmentType::Map - ? static_cast(std::cos(state.getPitch())) * state.getCameraToCenterDistance() - : 1.0f); + ? static_cast(std::cos(state.getPitch())) * state.getCameraToCenterDistance() + : 1.0f); return makeValues::LayoutUniformValues>( isText, @@ -150,10 +132,9 @@ SymbolSDFProgram::layoutUniformValues(const tile, state, symbolFadeChange, - uniforms::gamma_scale::Value( gammaScale ), - uniforms::device_pixel_ratio::Value( pixelRatio ), - uniforms::is_halo::Value( part == SymbolSDFPart::Halo ) - ); + uniforms::gamma_scale::Value(gammaScale), + uniforms::device_pixel_ratio::Value(pixelRatio), + uniforms::is_halo::Value(part == SymbolSDFPart::Halo)); } SymbolTextAndIconProgram::LayoutUniformValues SymbolTextAndIconProgram::layoutUniformValues( @@ -168,23 +149,27 @@ SymbolTextAndIconProgram::LayoutUniformValues SymbolTextAndIconProgram::layoutUn const TransformState& state, const float symbolFadeChange, const SymbolSDFPart part) { - return {SymbolSDFProgram - ::layoutUniformValues( - true, - hasVariablePacement, - values, - texsize, - pixelsToGLUnits, - pixelRatio, - alongLine, - tile, - state, - symbolFadeChange, - part) - .concat(gfx::UniformValues(uniforms::texsize::Value(texsize_icon)))}; + return {SymbolSDFProgram::layoutUniformValues(true, + hasVariablePacement, + values, + texsize, + pixelsToGLUnits, + pixelRatio, + alongLine, + tile, + state, + symbolFadeChange, + part) + .concat(gfx::UniformValues(uniforms::texsize::Value(texsize_icon)))}; } -template class SymbolSDFProgram; -template class SymbolSDFProgram; +template class SymbolSDFProgram; +template class SymbolSDFProgram; } // namespace mbgl diff --git a/src/mbgl/programs/symbol_program.hpp b/src/mbgl/programs/symbol_program.hpp index 412b02b436b..e9507fb84bc 100644 --- a/src/mbgl/programs/symbol_program.hpp +++ b/src/mbgl/programs/symbol_program.hpp @@ -63,19 +63,17 @@ struct ZoomEvaluatedSize { float size; float layoutSize; }; -// Mimic the PaintPropertyBinder technique specifically for the {text,icon}-size layout properties -// in order to provide a 'custom' scheme for encoding the necessary attribute data. As with -// PaintPropertyBinder, SymbolSizeBinder is an abstract class whose implementations handle the -// particular attribute & uniform logic needed by each possible type of the {Text,Icon}Size properties. +// Mimic the PaintPropertyBinder technique specifically for the {text,icon}-size +// layout properties in order to provide a 'custom' scheme for encoding the +// necessary attribute data. As with PaintPropertyBinder, SymbolSizeBinder is +// an abstract class whose implementations handle the particular attribute & +// uniform logic needed by each possible type of the {Text,Icon}Size properties. class SymbolSizeBinder { public: virtual ~SymbolSizeBinder() = default; - using UniformList = TypeList< - uniforms::is_size_zoom_constant, - uniforms::is_size_feature_constant, - uniforms::size_t, - uniforms::size>; + using UniformList = + TypeList; using UniformValues = gfx::UniformValues; static std::unique_ptr create(float tileZoom, @@ -87,58 +85,53 @@ class SymbolSizeBinder { UniformValues uniformValues(float currentZoom) const { const ZoomEvaluatedSize u = evaluateForZoom(currentZoom); - return UniformValues { - uniforms::is_size_zoom_constant::Value( u.isZoomConstant ), - uniforms::is_size_feature_constant::Value( u.isFeatureConstant), - uniforms::size_t::Value( u.sizeT ), - uniforms::size::Value( u.size ) - }; + return UniformValues{uniforms::is_size_zoom_constant::Value(u.isZoomConstant), + uniforms::is_size_feature_constant::Value(u.isFeatureConstant), + uniforms::size_t::Value(u.sizeT), + uniforms::size::Value(u.size)}; } }; - class ConstantSymbolSizeBinder final : public SymbolSizeBinder { public: ConstantSymbolSizeBinder(const float /*tileZoom*/, const float& size, const float /*defaultValue*/) - : layoutSize(size) {} + : layoutSize(size) {} ConstantSymbolSizeBinder(const float /*tileZoom*/, const style::Undefined&, const float defaultValue) - : layoutSize(defaultValue) {} - - ConstantSymbolSizeBinder(const float tileZoom, const style::PropertyExpression& expression_, const float /*defaultValue*/) - : layoutSize(expression_.evaluate(tileZoom + 1)), - expression(expression_) { + : layoutSize(defaultValue) {} + + ConstantSymbolSizeBinder(const float tileZoom, + const style::PropertyExpression& expression_, + const float /*defaultValue*/ + ) + : layoutSize(expression_.evaluate(tileZoom + 1)), + expression(expression_) { const Range zoomLevels = expression_.getCoveringStops(tileZoom, tileZoom + 1); coveringRanges = std::make_tuple( - zoomLevels, - Range { expression_.evaluate(zoomLevels.min), expression_.evaluate(zoomLevels.max) } - ); + zoomLevels, Range{expression_.evaluate(zoomLevels.min), expression_.evaluate(zoomLevels.max)}); } - Range getVertexSizeData(const GeometryTileFeature&) override { return { 0.0f, 0.0f }; }; + Range getVertexSizeData(const GeometryTileFeature&) override { return {0.0f, 0.0f}; }; ZoomEvaluatedSize evaluateForZoom(float currentZoom) const override { float size = layoutSize; bool isZoomConstant = !(coveringRanges || expression); if (coveringRanges) { // Even though we could get the exact value of the camera function - // at z = currentZoom, we intentionally do not: instead, we interpolate - // between the camera function values at a pair of zoom stops covering - // [tileZoom, tileZoom + 1] in order to be consistent with this - // restriction on composite functions. + // at z = currentZoom, we intentionally do not: instead, we + // interpolate between the camera function values at a pair of zoom + // stops covering [tileZoom, tileZoom + 1] in order to be consistent + // with this restriction on composite functions. const Range& zoomLevels = std::get<0>(*coveringRanges); const Range& sizeLevels = std::get<1>(*coveringRanges); - float t = util::clamp( - expression->interpolationFactor(zoomLevels, currentZoom), - 0.0f, 1.0f - ); + float t = util::clamp(expression->interpolationFactor(zoomLevels, currentZoom), 0.0f, 1.0f); size = sizeLevels.min + t * (sizeLevels.max - sizeLevels.min); } else if (expression) { size = expression->evaluate(currentZoom); } const float unused = 0.0f; - return { isZoomConstant, true, unused, size, layoutSize }; + return {isZoomConstant, true, unused, size, layoutSize}; } float layoutSize; @@ -148,19 +141,20 @@ class ConstantSymbolSizeBinder final : public SymbolSizeBinder { class SourceFunctionSymbolSizeBinder final : public SymbolSizeBinder { public: - SourceFunctionSymbolSizeBinder(const float /*tileZoom*/, style::PropertyExpression expression_, const float defaultValue_) + SourceFunctionSymbolSizeBinder(const float /*tileZoom*/, + style::PropertyExpression expression_, + const float defaultValue_) : expression(std::move(expression_)), - defaultValue(defaultValue_) { - } + defaultValue(defaultValue_) {} Range getVertexSizeData(const GeometryTileFeature& feature) override { const float size = expression.evaluate(feature, defaultValue); - return { size, size }; + return {size, size}; }; ZoomEvaluatedSize evaluateForZoom(float) const override { const float unused = 0.0f; - return { true, false, unused, unused, unused }; + return {true, false, unused, unused, unused}; } style::PropertyExpression expression; @@ -169,29 +163,25 @@ class SourceFunctionSymbolSizeBinder final : public SymbolSizeBinder { class CompositeFunctionSymbolSizeBinder final : public SymbolSizeBinder { public: - - CompositeFunctionSymbolSizeBinder(const float tileZoom, style::PropertyExpression expression_, const float defaultValue_) + CompositeFunctionSymbolSizeBinder(const float tileZoom, + style::PropertyExpression expression_, + const float defaultValue_) : expression(std::move(expression_)), defaultValue(defaultValue_), layoutZoom(tileZoom + 1), - coveringZoomStops(expression.getCoveringStops(tileZoom, tileZoom + 1)) - {} + coveringZoomStops(expression.getCoveringStops(tileZoom, tileZoom + 1)) {} Range getVertexSizeData(const GeometryTileFeature& feature) override { - return { - expression.evaluate(coveringZoomStops.min, feature, defaultValue), - expression.evaluate(coveringZoomStops.max, feature, defaultValue) - }; + return {expression.evaluate(coveringZoomStops.min, feature, defaultValue), + expression.evaluate(coveringZoomStops.max, feature, defaultValue)}; }; ZoomEvaluatedSize evaluateForZoom(float currentZoom) const override { float sizeInterpolationT = util::clamp( - expression.interpolationFactor(coveringZoomStops, currentZoom), - 0.0f, 1.0f - ); + expression.interpolationFactor(coveringZoomStops, currentZoom), 0.0f, 1.0f); const float unused = 0.0f; - return { false, false, sizeInterpolationT, unused, unused }; + return {false, false, sizeInterpolationT, unused, unused}; } style::PropertyExpression expression; @@ -211,11 +201,13 @@ class SymbolProgramBase : public gfx::Shader { bool isSDF, Point pixelOffset, Point minFontScale) { - const uint16_t aSizeMin = - (std::min(MAX_PACKED_SIZE, static_cast(sizeData.min * SIZE_PACK_FACTOR)) << 1) + uint16_t(isSDF); + const uint16_t aSizeMin = (std::min(MAX_PACKED_SIZE, static_cast(sizeData.min * SIZE_PACK_FACTOR)) + << 1) + + uint16_t(isSDF); const uint16_t aSizeMax = std::min(MAX_PACKED_SIZE, static_cast(sizeData.max * SIZE_PACK_FACTOR)); return { - // combining pos and offset to reduce number of vertex attributes passed to shader (8 max for some devices) + // combining pos and offset to reduce number of vertex attributes + // passed to shader (8 max for some devices) {{static_cast(labelAnchor.x), static_cast(labelAnchor.y), static_cast(std::round(o.x * 32)), // use 1/32 pixels for placement @@ -229,19 +221,11 @@ class SymbolProgramBase : public gfx::Shader { } static gfx::Vertex dynamicLayoutVertex(Point anchorPoint, float labelAngle) { - return { - {{ - anchorPoint.x, - anchorPoint.y, - labelAngle - }} - }; + return {{{anchorPoint.x, anchorPoint.y, labelAngle}}}; } static gfx::Vertex opacityVertex(bool placed, float opacity) { - return { - {{ static_cast((static_cast(opacity * 127) << 1) | static_cast(placed)) }} - }; + return {{{static_cast((static_cast(opacity * 127) << 1) | static_cast(placed))}}}; } }; @@ -256,7 +240,8 @@ class SymbolProgram : public SymbolProgramBase { public: using LayoutVertex = gfx::Vertex; - using LayoutAndSizeAttributeList = TypeListConcat; + using LayoutAndSizeAttributeList = + TypeListConcat; using PaintProperties = PaintProps; using Binders = PaintPropertyBinders; @@ -280,12 +265,10 @@ class SymbolProgram : public SymbolProgramBase { switch (gfx::Backend::GetType()) { #ifdef MBGL_RENDER_BACKEND_OPENGL case gfx::Backend::Type::OpenGL: { - program = std::make_unique>(programParameters - .withDefaultSource({ - gfx::Backend::Type::OpenGL, - shaders::ShaderSource::vertex, - shaders::ShaderSource::fragment - })); + program = std::make_unique>(programParameters.withDefaultSource( + {gfx::Backend::Type::OpenGL, + shaders::ShaderSource::vertex, + shaders::ShaderSource::fragment})); break; } #endif @@ -295,12 +278,11 @@ class SymbolProgram : public SymbolProgramBase { } } - static UniformValues computeAllUniformValues( - const LayoutUniformValues& layoutUniformValues, - const SymbolSizeBinder& symbolSizeBinder, - const Binders& paintPropertyBinders, - const typename PaintProperties::PossiblyEvaluated& currentProperties, - float currentZoom) { + static UniformValues computeAllUniformValues(const LayoutUniformValues& layoutUniformValues, + const SymbolSizeBinder& symbolSizeBinder, + const Binders& paintPropertyBinders, + const typename PaintProperties::PossiblyEvaluated& currentProperties, + float currentZoom) { return layoutUniformValues.concat(symbolSizeBinder.uniformValues(currentZoom)) .concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties)); } @@ -348,21 +330,20 @@ class SymbolProgram : public SymbolProgramBase { drawScopeIt = segment.drawScopes.emplace(layerID, context.createDrawScope()).first; } - program->draw( - context, - renderPass, - drawMode, - depthMode, - stencilMode, - colorMode, - cullFaceMode, - uniformValues, - drawScopeIt->second, - allAttributeBindings.offset(segment.vertexOffset), - textureBindings, - indexBuffer, - segment.indexOffset, - segment.indexLength); + program->draw(context, + renderPass, + drawMode, + depthMode, + stencilMode, + colorMode, + cullFaceMode, + uniformValues, + drawScopeIt->second, + allAttributeBindings.offset(segment.vertexOffset), + textureBindings, + indexBuffer, + segment.indexOffset, + segment.indexLength); } template @@ -403,33 +384,27 @@ class SymbolProgram : public SymbolProgramBase { } }; -class SymbolIconProgram final : public SymbolProgram< - SymbolIconProgram, - shaders::BuiltIn::SymbolIconProgram, - gfx::PrimitiveType::Triangle, - SymbolLayoutAttributes, - TypeList< - uniforms::matrix, - uniforms::label_plane_matrix, - uniforms::coord_matrix, - uniforms::extrude_scale, - uniforms::texsize, - uniforms::fade_change, - uniforms::is_text, - uniforms::camera_to_center_distance, - uniforms::pitch, - uniforms::pitch_with_map, - uniforms::rotate_symbol, - uniforms::aspect_ratio>, - TypeList< - textures::texture>, - style::IconPaintProperties> -{ +class SymbolIconProgram final : public SymbolProgram, + TypeList, + style::IconPaintProperties> { public: static constexpr std::string_view Name{"SymbolIconProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using SymbolProgram::SymbolProgram; @@ -511,9 +486,7 @@ class SymbolTextAndIconProgram final style::TextPaintProperties> { public: static constexpr std::string_view Name{"SymbolTextAndIconProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using BaseProgram = SymbolProgram -{ +class SymbolSDFIconProgram final : public SymbolSDFProgram { public: static constexpr std::string_view Name{"SymbolSDFIconProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using SymbolSDFProgram::SymbolSDFProgram; }; -class SymbolSDFTextProgram final : public SymbolSDFProgram< - SymbolSDFTextProgram, - shaders::BuiltIn::SymbolSDFTextProgram, - style::TextPaintProperties> -{ +class SymbolSDFTextProgram final : public SymbolSDFProgram { public: static constexpr std::string_view Name{"SymbolSDFTextProgram"}; - const std::string_view typeName() const noexcept override { - return Name; - } + const std::string_view typeName() const noexcept override { return Name; } using SymbolSDFProgram::SymbolSDFProgram; }; diff --git a/src/mbgl/renderer/backend_scope.cpp b/src/mbgl/renderer/backend_scope.cpp index f3d78714732..b34fde2228c 100644 --- a/src/mbgl/renderer/backend_scope.cpp +++ b/src/mbgl/renderer/backend_scope.cpp @@ -48,9 +48,8 @@ BackendScope::~BackendScope() { } void BackendScope::activate() { - if (scopeType == ScopeType::Explicit && - !(priorScope && this->backend == priorScope->backend) && - !(nextScope && this->backend == nextScope->backend)) { + if (scopeType == ScopeType::Explicit && !(priorScope && this->backend == priorScope->backend) && + !(nextScope && this->backend == nextScope->backend)) { // Only activate when set to Explicit and // only once per RenderBackend backend.activate(); @@ -59,8 +58,7 @@ void BackendScope::activate() { } void BackendScope::deactivate() { - if (activated && - !(nextScope && this->backend == nextScope->backend)) { + if (activated && !(nextScope && this->backend == nextScope->backend)) { // Only deactivate when set to Explicit and // only once per RenderBackend backend.deactivate(); diff --git a/src/mbgl/renderer/bucket.hpp b/src/mbgl/renderer/bucket.hpp index 68d6c46b7f8..0bae72e6625 100644 --- a/src/mbgl/renderer/bucket.hpp +++ b/src/mbgl/renderer/bucket.hpp @@ -41,20 +41,17 @@ class Bucket { virtual void update(const FeatureStates&, const GeometryTileLayer&, const std::string&, const ImagePositions&) {} - // As long as this bucket has a Prepare render pass, this function is getting called. Typically, - // this only happens once when the bucket is being rendered for the first time. + // As long as this bucket has a Prepare render pass, this function is + // getting called. Typically, this only happens once when the bucket is + // being rendered for the first time. virtual void upload(gfx::UploadPass&) = 0; virtual bool hasData() const = 0; - virtual float getQueryRadius(const RenderLayer&) const { - return 0; - }; + virtual float getQueryRadius(const RenderLayer&) const { return 0; }; + + bool needsUpload() const { return hasData() && !uploaded; } - bool needsUpload() const { - return hasData() && !uploaded; - } - // The following methods are implemented by buckets that require cross-tile indexing and placement. // Returns a pair, the first element of which is a bucket cross-tile id @@ -70,7 +67,7 @@ class Bucket { protected: Bucket() = default; - std::atomic uploaded { false }; + std::atomic uploaded{false}; }; } // namespace mbgl diff --git a/src/mbgl/renderer/bucket_parameters.cpp b/src/mbgl/renderer/bucket_parameters.cpp index 35b87bffea0..159a2aa1707 100644 --- a/src/mbgl/renderer/bucket_parameters.cpp +++ b/src/mbgl/renderer/bucket_parameters.cpp @@ -1,5 +1,3 @@ #include -namespace mbgl { - -} // namespace mbgl +namespace mbgl {} // namespace mbgl diff --git a/src/mbgl/renderer/bucket_parameters.hpp b/src/mbgl/renderer/bucket_parameters.hpp index 7547f4517bb..81c5bcfa4bd 100644 --- a/src/mbgl/renderer/bucket_parameters.hpp +++ b/src/mbgl/renderer/bucket_parameters.hpp @@ -5,7 +5,7 @@ namespace mbgl { namespace style { - struct LayerTypeInfo; +struct LayerTypeInfo; } // namespace style class BucketParameters { diff --git a/src/mbgl/renderer/buckets/circle_bucket.cpp b/src/mbgl/renderer/buckets/circle_bucket.cpp index 5a1184f5fd3..a246ebfc7cd 100644 --- a/src/mbgl/renderer/buckets/circle_bucket.cpp +++ b/src/mbgl/renderer/buckets/circle_bucket.cpp @@ -41,7 +41,9 @@ bool CircleBucket::hasData() const { } template -static float get(const CirclePaintProperties::PossiblyEvaluated& evaluated, const std::string& id, const std::map& paintPropertyBinders) { +static float get(const CirclePaintProperties::PossiblyEvaluated& evaluated, + const std::string& id, + const std::map& paintPropertyBinders) { auto it = paintPropertyBinders.find(id); if (it == paintPropertyBinders.end() || !it->second.statistics().max()) { return evaluated.get().constantOr(Property::defaultValue()); @@ -58,7 +60,9 @@ float CircleBucket::getQueryRadius(const RenderLayer& layer) const { return radius + stroke + util::length(translate[0], translate[1]); } -void CircleBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, const std::string& layerID, +void CircleBucket::update(const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, const ImagePositions& imagePositions) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { diff --git a/src/mbgl/renderer/buckets/debug_bucket.cpp b/src/mbgl/renderer/buckets/debug_bucket.cpp index e752a1f1ce2..1df0f561467 100644 --- a/src/mbgl/renderer/buckets/debug_bucket.cpp +++ b/src/mbgl/renderer/buckets/debug_bucket.cpp @@ -20,10 +20,9 @@ DebugBucket::DebugBucket(const OverscaledTileID& id, modified(std::move(modified_)), expires(std::move(expires_)), debugMode(debugMode_) { - auto addText = [&] (const std::string& text, double left, double baseline, double scale) { + auto addText = [&](const std::string& text, double left, double baseline, double scale) { for (uint8_t c : text) { - if (c < 32 || c >= 127) - continue; + if (c < 32 || c >= 127) continue; std::optional> prev; @@ -32,10 +31,8 @@ DebugBucket::DebugBucket(const OverscaledTileID& id, if (glyph.data[j] == -1 && glyph.data[j + 1] == -1) { prev = {}; } else { - Point p { - int16_t(::round(left + glyph.data[j] * scale)), - int16_t(::round(baseline - glyph.data[j + 1] * scale)) - }; + Point p{int16_t(::round(left + glyph.data[j] * scale)), + int16_t(::round(baseline - glyph.data[j + 1] * scale))}; vertices.emplace_back(FillProgram::layoutVertex(p)); @@ -55,7 +52,9 @@ DebugBucket::DebugBucket(const OverscaledTileID& id, double baseline = 200; if (debugMode & MapDebugOptions::ParseStatus) { const std::string text = util::toString(id) + " - " + - (complete ? "complete" : renderable ? "renderable" : "pending"); + (complete ? "complete" + : renderable ? "renderable" + : "pending"); addText(text, 50, baseline, 5); baseline += 200; } diff --git a/src/mbgl/renderer/buckets/debug_bucket.hpp b/src/mbgl/renderer/buckets/debug_bucket.hpp index 34d6f9e8aba..c70148b7add 100644 --- a/src/mbgl/renderer/buckets/debug_bucket.hpp +++ b/src/mbgl/renderer/buckets/debug_bucket.hpp @@ -30,7 +30,6 @@ class DebugBucket : private util::noncopyable { const std::optional expires; const MapDebugOptions debugMode; - gfx::VertexVector vertices; gfx::IndexVector indices; diff --git a/src/mbgl/renderer/buckets/fill_bucket.cpp b/src/mbgl/renderer/buckets/fill_bucket.cpp index 6554cb2ab31..02b0e12c49d 100644 --- a/src/mbgl/renderer/buckets/fill_bucket.cpp +++ b/src/mbgl/renderer/buckets/fill_bucket.cpp @@ -20,11 +20,13 @@ namespace mapbox { namespace util { -template <> struct nth<0, mbgl::GeometryCoordinate> { +template <> +struct nth<0, mbgl::GeometryCoordinate> { static int64_t get(const mbgl::GeometryCoordinate& t) { return t.x; }; }; -template <> struct nth<1, mbgl::GeometryCoordinate> { +template <> +struct nth<1, mbgl::GeometryCoordinate> { static int64_t get(const mbgl::GeometryCoordinate& t) { return t.y; }; }; } // namespace util @@ -41,12 +43,9 @@ FillBucket::FillBucket(const FillBucket::PossiblyEvaluatedLayoutProperties&, const float zoom, const uint32_t) { for (const auto& pair : layerPaintProperties) { - paintPropertyBinders.emplace( - std::piecewise_construct, - std::forward_as_tuple(pair.first), - std::forward_as_tuple( - getEvaluated(pair.second), - zoom)); + paintPropertyBinders.emplace(std::piecewise_construct, + std::forward_as_tuple(pair.first), + std::forward_as_tuple(getEvaluated(pair.second), zoom)); } } @@ -66,8 +65,7 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, for (const auto& ring : polygon) { totalVertices += ring.size(); - if (totalVertices > std::numeric_limits::max()) - throw GeometryTooLongException(); + if (totalVertices > std::numeric_limits::max()) throw GeometryTooLongException(); } std::size_t startVertices = vertices.elements(); @@ -75,10 +73,10 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, for (const auto& ring : polygon) { std::size_t nVertices = ring.size(); - if (nVertices == 0) - continue; + if (nVertices == 0) continue; - if (lineSegments.empty() || lineSegments.back().vertexLength + nVertices > std::numeric_limits::max()) { + if (lineSegments.empty() || + lineSegments.back().vertexLength + nVertices > std::numeric_limits::max()) { lineSegments.emplace_back(vertices.elements(), lines.elements()); } @@ -103,7 +101,8 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, std::size_t nIndicies = indices.size(); assert(nIndicies % 3 == 0); - if (triangleSegments.empty() || triangleSegments.back().vertexLength + totalVertices > std::numeric_limits::max()) { + if (triangleSegments.empty() || + triangleSegments.back().vertexLength + totalVertices > std::numeric_limits::max()) { triangleSegments.emplace_back(startVertices, triangles.elements()); } @@ -112,9 +111,8 @@ void FillBucket::addFeature(const GeometryTileFeature& feature, const auto triangleIndex = static_cast(triangleSegment.vertexLength); for (std::size_t i = 0; i < nIndicies; i += 3) { - triangles.emplace_back(triangleIndex + indices[i], - triangleIndex + indices[i + 1], - triangleIndex + indices[i + 2]); + triangles.emplace_back( + triangleIndex + indices[i], triangleIndex + indices[i + 1], triangleIndex + indices[i + 2]); } triangleSegment.vertexLength += totalVertices; @@ -136,8 +134,8 @@ void FillBucket::upload(gfx::UploadPass& uploadPass) { if (!uploaded) { vertexBuffer = uploadPass.createVertexBuffer(std::move(vertices)); lineIndexBuffer = uploadPass.createIndexBuffer(std::move(lines)); - triangleIndexBuffer = - triangles.empty() ? std::optional{} : uploadPass.createIndexBuffer(std::move(triangles)); + triangleIndexBuffer = triangles.empty() ? std::optional{} + : uploadPass.createIndexBuffer(std::move(triangles)); } for (auto& pair : paintPropertyBinders) { @@ -157,7 +155,9 @@ float FillBucket::getQueryRadius(const RenderLayer& layer) const { return util::length(translate[0], translate[1]); } -void FillBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, const std::string& layerID, +void FillBucket::update(const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, const ImagePositions& imagePositions) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { diff --git a/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp b/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp index fbf21d91207..6b3eb461e37 100644 --- a/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp +++ b/src/mbgl/renderer/buckets/fill_extrusion_bucket.cpp @@ -23,16 +23,12 @@ namespace mapbox { namespace util { template <> struct nth<0, mbgl::GeometryCoordinate> { - static int64_t get(const mbgl::GeometryCoordinate& t) { - return t.x; - }; + static int64_t get(const mbgl::GeometryCoordinate& t) { return t.x; }; }; template <> struct nth<1, mbgl::GeometryCoordinate> { - static int64_t get(const mbgl::GeometryCoordinate& t) { - return t.y; - }; + static int64_t get(const mbgl::GeometryCoordinate& t) { return t.y; }; }; } // namespace util } // namespace mapbox @@ -43,17 +39,16 @@ using namespace style; struct GeometryTooLongException : std::exception {}; -FillExtrusionBucket::FillExtrusionBucket(const FillExtrusionBucket::PossiblyEvaluatedLayoutProperties&, - const std::map>& layerPaintProperties, - const float zoom, - const uint32_t) { +FillExtrusionBucket::FillExtrusionBucket( + const FillExtrusionBucket::PossiblyEvaluatedLayoutProperties&, + const std::map>& layerPaintProperties, + const float zoom, + const uint32_t) { for (const auto& pair : layerPaintProperties) { paintPropertyBinders.emplace( std::piecewise_construct, std::forward_as_tuple(pair.first), - std::forward_as_tuple( - getEvaluated(pair.second), - zoom)); + std::forward_as_tuple(getEvaluated(pair.second), zoom)); } } @@ -73,8 +68,7 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, for (const auto& ring : polygon) { totalVertices += ring.size(); - if (totalVertices > std::numeric_limits::max()) - throw GeometryTooLongException(); + if (totalVertices > std::numeric_limits::max()) throw GeometryTooLongException(); } if (totalVertices == 0) continue; @@ -84,9 +78,8 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, std::size_t startVertices = vertices.elements(); - if (triangleSegments.empty() || - triangleSegments.back().vertexLength + (5 * (totalVertices - 1) + 1) > - std::numeric_limits::max()) { + if (triangleSegments.empty() || triangleSegments.back().vertexLength + (5 * (totalVertices - 1) + 1) > + std::numeric_limits::max()) { triangleSegments.emplace_back(startVertices, triangles.elements()); } @@ -94,14 +87,12 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, assert(triangleSegment.vertexLength <= std::numeric_limits::max()); auto triangleIndex = static_cast(triangleSegment.vertexLength); - assert(triangleIndex + (5 * (totalVertices - 1) + 1) <= - std::numeric_limits::max()); + assert(triangleIndex + (5 * (totalVertices - 1) + 1) <= std::numeric_limits::max()); for (const auto& ring : polygon) { std::size_t nVertices = ring.size(); - if (nVertices == 0) - continue; + if (nVertices == 0) continue; std::size_t edgeDistance = 0; @@ -121,22 +112,21 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, const Point perp = util::unit(util::perp(d1 - d2)); const size_t dist = util::dist(d1, d2); - if (edgeDistance + dist > - static_cast(std::numeric_limits::max())) { + if (edgeDistance + dist > static_cast(std::numeric_limits::max())) { edgeDistance = 0; } - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p1, perp.x, perp.y, 0, 0, static_cast(edgeDistance))); - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p1, perp.x, perp.y, 0, 1, static_cast(edgeDistance))); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p1, perp.x, perp.y, 0, 0, static_cast(edgeDistance))); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p1, perp.x, perp.y, 0, 1, static_cast(edgeDistance))); edgeDistance += dist; - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p2, perp.x, perp.y, 0, 0, static_cast(edgeDistance))); - vertices.emplace_back( - FillExtrusionProgram::layoutVertex(p2, perp.x, perp.y, 0, 1, static_cast(edgeDistance))); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p2, perp.x, perp.y, 0, 0, static_cast(edgeDistance))); + vertices.emplace_back(FillExtrusionProgram::layoutVertex( + p2, perp.x, perp.y, 0, 1, static_cast(edgeDistance))); // ┌──────┐ // │ 0 1 │ Counter-Clockwise winding order. @@ -159,8 +149,7 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, for (std::size_t i = 0; i < nIndices; i += 3) { // Counter-Clockwise winding order. - triangles.emplace_back(flatIndices[indices[i]], flatIndices[indices[i + 2]], - flatIndices[indices[i + 1]]); + triangles.emplace_back(flatIndices[indices[i]], flatIndices[indices[i + 2]], flatIndices[indices[i + 1]]); } triangleSegment.vertexLength += totalVertices; @@ -169,7 +158,7 @@ void FillExtrusionBucket::addFeature(const GeometryTileFeature& feature, for (auto& pair : paintPropertyBinders) { const auto it = patternDependencies.find(pair.first); - if (it != patternDependencies.end()){ + if (it != patternDependencies.end()) { pair.second.populateVertexVectors( feature, vertices.elements(), index, patternPositions, it->second, canonical); } else { @@ -201,8 +190,10 @@ float FillExtrusionBucket::getQueryRadius(const RenderLayer& layer) const { return util::length(translate[0], translate[1]); } -void FillExtrusionBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, - const std::string& layerID, const ImagePositions& imagePositions) { +void FillExtrusionBucket::update(const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, + const ImagePositions& imagePositions) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { it->second.updateVertexVectors(states, layer, imagePositions); diff --git a/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp b/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp index da59981fbb0..22770a9cb21 100644 --- a/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp +++ b/src/mbgl/renderer/buckets/fill_extrusion_bucket.hpp @@ -45,7 +45,7 @@ class FillExtrusionBucket final : public Bucket { std::optional> vertexBuffer; std::optional indexBuffer; - + std::unordered_map paintPropertyBinders; }; diff --git a/src/mbgl/renderer/buckets/heatmap_bucket.cpp b/src/mbgl/renderer/buckets/heatmap_bucket.cpp index 6689d759d02..c8f560fadb7 100644 --- a/src/mbgl/renderer/buckets/heatmap_bucket.cpp +++ b/src/mbgl/renderer/buckets/heatmap_bucket.cpp @@ -10,15 +10,14 @@ namespace mbgl { using namespace style; -HeatmapBucket::HeatmapBucket(const BucketParameters& parameters, const std::vector>& layers) +HeatmapBucket::HeatmapBucket(const BucketParameters& parameters, + const std::vector>& layers) : mode(parameters.mode) { for (const auto& layer : layers) { paintPropertyBinders.emplace( std::piecewise_construct, std::forward_as_tuple(layer->baseImpl->id), - std::forward_as_tuple( - getEvaluated(layer), - parameters.tileID.overscaledZ)); + std::forward_as_tuple(getEvaluated(layer), parameters.tileID.overscaledZ)); } } @@ -48,7 +47,7 @@ void HeatmapBucket::addFeature(const GeometryTileFeature& feature, constexpr const uint16_t vertexLength = 4; for (auto& points : geometry) { - for(auto& point : points) { + for (auto& point : points) { auto x = point.x; auto y = point.y; @@ -57,7 +56,8 @@ void HeatmapBucket::addFeature(const GeometryTileFeature& feature, continue; } - if (segments.empty() || segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { + if (segments.empty() || + segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { // Move to a new segments because the old one can't hold the geometry. segments.emplace_back(vertices.elements(), triangles.elements()); } @@ -72,9 +72,9 @@ void HeatmapBucket::addFeature(const GeometryTileFeature& feature, // └─────────┘ // vertices.emplace_back(HeatmapProgram::vertex(point, -1, -1)); // 1 - vertices.emplace_back(HeatmapProgram::vertex(point, 1, -1)); // 2 - vertices.emplace_back(HeatmapProgram::vertex(point, 1, 1)); // 3 - vertices.emplace_back(HeatmapProgram::vertex(point, -1, 1)); // 4 + vertices.emplace_back(HeatmapProgram::vertex(point, 1, -1)); // 2 + vertices.emplace_back(HeatmapProgram::vertex(point, 1, 1)); // 3 + vertices.emplace_back(HeatmapProgram::vertex(point, -1, 1)); // 4 auto& segment = segments.back(); assert(segment.vertexLength <= std::numeric_limits::max()); diff --git a/src/mbgl/renderer/buckets/hillshade_bucket.cpp b/src/mbgl/renderer/buckets/hillshade_bucket.cpp index a2a3db8d1d9..0796409bda1 100644 --- a/src/mbgl/renderer/buckets/hillshade_bucket.cpp +++ b/src/mbgl/renderer/buckets/hillshade_bucket.cpp @@ -9,12 +9,10 @@ namespace mbgl { using namespace style; HillshadeBucket::HillshadeBucket(PremultipliedImage&& image_, Tileset::DEMEncoding encoding) - : demdata(image_, encoding) { -} + : demdata(image_, encoding) {} HillshadeBucket::HillshadeBucket(DEMData&& demdata_) - : demdata(std::move(demdata_)) { -} + : demdata(std::move(demdata_)) {} HillshadeBucket::~HillshadeBucket() = default; @@ -62,14 +60,15 @@ void HillshadeBucket::setMask(TileMask&& mask_) { mask = std::move(mask_); clear(); - if (mask == TileMask{ { 0, 0, 0 } }) { - // We want to render the full tile, and keeping the segments/vertices/indices empty means - // using the global shared buffers for covering the entire tile. + if (mask == TileMask{{0, 0, 0}}) { + // We want to render the full tile, and keeping the + // segments/vertices/indices empty means using the global shared buffers + // for covering the entire tile. return; } - // Create a new segment so that we will upload (empty) buffers even when there is nothing to - // draw for this tile. + // Create a new segment so that we will upload (empty) buffers even when + // there is nothing to draw for this tile. segments.emplace_back(0, 0); constexpr const uint16_t vertexLength = 4; @@ -79,24 +78,24 @@ void HillshadeBucket::setMask(TileMask&& mask_) { // Create a quad for every masked tile. const int32_t vertexExtent = util::EXTENT >> id.z; - const Point tlVertex = { static_cast(id.x * vertexExtent), - static_cast(id.y * vertexExtent) }; - const Point brVertex = { static_cast(tlVertex.x + vertexExtent), - static_cast(tlVertex.y + vertexExtent) }; + const Point tlVertex = {static_cast(id.x * vertexExtent), + static_cast(id.y * vertexExtent)}; + const Point brVertex = {static_cast(tlVertex.x + vertexExtent), + static_cast(tlVertex.y + vertexExtent)}; if (segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { // Move to a new segments because the old one can't hold the geometry. segments.emplace_back(vertices.elements(), indices.elements()); } - vertices.emplace_back( - HillshadeProgram::layoutVertex({ tlVertex.x, tlVertex.y }, { static_cast(tlVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - HillshadeProgram::layoutVertex({ brVertex.x, tlVertex.y }, { static_cast(brVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - HillshadeProgram::layoutVertex({ tlVertex.x, brVertex.y }, { static_cast(tlVertex.x), static_cast(brVertex.y) })); - vertices.emplace_back( - HillshadeProgram::layoutVertex({ brVertex.x, brVertex.y }, { static_cast(brVertex.x), static_cast(brVertex.y) })); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {tlVertex.x, tlVertex.y}, {static_cast(tlVertex.x), static_cast(tlVertex.y)})); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {brVertex.x, tlVertex.y}, {static_cast(brVertex.x), static_cast(tlVertex.y)})); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {tlVertex.x, brVertex.y}, {static_cast(tlVertex.x), static_cast(brVertex.y)})); + vertices.emplace_back(HillshadeProgram::layoutVertex( + {brVertex.x, brVertex.y}, {static_cast(brVertex.x), static_cast(brVertex.y)})); auto& segment = segments.back(); assert(segment.vertexLength <= std::numeric_limits::max()); @@ -116,5 +115,4 @@ bool HillshadeBucket::hasData() const { return demdata.getImage()->valid(); } - } // namespace mbgl diff --git a/src/mbgl/renderer/buckets/hillshade_bucket.hpp b/src/mbgl/renderer/buckets/hillshade_bucket.hpp index 5d5dfb72a7b..a2098a93e1b 100644 --- a/src/mbgl/renderer/buckets/hillshade_bucket.hpp +++ b/src/mbgl/renderer/buckets/hillshade_bucket.hpp @@ -30,18 +30,14 @@ class HillshadeBucket final : public Bucket { std::optional dem; std::optional texture; - TileMask mask{ { 0, 0, 0 } }; + TileMask mask{{0, 0, 0}}; const DEMData& getDEMData() const; DEMData& getDEMData(); - bool isPrepared() const { - return prepared; - } + bool isPrepared() const { return prepared; } - void setPrepared (bool preparedState) { - prepared = preparedState; - } + void setPrepared(bool preparedState) { prepared = preparedState; } // Raster-DEM Tile Sources use the default buffers from Painter gfx::VertexVector vertices; @@ -50,7 +46,8 @@ class HillshadeBucket final : public Bucket { std::optional> vertexBuffer; std::optional indexBuffer; -private: + +private: DEMData demdata; bool prepared = false; }; diff --git a/src/mbgl/renderer/buckets/line_bucket.cpp b/src/mbgl/renderer/buckets/line_bucket.cpp index 92e71f377f9..952810cae27 100644 --- a/src/mbgl/renderer/buckets/line_bucket.cpp +++ b/src/mbgl/renderer/buckets/line_bucket.cpp @@ -15,14 +15,13 @@ LineBucket::LineBucket(LineBucket::PossiblyEvaluatedLayoutProperties layout_, const std::map>& layerPaintProperties, const float zoom_, const uint32_t overscaling_) - : layout(std::move(layout_)), zoom(zoom_), overscaling(overscaling_) { + : layout(std::move(layout_)), + zoom(zoom_), + overscaling(overscaling_) { for (const auto& pair : layerPaintProperties) { - paintPropertyBinders.emplace( - std::piecewise_construct, - std::forward_as_tuple(pair.first), - std::forward_as_tuple( - getEvaluated(pair.second), - zoom)); + paintPropertyBinders.emplace(std::piecewise_construct, + std::forward_as_tuple(pair.first), + std::forward_as_tuple(getEvaluated(pair.second), zoom)); } } @@ -40,7 +39,7 @@ void LineBucket::addFeature(const GeometryTileFeature& feature, for (auto& pair : paintPropertyBinders) { const auto it = patternDependencies.find(pair.first); - if (it != patternDependencies.end()){ + if (it != patternDependencies.end()) { pair.second.populateVertexVectors( feature, vertices.elements(), index, patternPositions, it->second, canonical); } else { @@ -80,7 +79,9 @@ const auto MAX_LINE_DISTANCE = static_cast(std::pow(2, LINE_DISTANCE_BUFF class LineBucket::Distances { public: Distances(double clipStart_, double clipEnd_, double total_) - : clipStart(clipStart_), clipEnd(clipEnd_), total(total_) {} + : clipStart(clipStart_), + clipEnd(clipEnd_), + total(total_) {} // Scale line distance from tile units to [0, 2^15). double scaleToMaxLineDistance(double tileDistance) const { @@ -127,7 +128,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, std::optional lineDistances; - const auto &props = feature.getProperties(); + const auto& props = feature.getProperties(); auto clip_start_it = props.find("mapbox_clip_start"); auto clip_end_it = props.find("mapbox_clip_end"); if (clip_start_it != props.end() && clip_end_it != props.end()) { @@ -147,8 +148,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const double sharpCornerOffset = overscaling == 0 ? SHARP_CORNER_OFFSET * (util::EXTENT / util::tileSize_D) - : (overscaling <= 16.0 ? SHARP_CORNER_OFFSET * (util::EXTENT / (util::tileSize_D * overscaling)) - : 0.0); + : (overscaling <= 16.0 ? SHARP_CORNER_OFFSET * (util::EXTENT / (util::tileSize_D * overscaling)) : 0.0); const GeometryCoordinate firstCoordinate = coordinates[first]; const LineCapType beginCap = layout.get(); @@ -200,10 +200,10 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, currentCoordinate = coordinates[i]; // Calculate the normal towards the next vertex in this line. In case - // there is no next vertex, pretend that the line is continuing straight, - // meaning that we are just using the previous normal. + // there is no next vertex, pretend that the line is continuing + // straight, meaning that we are just using the previous normal. nextNormal = nextCoordinate ? util::perp(util::unit(convertPoint(*nextCoordinate - *currentCoordinate))) - : prevNormal; + : prevNormal; // If we still don't have a previous normal, this is the beginning of a // non-closed line, so we're doing a straight "join". @@ -213,10 +213,11 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Determine the normal of the join extrusion. It is the angle bisector // of the segments between the previous line and the next line. - // In the case of 180° angles, the prev and next normals cancel each other out: - // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be - // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle - // below will also become 0 and miterLength will become Infinity. + // In the case of 180° angles, the prev and next normals cancel each + // other out: prevNormal + nextNormal = (0, 0), its magnitude is 0, so + // the unit vector would be undefined. In that case, we're keeping the + // joinNormal at (0, 0), so that the cosHalfAngle below will also become + // 0 and miterLength will become Infinity. Point joinNormal = *prevNormal + *nextNormal; if (joinNormal.x != 0 || joinNormal.y != 0) { joinNormal = util::unit(joinNormal); @@ -238,8 +239,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Calculate the length of the miter (the ratio of the miter to the width) // as the inverse of cosine of the angle between next and join normals. - const double miterLength = - cosHalfAngle != 0 ? 1 / cosHalfAngle : std::numeric_limits::infinity(); + const double miterLength = cosHalfAngle != 0 ? 1 / cosHalfAngle : std::numeric_limits::infinity(); // Approximate angle from cosine. const double approxAngle = 2 * std::sqrt(2 - 2 * cosHalfAngle); @@ -249,9 +249,13 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, if (isSharpCorner && i > first) { const auto prevSegmentLength = util::dist(*currentCoordinate, *prevCoordinate); if (prevSegmentLength > 2.0 * sharpCornerOffset) { - GeometryCoordinate newPrevVertex = *currentCoordinate - convertPoint(util::round(convertPoint(*currentCoordinate - *prevCoordinate) * (sharpCornerOffset / prevSegmentLength))); + GeometryCoordinate newPrevVertex = *currentCoordinate - + convertPoint(util::round( + convertPoint(*currentCoordinate - *prevCoordinate) * + (sharpCornerOffset / prevSegmentLength))); distance += util::dist(newPrevVertex, *prevCoordinate); - addCurrentVertex(newPrevVertex, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances); + addCurrentVertex( + newPrevVertex, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances); prevCoordinate = newPrevVertex; } } @@ -275,8 +279,9 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, } if (currentJoin == LineJoinType::Bevel) { - // The maximum extrude length is 128 / 63 = 2 times the width of the line - // so if miterLength >= 2 we need to draw a different type of bevel here. + // The maximum extrude length is 128 / 63 = 2 times the width of + // the line so if miterLength >= 2 we need to draw a different + // type of bevel here. if (miterLength > 2) { currentJoin = LineJoinType::FlipBevel; } @@ -290,13 +295,12 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, } // Calculate how far along the line the currentVertex is - if (prevCoordinate) - distance += util::dist(*currentCoordinate, *prevCoordinate); + if (prevCoordinate) distance += util::dist(*currentCoordinate, *prevCoordinate); if (middleVertex && currentJoin == LineJoinType::Miter) { joinNormal = joinNormal * miterLength; - addCurrentVertex(*currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, - triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, triangleStore, lineDistances); } else if (middleVertex && currentJoin == LineJoinType::FlipBevel) { // miter is too big, flip the direction to make a beveled join @@ -307,15 +311,22 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, } else { const double direction = prevNormal->x * nextNormal->y - prevNormal->y * nextNormal->x > 0 ? -1 : 1; const double bevelLength = miterLength * util::mag(*prevNormal + *nextNormal) / - util::mag(*prevNormal - *nextNormal); + util::mag(*prevNormal - *nextNormal); joinNormal = util::perp(joinNormal) * bevelLength * direction; } - addCurrentVertex(*currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, - triangleStore, lineDistances); - - addCurrentVertex(*currentCoordinate, distance, joinNormal * -1.0, 0, 0, false, startVertex, - triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, joinNormal, 0, 0, false, startVertex, triangleStore, lineDistances); + + addCurrentVertex(*currentCoordinate, + distance, + joinNormal * -1.0, + 0, + 0, + false, + startVertex, + triangleStore, + lineDistances); } else if (middleVertex && (currentJoin == LineJoinType::Bevel || currentJoin == LineJoinType::FakeRound)) { const bool lineTurnsLeft = (prevNormal->x * nextNormal->y - prevNormal->y * nextNormal->x) > 0; const auto offset = static_cast(-std::sqrt(miterLength * miterLength - 1)); @@ -332,57 +343,80 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Close previous segement with bevel if (!startOfLine) { - addCurrentVertex(*currentCoordinate, distance, *prevNormal, offsetA, offsetB, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex(*currentCoordinate, + distance, + *prevNormal, + offsetA, + offsetB, + false, + startVertex, + triangleStore, + lineDistances); } if (currentJoin == LineJoinType::FakeRound) { - // The join angle is sharp enough that a round join would be visible. - // Bevel joins fill the gap between segments with a single pie slice triangle. - // Create a round join by adding multiple pie slices. The join isn't actually round, but - // it looks like it is at the sizes we render lines at. - - // Pick the number of triangles for approximating round join by based on the angle between normals. + // The join angle is sharp enough that a round join would be + // visible. Bevel joins fill the gap between segments with a + // single pie slice triangle. Create a round join by adding + // multiple pie slices. The join isn't actually round, but it + // looks like it is at the sizes we render lines at. + + // Pick the number of triangles for approximating round join by + // based on the angle between normals. const auto n = static_cast(::round((approxAngle * 180 / M_PI) / DEG_PER_TRIANGLE)); for (unsigned m = 1; m < n; ++m) { double t = static_cast(m) / n; if (t != 0.5) { - // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp + // approximate spherical interpolation + // https://observablehq.com/@mourner/approximating-geometric-slerp const double t2 = t - 0.5; const double A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519)); const double B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638); t = t + t * t2 * (t - 1) * (A * t2 * t2 + B); } auto approxFractionalNormal = util::unit(*prevNormal * (1.0 - t) + *nextNormal * t); - addPieSliceVertex(*currentCoordinate, distance, approxFractionalNormal, lineTurnsLeft, startVertex, triangleStore, lineDistances); + addPieSliceVertex(*currentCoordinate, + distance, + approxFractionalNormal, + lineTurnsLeft, + startVertex, + triangleStore, + lineDistances); } } // Start next segment if (nextCoordinate) { - addCurrentVertex(*currentCoordinate, distance, *nextNormal, -offsetA, -offsetB, - false, startVertex, triangleStore, lineDistances); + addCurrentVertex(*currentCoordinate, + distance, + *nextNormal, + -offsetA, + -offsetB, + false, + startVertex, + triangleStore, + lineDistances); } } else if (!middleVertex && currentCap == LineCapType::Butt) { if (!startOfLine) { // Close previous segment with a butt - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances); } // Start next segment with a butt if (nextCoordinate) { - addCurrentVertex(*currentCoordinate, distance, *nextNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances); } } else if (!middleVertex && currentCap == LineCapType::Square) { if (!startOfLine) { // Close previous segment with a square cap - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 1, 1, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 1, 1, false, startVertex, triangleStore, lineDistances); // The segment is done. Unset vertices to disconnect segments. e1 = e2 = -1; @@ -390,19 +424,26 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Start next segment if (nextCoordinate) { - addCurrentVertex(*currentCoordinate, distance, *nextNormal, -1, -1, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex(*currentCoordinate, + distance, + *nextNormal, + -1, + -1, + false, + startVertex, + triangleStore, + lineDistances); } } else if (middleVertex ? currentJoin == LineJoinType::Round : currentCap == LineCapType::Round) { if (!startOfLine) { // Close previous segment with a butt - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances); // Add round cap or linejoin at end of segment - addCurrentVertex(*currentCoordinate, distance, *prevNormal, 1, 1, true, startVertex, - triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *prevNormal, 1, 1, true, startVertex, triangleStore, lineDistances); // The segment is done. Unset vertices to disconnect segments. e1 = e2 = -1; @@ -411,20 +452,24 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, // Start next segment with a butt if (nextCoordinate) { // Add round cap before first segment - addCurrentVertex(*currentCoordinate, distance, *nextNormal, -1, -1, true, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *nextNormal, -1, -1, true, startVertex, triangleStore, lineDistances); - addCurrentVertex(*currentCoordinate, distance, *nextNormal, 0, 0, false, - startVertex, triangleStore, lineDistances); + addCurrentVertex( + *currentCoordinate, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances); } } if (isSharpCorner && i < len - 1) { const auto nextSegmentLength = util::dist(*currentCoordinate, *nextCoordinate); if (nextSegmentLength > 2 * sharpCornerOffset) { - GeometryCoordinate newCurrentVertex = *currentCoordinate + convertPoint(util::round(convertPoint(*nextCoordinate - *currentCoordinate) * (sharpCornerOffset / nextSegmentLength))); + GeometryCoordinate newCurrentVertex = *currentCoordinate + + convertPoint(util::round( + convertPoint(*nextCoordinate - *currentCoordinate) * + (sharpCornerOffset / nextSegmentLength))); distance += util::dist(newCurrentVertex, *currentCoordinate); - addCurrentVertex(newCurrentVertex, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances); + addCurrentVertex( + newCurrentVertex, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances); currentCoordinate = newCurrentVertex; } } @@ -452,7 +497,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, } void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, - double &distance, + double& distance, const Point& normal, double endLeft, double endRight, @@ -463,9 +508,13 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, Point extrude = normal; double scaledDistance = lineDistances ? lineDistances->scaleToMaxLineDistance(distance) : distance; - if (endLeft) - extrude = extrude - (util::perp(normal) * endLeft); - vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, false, static_cast(endLeft), static_cast(scaledDistance * LINE_DISTANCE_SCALE))); + if (endLeft) extrude = extrude - (util::perp(normal) * endLeft); + vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, + extrude, + round, + false, + static_cast(endLeft), + static_cast(scaledDistance * LINE_DISTANCE_SCALE))); e3 = vertices.elements() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(static_cast(e1), static_cast(e2), static_cast(e3)); @@ -474,9 +523,13 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, e2 = e3; extrude = normal * -1.0; - if (endRight) - extrude = extrude - (util::perp(normal) * endRight); - vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, true, static_cast(-endRight), static_cast(scaledDistance * LINE_DISTANCE_SCALE))); + if (endRight) extrude = extrude - (util::perp(normal) * endRight); + vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, + extrude, + round, + true, + static_cast(-endRight), + static_cast(scaledDistance * LINE_DISTANCE_SCALE))); e3 = vertices.elements() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(static_cast(e1), static_cast(e2), static_cast(e3)); @@ -484,13 +537,14 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, e1 = e2; e2 = e3; - // There is a maximum "distance along the line" that we can store in the buffers. - // When we get close to the distance, reset it to zero and add the vertex again with - // a distance of zero. The max distance is determined by the number of bits we allocate - // to `linesofar`. + // There is a maximum "distance along the line" that we can store in the + // buffers. When we get close to the distance, reset it to zero and add the + // vertex again with a distance of zero. The max distance is determined by + // the number of bits we allocate to `linesofar`. if (distance > MAX_LINE_DISTANCE / 2.0f && !lineDistances) { distance = 0.0; - addCurrentVertex(currentCoordinate, distance, normal, endLeft, endRight, round, startVertex, triangleStore, lineDistances); + addCurrentVertex( + currentCoordinate, distance, normal, endLeft, endRight, round, startVertex, triangleStore, lineDistances); } } @@ -506,7 +560,8 @@ void LineBucket::addPieSliceVertex(const GeometryCoordinate& currentVertex, distance = lineDistances->scaleToMaxLineDistance(distance); } - vertices.emplace_back(LineProgram::layoutVertex(currentVertex, flippedExtrude, false, lineTurnsLeft, 0, static_cast(distance * LINE_DISTANCE_SCALE))); + vertices.emplace_back(LineProgram::layoutVertex( + currentVertex, flippedExtrude, false, lineTurnsLeft, 0, static_cast(distance * LINE_DISTANCE_SCALE))); e3 = vertices.elements() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(static_cast(e1), static_cast(e2), static_cast(e3)); @@ -537,7 +592,9 @@ bool LineBucket::hasData() const { } template -static float get(const LinePaintProperties::PossiblyEvaluated& evaluated, const std::string& id, const std::map& paintPropertyBinders) { +static float get(const LinePaintProperties::PossiblyEvaluated& evaluated, + const std::string& id, + const std::map& paintPropertyBinders) { auto it = paintPropertyBinders.find(id); if (it == paintPropertyBinders.end() || !it->second.statistics().max()) { return evaluated.get().constantOr(Property::defaultValue()); @@ -559,7 +616,9 @@ float LineBucket::getQueryRadius(const RenderLayer& layer) const { return lineWidth / 2.0f + std::abs(offset) + util::length(translate[0], translate[1]); } -void LineBucket::update(const FeatureStates& states, const GeometryTileLayer& layer, const std::string& layerID, +void LineBucket::update(const FeatureStates& states, + const GeometryTileLayer& layer, + const std::string& layerID, const ImagePositions& imagePositions) { auto it = paintPropertyBinders.find(layerID); if (it != paintPropertyBinders.end()) { diff --git a/src/mbgl/renderer/buckets/line_bucket.hpp b/src/mbgl/renderer/buckets/line_bucket.hpp index e3daa517705..f98bed20a59 100644 --- a/src/mbgl/renderer/buckets/line_bucket.hpp +++ b/src/mbgl/renderer/buckets/line_bucket.hpp @@ -55,7 +55,10 @@ class LineBucket final : public Bucket { void addGeometry(const GeometryCoordinates&, const GeometryTileFeature&, const CanonicalTileID&); struct TriangleElement { - TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) : a(a_), b(b_), c(c_) {} + TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) + : a(a_), + b(b_), + c(c_) {} uint16_t a, b, c; }; @@ -70,10 +73,13 @@ class LineBucket final : public Bucket { std::vector& triangleStore, std::optional distances); - void addPieSliceVertex(const GeometryCoordinate& currentVertex, double distance, - const Point& extrude, bool lineTurnsLeft, std::size_t startVertex, - std::vector& triangleStore, - std::optional distances); + void addPieSliceVertex(const GeometryCoordinate& currentVertex, + double distance, + const Point& extrude, + bool lineTurnsLeft, + std::size_t startVertex, + std::vector& triangleStore, + std::optional distances); std::ptrdiff_t e1; std::ptrdiff_t e2; diff --git a/src/mbgl/renderer/buckets/raster_bucket.cpp b/src/mbgl/renderer/buckets/raster_bucket.cpp index a877e6e17b3..2b0cf65c12f 100644 --- a/src/mbgl/renderer/buckets/raster_bucket.cpp +++ b/src/mbgl/renderer/buckets/raster_bucket.cpp @@ -10,7 +10,8 @@ using namespace style; RasterBucket::RasterBucket(PremultipliedImage&& image_) : image(std::make_shared(std::move(image_))) {} -RasterBucket::RasterBucket(std::shared_ptr image_) : image(std::move(image_)) {} +RasterBucket::RasterBucket(std::shared_ptr image_) + : image(std::move(image_)) {} RasterBucket::~RasterBucket() = default; @@ -54,14 +55,15 @@ void RasterBucket::setMask(TileMask&& mask_) { mask = std::move(mask_); clear(); - if (mask == TileMask{ { 0, 0, 0 } }) { - // We want to render the full tile, and keeping the segments/vertices/indices empty means - // using the global shared buffers for covering the entire tile. + if (mask == TileMask{{0, 0, 0}}) { + // We want to render the full tile, and keeping the + // segments/vertices/indices empty means using the global shared buffers + // for covering the entire tile. return; } - // Create a new segment so that we will upload (empty) buffers even when there is nothing to - // draw for this tile. + // Create a new segment so that we will upload (empty) buffers even when + // there is nothing to draw for this tile. segments.emplace_back(0, 0); constexpr const uint16_t vertexLength = 4; @@ -71,24 +73,24 @@ void RasterBucket::setMask(TileMask&& mask_) { // Create a quad for every masked tile. const int32_t vertexExtent = util::EXTENT >> id.z; - const Point tlVertex = { static_cast(id.x * vertexExtent), - static_cast(id.y * vertexExtent) }; - const Point brVertex = { static_cast(tlVertex.x + vertexExtent), - static_cast(tlVertex.y + vertexExtent) }; + const Point tlVertex = {static_cast(id.x * vertexExtent), + static_cast(id.y * vertexExtent)}; + const Point brVertex = {static_cast(tlVertex.x + vertexExtent), + static_cast(tlVertex.y + vertexExtent)}; if (segments.back().vertexLength + vertexLength > std::numeric_limits::max()) { // Move to a new segments because the old one can't hold the geometry. segments.emplace_back(vertices.elements(), indices.elements()); } - vertices.emplace_back( - RasterProgram::layoutVertex({ tlVertex.x, tlVertex.y }, { static_cast(tlVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - RasterProgram::layoutVertex({ brVertex.x, tlVertex.y }, { static_cast(brVertex.x), static_cast(tlVertex.y) })); - vertices.emplace_back( - RasterProgram::layoutVertex({ tlVertex.x, brVertex.y }, { static_cast(tlVertex.x), static_cast(brVertex.y) })); - vertices.emplace_back( - RasterProgram::layoutVertex({ brVertex.x, brVertex.y }, { static_cast(brVertex.x), static_cast(brVertex.y) })); + vertices.emplace_back(RasterProgram::layoutVertex( + {tlVertex.x, tlVertex.y}, {static_cast(tlVertex.x), static_cast(tlVertex.y)})); + vertices.emplace_back(RasterProgram::layoutVertex( + {brVertex.x, tlVertex.y}, {static_cast(brVertex.x), static_cast(tlVertex.y)})); + vertices.emplace_back(RasterProgram::layoutVertex( + {tlVertex.x, brVertex.y}, {static_cast(tlVertex.x), static_cast(brVertex.y)})); + vertices.emplace_back(RasterProgram::layoutVertex( + {brVertex.x, brVertex.y}, {static_cast(brVertex.x), static_cast(brVertex.y)})); auto& segment = segments.back(); assert(segment.vertexLength <= std::numeric_limits::max()); @@ -108,5 +110,4 @@ bool RasterBucket::hasData() const { return !!image; } - } // namespace mbgl diff --git a/src/mbgl/renderer/buckets/raster_bucket.hpp b/src/mbgl/renderer/buckets/raster_bucket.hpp index eeb00afb6dc..76ee30c0d91 100644 --- a/src/mbgl/renderer/buckets/raster_bucket.hpp +++ b/src/mbgl/renderer/buckets/raster_bucket.hpp @@ -28,7 +28,7 @@ class RasterBucket final : public Bucket { std::shared_ptr image; std::optional texture; - TileMask mask{ { 0, 0, 0 } }; + TileMask mask{{0, 0, 0}}; // Bucket specific vertices are used for Image Sources only // Raster Tile Sources use the default buffers from Painter diff --git a/src/mbgl/renderer/buckets/symbol_bucket.cpp b/src/mbgl/renderer/buckets/symbol_bucket.cpp index 74d04ece7a3..eb6c2547656 100644 --- a/src/mbgl/renderer/buckets/symbol_bucket.cpp +++ b/src/mbgl/renderer/buckets/symbol_bucket.cpp @@ -55,10 +55,8 @@ SymbolBucket::SymbolBucket(Immutable& triangles, const PlacedSymbol& placedSymbol) { auto endIndex = placedSymbol.vertexStartIndex + placedSymbol.glyphOffsets.size() * 4; for (auto vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { - triangles.emplace_back(static_cast(vertexIndex + 0), static_cast(vertexIndex + 1), static_cast(vertexIndex + 2)); - triangles.emplace_back(static_cast(vertexIndex + 1), static_cast(vertexIndex + 2), static_cast(vertexIndex + 3)); + triangles.emplace_back(static_cast(vertexIndex + 0), + static_cast(vertexIndex + 1), + static_cast(vertexIndex + 2)); + triangles.emplace_back(static_cast(vertexIndex + 1), + static_cast(vertexIndex + 2), + static_cast(vertexIndex + 3)); } } @@ -226,8 +240,9 @@ void SymbolBucket::sortFeatures(const float angle) { sortedAngle = angle; - // The current approach to sorting doesn't sort across text and icon segments so don't try. - // Sorting within segments separately seemed not to be worth the complexity. + // The current approach to sorting doesn't sort across text and icon + // segments so don't try. Sorting within segments separately seemed not to + // be worth the complexity. if (text.segments.size() > 1 || (icon.segments.size() > 1 || sdfIcon.segments.size() > 1)) { return; } @@ -242,9 +257,9 @@ void SymbolBucket::sortFeatures(const float angle) { auto symbolsSortOrder = std::make_unique>(); symbolsSortOrder->reserve(symbolInstances.size()); - // If the symbols are allowed to overlap sort them by their vertical screen position. - // The index array buffer is rewritten to reference the (unchanged) vertices in the - // sorted order. + // If the symbols are allowed to overlap sort them by their vertical screen + // position. The index array buffer is rewritten to reference the + // (unchanged) vertices in the sorted order. for (const SymbolInstance& symbolInstance : getSortedSymbols(angle)) { symbolsSortOrder->push_back(symbolInstance.dataFeatureIndex); @@ -288,7 +303,7 @@ SymbolInstanceReferences SymbolBucket::getSortedSymbols(const float angle) const if (aRotated != bRotated) { return aRotated < bRotated; } - return a.dataFeatureIndex > b.dataFeatureIndex; // aRotated == bRotated + return a.dataFeatureIndex > b.dataFeatureIndex; // aRotated == bRotated }); return result; @@ -305,7 +320,7 @@ SymbolInstanceReferences SymbolBucket::getSymbols(const std::optionalget()); + hasFormatSectionOverrides_ = SymbolLayerPaintPropertyOverrides::hasOverrides(layout->get()); } return *hasFormatSectionOverrides_; } diff --git a/src/mbgl/renderer/buckets/symbol_bucket.hpp b/src/mbgl/renderer/buckets/symbol_bucket.hpp index 9f091ac44bf..6d6f8b0d9c4 100644 --- a/src/mbgl/renderer/buckets/symbol_bucket.hpp +++ b/src/mbgl/renderer/buckets/symbol_bucket.hpp @@ -54,8 +54,8 @@ class PlacedSymbol { size_t vertexStartIndex; // The crossTileID is only filled/used on the foreground for variable text anchors uint32_t crossTileID = 0u; - // The placedOrientation is only used when symbol layer's property is set to support - // placement for orientation variants. + // The placedOrientation is only used when symbol layer's property is set to + // support placement for orientation variants. std::optional placedOrientation; float angle = 0; @@ -99,8 +99,9 @@ class SymbolBucket final : public Bucket { void sortFeatures(float angle); // Returns references to the `symbolInstances` items, sorted by viewport Y. SymbolInstanceReferences getSortedSymbols(float angle) const; - // Returns references to the `symbolInstances` items, which belong to the `sortKeyRange` range; - // returns references to all the symbols if |sortKeyRange| is `std::nullopt`. + // Returns references to the `symbolInstances` items, which belong to the + // `sortKeyRange` range; returns references to all the symbols if + // |sortKeyRange| is `std::nullopt`. SymbolInstanceReferences getSymbols(const std::optional& sortKeyRange = std::nullopt) const; Immutable layout; @@ -149,7 +150,7 @@ class SymbolBucket final : public Bucket { Buffer icon; Buffer sdfIcon; - + struct CollisionBuffer { gfx::VertexVector> vertices; gfx::VertexVector> dynamicVertices; diff --git a/src/mbgl/renderer/cross_faded_property_evaluator.cpp b/src/mbgl/renderer/cross_faded_property_evaluator.cpp index 65f5b31467b..5369c531321 100644 --- a/src/mbgl/renderer/cross_faded_property_evaluator.cpp +++ b/src/mbgl/renderer/cross_faded_property_evaluator.cpp @@ -26,9 +26,7 @@ Faded CrossFadedPropertyEvaluator::operator()(const style::PropertyExpress template Faded CrossFadedPropertyEvaluator::calculate(const T& min, const T& mid, const T& max) const { const float z = parameters.z; - return z > parameters.zoomHistory.lastIntegerZoom - ? Faded { min, mid } - : Faded { max, mid }; + return z > parameters.zoomHistory.lastIntegerZoom ? Faded{min, mid} : Faded{max, mid}; } template class CrossFadedPropertyEvaluator; diff --git a/src/mbgl/renderer/cross_faded_property_evaluator.hpp b/src/mbgl/renderer/cross_faded_property_evaluator.hpp index e925b96fa3b..f0fe90f69ae 100644 --- a/src/mbgl/renderer/cross_faded_property_evaluator.hpp +++ b/src/mbgl/renderer/cross_faded_property_evaluator.hpp @@ -35,8 +35,7 @@ class CrossFadedPropertyEvaluator { namespace util { template -struct Interpolator> - : Uninterpolated {}; +struct Interpolator> : Uninterpolated {}; } // namespace util } // namespace mbgl diff --git a/src/mbgl/renderer/data_driven_property_evaluator.hpp b/src/mbgl/renderer/data_driven_property_evaluator.hpp index bd476ebe585..25b8bc8d10c 100644 --- a/src/mbgl/renderer/data_driven_property_evaluator.hpp +++ b/src/mbgl/renderer/data_driven_property_evaluator.hpp @@ -18,16 +18,12 @@ class DataDrivenPropertyEvaluator { : parameters(parameters_), defaultValue(std::move(defaultValue_)) {} - ResultType operator()(const style::Undefined&) const { - return ResultType(defaultValue); - } + ResultType operator()(const style::Undefined&) const { return ResultType(defaultValue); } - ResultType operator()(const T& constant) const { - return ResultType(constant); - } + ResultType operator()(const T& constant) const { return ResultType(constant); } ResultType operator()(const style::PropertyExpression& expression) const { - if (useIntegerZoom) { // Compiler will optimize out the unused branch. + if (useIntegerZoom) { // Compiler will optimize out the unused branch. if (!expression.isFeatureConstant() || !expression.isRuntimeConstant()) { auto returnExpression = expression; returnExpression.useIntegerZoom = true; @@ -53,14 +49,12 @@ class DataDrivenPropertyEvaluator> { using ResultType = PossiblyEvaluatedPropertyValue>; DataDrivenPropertyEvaluator(const PropertyEvaluationParameters& parameters_, T defaultValue_) - : parameters(parameters_), - defaultValue(std::move(defaultValue_)) {} + : parameters(parameters_), + defaultValue(std::move(defaultValue_)) {} - ResultType operator()(const T& constant) const { - return ResultType(calculate(constant, constant, constant)); - } + ResultType operator()(const T& constant) const { return ResultType(calculate(constant, constant, constant)); } - ResultType operator()(const style::Undefined& ) const { + ResultType operator()(const style::Undefined&) const { return ResultType(calculate(defaultValue, defaultValue, defaultValue)); } @@ -73,13 +67,10 @@ class DataDrivenPropertyEvaluator> { } } - private: Faded calculate(const T& min, const T& mid, const T& max) const { const float z = parameters.z; - return z > parameters.zoomHistory.lastIntegerZoom - ? Faded { min, mid } - : Faded { max, mid }; + return z > parameters.zoomHistory.lastIntegerZoom ? Faded{min, mid} : Faded{max, mid}; }; const PropertyEvaluationParameters& parameters; diff --git a/src/mbgl/renderer/image_atlas.cpp b/src/mbgl/renderer/image_atlas.cpp index 36da19bbce3..dcd78f58f39 100644 --- a/src/mbgl/renderer/image_atlas.cpp +++ b/src/mbgl/renderer/image_atlas.cpp @@ -15,45 +15,37 @@ ImagePosition::ImagePosition(const mapbox::Bin& bin, const style::Image::Impl& i stretchY(image.stretchY), content(image.content) {} -const mapbox::Bin& _packImage(mapbox::ShelfPack& pack, const style::Image::Impl& image, ImageAtlas& resultImage, ImageType imageType) { - const mapbox::Bin& bin = *pack.packOne(-1, - image.image.size.width + 2 * padding, - image.image.size.height + 2 * padding); - - resultImage.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); - - PremultipliedImage::copy(image.image, - resultImage.image, - { 0, 0 }, - { - bin.x + padding, - bin.y + padding - }, - image.image.size); +const mapbox::Bin& _packImage(mapbox::ShelfPack& pack, + const style::Image::Impl& image, + ImageAtlas& resultImage, + ImageType imageType) { + const mapbox::Bin& bin = *pack.packOne( + -1, image.image.size.width + 2 * padding, image.image.size.height + 2 * padding); + + resultImage.image.resize({static_cast(pack.width()), static_cast(pack.height())}); + + PremultipliedImage::copy( + image.image, resultImage.image, {0, 0}, {bin.x + padding, bin.y + padding}, image.image.size); uint32_t x = bin.x + padding; uint32_t y = bin.y + padding; uint32_t w = image.image.size.width; uint32_t h = image.image.size.height; if (imageType == ImageType::Pattern) { - // Add 1 pixel wrapped padding on each side of the image. - PremultipliedImage::copy(image.image, resultImage.image, { 0, h - 1 }, { x, y - 1 }, { w, 1 }); // T - PremultipliedImage::copy(image.image, resultImage.image, { 0, 0 }, { x, y + h }, { w, 1 }); // B - PremultipliedImage::copy(image.image, resultImage.image, { w - 1, 0 }, { x - 1, y }, { 1, h }); // L - PremultipliedImage::copy(image.image, resultImage.image, { 0, 0 }, { x + w, y }, { 1, h }); // R + // Add 1 pixel wrapped padding on each side of the image. + PremultipliedImage::copy(image.image, resultImage.image, {0, h - 1}, {x, y - 1}, {w, 1}); // T + PremultipliedImage::copy(image.image, resultImage.image, {0, 0}, {x, y + h}, {w, 1}); // B + PremultipliedImage::copy(image.image, resultImage.image, {w - 1, 0}, {x - 1, y}, {1, h}); // L + PremultipliedImage::copy(image.image, resultImage.image, {0, 0}, {x + w, y}, {1, h}); // R } return bin; } namespace { -void populateImagePatches( - ImagePositions& imagePositions, - const ImageManager& imageManager, - std::vector& /*out*/ patches) { +void populateImagePatches(ImagePositions& imagePositions, + const ImageManager& imageManager, + std::vector& /*out*/ patches) { for (auto& updatedImageVersion : imageManager.updatedImageVersions) { const std::string& name = updatedImageVersion.first; const uint32_t version = updatedImageVersion.second; @@ -80,7 +72,9 @@ std::vector ImageAtlas::getImagePatchesAndUpdateVersions(const Image return imagePatches; } -ImageAtlas makeImageAtlas(const ImageMap& icons, const ImageMap& patterns, const std::unordered_map& versionMap) { +ImageAtlas makeImageAtlas(const ImageMap& icons, + const ImageMap& patterns, + const std::unordered_map& versionMap) { ImageAtlas result; mapbox::ShelfPack::ShelfPackOptions options; @@ -92,7 +86,7 @@ ImageAtlas makeImageAtlas(const ImageMap& icons, const ImageMap& patterns, const const mapbox::Bin& bin = _packImage(pack, image, result, ImageType::Icon); auto it = versionMap.find(entry.first); auto version = it != versionMap.end() ? it->second : 0; - result.iconPositions.emplace(image.id, ImagePosition { bin, image, version }); + result.iconPositions.emplace(image.id, ImagePosition{bin, image, version}); } for (const auto& entry : patterns) { @@ -100,14 +94,11 @@ ImageAtlas makeImageAtlas(const ImageMap& icons, const ImageMap& patterns, const const mapbox::Bin& bin = _packImage(pack, image, result, ImageType::Pattern); auto it = versionMap.find(entry.first); auto version = it != versionMap.end() ? it->second : 0; - result.patternPositions.emplace(image.id, ImagePosition { bin, image, version }); + result.patternPositions.emplace(image.id, ImagePosition{bin, image, version}); } pack.shrink(); - result.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); + result.image.resize({static_cast(pack.width()), static_cast(pack.height())}); return result; } diff --git a/src/mbgl/renderer/image_atlas.hpp b/src/mbgl/renderer/image_atlas.hpp index d8f021faf42..f27557dd528 100644 --- a/src/mbgl/renderer/image_atlas.hpp +++ b/src/mbgl/renderer/image_atlas.hpp @@ -41,7 +41,7 @@ class ImagePosition { std::array tlbr() const { const auto _tl = tl(); const auto _br = br(); - return {{ _tl[0], _tl[1], _br[0], _br[1] }}; + return {{_tl[0], _tl[1], _br[0], _br[1]}}; } std::array displaySize() const { @@ -57,7 +57,8 @@ using ImagePositions = std::map; class ImagePatch { public: ImagePatch(Immutable image_, const Rect& paddedRect_) - : image(std::move(image_)), paddedRect(paddedRect_) {} + : image(std::move(image_)), + paddedRect(paddedRect_) {} Immutable image; Rect paddedRect; @@ -72,6 +73,8 @@ class ImageAtlas { std::vector getImagePatchesAndUpdateVersions(const ImageManager&); }; -ImageAtlas makeImageAtlas(const ImageMap&, const ImageMap&, const std::unordered_map& versionMap); +ImageAtlas makeImageAtlas(const ImageMap&, + const ImageMap&, + const std::unordered_map& versionMap); } // namespace mbgl diff --git a/src/mbgl/renderer/image_manager.cpp b/src/mbgl/renderer/image_manager.cpp index 62df741e196..74d109f0107 100644 --- a/src/mbgl/renderer/image_manager.cpp +++ b/src/mbgl/renderer/image_manager.cpp @@ -220,8 +220,9 @@ void ImageManager::checkMissingAndNotify(ImageRequestor& requestor, const ImageR // The request for this image has been already delivered // to the client, so we do not treat it as pending. existingRequestors.emplace(requestorPtr); - // TODO: we could `continue;` here, but we need to call `observer->onStyleImageMissing`, - // so that rendering is re-launched from the handler at Map::Impl. + // TODO: we could `continue;` here, but we need to call + // `observer->onStyleImageMissing`, so that rendering is + // re-launched from the handler at Map::Impl. } else { requestedImages[missingImage].emplace(requestorPtr); requestor.addPendingRequest(missingImage); @@ -277,8 +278,8 @@ void ImageManager::dumpDebugLogs() const { Log::Info(Event::General, ss.str()); } -ImageRequestor::ImageRequestor(ImageManager& imageManager_) : imageManager(imageManager_) { -} +ImageRequestor::ImageRequestor(ImageManager& imageManager_) + : imageManager(imageManager_) {} ImageRequestor::~ImageRequestor() { imageManager.removeRequestor(*this); diff --git a/src/mbgl/renderer/image_manager.hpp b/src/mbgl/renderer/image_manager.hpp index fec19981f52..ad6715fe6e5 100644 --- a/src/mbgl/renderer/image_manager.hpp +++ b/src/mbgl/renderer/image_manager.hpp @@ -19,7 +19,8 @@ class ImageManagerObserver; class ImageRequestor; /** - * @brief tracks requests for icon images from tile workers and sends responses when the requests are fulfilled. + * @brief tracks requests for icon images from tile workers and sends responses + * when the requests are fulfilled. */ class ImageManager { public: @@ -75,7 +76,10 @@ class ImageRequestor { public: explicit ImageRequestor(ImageManager&); virtual ~ImageRequestor(); - virtual void onImagesAvailable(ImageMap icons, ImageMap patterns, ImageVersionMap versionMap, uint64_t imageCorrelationID) = 0; + virtual void onImagesAvailable(ImageMap icons, + ImageMap patterns, + ImageVersionMap versionMap, + uint64_t imageCorrelationID) = 0; void addPendingRequest(const std::string& imageId) { pendingRequests.insert(imageId); } bool hasPendingRequest(const std::string& imageId) const { return pendingRequests.count(imageId); } diff --git a/src/mbgl/renderer/layers/render_background_layer.cpp b/src/mbgl/renderer/layers/render_background_layer.cpp index 95537c0ffaf..1a63e776b60 100644 --- a/src/mbgl/renderer/layers/render_background_layer.cpp +++ b/src/mbgl/renderer/layers/render_background_layer.cpp @@ -31,24 +31,22 @@ RenderBackgroundLayer::RenderBackgroundLayer(Immutable( - staticImmutableCast(baseImpl), - parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); - - passes = properties->evaluated.get() == 0.0f - ? RenderPass::None - : (!unevaluated.get().isUndefined() - || properties->evaluated.get() < 1.0f - || properties->evaluated.get().a < 1.0f) - ? RenderPass::Translucent - // Supply both - evaluated based on opaquePassCutoff in render(). - : RenderPass::Opaque | RenderPass::Translucent; +void RenderBackgroundLayer::evaluate(const PropertyEvaluationParameters& parameters) { + auto properties = makeMutable(staticImmutableCast(baseImpl), + parameters.getCrossfadeParameters(), + unevaluated.evaluate(parameters)); + + passes = properties->evaluated.get() == 0.0f ? RenderPass::None + : (!unevaluated.get().isUndefined() || + properties->evaluated.get() < 1.0f || + properties->evaluated.get().a < 1.0f) + ? RenderPass::Translucent + // Supply both - evaluated based on opaquePassCutoff in render(). + : RenderPass::Opaque | RenderPass::Translucent; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -62,8 +60,8 @@ bool RenderBackgroundLayer::hasCrossfade() const { } void RenderBackgroundLayer::render(PaintParameters& parameters) { - // Note that for bottommost layers without a pattern, the background color is drawn with - // glClear rather than this method. + // Note that for bottommost layers without a pattern, the background color + // is drawn with glClear rather than this method. // Ensure programs are available if (!parameters.shaders.populate(backgroundProgram)) return; @@ -73,16 +71,13 @@ void RenderBackgroundLayer::render(PaintParameters& parameters) { const BackgroundProgram::Binders paintAttributeData(properties, 0); auto draw = [&](auto& program, auto&& uniformValues, const auto& textureBindings, const uint32_t id) { - const auto allUniformValues = - program.computeAllUniformValues(std::forward(uniformValues), - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = program.computeAllAttributeBindings( - *parameters.staticData.tileVertexBuffer, + const auto allUniformValues = program.computeAllUniformValues( + std::forward(uniformValues), paintAttributeData, - properties - ); + properties, + static_cast(parameters.state.getZoom())); + const auto allAttributeBindings = program.computeAllAttributeBindings( + *parameters.staticData.tileVertexBuffer, paintAttributeData, properties); checkRenderability(parameters, program.activeBindingCount(allAttributeBindings)); @@ -111,13 +106,12 @@ void RenderBackgroundLayer::render(PaintParameters& parameters) { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; const auto& crossfade = static_cast(*evaluatedProperties).crossfade; if (!evaluated.get().to.empty()) { - std::optional imagePosA = - parameters.patternAtlas.getPattern(evaluated.get().from.id()); - std::optional imagePosB = - parameters.patternAtlas.getPattern(evaluated.get().to.id()); + std::optional imagePosA = parameters.patternAtlas.getPattern( + evaluated.get().from.id()); + std::optional imagePosB = parameters.patternAtlas.getPattern( + evaluated.get().to.id()); - if (!imagePosA || !imagePosB) - return; + if (!imagePosA || !imagePosB) return; uint32_t i = 0; for (const auto& tileID : util::tileCover(parameters.state, parameters.state.getIntegerZoom())) { @@ -137,9 +131,11 @@ void RenderBackgroundLayer::render(PaintParameters& parameters) { i++); } } else { - auto backgroundRenderPass = (evaluated.get().a >= 1.0f - && evaluated.get() >= 1.0f - && parameters.currentLayer >= parameters.opaquePassCutoff) ? RenderPass::Opaque : RenderPass::Translucent; + auto backgroundRenderPass = (evaluated.get().a >= 1.0f && + evaluated.get() >= 1.0f && + parameters.currentLayer >= parameters.opaquePassCutoff) + ? RenderPass::Opaque + : RenderPass::Translucent; if (parameters.pass != backgroundRenderPass) { return; } @@ -163,7 +159,7 @@ std::optional RenderBackgroundLayer::getSolidBackground() const { return std::nullopt; } - return { evaluated.get() * evaluated.get() }; + return {evaluated.get() * evaluated.get()}; } namespace { @@ -172,14 +168,14 @@ void addPatternIfNeeded(const std::string& id, const LayerPrepareParameters& par if (auto* image = params.imageManager.getImage(id)) { params.patternAtlas.addPattern(*image); } - } + } } } // namespace void RenderBackgroundLayer::prepare(const LayerPrepareParameters& params) { const auto& evaluated = getEvaluated(evaluatedProperties); if (!evaluated.get().to.empty()) { - // Ensures that the pattern bitmap gets copied to atlas bitmap. + // Ensures that the pattern bitmap gets copied to atlas bitmap. // Atlas bitmap is uploaded to atlas texture in upload. addPatternIfNeeded(evaluated.get().from.id(), params); addPatternIfNeeded(evaluated.get().to.id(), params); diff --git a/src/mbgl/renderer/layers/render_circle_layer.cpp b/src/mbgl/renderer/layers/render_circle_layer.cpp index 28e9368ed16..58b7af4ce92 100644 --- a/src/mbgl/renderer/layers/render_circle_layer.cpp +++ b/src/mbgl/renderer/layers/render_circle_layer.cpp @@ -23,7 +23,10 @@ struct RenderableSegment { const RenderTile& tile_, const LayerRenderData* renderData_, float sortKey_) - : segment(segment_), tile(tile_), renderData(renderData_), sortKey(sortKey_) {} + : segment(segment_), + tile(tile_), + renderData(renderData_), + sortKey(sortKey_) {} const Segment& segment; const RenderTile& tile; @@ -52,18 +55,18 @@ void RenderCircleLayer::transition(const TransitionParameters& parameters) { } void RenderCircleLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + auto properties = makeMutable(staticImmutableCast(baseImpl), + unevaluated.evaluate(parameters)); const auto& evaluated = properties->evaluated; passes = ((evaluated.get().constantOr(1) > 0 || - evaluated.get().constantOr(1) > 0) - && (evaluated.get().constantOr(Color::black()).a > 0 || - evaluated.get().constantOr(Color::black()).a > 0) - && (evaluated.get().constantOr(1) > 0 || - evaluated.get().constantOr(1) > 0)) - ? RenderPass::Translucent : RenderPass::None; + evaluated.get().constantOr(1) > 0) && + (evaluated.get().constantOr(Color::black()).a > 0 || + evaluated.get().constantOr(Color::black()).a > 0) && + (evaluated.get().constantOr(1) > 0 || + evaluated.get().constantOr(1) > 0)) + ? RenderPass::Translucent + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -99,8 +102,10 @@ void RenderCircleLayer::render(PaintParameters& parameters) { parameters.state)), uniforms::scale_with_map::Value(scaleWithMap), uniforms::extrude_scale::Value( - pitchWithMap ? std::array{{tile.id.pixelsToTileUnits(1.0f, static_cast(parameters.state.getZoom())), - tile.id.pixelsToTileUnits(1.0f, static_cast(parameters.state.getZoom()))}} + pitchWithMap ? std::array{{tile.id.pixelsToTileUnits( + 1.0f, static_cast(parameters.state.getZoom())), + tile.id.pixelsToTileUnits( + 1.0f, static_cast(parameters.state.getZoom()))}} : parameters.pixelsToGLUnits), uniforms::device_pixel_ratio::Value(parameters.pixelRatio), uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance()), @@ -108,8 +113,8 @@ void RenderCircleLayer::render(PaintParameters& parameters) { paintPropertyBinders, evaluated, static_cast(parameters.state.getZoom())); - const auto& allAttributeBindings = - CircleProgram::computeAllAttributeBindings(*circleBucket.vertexBuffer, paintPropertyBinders, evaluated); + const auto& allAttributeBindings = CircleProgram::computeAllAttributeBindings( + *circleBucket.vertexBuffer, paintPropertyBinders, evaluated); checkRenderability(parameters, CircleProgram::activeBindingCount(allAttributeBindings)); @@ -154,15 +159,15 @@ void RenderCircleLayer::render(PaintParameters& parameters) { } GeometryCoordinate projectPoint(const GeometryCoordinate& p, const mat4& posMatrix, const Size& size) { - vec4 pos = {{ static_cast(p.x), static_cast(p.y), 0, 1 }}; + vec4 pos = {{static_cast(p.x), static_cast(p.y), 0, 1}}; matrix::transformMat4(pos, pos, posMatrix); - return { - static_cast((static_cast(pos[0] / pos[3]) + 1) * size.width * 0.5), - static_cast((static_cast(pos[1] / pos[3]) + 1) * size.height * 0.5) - }; + return {static_cast((static_cast(pos[0] / pos[3]) + 1) * size.width * 0.5), + static_cast((static_cast(pos[1] / pos[3]) + 1) * size.height * 0.5)}; } -GeometryCoordinates projectQueryGeometry(const GeometryCoordinates& queryGeometry, const mat4& posMatrix, const Size& size) { +GeometryCoordinates projectQueryGeometry(const GeometryCoordinates& queryGeometry, + const mat4& posMatrix, + const Size& size) { GeometryCoordinates projectedGeometry; for (auto& p : queryGeometry) { projectedGeometry.push_back(projectPoint(p, posMatrix, size)); @@ -171,40 +176,49 @@ GeometryCoordinates projectQueryGeometry(const GeometryCoordinates& queryGeometr } bool RenderCircleLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float zoom, - const TransformState& transformState, const float pixelsToTileUnits, - const mat4& posMatrix, const FeatureState& featureState) const { + const GeometryTileFeature& feature, + const float zoom, + const TransformState& transformState, + const float pixelsToTileUnits, + const mat4& posMatrix, + const FeatureState& featureState) const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; // Translate query geometry const GeometryCoordinates& translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits).value_or(queryGeometry); + queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits) + .value_or(queryGeometry); // Evaluate functions auto radius = evaluated.evaluate(zoom, feature, featureState); auto stroke = evaluated.evaluate(zoom, feature, featureState); auto size = radius + stroke; - // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile - // Otherwise, compare geometry in the plane of the viewport - // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance - // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance + // For pitch-alignment: map, compare feature geometry to query geometry in + // the plane of the tile Otherwise, compare geometry in the plane of the + // viewport A circle with fixed scaling relative to the viewport gets larger + // in tile space as it moves into the distance A circle with fixed scaling + // relative to the map gets smaller in viewport space as it moves into the + // distance bool alignWithMap = evaluated.evaluate(zoom, feature) == AlignmentType::Map; - const GeometryCoordinates& transformedQueryGeometry = alignWithMap ? - translatedQueryGeometry : - projectQueryGeometry(translatedQueryGeometry, posMatrix, transformState.getSize()); + const GeometryCoordinates& transformedQueryGeometry = alignWithMap ? translatedQueryGeometry + : projectQueryGeometry(translatedQueryGeometry, + posMatrix, + transformState.getSize()); auto transformedSize = alignWithMap ? size * pixelsToTileUnits : size; const auto& geometry = feature.getGeometries(); for (auto& ring : geometry) { for (auto& point : ring) { - const GeometryCoordinate& transformedPoint = alignWithMap ? point : projectPoint(point, posMatrix, transformState.getSize()); + const GeometryCoordinate& transformedPoint = alignWithMap + ? point + : projectPoint(point, posMatrix, transformState.getSize()); float adjustedSize = transformedSize; - vec4 center = {{ static_cast(point.x), static_cast(point.y), 0, 1 }}; + vec4 center = {{static_cast(point.x), static_cast(point.y), 0, 1}}; matrix::transformMat4(center, center, posMatrix); auto pitchScale = evaluated.evaluate(zoom, feature); auto pitchAlignment = evaluated.evaluate(zoom, feature); @@ -214,7 +228,8 @@ bool RenderCircleLayer::queryIntersectsFeature(const GeometryCoordinates& queryG adjustedSize *= static_cast(transformState.getCameraToCenterDistance() / center[3]); } - if (util::polygonIntersectsBufferedPoint(transformedQueryGeometry, transformedPoint, adjustedSize)) return true; + if (util::polygonIntersectsBufferedPoint(transformedQueryGeometry, transformedPoint, adjustedSize)) + return true; } } diff --git a/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp b/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp index b6f4d9641a8..ad806523cda 100644 --- a/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp +++ b/src/mbgl/renderer/layers/render_fill_extrusion_layer.cpp @@ -42,10 +42,9 @@ void RenderFillExtrusionLayer::transition(const TransitionParameters& parameters } void RenderFillExtrusionLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); + auto properties = makeMutable(staticImmutableCast(baseImpl), + parameters.getCrossfadeParameters(), + unevaluated.evaluate(parameters)); passes = (properties->evaluated.get() > 0) ? (RenderPass::Translucent | RenderPass::Pass3D) @@ -98,151 +97,147 @@ void RenderFillExtrusionLayer::render(PaintParameters& parameters) { paintPropertyBinders.setPatternParameters(patternPositionA, patternPositionB, crossfade_); const auto allUniformValues = programInstance.computeAllUniformValues( - uniformValues, - paintPropertyBinders, - evaluated_, - static_cast(parameters.state.getZoom()) - ); + uniformValues, paintPropertyBinders, evaluated_, static_cast(parameters.state.getZoom())); const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *tileBucket.vertexBuffer, - paintPropertyBinders, - evaluated_ - ); + *tileBucket.vertexBuffer, paintPropertyBinders, evaluated_); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); - programInstance.draw( - parameters.context, - *parameters.renderPass, - gfx::Triangles(), - depthMode, - stencilMode, - colorMode, - gfx::CullFaceMode::backCCW(), - *tileBucket.indexBuffer, - tileBucket.triangleSegments, - allUniformValues, - allAttributeBindings, - textureBindings, - getID() + "/" + uniqueName); + programInstance.draw(parameters.context, + *parameters.renderPass, + gfx::Triangles(), + depthMode, + stencilMode, + colorMode, + gfx::CullFaceMode::backCCW(), + *tileBucket.indexBuffer, + tileBucket.triangleSegments, + allUniformValues, + allAttributeBindings, + textureBindings, + getID() + "/" + uniqueName); }; if (unevaluated.get().isUndefined()) { // Draw solid color extrusions - auto drawTiles = [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { - for (const RenderTile& tile : *renderTiles) { - const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); - if (!renderData) { - continue; + auto drawTiles = + [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { + for (const RenderTile& tile : *renderTiles) { + const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); + if (!renderData) { + continue; + } + auto& bucket = static_cast(*renderData->bucket); + draw(*fillExtrusionProgram, + evaluated, + crossfade, + stencilMode_, + colorMode_, + bucket, + FillExtrusionProgram::layoutUniformValues( + tile.translatedClipMatrix(evaluated.get(), + evaluated.get(), + parameters.state), + parameters.state, + evaluated.get(), + parameters.evaluatedLight, + evaluated.get()), + {}, + {}, + FillExtrusionProgram::TextureBindings{}, + name); } - auto& bucket = static_cast(*renderData->bucket); - draw( - *fillExtrusionProgram, - evaluated, - crossfade, - stencilMode_, - colorMode_, - bucket, - FillExtrusionProgram::layoutUniformValues( - tile.translatedClipMatrix(evaluated.get(), - evaluated.get(), - parameters.state), - parameters.state, - evaluated.get(), - parameters.evaluatedLight, - evaluated.get() - ), - {}, - {}, - FillExtrusionProgram::TextureBindings{}, - name - ); - } - }; + }; if (evaluated.get() == 1) { // Draw opaque extrusions drawTiles(gfx::StencilMode::disabled(), parameters.colorModeForRenderPass(), "color"); } else { - // Draw transparent buildings in two passes so that only the closest surface is drawn. - // First draw all the extrusions into only the depth buffer. No colors are drawn. + // Draw transparent buildings in two passes so that only the closest + // surface is drawn. First draw all the extrusions into only the + // depth buffer. No colors are drawn. drawTiles(gfx::StencilMode::disabled(), gfx::ColorMode::disabled(), "depth"); - // Then draw all the extrusions a second time, only coloring fragments if they have the - // same depth value as the closest fragment in the previous pass. Use the stencil buffer - // to prevent the second draw in cases where we have coincident polygons. + // Then draw all the extrusions a second time, only coloring + // fragments if they have the same depth value as the closest + // fragment in the previous pass. Use the stencil buffer to prevent + // the second draw in cases where we have coincident polygons. drawTiles(parameters.stencilModeFor3D(), parameters.colorModeForRenderPass(), "color"); } } else { // Draw textured extrusions - const auto fillPatternValue = - evaluated.get().constantOr(mbgl::Faded{"", ""}); - auto drawTiles = [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { - for (const RenderTile& tile : *renderTiles) { - const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); - if (!renderData) { - continue; + const auto fillPatternValue = evaluated.get().constantOr( + mbgl::Faded{"", ""}); + auto drawTiles = + [&](const gfx::StencilMode& stencilMode_, const gfx::ColorMode& colorMode_, const std::string& name) { + for (const RenderTile& tile : *renderTiles) { + const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); + if (!renderData) { + continue; + } + auto& bucket = static_cast(*renderData->bucket); + std::optional patternPosA = tile.getPattern(fillPatternValue.from.id()); + std::optional patternPosB = tile.getPattern(fillPatternValue.to.id()); + + draw(*fillExtrusionPatternProgram, + evaluated, + crossfade, + stencilMode_, + colorMode_, + bucket, + FillExtrusionPatternProgram::layoutUniformValues( + tile.translatedClipMatrix(evaluated.get(), + evaluated.get(), + parameters.state), + tile.getIconAtlasTexture().size, + crossfade, + tile.id, + parameters.state, + evaluated.get(), + static_cast(-std::pow(2, tile.id.canonical.z) / util::tileSize_D / 8.0), + parameters.pixelRatio, + parameters.evaluatedLight, + evaluated.get()), + patternPosA, + patternPosB, + FillExtrusionPatternProgram::TextureBindings{ + textures::image::Value{tile.getIconAtlasTexture().getResource(), + gfx::TextureFilterType::Linear}, + }, + name); } - auto& bucket = static_cast(*renderData->bucket); - std::optional patternPosA = tile.getPattern(fillPatternValue.from.id()); - std::optional patternPosB = tile.getPattern(fillPatternValue.to.id()); - - draw( - *fillExtrusionPatternProgram, - evaluated, - crossfade, - stencilMode_, - colorMode_, - bucket, - FillExtrusionPatternProgram::layoutUniformValues( - tile.translatedClipMatrix(evaluated.get(), - evaluated.get(), - parameters.state), - tile.getIconAtlasTexture().size, - crossfade, - tile.id, - parameters.state, - evaluated.get(), - static_cast(-std::pow(2, tile.id.canonical.z) / util::tileSize_D / 8.0), - parameters.pixelRatio, - parameters.evaluatedLight, - evaluated.get() - ), - patternPosA, - patternPosB, - FillExtrusionPatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, - }, - name - ); - } - }; - - // Draw transparent buildings in two passes so that only the closest surface is drawn. - // First draw all the extrusions into only the depth buffer. No colors are drawn. + }; + + // Draw transparent buildings in two passes so that only the closest + // surface is drawn. First draw all the extrusions into only the depth + // buffer. No colors are drawn. drawTiles(gfx::StencilMode::disabled(), gfx::ColorMode::disabled(), "depth"); - // Then draw all the extrusions a second time, only coloring fragments if they have the - // same depth value as the closest fragment in the previous pass. Use the stencil buffer - // to prevent the second draw in cases where we have coincident polygons. + // Then draw all the extrusions a second time, only coloring fragments + // if they have the same depth value as the closest fragment in the + // previous pass. Use the stencil buffer to prevent the second draw in + // cases where we have coincident polygons. drawTiles(parameters.stencilModeFor3D(), parameters.colorModeForRenderPass(), "color"); } } bool RenderFillExtrusionLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float, + const GeometryTileFeature& feature, + const float, const TransformState& transformState, - const float pixelsToTileUnits, const mat4&, + const float pixelsToTileUnits, + const mat4&, const FeatureState&) const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits); - - return util::polygonIntersectsMultiPolygon(translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries()); + queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits); + + return util::polygonIntersectsMultiPolygon(translatedQueryGeometry.value_or(queryGeometry), + feature.getGeometries()); } } // namespace mbgl diff --git a/src/mbgl/renderer/layers/render_fill_layer.cpp b/src/mbgl/renderer/layers/render_fill_layer.cpp index c3baae8bd59..2960ca71acd 100644 --- a/src/mbgl/renderer/layers/render_fill_layer.cpp +++ b/src/mbgl/renderer/layers/render_fill_layer.cpp @@ -42,10 +42,9 @@ void RenderFillLayer::transition(const TransitionParameters& parameters) { } void RenderFillLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); + auto properties = makeMutable(staticImmutableCast(baseImpl), + parameters.getCrossfadeParameters(), + unevaluated.evaluate(parameters)); auto& evaluated = properties->evaluated; if (unevaluated.get().isUndefined()) { @@ -54,9 +53,9 @@ void RenderFillLayer::evaluate(const PropertyEvaluationParameters& parameters) { passes = RenderPass::Translucent; - if (!(!unevaluated.get().isUndefined() - || evaluated.get().constantOr(Color()).a < 1.0f - || evaluated.get().constantOr(0) < 1.0f)) { + if (!(!unevaluated.get().isUndefined() || + evaluated.get().constantOr(Color()).a < 1.0f || + evaluated.get().constantOr(0) < 1.0f)) { // Supply both - evaluated based on opaquePassCutoff in render(). passes |= RenderPass::Opaque; } @@ -90,32 +89,25 @@ void RenderFillLayer::render(PaintParameters& parameters) { auto& bucket = static_cast(*renderData->bucket); const auto& evaluated = getEvaluated(renderData->layerProperties); - auto draw = [&] (auto& programInstance, - const auto& drawMode, - const auto& depthMode, - const auto& indexBuffer, - const auto& segments, - auto&& textureBindings) { + auto draw = [&](auto& programInstance, + const auto& drawMode, + const auto& depthMode, + const auto& indexBuffer, + const auto& segments, + auto&& textureBindings) { const auto& paintPropertyBinders = bucket.paintPropertyBinders.at(getID()); const auto allUniformValues = programInstance.computeAllUniformValues( - FillProgram::LayoutUniformValues { - uniforms::matrix::Value( - tile.translatedMatrix(evaluated.get(), - evaluated.get(), - parameters.state) - ), - uniforms::world::Value( parameters.backend.getDefaultRenderable().getSize() ), + FillProgram::LayoutUniformValues{ + uniforms::matrix::Value(tile.translatedMatrix( + evaluated.get(), evaluated.get(), parameters.state)), + uniforms::world::Value(parameters.backend.getDefaultRenderable().getSize()), }, paintPropertyBinders, evaluated, - static_cast(parameters.state.getZoom()) - ); + static_cast(parameters.state.getZoom())); const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *bucket.vertexBuffer, - paintPropertyBinders, - evaluated - ); + *bucket.vertexBuffer, paintPropertyBinders, evaluated); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); @@ -134,15 +126,18 @@ void RenderFillLayer::render(PaintParameters& parameters) { getID()); }; - auto fillRenderPass = (evaluated.get().constantOr(Color()).a >= 1.0f - && evaluated.get().constantOr(0) >= 1.0f - && parameters.currentLayer >= parameters.opaquePassCutoff) ? RenderPass::Opaque : RenderPass::Translucent; + auto fillRenderPass = (evaluated.get().constantOr(Color()).a >= 1.0f && + evaluated.get().constantOr(0) >= 1.0f && + parameters.currentLayer >= parameters.opaquePassCutoff) + ? RenderPass::Opaque + : RenderPass::Translucent; if (bucket.triangleIndexBuffer && parameters.pass == fillRenderPass) { draw(*fillProgram, gfx::Triangles(), - parameters.depthModeForSublayer(1, parameters.pass == RenderPass::Opaque - ? gfx::DepthMaskType::ReadWrite - : gfx::DepthMaskType::ReadOnly), + parameters.depthModeForSublayer(1, + parameters.pass == RenderPass::Opaque + ? gfx::DepthMaskType::ReadWrite + : gfx::DepthMaskType::ReadOnly), *bucket.triangleIndexBuffer, bucket.triangleSegments, FillProgram::TextureBindings{}); @@ -150,10 +145,9 @@ void RenderFillLayer::render(PaintParameters& parameters) { if (evaluated.get() && parameters.pass == RenderPass::Translucent) { draw(*fillOutlineProgram, - gfx::Lines{ 2.0f }, - parameters.depthModeForSublayer( - unevaluated.get().isUndefined() ? 2 : 0, - gfx::DepthMaskType::ReadOnly), + gfx::Lines{2.0f}, + parameters.depthModeForSublayer(unevaluated.get().isUndefined() ? 2 : 0, + gfx::DepthMaskType::ReadOnly), *bucket.lineIndexBuffer, bucket.lineSegments, FillOutlineProgram::TextureBindings{}); @@ -179,36 +173,30 @@ void RenderFillLayer::render(PaintParameters& parameters) { std::optional patternPosA = tile.getPattern(fillPatternValue.from.id()); std::optional patternPosB = tile.getPattern(fillPatternValue.to.id()); - auto draw = [&] (auto& programInstance, - const auto& drawMode, - const auto& depthMode, - const auto& indexBuffer, - const auto& segments, - auto&& textureBindings) { + auto draw = [&](auto& programInstance, + const auto& drawMode, + const auto& depthMode, + const auto& indexBuffer, + const auto& segments, + auto&& textureBindings) { const auto& paintPropertyBinders = bucket.paintPropertyBinders.at(getID()); paintPropertyBinders.setPatternParameters(patternPosA, patternPosB, crossfade); const auto allUniformValues = programInstance.computeAllUniformValues( FillPatternProgram::layoutUniformValues( - tile.translatedMatrix(evaluated.get(), - evaluated.get(), - parameters.state), + tile.translatedMatrix( + evaluated.get(), evaluated.get(), parameters.state), parameters.backend.getDefaultRenderable().getSize(), tile.getIconAtlasTexture().size, crossfade, tile.id, parameters.state, - parameters.pixelRatio - ), + parameters.pixelRatio), paintPropertyBinders, evaluated, - static_cast(parameters.state.getZoom()) - ); + static_cast(parameters.state.getZoom())); const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *bucket.vertexBuffer, - paintPropertyBinders, - evaluated - ); + *bucket.vertexBuffer, paintPropertyBinders, evaluated); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); @@ -234,17 +222,19 @@ void RenderFillLayer::render(PaintParameters& parameters) { *bucket.triangleIndexBuffer, bucket.triangleSegments, FillPatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, + textures::image::Value{tile.getIconAtlasTexture().getResource(), + gfx::TextureFilterType::Linear}, }); } if (evaluated.get() && unevaluated.get().isUndefined()) { draw(*fillOutlinePatternProgram, - gfx::Lines { 2.0f }, + gfx::Lines{2.0f}, parameters.depthModeForSublayer(2, gfx::DepthMaskType::ReadOnly), *bucket.lineIndexBuffer, bucket.lineSegments, FillOutlinePatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, + textures::image::Value{tile.getIconAtlasTexture().getResource(), + gfx::TextureFilterType::Linear}, }); } } @@ -252,18 +242,21 @@ void RenderFillLayer::render(PaintParameters& parameters) { } bool RenderFillLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float, - const TransformState& transformState, const float pixelsToTileUnits, - const mat4&, const FeatureState&) const { + const GeometryTileFeature& feature, + const float, + const TransformState& transformState, + const float pixelsToTileUnits, + const mat4&, + const FeatureState&) const { const auto& evaluated = getEvaluated(evaluatedProperties); - auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits); - - return util::polygonIntersectsMultiPolygon(translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries()); + auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry(queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits); + + return util::polygonIntersectsMultiPolygon(translatedQueryGeometry.value_or(queryGeometry), + feature.getGeometries()); } } // namespace mbgl diff --git a/src/mbgl/renderer/layers/render_heatmap_layer.cpp b/src/mbgl/renderer/layers/render_heatmap_layer.cpp index b652991d1e4..eda2b698d2a 100644 --- a/src/mbgl/renderer/layers/render_heatmap_layer.cpp +++ b/src/mbgl/renderer/layers/render_heatmap_layer.cpp @@ -40,13 +40,11 @@ void RenderHeatmapLayer::transition(const TransitionParameters& parameters) { } void RenderHeatmapLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + auto properties = makeMutable(staticImmutableCast(baseImpl), + unevaluated.evaluate(parameters)); - passes = (properties->evaluated.get() > 0) - ? (RenderPass::Translucent | RenderPass::Pass3D) - : RenderPass::None; + passes = (properties->evaluated.get() > 0) ? (RenderPass::Translucent | RenderPass::Pass3D) + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -61,8 +59,7 @@ bool RenderHeatmapLayer::hasCrossfade() const { void RenderHeatmapLayer::upload(gfx::UploadPass& uploadPass) { if (!colorRampTexture) { - colorRampTexture = - uploadPass.createTexture(colorRamp, gfx::TextureChannelDataType::UnsignedByte); + colorRampTexture = uploadPass.createTexture(colorRamp, gfx::TextureChannelDataType::UnsignedByte); } } @@ -85,8 +82,8 @@ void RenderHeatmapLayer::render(PaintParameters& parameters) { renderTexture = parameters.context.createOffscreenTexture(size, gfx::TextureChannelDataType::HalfFloat); } - auto renderPass = parameters.encoder->createRenderPass( - "heatmap texture", { *renderTexture, Color{ 0.0f, 0.0f, 0.0f, 1.0f }, {}, {} }); + auto renderPass = parameters.encoder->createRenderPass("heatmap texture", + {*renderTexture, Color{0.0f, 0.0f, 0.0f, 1.0f}, {}, {}}); for (const RenderTile& tile : *renderTiles) { const LayerRenderData* renderData = getRenderDataForPass(tile, parameters.pass); @@ -108,8 +105,8 @@ void RenderHeatmapLayer::render(PaintParameters& parameters) { paintPropertyBinders, evaluated, static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = - HeatmapProgram::computeAllAttributeBindings(*bucket.vertexBuffer, paintPropertyBinders, evaluated); + const auto allAttributeBindings = HeatmapProgram::computeAllAttributeBindings( + *bucket.vertexBuffer, paintPropertyBinders, evaluated); checkRenderability(parameters, HeatmapProgram::activeBindingCount(allAttributeBindings)); @@ -135,7 +132,7 @@ void RenderHeatmapLayer::render(PaintParameters& parameters) { matrix::ortho(viewportMat, 0, size.width, size.height, 0, 0, 1); const Properties<>::PossiblyEvaluated properties; - const HeatmapTextureProgram::Binders paintAttributeData{ properties, 0 }; + const HeatmapTextureProgram::Binders paintAttributeData{properties, 0}; const auto allUniformValues = HeatmapTextureProgram::computeAllUniformValues( HeatmapTextureProgram::LayoutUniformValues{ @@ -197,13 +194,16 @@ void RenderHeatmapLayer::updateColorRamp() { } bool RenderHeatmapLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float zoom, - const TransformState&, const float pixelsToTileUnits, const mat4&, + const GeometryTileFeature& feature, + const float zoom, + const TransformState&, + const float pixelsToTileUnits, + const mat4&, const FeatureState&) const { - (void) queryGeometry; - (void) feature; - (void) zoom; - (void) pixelsToTileUnits; + (void)queryGeometry; + (void)feature; + (void)zoom; + (void)pixelsToTileUnits; return false; } diff --git a/src/mbgl/renderer/layers/render_hillshade_layer.cpp b/src/mbgl/renderer/layers/render_hillshade_layer.cpp index 6f925005c82..7818763de41 100644 --- a/src/mbgl/renderer/layers/render_hillshade_layer.cpp +++ b/src/mbgl/renderer/layers/render_hillshade_layer.cpp @@ -43,7 +43,8 @@ std::array RenderHillshadeLayer::getLatRange(const UnwrappedTileID& id std::array RenderHillshadeLayer::getLight(const PaintParameters& parameters) { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; float azimuthal = util::deg2radf(evaluated.get()); - if (evaluated.get() == HillshadeIlluminationAnchorType::Viewport) azimuthal = azimuthal - static_cast(parameters.state.getBearing()); + if (evaluated.get() == HillshadeIlluminationAnchorType::Viewport) + azimuthal = azimuthal - static_cast(parameters.state.getBearing()); return {{evaluated.get(), azimuthal}}; } @@ -52,10 +53,9 @@ void RenderHillshadeLayer::transition(const TransitionParameters& parameters) { } void RenderHillshadeLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); - passes = (properties->evaluated.get() > 0) + auto properties = makeMutable(staticImmutableCast(baseImpl), + unevaluated.evaluate(parameters)); + passes = (properties->evaluated.get() > 0) ? (RenderPass::Translucent | RenderPass::Pass3D) : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); @@ -77,20 +77,19 @@ void RenderHillshadeLayer::prepare(const LayerPrepareParameters& params) { void RenderHillshadeLayer::render(PaintParameters& parameters) { assert(renderTiles); - if (parameters.pass != RenderPass::Translucent && parameters.pass != RenderPass::Pass3D) - return; + if (parameters.pass != RenderPass::Translucent && parameters.pass != RenderPass::Pass3D) return; if (!parameters.shaders.populate(hillshadeProgram)) return; if (!parameters.shaders.populate(hillshadePrepareProgram)) return; - const auto& evaluated = static_cast(*evaluatedProperties).evaluated; - auto draw = [&] (const mat4& matrix, - const auto& vertexBuffer, - const auto& indexBuffer, - const auto& segments, - const UnwrappedTileID& id, - const auto& textureBindings) { - const HillshadeProgram::Binders paintAttributeData{ evaluated, 0 }; + const auto& evaluated = static_cast(*evaluatedProperties).evaluated; + auto draw = [&](const mat4& matrix, + const auto& vertexBuffer, + const auto& indexBuffer, + const auto& segments, + const UnwrappedTileID& id, + const auto& textureBindings) { + const HillshadeProgram::Binders paintAttributeData{evaluated, 0}; const auto allUniformValues = HillshadeProgram::computeAllUniformValues( HillshadeProgram::LayoutUniformValues{ @@ -104,24 +103,24 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { paintAttributeData, evaluated, static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = - HillshadeProgram::computeAllAttributeBindings(vertexBuffer, paintAttributeData, evaluated); + const auto allAttributeBindings = HillshadeProgram::computeAllAttributeBindings( + vertexBuffer, paintAttributeData, evaluated); checkRenderability(parameters, HillshadeProgram::activeBindingCount(allAttributeBindings)); hillshadeProgram->draw(parameters.context, - *parameters.renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - indexBuffer, - segments, - allUniformValues, - allAttributeBindings, - textureBindings, - getID()); + *parameters.renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + indexBuffer, + segments, + allUniformValues, + allAttributeBindings, + textureBindings, + getID()); }; mat4 mat; @@ -135,7 +134,7 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { } auto& bucket = static_cast(*bucket_); - if (!bucket.hasData()){ + if (!bucket.hasData()) { continue; } @@ -146,11 +145,11 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { auto view = parameters.context.createOffscreenTexture({tilesize, tilesize}, gfx::TextureChannelDataType::UnsignedByte); - auto renderPass = parameters.encoder->createRenderPass( - "hillshade prepare", { *view, Color{ 0.0f, 0.0f, 0.0f, 0.0f }, {}, {} }); + auto renderPass = parameters.encoder->createRenderPass("hillshade prepare", + {*view, Color{0.0f, 0.0f, 0.0f, 0.0f}, {}, {}}); const Properties<>::PossiblyEvaluated properties; - const HillshadePrepareProgram::Binders paintAttributeData{ properties, 0 }; + const HillshadePrepareProgram::Binders paintAttributeData{properties, 0}; const auto allUniformValues = HillshadePrepareProgram::computeAllUniformValues( HillshadePrepareProgram::LayoutUniformValues{ @@ -168,24 +167,24 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { checkRenderability(parameters, HillshadePrepareProgram::activeBindingCount(allAttributeBindings)); - // Copy over the segments so that we can create our own DrawScopes that get destroyed - // after this draw call. + // Copy over the segments so that we can create our own DrawScopes + // that get destroyed after this draw call. auto segments = RenderStaticData::rasterSegments(); hillshadePrepareProgram->draw(parameters.context, - *renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - *parameters.staticData.quadTriangleIndexBuffer, - segments, - allUniformValues, - allAttributeBindings, - HillshadePrepareProgram::TextureBindings{ - textures::image::Value{bucket.dem->getResource()}, - }, - "prepare"); + *renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + *parameters.staticData.quadTriangleIndexBuffer, + segments, + allUniformValues, + allAttributeBindings, + HillshadePrepareProgram::TextureBindings{ + textures::image::Value{bucket.dem->getResource()}, + }, + "prepare"); bucket.texture = std::move(view->getTexture()); bucket.setPrepared(true); } else if (parameters.pass == RenderPass::Translucent) { @@ -199,7 +198,7 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { bucket.segments, tile.id, HillshadeProgram::TextureBindings{ - textures::image::Value{ bucket.texture->getResource(), gfx::TextureFilterType::Linear }, + textures::image::Value{bucket.texture->getResource(), gfx::TextureFilterType::Linear}, }); } else { // Draw the full tile. @@ -217,8 +216,6 @@ void RenderHillshadeLayer::render(PaintParameters& parameters) { }); } } - - } } diff --git a/src/mbgl/renderer/layers/render_hillshade_layer.hpp b/src/mbgl/renderer/layers/render_hillshade_layer.hpp index 1f21892c222..97bf807ce86 100644 --- a/src/mbgl/renderer/layers/render_hillshade_layer.hpp +++ b/src/mbgl/renderer/layers/render_hillshade_layer.hpp @@ -10,7 +10,7 @@ namespace mbgl { class HillshadeProgram; class HillshadePrepareProgram; -class RenderHillshadeLayer: public RenderLayer { +class RenderHillshadeLayer : public RenderLayer { public: explicit RenderHillshadeLayer(Immutable); ~RenderHillshadeLayer() override; diff --git a/src/mbgl/renderer/layers/render_line_layer.cpp b/src/mbgl/renderer/layers/render_line_layer.cpp index 8dc72bab92f..13da300f87a 100644 --- a/src/mbgl/renderer/layers/render_line_layer.cpp +++ b/src/mbgl/renderer/layers/render_line_layer.cpp @@ -43,16 +43,16 @@ void RenderLineLayer::transition(const TransitionParameters& parameters) { } void RenderLineLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - parameters.getCrossfadeParameters(), - unevaluated.evaluate(parameters)); + auto properties = makeMutable(staticImmutableCast(baseImpl), + parameters.getCrossfadeParameters(), + unevaluated.evaluate(parameters)); auto& evaluated = properties->evaluated; - passes = (evaluated.get().constantOr(1.0) > 0 - && evaluated.get().constantOr(Color::black()).a > 0 - && evaluated.get().constantOr(1.0) > 0) - ? RenderPass::Translucent : RenderPass::None; + passes = (evaluated.get().constantOr(1.0) > 0 && + evaluated.get().constantOr(Color::black()).a > 0 && + evaluated.get().constantOr(1.0) > 0) + ? RenderPass::Translucent + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -75,8 +75,8 @@ void RenderLineLayer::prepare(const LayerPrepareParameters& params) { if (evaluated.get().from.empty()) continue; auto& bucket = static_cast(*renderData->bucket); - const LinePatternCap cap = bucket.layout.get() == LineCapType::Round - ? LinePatternCap::Round : LinePatternCap::Square; + const LinePatternCap cap = bucket.layout.get() == LineCapType::Round ? LinePatternCap::Round + : LinePatternCap::Square; // Ensures that the dash data gets added to the atlas. params.lineAtlas.getDashPatternTexture( evaluated.get().from, evaluated.get().to, cap); @@ -114,21 +114,19 @@ void RenderLineLayer::render(PaintParameters& parameters) { auto draw = [&](auto& programInstance, auto&& uniformValues, const std::optional& patternPositionA, - const std::optional& patternPositionB, auto&& textureBindings) { + const std::optional& patternPositionB, + auto&& textureBindings) { const auto& paintPropertyBinders = bucket.paintPropertyBinders.at(getID()); paintPropertyBinders.setPatternParameters(patternPositionA, patternPositionB, crossfade); - const auto allUniformValues = - programInstance.computeAllUniformValues(std::forward(uniformValues), - paintPropertyBinders, - evaluated, - static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *bucket.vertexBuffer, + const auto allUniformValues = programInstance.computeAllUniformValues( + std::forward(uniformValues), paintPropertyBinders, - evaluated - ); + evaluated, + static_cast(parameters.state.getZoom())); + const auto allAttributeBindings = programInstance.computeAllAttributeBindings( + *bucket.vertexBuffer, paintPropertyBinders, evaluated); checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); @@ -148,8 +146,8 @@ void RenderLineLayer::render(PaintParameters& parameters) { }; if (!evaluated.get().from.empty()) { - const LinePatternCap cap = - bucket.layout.get() == LineCapType::Round ? LinePatternCap::Round : LinePatternCap::Square; + const LinePatternCap cap = bucket.layout.get() == LineCapType::Round ? LinePatternCap::Round + : LinePatternCap::Square; const auto& dashPatternTexture = parameters.lineAtlas.getDashPatternTexture( evaluated.get().from, evaluated.get().to, cap); @@ -177,42 +175,33 @@ void RenderLineLayer::render(PaintParameters& parameters) { std::optional posB = tile.getPattern(linePatternValue.to.id()); draw(*linePatternProgram, - LinePatternProgram::layoutUniformValues( - evaluated, - tile, - parameters.state, - parameters.pixelsToGLUnits, - parameters.pixelRatio, - texsize, - crossfade), - posA, - posB, - LinePatternProgram::TextureBindings{ - textures::image::Value{ tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear }, - }); + LinePatternProgram::layoutUniformValues(evaluated, + tile, + parameters.state, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + texsize, + crossfade), + posA, + posB, + LinePatternProgram::TextureBindings{ + textures::image::Value{tile.getIconAtlasTexture().getResource(), gfx::TextureFilterType::Linear}, + }); } else if (!unevaluated.get().getValue().isUndefined()) { assert(colorRampTexture); draw(*lineGradientProgram, LineGradientProgram::layoutUniformValues( - evaluated, - tile, - parameters.state, - parameters.pixelsToGLUnits, - parameters.pixelRatio), - {}, - {}, - LineGradientProgram::TextureBindings{ - textures::image::Value{ colorRampTexture->getResource(), gfx::TextureFilterType::Linear }, - }); + evaluated, tile, parameters.state, parameters.pixelsToGLUnits, parameters.pixelRatio), + {}, + {}, + LineGradientProgram::TextureBindings{ + textures::image::Value{colorRampTexture->getResource(), gfx::TextureFilterType::Linear}, + }); } else { draw(*lineProgram, LineProgram::layoutUniformValues( - evaluated, - tile, - parameters.state, - parameters.pixelsToGLUnits, - parameters.pixelRatio), + evaluated, tile, parameters.state, parameters.pixelsToGLUnits, parameters.pixelRatio), {}, {}, LineProgram::TextureBindings{}); @@ -238,12 +227,9 @@ GeometryCollection offsetLine(const GeometryCollection& rings, double offset) { for (auto i = ring.begin(); i != ring.end(); ++i) { auto& p = *i; - Point aToB = i == ring.begin() ? - zero : - util::perp(util::unit(convertPoint(p - *(i - 1)))); - Point bToC = i + 1 == ring.end() ? - zero : - util::perp(util::unit(convertPoint(*(i + 1) - p))); + Point aToB = i == ring.begin() ? zero : util::perp(util::unit(convertPoint(p - *(i - 1)))); + Point bToC = i + 1 == ring.end() ? zero + : util::perp(util::unit(convertPoint(*(i + 1) - p))); Point extrude = util::unit(aToB + bToC); const double cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y; @@ -259,37 +245,35 @@ GeometryCollection offsetLine(const GeometryCollection& rings, double offset) { } // namespace bool RenderLineLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, - const GeometryTileFeature& feature, const float zoom, - const TransformState& transformState, const float pixelsToTileUnits, - const mat4&, const FeatureState& featureState) const { + const GeometryTileFeature& feature, + const float zoom, + const TransformState& transformState, + const float pixelsToTileUnits, + const mat4&, + const FeatureState& featureState) const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; // Translate query geometry - auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( - queryGeometry, - evaluated.get(), - evaluated.get(), - static_cast(transformState.getBearing()), - pixelsToTileUnits); + auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry(queryGeometry, + evaluated.get(), + evaluated.get(), + static_cast(transformState.getBearing()), + pixelsToTileUnits); // Evaluate function - auto offset = - evaluated.get().evaluate(feature, zoom, featureState, style::LineOffset::defaultValue()) * - pixelsToTileUnits; + auto offset = evaluated.get().evaluate( + feature, zoom, featureState, style::LineOffset::defaultValue()) * + pixelsToTileUnits; // Test intersection const auto halfWidth = static_cast(getLineWidth(feature, zoom, featureState) / 2.0 * pixelsToTileUnits); // Apply offset to geometry if (offset != 0.0f && !feature.getGeometries().empty()) { return util::polygonIntersectsBufferedMultiLine( - translatedQueryGeometry.value_or(queryGeometry), - offsetLine(feature.getGeometries(), offset), - halfWidth); + translatedQueryGeometry.value_or(queryGeometry), offsetLine(feature.getGeometries(), offset), halfWidth); } return util::polygonIntersectsBufferedMultiLine( - translatedQueryGeometry.value_or(queryGeometry), - feature.getGeometries(), - halfWidth); + translatedQueryGeometry.value_or(queryGeometry), feature.getGeometries(), halfWidth); } void RenderLineLayer::updateColorRamp() { @@ -313,13 +297,14 @@ void RenderLineLayer::updateColorRamp() { } } -float RenderLineLayer::getLineWidth(const GeometryTileFeature& feature, const float zoom, +float RenderLineLayer::getLineWidth(const GeometryTileFeature& feature, + const float zoom, const FeatureState& featureState) const { const auto& evaluated = static_cast(*evaluatedProperties).evaluated; - float lineWidth = - evaluated.get().evaluate(feature, zoom, featureState, style::LineWidth::defaultValue()); - float gapWidth = - evaluated.get().evaluate(feature, zoom, featureState, style::LineGapWidth::defaultValue()); + float lineWidth = evaluated.get().evaluate( + feature, zoom, featureState, style::LineWidth::defaultValue()); + float gapWidth = evaluated.get().evaluate( + feature, zoom, featureState, style::LineGapWidth::defaultValue()); if (gapWidth) { return gapWidth + 2 * lineWidth; } else { diff --git a/src/mbgl/renderer/layers/render_location_indicator_layer.cpp b/src/mbgl/renderer/layers/render_location_indicator_layer.cpp index 14b55c63b23..00996f25176 100644 --- a/src/mbgl/renderer/layers/render_location_indicator_layer.cpp +++ b/src/mbgl/renderer/layers/render_location_indicator_layer.cpp @@ -40,7 +40,8 @@ namespace mbgl { struct LocationIndicatorRenderParameters { LocationIndicatorRenderParameters() = default; - explicit LocationIndicatorRenderParameters(const TransformParameters& tp) : state(&tp.state) {} + explicit LocationIndicatorRenderParameters(const TransformParameters& tp) + : state(&tp.state) {} LocationIndicatorRenderParameters(const LocationIndicatorRenderParameters& o) = default; LocationIndicatorRenderParameters& operator=(const LocationIndicatorRenderParameters& o) = default; @@ -76,9 +77,13 @@ class RenderLocationIndicatorImpl { GLfloat x = 0.0f; GLfloat y = 0.0f; - vec2(GLfloat x_, GLfloat y_) : x(x_), y(y_) {} + vec2(GLfloat x_, GLfloat y_) + : x(x_), + y(y_) {} vec2() = default; - explicit vec2(const Point& p) : x(static_cast(p.x)), y(static_cast(p.y)) {} + explicit vec2(const Point& p) + : x(static_cast(p.x)), + y(static_cast(p.y)) {} vec2(const vec2& o) = default; vec2(vec2&& o) = default; vec2& operator=(vec2&& o) = default; @@ -103,7 +108,8 @@ class RenderLocationIndicatorImpl { const vec2 norm = normalized(); // From theta to bearing - return util::rad2degf(util::wrap(static_cast(M_PI_2) - std::atan2(-norm.y, norm.x), 0.0f, static_cast(M_PI * 2.0))); + return util::rad2degf(util::wrap( + static_cast(M_PI_2) - std::atan2(-norm.y, norm.x), 0.0f, static_cast(M_PI * 2.0))); } Point toPoint() const { return {x, y}; } @@ -148,8 +154,8 @@ class RenderLocationIndicatorImpl { }; struct SimpleShader : public Shader { - // Note that custom layers need to draw geometry with a z value of 1 to take advantage of - // depth-based fragment culling. + // Note that custom layers need to draw geometry with a z value of 1 to + // take advantage of depth-based fragment culling. const GLchar* vertexShaderSource = R"MBGL_SHADER( #ifdef GL_ES precision highp float; @@ -282,7 +288,8 @@ void main() { image = nullptr; } /* - Assign can be called any time. Conversely, upload must be called with a bound gl context. + Assign can be called any time. Conversely, upload must be called + with a bound gl context. */ void assign(const Immutable* img) { imageDirty = true; @@ -361,8 +368,8 @@ void main() { static bool hasAnisotropicFiltering() { const auto* extensions = reinterpret_cast(glGetString(GL_EXTENSIONS)); GLenum error = glGetError(); - if (error != GL_NO_ERROR) { // glGetString(GL_EXTENSIONS) is deprecated in OpenGL Desktop 3.0+. But OpenGL 3.0+ - // has anisotropic filtering. + if (error != GL_NO_ERROR) { // glGetString(GL_EXTENSIONS) is deprecated in OpenGL + // Desktop 3.0+. But OpenGL 3.0+ has anisotropic filtering. return true; } else { if (strstr(extensions, "GL_EXT_texture_filter_anisotropic") != nullptr) return true; @@ -448,8 +455,8 @@ void main() { featureEnvelope->clear(); if (!texPuck || !texPuck->isValid()) return; - feature->geometry = - mapbox::geometry::point{oldParams.puckPosition.latitude(), oldParams.puckPosition.longitude()}; + feature->geometry = mapbox::geometry::point{oldParams.puckPosition.latitude(), + oldParams.puckPosition.longitude()}; mapbox::geometry::linear_ring border; for (const auto& v : puckGeometry) { vec4 p{{v.x, v.y, 0, 1}}; @@ -484,7 +491,8 @@ void main() { void updateRadius(const mbgl::LocationIndicatorRenderParameters& params) { const TransformState& s = *params.state; const auto numVtxCircumference = static_cast(circle.size() - 1); - const float bearingStep = 360.0f / static_cast(numVtxCircumference - 1); // first and last points are the same + const float bearingStep = 360.0f / + static_cast(numVtxCircumference - 1); // first and last points are the same const mapbox::cheap_ruler::point centerPoint(params.puckPosition.longitude(), params.puckPosition.latitude()); Point center = project(params.puckPosition, s); circle[0] = {0, 0}; @@ -556,29 +564,36 @@ void main() { void updatePuckPerspective(const mbgl::LocationIndicatorRenderParameters& params) { const TransformState& s = *params.state; - projectionPuck = projectionCircle; // Duplicated as it might change, depending on what puck style is chosen. + projectionPuck = projectionCircle; // Duplicated as it might change, depending + // on what puck style is chosen. const mapbox::cheap_ruler::point centerPoint(params.puckPosition.longitude(), params.puckPosition.latitude()); static constexpr float bearings[]{ 225.0f, 315.0f, 45.0f, 135.0f}; // Quads will be drawn as triangle fans. so bl, tl, tr, br #ifndef M_SQRT2 static constexpr const float M_SQRT2 = std::sqrt(2.0f); #endif - // The puck has to stay square at all zoom levels. CheapRuler::destination does not guarantee this at low zoom - // levels, so the extent has to be produced in mercator space + // The puck has to stay square at all zoom levels. CheapRuler::destination + // does not guarantee this at low zoom levels, so the extent has to be produced in mercator space const double tilt = s.getPitch(); - // Point verticalShiftAtCenter { float(std::sin(util::DEG2RAD_D * util::wrap(-t.getBearing() * - // util::RAD2DEG, 0.0f, 360.0f) )), - // -float(std::cos(util::DEG2RAD_D * util::wrap(-t.getBearing() * - // util::RAD2DEG_D, 0.0f, 360.0f))) }; - // would be correct only in the vertical center of the map. As soon as position goes away from that line, - // the shift direction is skewed by the perspective projection. - // So the way to have a shift aligned to the screen vertical axis is to find this direction in screen space, and - // convert it back to map space. This would yield an always straight up shift. However, going further (= the - // opposite direction of where the lines are converging in the projection) might produce an even more realistic - // effect. But in this case, it empirically seems that the largest shift that look acceptable is what is - // obtained at the bottom of the window, avoiding the wider converging lines that pass by the edge of the screen - // going toward the top. + // Point verticalShiftAtCenter { float(std::sin(util::DEG2RAD_D + // * util::wrap(-t.getBearing() * util::RAD2DEG, 0.0f, 360.0f) + // )), + // -float(std::cos(util::DEG2RAD_D + // * util::wrap(-t.getBearing() * + // util::RAD2DEG_D, 0.0f, 360.0f))) + // }; + // would be correct only in the vertical center of the map. As soon as + // position goes away from that line, the shift direction is skewed by + // the perspective projection. So the way to have a shift aligned to the + // screen vertical axis is to find this direction in screen space, and + // convert it back to map space. This would yield an always straight up + // shift. However, going further (= the opposite direction of where the + // lines are converging in the projection) might produce an even more + // realistic effect. But in this case, it empirically seems that the + // largest shift that look acceptable is what is obtained at the bottom + // of the window, avoiding the wider converging lines that pass by the + // edge of the screen going toward the top. Point verticalShift = hatShadowShiftVector(params.puckPosition, params); const float horizontalScaleFactor = @@ -586,9 +601,10 @@ void main() { util::clamp(pixelSizeToWorldSizeH(params.puckPosition, s), 0.8f, 100.1f) * params.perspectiveCompensation; // Compensation factor for the perspective deformation // ^ clamping this to 0.8 to avoid growing the puck too much close to the camera. - const double shadowRadius = - ((texShadow) ? texShadow->width / texShadow->pixelRatio : 0.0) * params.puckShadowScale * M_SQRT2 * 0.5 * - horizontalScaleFactor; // Technically it's not the radius, but the half diagonal of the quad. + const double shadowRadius = ((texShadow) ? texShadow->width / texShadow->pixelRatio : 0.0) * + params.puckShadowScale * M_SQRT2 * 0.5 * + horizontalScaleFactor; // Technically it's not the radius, but + // the half diagonal of the quad. const double puckRadius = ((texPuck) ? texPuck->width / texPuck->pixelRatio : 0.0) * params.puckScale * M_SQRT2 * 0.5 * horizontalScaleFactor; const double hatRadius = ((texPuckHat) ? texPuckHat->width / texPuckHat->pixelRatio : 0.0) * @@ -597,18 +613,17 @@ void main() { for (unsigned long i = 0; i < 4; ++i) { const auto b = util::wrap(static_cast(params.puckBearing) + bearings[i], 0.0f, 360.0f); - const Point cornerDirection{std::sin(util::deg2rad(b)), - -std::cos(util::deg2rad(b))}; + const Point cornerDirection{std::sin(util::deg2rad(b)), -std::cos(util::deg2rad(b))}; Point shadowOffset = cornerDirection * shadowRadius; Point puckOffset = cornerDirection * puckRadius; Point hatOffset = cornerDirection * hatRadius; - shadowGeometry[i] = - vec2(shadowOffset + (verticalShift * (tilt * -params.puckLayersDisplacement * horizontalScaleFactor))); + shadowGeometry[i] = vec2(shadowOffset + + (verticalShift * (tilt * -params.puckLayersDisplacement * horizontalScaleFactor))); puckGeometry[i] = vec2(puckOffset); - hatGeometry[i] = - vec2(hatOffset + (verticalShift * (tilt * params.puckLayersDisplacement * horizontalScaleFactor))); + hatGeometry[i] = vec2(hatOffset + + (verticalShift * (tilt * params.puckLayersDisplacement * horizontalScaleFactor))); } } @@ -658,11 +673,17 @@ void main() { texturedShader.detach(); } - void drawShadow() { drawQuad(shadowBuffer, shadowGeometry, texShadow); } + void drawShadow() { + drawQuad(shadowBuffer, shadowGeometry, texShadow); + } - void drawPuck() { drawQuad(puckBuffer, puckGeometry, texPuck); } + void drawPuck() { + drawQuad(puckBuffer, puckGeometry, texPuck); + } - void drawHat() { drawQuad(hatBuffer, hatGeometry, texPuckHat); } + void drawHat() { + drawQuad(hatBuffer, hatGeometry, texPuckHat); + } static LatLng screenCoordinateToLatLng(const ScreenCoordinate& p, const TransformState& s, @@ -838,8 +859,8 @@ void RenderLocationIndicatorLayer::render(PaintParameters& paintParameters) { MBGL_CHECK_ERROR(renderImpl->render(renderImpl->parameters)); - // Reset the view back to our original one, just in case the CustomLayer changed - // the viewport or Framebuffer. + // Reset the view back to our original one, just in case the CustomLayer + // changed the viewport or Framebuffer. paintParameters.backend.getDefaultRenderable().getResource().bind(); glContext.setDirtyState(); } diff --git a/src/mbgl/renderer/layers/render_raster_layer.cpp b/src/mbgl/renderer/layers/render_raster_layer.cpp index 4aeff8f136b..5684e13c7c4 100644 --- a/src/mbgl/renderer/layers/render_raster_layer.cpp +++ b/src/mbgl/renderer/layers/render_raster_layer.cpp @@ -35,9 +35,8 @@ void RenderRasterLayer::transition(const TransitionParameters& parameters) { } void RenderRasterLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + auto properties = makeMutable(staticImmutableCast(baseImpl), + unevaluated.evaluate(parameters)); passes = properties->evaluated.get() > 0 ? RenderPass::Translucent : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); @@ -71,11 +70,8 @@ static std::array spinWeights(float spin) { spin = util::deg2radf(spin); float s = std::sin(spin); float c = std::cos(spin); - std::array spin_weights = {{ - (2 * c + 1) / 3, - (-std::sqrt(3.0f) * s - c + 1) / 3, - (std::sqrt(3.0f) * s - c + 1) / 3 - }}; + std::array spin_weights = { + {(2 * c + 1) / 3, (-std::sqrt(3.0f) * s - c + 1) / 3, (std::sqrt(3.0f) * s - c + 1) / 3}}; return spin_weights; } @@ -94,14 +90,14 @@ void RenderRasterLayer::render(PaintParameters& parameters) { if (!parameters.shaders.populate(rasterProgram)) return; const auto& evaluated = static_cast(*evaluatedProperties).evaluated; - RasterProgram::Binders paintAttributeData{ evaluated, 0 }; - - auto draw = [&] (const mat4& matrix, - const auto& vertexBuffer, - const auto& indexBuffer, - const auto& segments, - const auto& textureBindings, - const std::string& drawScopeID) { + RasterProgram::Binders paintAttributeData{evaluated, 0}; + + auto draw = [&](const mat4& matrix, + const auto& vertexBuffer, + const auto& indexBuffer, + const auto& segments, + const auto& textureBindings, + const std::string& drawScopeID) { const auto allUniformValues = RasterProgram::computeAllUniformValues( RasterProgram::LayoutUniformValues{ uniforms::matrix::Value(matrix), @@ -119,29 +115,29 @@ void RenderRasterLayer::render(PaintParameters& parameters) { paintAttributeData, evaluated, static_cast(parameters.state.getZoom())); - const auto allAttributeBindings = - RasterProgram::computeAllAttributeBindings(vertexBuffer, paintAttributeData, evaluated); + const auto allAttributeBindings = RasterProgram::computeAllAttributeBindings( + vertexBuffer, paintAttributeData, evaluated); checkRenderability(parameters, RasterProgram::activeBindingCount(allAttributeBindings)); - rasterProgram->draw( - parameters.context, - *parameters.renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - indexBuffer, - segments, - allUniformValues, - allAttributeBindings, - textureBindings, - getID() + "/" + drawScopeID - ); + rasterProgram->draw(parameters.context, + *parameters.renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + indexBuffer, + segments, + allUniformValues, + allAttributeBindings, + textureBindings, + getID() + "/" + drawScopeID); }; - const gfx::TextureFilterType filter = evaluated.get() == RasterResamplingType::Nearest ? gfx::TextureFilterType::Nearest : gfx::TextureFilterType::Linear; + const gfx::TextureFilterType filter = evaluated.get() == RasterResamplingType::Nearest + ? gfx::TextureFilterType::Nearest + : gfx::TextureFilterType::Linear; if (imageData && !imageData->bucket->needsUpload()) { RasterBucket& bucket = *imageData->bucket; @@ -167,8 +163,7 @@ void RenderRasterLayer::render(PaintParameters& parameters) { } auto& bucket = static_cast(*bucket_); - if (!bucket.hasData()) - continue; + if (!bucket.hasData()) continue; assert(bucket.texture); if (bucket.vertexBuffer && bucket.indexBuffer) { diff --git a/src/mbgl/renderer/layers/render_symbol_layer.cpp b/src/mbgl/renderer/layers/render_symbol_layer.cpp index c8af678d64f..807d1b67b05 100644 --- a/src/mbgl/renderer/layers/render_symbol_layer.cpp +++ b/src/mbgl/renderer/layers/render_symbol_layer.cpp @@ -29,31 +29,26 @@ namespace { style::SymbolPropertyValues iconPropertyValues(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_, const style::SymbolLayoutProperties::PossiblyEvaluated& layout_) { - return style::SymbolPropertyValues { - layout_.get(), - layout_.get(), - layout_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get().constantOr(Color::black()).a > 0 && - evaluated_.get().constantOr(1), - evaluated_.get().constantOr(Color::black()).a > 0 - }; + return style::SymbolPropertyValues{layout_.get(), + layout_.get(), + layout_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get().constantOr(Color::black()).a > 0 && + evaluated_.get().constantOr(1), + evaluated_.get().constantOr(Color::black()).a > 0}; } - style::SymbolPropertyValues textPropertyValues(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_, const style::SymbolLayoutProperties::PossiblyEvaluated& layout_) { - return style::SymbolPropertyValues { - layout_.get(), - layout_.get(), - layout_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get().constantOr(Color::black()).a > 0 && - evaluated_.get().constantOr(1), - evaluated_.get().constantOr(Color::black()).a > 0 - }; + return style::SymbolPropertyValues{layout_.get(), + layout_.get(), + layout_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get().constantOr(Color::black()).a > 0 && + evaluated_.get().constantOr(1), + evaluated_.get().constantOr(Color::black()).a > 0}; } using SegmentWrapper = std::reference_wrapper>; @@ -81,20 +76,21 @@ struct RenderableSegment { float sortKey; SymbolType type; - friend bool operator < (const RenderableSegment& lhs, const RenderableSegment& rhs) { + friend bool operator<(const RenderableSegment& lhs, const RenderableSegment& rhs) { // Sort renderable segments by a sort key. if (lhs.sortKey < rhs.sortKey) { return true; } - // In cases when sort key is the same, sort by the type of a segment (text over icons), - // and for segments of the same type with the same sort key, sort by a tile id. + // In cases when sort key is the same, sort by the type of a segment + // (text over icons), and for segments of the same type with the same + // sort key, sort by a tile id. if (lhs.sortKey == rhs.sortKey) { if (lhs.type != SymbolType::Text && rhs.type == SymbolType::Text) { return true; } - if (lhs.type == rhs.type) { + if (lhs.type == rhs.type) { return lhs.tile.id < rhs.tile.id; } } @@ -119,17 +115,15 @@ void drawIcon(const RenderSymbolLayer::Programs& programs, const auto& paintPropertyValues = RenderSymbolLayer::iconPaintProperties(evaluated); const bool alongLine = layout.get() != SymbolPlacementType::Point && - layout.get() == AlignmentType::Map; + layout.get() == AlignmentType::Map; const bool iconScaled = layout.get().constantOr(1.0) != 1.0 || bucket.iconsNeedLinear; const bool iconTransformed = values.rotationAlignment == AlignmentType::Map || parameters.state.getPitch() != 0; - const gfx::TextureBinding textureBinding{ tile.getIconAtlasTexture().getResource(), - sdfIcons || - parameters.state.isChanging() || - iconScaled || iconTransformed - ? gfx::TextureFilterType::Linear - : gfx::TextureFilterType::Nearest }; + const gfx::TextureBinding textureBinding{tile.getIconAtlasTexture().getResource(), + sdfIcons || parameters.state.isChanging() || iconScaled || iconTransformed + ? gfx::TextureFilterType::Linear + : gfx::TextureFilterType::Nearest}; const Size& iconSize = tile.getIconAtlasTexture().size; const bool variablePlacedIcon = bucket.hasVariablePlacement && layout.get() != IconTextFitType::None; @@ -137,43 +131,65 @@ void drawIcon(const RenderSymbolLayer::Programs& programs, if (sdfIcons) { if (values.hasHalo) { draw(*programs.symbolSDFIconProgram, - SymbolSDFIconProgram::layoutUniformValues(false, variablePlacedIcon, values, iconSize, parameters.pixelsToGLUnits, parameters.pixelRatio, alongLine, tile, parameters.state, parameters.symbolFadeChange, SymbolSDFPart::Halo), - bucket.sdfIcon, - iconSegments, - bucket.iconSizeBinder, - bucketPaintProperties.iconBinders, - paintPropertyValues, - SymbolSDFIconProgram::TextureBindings{ - textureBinding - }, - "halo"); + SymbolSDFIconProgram::layoutUniformValues(false, + variablePlacedIcon, + values, + iconSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Halo), + bucket.sdfIcon, + iconSegments, + bucket.iconSizeBinder, + bucketPaintProperties.iconBinders, + paintPropertyValues, + SymbolSDFIconProgram::TextureBindings{textureBinding}, + "halo"); } if (values.hasFill) { draw(*programs.symbolSDFIconProgram, - SymbolSDFIconProgram::layoutUniformValues(false, variablePlacedIcon, values, iconSize, parameters.pixelsToGLUnits, parameters.pixelRatio, alongLine, tile, parameters.state, parameters.symbolFadeChange, SymbolSDFPart::Fill), - bucket.sdfIcon, - iconSegments, - bucket.iconSizeBinder, - bucketPaintProperties.iconBinders, - paintPropertyValues, - SymbolSDFIconProgram::TextureBindings{ - textureBinding - }, - "fill"); + SymbolSDFIconProgram::layoutUniformValues(false, + variablePlacedIcon, + values, + iconSize, + parameters.pixelsToGLUnits, + parameters.pixelRatio, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange, + SymbolSDFPart::Fill), + bucket.sdfIcon, + iconSegments, + bucket.iconSizeBinder, + bucketPaintProperties.iconBinders, + paintPropertyValues, + SymbolSDFIconProgram::TextureBindings{textureBinding}, + "fill"); } } else { draw(*programs.symbolIconProgram, - SymbolIconProgram::layoutUniformValues(false, variablePlacedIcon, values, iconSize, parameters.pixelsToGLUnits, alongLine, tile, parameters.state, parameters.symbolFadeChange), - bucket.icon, - iconSegments, - bucket.iconSizeBinder, - bucketPaintProperties.iconBinders, - paintPropertyValues, - SymbolIconProgram::TextureBindings{ - textureBinding - }, - "icon"); + SymbolIconProgram::layoutUniformValues(false, + variablePlacedIcon, + values, + iconSize, + parameters.pixelsToGLUnits, + alongLine, + tile, + parameters.state, + parameters.symbolFadeChange), + bucket.icon, + iconSegments, + bucket.iconSizeBinder, + bucketPaintProperties.iconBinders, + paintPropertyValues, + SymbolIconProgram::TextureBindings{textureBinding}, + "icon"); } } @@ -193,7 +209,7 @@ void drawText(const RenderSymbolLayer::Programs& programs, const auto& paintPropertyValues = RenderSymbolLayer::textPaintProperties(evaluated); const bool alongLine = layout.get() != SymbolPlacementType::Point && - layout.get() == AlignmentType::Map; + layout.get() == AlignmentType::Map; const Size& glyphTexSize = tile.getGlyphAtlasTexture().size; const gfx::TextureBinding glyphTextureBinding{tile.getGlyphAtlasTexture().getResource(), @@ -212,8 +228,8 @@ void drawText(const RenderSymbolLayer::Programs& programs, }; if (bucket.iconsInText) { - const ZoomEvaluatedSize partiallyEvaluatedTextSize = - bucket.textSizeBinder->evaluateForZoom(static_cast(parameters.state.getZoom())); + const ZoomEvaluatedSize partiallyEvaluatedTextSize = bucket.textSizeBinder->evaluateForZoom( + static_cast(parameters.state.getZoom())); const bool transformed = values.rotationAlignment == AlignmentType::Map || parameters.state.getPitch() != 0; const Size& iconTexSize = tile.getIconAtlasTexture().size; const gfx::TextureBinding iconTextureBinding{ @@ -306,14 +322,13 @@ RenderSymbolLayer::~RenderSymbolLayer() = default; void RenderSymbolLayer::transition(const TransitionParameters& parameters) { unevaluated = impl_cast(baseImpl).paint.transitioned(parameters, std::move(unevaluated)); - hasFormatSectionOverrides = - SymbolLayerPaintPropertyOverrides::hasOverrides(impl_cast(baseImpl).layout.get()); + hasFormatSectionOverrides = SymbolLayerPaintPropertyOverrides::hasOverrides( + impl_cast(baseImpl).layout.get()); } void RenderSymbolLayer::evaluate(const PropertyEvaluationParameters& parameters) { - auto properties = makeMutable( - staticImmutableCast(baseImpl), - unevaluated.evaluate(parameters)); + auto properties = makeMutable(staticImmutableCast(baseImpl), + unevaluated.evaluate(parameters)); auto& evaluated = properties->evaluated; auto& layout = impl_cast(baseImpl).layout; @@ -326,9 +341,10 @@ void RenderSymbolLayer::evaluate(const PropertyEvaluationParameters& parameters) auto hasTextOpacity = evaluated.get().constantOr(Color::black()).a > 0 || evaluated.get().constantOr(Color::black()).a > 0; - passes = ((evaluated.get().constantOr(1) > 0 && hasIconOpacity && iconSize > 0) - || (evaluated.get().constantOr(1) > 0 && hasTextOpacity && textSize > 0)) - ? RenderPass::Translucent : RenderPass::None; + passes = ((evaluated.get().constantOr(1) > 0 && hasIconOpacity && iconSize > 0) || + (evaluated.get().constantOr(1) > 0 && hasTextOpacity && textSize > 0)) + ? RenderPass::Translucent + : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } @@ -357,69 +373,57 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { const bool sortFeaturesByKey = !impl_cast(baseImpl).layout.get().isUndefined(); std::multiset renderableSegments; - const auto draw = [¶meters, this] (auto& programInstance, - const auto& uniformValues, - const auto& buffers, - auto& segments, - const auto& symbolSizeBinder, - const auto& binders, - const auto& paintProperties, - const auto& textureBindings, - const std::string& suffix) { + const auto draw = [¶meters, this](auto& programInstance, + const auto& uniformValues, + const auto& buffers, + auto& segments, + const auto& symbolSizeBinder, + const auto& binders, + const auto& paintProperties, + const auto& textureBindings, + const std::string& suffix) { const auto allUniformValues = programInstance.computeAllUniformValues( - uniformValues, - *symbolSizeBinder, - binders, - paintProperties, - static_cast(parameters.state.getZoom()) - ); - - const auto allAttributeBindings = programInstance.computeAllAttributeBindings( - *buffers.vertexBuffer, - *buffers.dynamicVertexBuffer, - *buffers.opacityVertexBuffer, - binders, - paintProperties - ); + uniformValues, *symbolSizeBinder, binders, paintProperties, static_cast(parameters.state.getZoom())); + + const auto allAttributeBindings = programInstance.computeAllAttributeBindings(*buffers.vertexBuffer, + *buffers.dynamicVertexBuffer, + *buffers.opacityVertexBuffer, + binders, + paintProperties); this->checkRenderability(parameters, programInstance.activeBindingCount(allAttributeBindings)); segments.match( [&](const std::reference_wrapper>& segment) { - programInstance.draw( - parameters.context, - *parameters.renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - *buffers.indexBuffer, - segment, - allUniformValues, - allAttributeBindings, - textureBindings, - this->getID() + "/" + suffix - ); + programInstance.draw(parameters.context, + *parameters.renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + *buffers.indexBuffer, + segment, + allUniformValues, + allAttributeBindings, + textureBindings, + this->getID() + "/" + suffix); }, [&](const std::reference_wrapper>& segmentVector) { - programInstance.draw( - parameters.context, - *parameters.renderPass, - gfx::Triangles(), - parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), - gfx::StencilMode::disabled(), - parameters.colorModeForRenderPass(), - gfx::CullFaceMode::disabled(), - *buffers.indexBuffer, - segmentVector, - allUniformValues, - allAttributeBindings, - textureBindings, - this->getID() + "/" + suffix - ); - } - ); + programInstance.draw(parameters.context, + *parameters.renderPass, + gfx::Triangles(), + parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), + gfx::StencilMode::disabled(), + parameters.colorModeForRenderPass(), + gfx::CullFaceMode::disabled(), + *buffers.indexBuffer, + segmentVector, + allUniformValues, + allAttributeBindings, + textureBindings, + this->getID() + "/" + suffix); + }); }; for (const RenderTile& tile : *renderTiles) { @@ -435,25 +439,49 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { // Prevent a flickering issue when a symbol is moved. // bucket.justReloaded = false; - auto addRenderables = [&renderableSegments, &tile, renderData, &bucketPaintProperties, it = renderableSegments.begin()] (auto& segments, const SymbolType type) mutable { - for (auto& segment : segments) { - it = renderableSegments.emplace_hint(it, SegmentWrapper{std::ref(segment)}, tile, *renderData, bucketPaintProperties, segment.sortKey, type); - } - }; + auto addRenderables = + [&renderableSegments, &tile, renderData, &bucketPaintProperties, it = renderableSegments.begin()]( + auto& segments, const SymbolType type) mutable { + for (auto& segment : segments) { + it = renderableSegments.emplace_hint(it, + SegmentWrapper{std::ref(segment)}, + tile, + *renderData, + bucketPaintProperties, + segment.sortKey, + type); + } + }; if (bucket.hasIconData()) { if (sortFeaturesByKey) { addRenderables(bucket.icon.segments, SymbolType::IconRGBA); } else { - drawIcon(programs, draw, tile, *renderData, std::ref(bucket.icon.segments), bucketPaintProperties, parameters, false /*sdfIcon*/); + drawIcon(programs, + draw, + tile, + *renderData, + std::ref(bucket.icon.segments), + bucketPaintProperties, + parameters, + false /*sdfIcon*/ + ); } } - + if (bucket.hasSdfIconData()) { if (sortFeaturesByKey) { addRenderables(bucket.sdfIcon.segments, SymbolType::IconSDF); } else { - drawIcon(programs, draw, tile, *renderData, std::ref(bucket.sdfIcon.segments), bucketPaintProperties, parameters, true /*sdfIcon*/); + drawIcon(programs, + draw, + tile, + *renderData, + std::ref(bucket.sdfIcon.segments), + bucketPaintProperties, + parameters, + true /*sdfIcon*/ + ); } } @@ -461,25 +489,31 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { if (sortFeaturesByKey) { addRenderables(bucket.text.segments, SymbolType::Text); } else { - drawText(programs, draw, tile, *renderData, std::ref(bucket.text.segments), bucketPaintProperties, parameters); + drawText(programs, + draw, + tile, + *renderData, + std::ref(bucket.text.segments), + bucketPaintProperties, + parameters); } } - const auto drawCollisonData = [&](const bool isText, const bool hasCollisionBox, const bool hasCollisionCircle) { + const auto drawCollisonData = [&](const bool isText, + const bool hasCollisionBox, + const bool hasCollisionCircle) { if (!hasCollisionBox && !hasCollisionCircle) return; static const style::Properties<>::PossiblyEvaluated properties{}; static const CollisionBoxProgram::Binders paintAttributeData(properties, 0); const auto pixelRatio = tile.id.pixelsToTileUnits(1.0f, static_cast(parameters.state.getZoom())); - const auto scale = static_cast(std::pow(2, parameters.state.getZoom() - tile.getOverscaledTileID().overscaledZ)); - std::array extrudeScale = - {{ - parameters.pixelsToGLUnits[0] / (pixelRatio * scale), - parameters.pixelsToGLUnits[1] / (pixelRatio * scale) - }}; + const auto scale = static_cast( + std::pow(2, parameters.state.getZoom() - tile.getOverscaledTileID().overscaledZ)); + std::array extrudeScale = {{parameters.pixelsToGLUnits[0] / (pixelRatio * scale), + parameters.pixelsToGLUnits[1] / (pixelRatio * scale)}}; const auto& evaluated = getEvaluated(renderData->layerProperties); const auto& layout = *bucket.layout; - const auto values = isText ? textPropertyValues(evaluated, layout): iconPropertyValues(evaluated, layout); + const auto values = isText ? textPropertyValues(evaluated, layout) : iconPropertyValues(evaluated, layout); const bool needTranslate = values.translate[0] != 0 || values.translate[1] != 0; if (hasCollisionBox) { @@ -487,18 +521,18 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { programs.collisionBoxProgram->draw( parameters.context, *parameters.renderPass, - gfx::Lines{ 1.0f }, + gfx::Lines{1.0f}, gfx::DepthMode::disabled(), gfx::StencilMode::disabled(), parameters.colorModeForRenderPass(), gfx::CullFaceMode::disabled(), - CollisionBoxProgram::LayoutUniformValues { - uniforms::matrix::Value((needTranslate + CollisionBoxProgram::LayoutUniformValues{ + uniforms::matrix::Value( + (needTranslate ? tile.translatedMatrix(values.translate, values.translateAnchor, parameters.state) : tile.matrix)), uniforms::extrude_scale::Value(extrudeScale), - uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance()) - }, + uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance())}, *collisionBox->vertexBuffer, *collisionBox->dynamicVertexBuffer, *collisionBox->indexBuffer, @@ -519,14 +553,15 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { gfx::StencilMode::disabled(), parameters.colorModeForRenderPass(), gfx::CullFaceMode::disabled(), - CollisionCircleProgram::LayoutUniformValues { - uniforms::matrix::Value((needTranslate + CollisionCircleProgram::LayoutUniformValues{ + uniforms::matrix::Value( + (needTranslate ? tile.translatedMatrix(values.translate, values.translateAnchor, parameters.state) : tile.matrix)), uniforms::extrude_scale::Value(extrudeScale), - uniforms::overscale_factor::Value(static_cast(tile.getOverscaledTileID().overscaleFactor())), - uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance()) - }, + uniforms::overscale_factor::Value( + static_cast(tile.getOverscaledTileID().overscaleFactor())), + uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance())}, *collisionCircle->vertexBuffer, *collisionCircle->dynamicVertexBuffer, *collisionCircle->indexBuffer, @@ -545,38 +580,49 @@ void RenderSymbolLayer::render(PaintParameters& parameters) { if (sortFeaturesByKey) { for (auto& renderable : renderableSegments) { if (renderable.type == SymbolType::Text) { - drawText(programs, draw, renderable.tile, renderable.renderData, renderable.segment, renderable.bucketPaintProperties, parameters); + drawText(programs, + draw, + renderable.tile, + renderable.renderData, + renderable.segment, + renderable.bucketPaintProperties, + parameters); } else { - drawIcon(programs, draw, renderable.tile, renderable.renderData, renderable.segment, renderable.bucketPaintProperties, parameters, renderable.type == SymbolType::IconSDF); + drawIcon(programs, + draw, + renderable.tile, + renderable.renderData, + renderable.segment, + renderable.bucketPaintProperties, + parameters, + renderable.type == SymbolType::IconSDF); } } } } // static -style::IconPaintProperties::PossiblyEvaluated RenderSymbolLayer::iconPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_) { - return style::IconPaintProperties::PossiblyEvaluated { - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get() - }; +style::IconPaintProperties::PossiblyEvaluated RenderSymbolLayer::iconPaintProperties( + const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_) { + return style::IconPaintProperties::PossiblyEvaluated{evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get()}; } // static -style::TextPaintProperties::PossiblyEvaluated RenderSymbolLayer::textPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_) { - return style::TextPaintProperties::PossiblyEvaluated { - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get(), - evaluated_.get() - }; +style::TextPaintProperties::PossiblyEvaluated RenderSymbolLayer::textPaintProperties( + const style::SymbolPaintProperties::PossiblyEvaluated& evaluated_) { + return style::TextPaintProperties::PossiblyEvaluated{evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get(), + evaluated_.get()}; } void RenderSymbolLayer::prepare(const LayerPrepareParameters& params) { diff --git a/src/mbgl/renderer/layers/render_symbol_layer.hpp b/src/mbgl/renderer/layers/render_symbol_layer.hpp index 83df195a168..ea1cf5a2f3b 100644 --- a/src/mbgl/renderer/layers/render_symbol_layer.hpp +++ b/src/mbgl/renderer/layers/render_symbol_layer.hpp @@ -13,28 +13,24 @@ namespace style { // {icon,text}-specific paint-property packs for use in the symbol Programs. // Since each program deals either with icons or text, using a smaller property set // lets us avoid unnecessarily binding attributes for properties the program wouldn't use. -class IconPaintProperties : public Properties< - IconOpacity, - IconColor, - IconHaloColor, - IconHaloWidth, - IconHaloBlur, - IconTranslate, - IconTranslateAnchor -> {}; - -class TextPaintProperties : public Properties< - TextOpacity, - TextColor, - TextHaloColor, - TextHaloWidth, - TextHaloBlur, - TextTranslate, - TextTranslateAnchor -> {}; - -// Repackaging evaluated values from SymbolLayoutProperties + SymbolPaintProperties -// for genericity over icons vs. text. +class IconPaintProperties : public Properties {}; + +class TextPaintProperties : public Properties {}; + +// Repackaging evaluated values from SymbolLayoutProperties + +// SymbolPaintProperties for genericity over icons vs. text. class SymbolPropertyValues { public: // Layout @@ -65,7 +61,7 @@ class SymbolTextAndIconProgram; class CollisionBoxProgram; class CollisionCircleProgram; -class RenderSymbolLayer final: public RenderLayer { +class RenderSymbolLayer final : public RenderLayer { public: struct Programs { std::shared_ptr symbolIconProgram; @@ -80,8 +76,10 @@ class RenderSymbolLayer final: public RenderLayer { explicit RenderSymbolLayer(Immutable); ~RenderSymbolLayer() override; - static style::IconPaintProperties::PossiblyEvaluated iconPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); - static style::TextPaintProperties::PossiblyEvaluated textPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); + static style::IconPaintProperties::PossiblyEvaluated iconPaintProperties( + const style::SymbolPaintProperties::PossiblyEvaluated&); + static style::TextPaintProperties::PossiblyEvaluated textPaintProperties( + const style::SymbolPaintProperties::PossiblyEvaluated&); private: void transition(const TransitionParameters&) override; diff --git a/src/mbgl/renderer/paint_parameters.cpp b/src/mbgl/renderer/paint_parameters.cpp index caa44e1890b..ddc43b4bc04 100644 --- a/src/mbgl/renderer/paint_parameters.cpp +++ b/src/mbgl/renderer/paint_parameters.cpp @@ -15,8 +15,8 @@ TransformParameters::TransformParameters(const TransformState& state_) // Update the default matrices to the current viewport dimensions. state.getProjMatrix(projMatrix); - // Also compute a projection matrix that aligns with the current pixel grid, taking into account - // odd viewport sizes. + // Also compute a projection matrix that aligns with the current pixel grid, + // taking into account odd viewport sizes. state.getProjMatrix(alignedProjMatrix, 1, true); // Calculate a second projection matrix with the near plane moved further, @@ -27,37 +27,36 @@ TransformParameters::TransformParameters(const TransformState& state_) } PaintParameters::PaintParameters(gfx::Context& context_, - float pixelRatio_, - gfx::RendererBackend& backend_, - const EvaluatedLight& evaluatedLight_, - MapMode mode_, - MapDebugOptions debugOptions_, - TimePoint timePoint_, - const TransformParameters& transformParams_, - RenderStaticData& staticData_, - LineAtlas& lineAtlas_, - PatternAtlas& patternAtlas_) + float pixelRatio_, + gfx::RendererBackend& backend_, + const EvaluatedLight& evaluatedLight_, + MapMode mode_, + MapDebugOptions debugOptions_, + TimePoint timePoint_, + const TransformParameters& transformParams_, + RenderStaticData& staticData_, + LineAtlas& lineAtlas_, + PatternAtlas& patternAtlas_) : context(context_), - backend(backend_), - encoder(context.createCommandEncoder()), - transformParams(transformParams_), - state(transformParams_.state), - evaluatedLight(evaluatedLight_), - staticData(staticData_), - lineAtlas(lineAtlas_), - patternAtlas(patternAtlas_), - mapMode(mode_), - debugOptions(debugOptions_), - timePoint(timePoint_), - pixelRatio(pixelRatio_), + backend(backend_), + encoder(context.createCommandEncoder()), + transformParams(transformParams_), + state(transformParams_.state), + evaluatedLight(evaluatedLight_), + staticData(staticData_), + lineAtlas(lineAtlas_), + patternAtlas(patternAtlas_), + mapMode(mode_), + debugOptions(debugOptions_), + timePoint(timePoint_), + pixelRatio(pixelRatio_), #ifndef NDEBUG - programs((debugOptions & MapDebugOptions::Overdraw) ? staticData_.overdrawPrograms : staticData_.programs), + programs((debugOptions & MapDebugOptions::Overdraw) ? staticData_.overdrawPrograms : staticData_.programs), #else - programs(staticData_.programs), + programs(staticData_.programs), #endif - shaders(*staticData_.shaders) -{ - pixelsToGLUnits = {{ 2.0f / state.getSize().width, -2.0f / state.getSize().height }}; + shaders(*staticData_.shaders) { + pixelsToGLUnits = {{2.0f / state.getSize().width, -2.0f / state.getSize().height}}; if (state.getViewportMode() == ViewportMode::FlippedY) { pixelsToGLUnits[1] *= -1; @@ -78,13 +77,11 @@ gfx::DepthMode PaintParameters::depthModeForSublayer(uint8_t n, gfx::DepthMaskTy return gfx::DepthMode::disabled(); } float depth = depthRangeSize + ((1 + currentLayer) * numSublayers + n) * depthEpsilon; - return gfx::DepthMode { gfx::DepthFunctionType::LessEqual, mask, { depth, depth } }; + return gfx::DepthMode{gfx::DepthFunctionType::LessEqual, mask, {depth, depth}}; } gfx::DepthMode PaintParameters::depthModeFor3D() const { - return gfx::DepthMode{ gfx::DepthFunctionType::LessEqual, - gfx::DepthMaskType::ReadWrite, - { 0.0, depthRangeSize } }; + return gfx::DepthMode{gfx::DepthFunctionType::LessEqual, gfx::DepthMaskType::ReadWrite, {0.0, depthRangeSize}}; } void PaintParameters::clearStencil() { @@ -95,16 +92,18 @@ void PaintParameters::clearStencil() { namespace { // Detects a difference in keys of renderTiles and tileClippingMaskIDs -bool tileIDsIdentical(const RenderTiles& renderTiles, - const std::map& tileClippingMaskIDs) { +bool tileIDsIdentical(const RenderTiles& renderTiles, const std::map& tileClippingMaskIDs) { assert(renderTiles); - assert(std::is_sorted(renderTiles->begin(), renderTiles->end(), - [](const RenderTile& a, const RenderTile& b) { return a.id < b.id; })); + assert(std::is_sorted(renderTiles->begin(), renderTiles->end(), [](const RenderTile& a, const RenderTile& b) { + return a.id < b.id; + })); if (renderTiles->size() != tileClippingMaskIDs.size()) { return false; } - return std::equal(renderTiles->begin(), renderTiles->end(), tileClippingMaskIDs.begin(), - [](const RenderTile& a, const auto& b) { return a.id == b.first; }); + return std::equal( + renderTiles->begin(), renderTiles->end(), tileClippingMaskIDs.begin(), [](const RenderTile& a, const auto& b) { + return a.id == b.first; + }); } } // namespace @@ -126,8 +125,8 @@ void PaintParameters::renderTileClippingMasks(const RenderTiles& renderTiles) { if (!program) { return; } - - const style::Properties<>::PossiblyEvaluated properties {}; + + const style::Properties<>::PossiblyEvaluated properties{}; const ClippingMaskProgram::Binders paintAttributeData(properties, 0); for (const RenderTile& renderTile : *renderTiles) { @@ -135,30 +134,30 @@ void PaintParameters::renderTileClippingMasks(const RenderTiles& renderTiles) { tileClippingMaskIDs.emplace(renderTile.id, stencilID); program->draw(context, - *renderPass, - gfx::Triangles(), - gfx::DepthMode::disabled(), - gfx::StencilMode{gfx::StencilMode::Always{}, - stencilID, - 0b11111111, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Replace}, - gfx::ColorMode::disabled(), - gfx::CullFaceMode::disabled(), - *staticData.quadTriangleIndexBuffer, - staticData.clippingMaskSegments, - ClippingMaskProgram::computeAllUniformValues( - ClippingMaskProgram::LayoutUniformValues{ - uniforms::matrix::Value(matrixForTile(renderTile.id)), - }, - paintAttributeData, - properties, - static_cast(state.getZoom())), - ClippingMaskProgram::computeAllAttributeBindings( - *staticData.tileVertexBuffer, paintAttributeData, properties), - ClippingMaskProgram::TextureBindings{}, - "clipping/" + util::toString(stencilID)); + *renderPass, + gfx::Triangles(), + gfx::DepthMode::disabled(), + gfx::StencilMode{gfx::StencilMode::Always{}, + stencilID, + 0b11111111, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Replace}, + gfx::ColorMode::disabled(), + gfx::CullFaceMode::disabled(), + *staticData.quadTriangleIndexBuffer, + staticData.clippingMaskSegments, + ClippingMaskProgram::computeAllUniformValues( + ClippingMaskProgram::LayoutUniformValues{ + uniforms::matrix::Value(matrixForTile(renderTile.id)), + }, + paintAttributeData, + properties, + static_cast(state.getZoom())), + ClippingMaskProgram::computeAllAttributeBindings( + *staticData.tileVertexBuffer, paintAttributeData, properties), + ClippingMaskProgram::TextureBindings{}, + "clipping/" + util::toString(stencilID)); } } @@ -166,12 +165,12 @@ gfx::StencilMode PaintParameters::stencilModeForClipping(const UnwrappedTileID& auto it = tileClippingMaskIDs.find(tileID); assert(it != tileClippingMaskIDs.end()); const int32_t id = it != tileClippingMaskIDs.end() ? it->second : 0b00000000; - return gfx::StencilMode{ gfx::StencilMode::Equal{ 0b11111111 }, - id, - 0b00000000, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Replace }; + return gfx::StencilMode{gfx::StencilMode::Equal{0b11111111}, + id, + 0b00000000, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Replace}; } gfx::StencilMode PaintParameters::stencilModeFor3D() { @@ -179,30 +178,26 @@ gfx::StencilMode PaintParameters::stencilModeFor3D() { clearStencil(); } - // We're potentially destroying the stencil clipping mask in this pass. That means we'll have - // to recreate it for the next source if any. + // We're potentially destroying the stencil clipping mask in this pass. That + // means we'll have to recreate it for the next source if any. tileClippingMaskIDs.clear(); const int32_t id = nextStencilID++; - return gfx::StencilMode{ gfx::StencilMode::NotEqual{ 0b11111111 }, - id, - 0b11111111, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Keep, - gfx::StencilOpType::Replace }; + return gfx::StencilMode{gfx::StencilMode::NotEqual{0b11111111}, + id, + 0b11111111, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Keep, + gfx::StencilOpType::Replace}; } gfx::ColorMode PaintParameters::colorModeForRenderPass() const { if (debugOptions & MapDebugOptions::Overdraw) { const float overdraw = 1.0f / 8.0f; - return gfx::ColorMode { - gfx::ColorMode::Add { - gfx::ColorBlendFactorType::ConstantColor, - gfx::ColorBlendFactorType::One - }, - Color { overdraw, overdraw, overdraw, 0.0f }, - gfx::ColorMode::Mask { true, true, true, true } - }; + return gfx::ColorMode{ + gfx::ColorMode::Add{gfx::ColorBlendFactorType::ConstantColor, gfx::ColorBlendFactorType::One}, + Color{overdraw, overdraw, overdraw, 0.0f}, + gfx::ColorMode::Mask{true, true, true, true}}; } else if (pass == RenderPass::Translucent) { return gfx::ColorMode::alphaBlended(); } else { diff --git a/src/mbgl/renderer/paint_parameters.hpp b/src/mbgl/renderer/paint_parameters.hpp index 75c28c17e29..802b5340721 100644 --- a/src/mbgl/renderer/paint_parameters.hpp +++ b/src/mbgl/renderer/paint_parameters.hpp @@ -33,7 +33,6 @@ class RenderPass; class ShaderRegistry; } // namespace gfx - class TransformParameters { public: TransformParameters(const TransformState&); diff --git a/src/mbgl/renderer/paint_property_binder.hpp b/src/mbgl/renderer/paint_property_binder.hpp index 14d23881aa4..ffda591899a 100644 --- a/src/mbgl/renderer/paint_property_binder.hpp +++ b/src/mbgl/renderer/paint_property_binder.hpp @@ -29,16 +29,17 @@ struct FeatureVertexRange { using FeatureVertexRangeMap = std::map>; /* - ZoomInterpolatedAttribute is a 'compound' attribute, representing two values of the - the base attribute Attr. These two values are provided to the shader to allow interpolation - between zoom levels, without the need to repopulate vertex buffers each frame as the map is - being zoomed. + ZoomInterpolatedAttribute is a 'compound' attribute, representing two + values of the the base attribute Attr. These two values are provided to the + shader to allow interpolation between zoom levels, without the need to + repopulate vertex buffers each frame as the map is being zoomed. */ template -using ZoomInterpolatedAttributeType = gfx::AttributeType; +using ZoomInterpolatedAttributeType = + gfx::AttributeType; inline std::array attributeValue(float v) { - return {{ v }}; + return {{v}}; } /* @@ -55,54 +56,54 @@ inline uint16_t packUint8Pair(T a, T b) { Encode a four-component color value into a pair of floats. Since csscolorparser uses 8-bit precision for each color component, for each float we use the upper 8 bits for one component (e.g. (color.r * 255) * 256), and the lower 8 for another. - + Also note that colors come in as floats 0..1, so we scale by 255. */ inline std::array attributeValue(const Color& color) { - return {{ - static_cast(packUint8Pair(255 * color.r, 255 * color.g)), - static_cast(packUint8Pair(255 * color.b, 255 * color.a)) - }}; + return {{static_cast(packUint8Pair(255 * color.r, 255 * color.g)), + static_cast(packUint8Pair(255 * color.b, 255 * color.a))}}; } template -std::array zoomInterpolatedAttributeValue(const std::array& min, const std::array& max) { - std::array result; +std::array zoomInterpolatedAttributeValue(const std::array& min, + const std::array& max) { + std::array result; for (size_t i = 0; i < N; i++) { - result[i] = min[i]; - result[i+N] = max[i]; + result[i] = min[i]; + result[i + N] = max[i]; } return result; } /* - PaintPropertyBinder is an abstract class serving as the interface definition for - the strategy used for constructing, uploading, and binding paint property data as - GLSL attributes. + PaintPropertyBinder is an abstract class serving as the interface definition + for the strategy used for constructing, uploading, and binding paint property + data as GLSL attributes. - It has three concrete subclasses, one for each of the three strategies we use: + It has three concrete subclasses, one for each of the three strategies we + use: - * For _constant_ properties -- those whose value is a constant, or the constant - result of evaluating a camera function at a particular camera position -- we - don't need a vertex buffer, and instead use a uniform. + * For _constant_ properties -- those whose value is a constant, or the + constant result of evaluating a camera function at a particular camera + position -- we don't need a vertex buffer, and instead use a uniform. * For source functions, we use a vertex buffer with a single attribute value, the evaluated result of the source function for the given feature. - * For composite functions, we use a vertex buffer with two attributes: min and - max values covering the range of zooms at which we expect the tile to be - displayed. These values are calculated by evaluating the composite function for - the given feature at strategically chosen zoom levels. In addition to this - attribute data, we also use a uniform value which the shader uses to interpolate - between the min and max value at the final displayed zoom level. The use of a - uniform allows us to cheaply update the value on every frame. - - Note that the shader source varies depending on whether we're using a uniform or - attribute. Like GL JS, we dynamically compile shaders at runtime to accomodate this. + * For composite functions, we use a vertex buffer with two attributes: min + and max values covering the range of zooms at which we expect the tile to be + displayed. These values are calculated by evaluating the composite function + for the given feature at strategically chosen zoom levels. In addition to + this attribute data, we also use a uniform value which the shader uses to + interpolate between the min and max value at the final displayed zoom level. + The use of a uniform allows us to cheaply update the value on every frame. + + Note that the shader source varies depending on whether we're using a uniform + or attribute. Like GL JS, we dynamically compile shaders at runtime to + accomodate this. */ template class PaintPropertyBinder { public: - virtual ~PaintPropertyBinder() = default; virtual void populateVertexVector(const GeometryTileFeature& feature, @@ -118,10 +119,14 @@ class PaintPropertyBinder { virtual void updateVertexVector(std::size_t, std::size_t, const GeometryTileFeature&, const FeatureState&) = 0; virtual void upload(gfx::UploadPass&) = 0; - virtual void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) = 0; - virtual std::tuple>...> attributeBinding(const PossiblyEvaluatedType& currentValue) const = 0; + virtual void setPatternParameters(const std::optional&, + const std::optional&, + const CrossfadeParameters&) = 0; + virtual std::tuple>...> attributeBinding( + const PossiblyEvaluatedType& currentValue) const = 0; virtual std::tuple...> interpolationFactor(float currentZoom) const = 0; - virtual std::tuple...> uniformValue(const PossiblyEvaluatedType& currentValue) const = 0; + virtual std::tuple...> uniformValue( + const PossiblyEvaluatedType& currentValue) const = 0; static std::unique_ptr create(const PossiblyEvaluatedType& value, float zoom, T defaultValue); @@ -132,8 +137,7 @@ template class ConstantPaintPropertyBinder : public PaintPropertyBinder, A> { public: ConstantPaintPropertyBinder(T constant_) - : constant(std::move(constant_)) { - } + : constant(std::move(constant_)) {} void populateVertexVector(const GeometryTileFeature&, std::size_t, @@ -144,18 +148,19 @@ class ConstantPaintPropertyBinder : public PaintPropertyBinder&, const std::optional&, const CrossfadeParameters&) override {}; + void setPatternParameters(const std::optional&, + const std::optional&, + const CrossfadeParameters&) override{}; - std::tuple> attributeBinding(const PossiblyEvaluatedPropertyValue&) const override { + std::tuple> attributeBinding( + const PossiblyEvaluatedPropertyValue&) const override { return {}; } - std::tuple interpolationFactor(float) const override { - return std::tuple { 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f}; } std::tuple uniformValue(const PossiblyEvaluatedPropertyValue& currentValue) const override { - return std::tuple { currentValue.constantOr(constant) }; + return std::tuple{currentValue.constantOr(constant)}; } private: @@ -163,11 +168,12 @@ class ConstantPaintPropertyBinder : public PaintPropertyBinder -class ConstantCrossFadedPaintPropertyBinder final : public PaintPropertyBinder,PossiblyEvaluatedPropertyValue>, As...> { +class ConstantCrossFadedPaintPropertyBinder final + : public PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, As...> { public: ConstantCrossFadedPaintPropertyBinder(Faded constant_) - : constant(std::move(constant_)), constantPatternPositions({}) { - } + : constant(std::move(constant_)), + constantPatternPositions({}) {} void populateVertexVector(const GeometryTileFeature&, std::size_t, @@ -179,24 +185,26 @@ class ConstantCrossFadedPaintPropertyBinder final : public PaintPropertyBinder& posA, const std::optional& posB, const CrossfadeParameters&) override { + void setPatternParameters(const std::optional& posA, + const std::optional& posB, + const CrossfadeParameters&) override { if (!posA || !posB) { return; } else { - constantPatternPositions = std::tuple, std::array> { posB->tlbr(), posA->tlbr() }; + constantPatternPositions = std::tuple, std::array>{posB->tlbr(), + posA->tlbr()}; } } - std::tuple, std::optional> - attributeBinding(const PossiblyEvaluatedPropertyValue>&) const override { + std::tuple, std::optional> attributeBinding( + const PossiblyEvaluatedPropertyValue>&) const override { return {}; } - std::tuple interpolationFactor(float) const override { - return std::tuple { 0.0f, 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f, 0.0f}; } - std::tuple, std::array> uniformValue(const PossiblyEvaluatedPropertyValue>&) const override { + std::tuple, std::array> uniformValue( + const PossiblyEvaluatedPropertyValue>&) const override { return constantPatternPositions; } @@ -215,9 +223,10 @@ class SourceFunctionPaintPropertyBinder final : public PaintPropertyBinder expression_, T defaultValue_) : expression(std::move(expression_)), - defaultValue(std::move(defaultValue_)) { - } - void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) override {}; + defaultValue(std::move(defaultValue_)) {} + void setPatternParameters(const std::optional&, + const std::optional&, + const CrossfadeParameters&) override{}; void populateVertexVector(const GeometryTileFeature& feature, std::size_t length, std::size_t index, @@ -233,7 +242,7 @@ class SourceFunctionPaintPropertyBinder final : public PaintPropertyBinder idStr = featureIDtoString(feature.getID()); if (idStr) { @@ -241,7 +250,8 @@ class SourceFunctionPaintPropertyBinder final : public PaintPropertyBinder> attributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const override { + std::tuple> attributeBinding( + const PossiblyEvaluatedPropertyValue& currentValue) const override { if (currentValue.isConstant()) { return {}; } else { - return std::tuple>{ - gfx::attributeBinding(*vertexBuffer) - }; + return std::tuple>{gfx::attributeBinding(*vertexBuffer)}; } } - std::tuple interpolationFactor(float) const override { - return std::tuple { 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f}; } std::tuple uniformValue(const PossiblyEvaluatedPropertyValue& currentValue) const override { if (currentValue.isConstant()) { - return std::tuple{ *currentValue.constant() }; + return std::tuple{*currentValue.constant()}; } else { // Uniform values for vertex attribute arrays are unused. return {}; @@ -306,9 +315,9 @@ class SourceFunctionPaintPropertyBinder final : public PaintPropertyBinder -class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder, A> { +class CompositeFunctionPaintPropertyBinder final + : public PaintPropertyBinder, A> { public: - using AttributeType = ZoomInterpolatedAttributeType; using AttributeValue = typename AttributeType::Value; using Vertex = gfx::VertexType; @@ -316,9 +325,10 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder expression_, float zoom, T defaultValue_) : expression(std::move(expression_)), defaultValue(std::move(defaultValue_)), - zoomRange({zoom, zoom + 1}) { - } - void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters&) override {}; + zoomRange({zoom, zoom + 1}) {} + void setPatternParameters(const std::optional&, + const std::optional&, + const CrossfadeParameters&) override{}; void populateVertexVector(const GeometryTileFeature& feature, std::size_t length, std::size_t index, @@ -339,12 +349,10 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinderstatistics.add(range.min); this->statistics.add(range.max); - AttributeValue value = zoomInterpolatedAttributeValue( - attributeValue(range.min), - attributeValue(range.max)); + AttributeValue value = zoomInterpolatedAttributeValue(attributeValue(range.min), attributeValue(range.max)); auto elements = vertexVector.elements(); for (std::size_t i = elements; i < length; ++i) { - vertexVector.emplace_back(Vertex { value }); + vertexVector.emplace_back(Vertex{value}); } std::optional idStr = featureIDtoString(feature.getID()); if (idStr) { @@ -352,7 +360,8 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder range = { @@ -389,13 +400,12 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder> attributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const override { + std::tuple> attributeBinding( + const PossiblyEvaluatedPropertyValue& currentValue) const override { if (currentValue.isConstant()) { return {}; } else { - return std::tuple>{ - gfx::attributeBinding(*vertexBuffer) - }; + return std::tuple>{gfx::attributeBinding(*vertexBuffer)}; } } @@ -408,7 +418,7 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder uniformValue(const PossiblyEvaluatedPropertyValue& currentValue) const override { if (currentValue.isConstant()) { - return std::tuple { *currentValue.constant() }; + return std::tuple{*currentValue.constant()}; } else { // Uniform values for vertex attribute arrays are unused. return {}; @@ -425,7 +435,8 @@ class CompositeFunctionPaintPropertyBinder final : public PaintPropertyBinder -class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2> { +class CompositeCrossFadedPaintPropertyBinder final + : public PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2> { public: using AttributeType = ZoomInterpolatedAttributeType; using AttributeType2 = ZoomInterpolatedAttributeType; @@ -439,10 +450,11 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< CompositeCrossFadedPaintPropertyBinder(style::PropertyExpression expression_, float zoom, T defaultValue_) : expression(std::move(expression_)), defaultValue(std::move(defaultValue_)), - zoomRange({zoom, zoom + 1}) { - } + zoomRange({zoom, zoom + 1}) {} - void setPatternParameters(const std::optional&, const std::optional&, const CrossfadeParameters& crossfade_) override { + void setPatternParameters(const std::optional&, + const std::optional&, + const CrossfadeParameters& crossfade_) override { crossfade = crossfade_; }; @@ -453,14 +465,17 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< const std::optional& patternDependencies, const CanonicalTileID&, const style::expression::Value&) override { - if (!patternDependencies || patternDependencies->mid.empty()) { - // Unlike other propperties with expressions that evaluate to null, the default value for `*-pattern` properties is an empty - // string and will not have a valid entry in patternPositions. We still need to populate the attribute buffers to avoid crashes - // when we try to draw the layer because we don't know at draw time if all features were evaluated to valid pattern dependencies. + if (!patternDependencies || patternDependencies->mid.empty()) { + // Unlike other propperties with expressions that evaluate to null, + // the default value for `*-pattern` properties is an empty string + // and will not have a valid entry in patternPositions. We still + // need to populate the attribute buffers to avoid crashes when we + // try to draw the layer because we don't know at draw time if all + // features were evaluated to valid pattern dependencies. for (std::size_t i = zoomInVertexVector.elements(); i < length; ++i) { - patternToVertexVector.emplace_back(Vertex { std::array{{0, 0, 0, 0}} }); - zoomInVertexVector.emplace_back(Vertex2 { std::array{{0, 0, 0, 0}} } ); - zoomOutVertexVector.emplace_back(Vertex2 { std::array{{0, 0, 0, 0}} }); + patternToVertexVector.emplace_back(Vertex{std::array{{0, 0, 0, 0}}}); + zoomInVertexVector.emplace_back(Vertex2{std::array{{0, 0, 0, 0}}}); + zoomOutVertexVector.emplace_back(Vertex2{std::array{{0, 0, 0, 0}}}); } } else if (!patternPositions.empty()) { const auto min = patternPositions.find(patternDependencies->min); @@ -475,9 +490,9 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< const ImagePosition imageMax = max->second; for (std::size_t i = zoomInVertexVector.elements(); i < length; ++i) { - patternToVertexVector.emplace_back(Vertex { imageMid.tlbr() }); - zoomInVertexVector.emplace_back(Vertex2 { imageMin.tlbr() }); - zoomOutVertexVector.emplace_back(Vertex2 { imageMax.tlbr() }); + patternToVertexVector.emplace_back(Vertex{imageMid.tlbr()}); + zoomInVertexVector.emplace_back(Vertex2{imageMin.tlbr()}); + zoomOutVertexVector.emplace_back(Vertex2{imageMax.tlbr()}); } } } @@ -494,7 +509,8 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< } } - std::tuple, std::optional> attributeBinding(const PossiblyEvaluatedPropertyValue>& currentValue) const override { + std::tuple, std::optional> attributeBinding( + const PossiblyEvaluatedPropertyValue>& currentValue) const override { if (currentValue.isConstant()) { return {}; } else { @@ -503,19 +519,18 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< assert(zoomOutVertexBuffer); return std::tuple, std::optional>{ gfx::attributeBinding(*patternToVertexBuffer), - gfx::attributeBinding(crossfade.fromScale == 2 ? *zoomInVertexBuffer : *zoomOutVertexBuffer) - }; + gfx::attributeBinding(crossfade.fromScale == 2 ? *zoomInVertexBuffer : *zoomOutVertexBuffer)}; } - return std::tuple, std::optional>{std::nullopt, std::nullopt}; + return std::tuple, std::optional>{std::nullopt, + std::nullopt}; } } - std::tuple interpolationFactor(float) const override { - return std::tuple { 0.0f, 0.0f }; - } + std::tuple interpolationFactor(float) const override { return std::tuple{0.0f, 0.0f}; } - std::tuple, std::array> uniformValue(const PossiblyEvaluatedPropertyValue>& ) const override { + std::tuple, std::array> uniformValue( + const PossiblyEvaluatedPropertyValue>&) const override { // Uniform values for vertex attribute arrays are unused. return {}; } @@ -536,40 +551,49 @@ class CompositeCrossFadedPaintPropertyBinder final : public PaintPropertyBinder< template struct CreateBinder { template - static std::unique_ptr> create(const PossiblyEvaluatedType& value, float zoom, T defaultValue) { + static std::unique_ptr> create( + const PossiblyEvaluatedType& value, float zoom, T defaultValue) { return value.match( - [&] (const T& constant) -> std::unique_ptr> { + [&](const T& constant) -> std::unique_ptr> { return std::make_unique>(constant); }, - [&] (const style::PropertyExpression& expression) -> std::unique_ptr> { + [&](const style::PropertyExpression& expression) + -> std::unique_ptr> { if (expression.isZoomConstant()) { return std::make_unique>(expression, defaultValue); } else { return std::make_unique>(expression, zoom, defaultValue); } - } - ); + }); } }; template struct CreateBinder>> { template - static std::unique_ptr, PossiblyEvaluatedPropertyValue>, A1, A2>> create(const PossiblyEvaluatedPropertyValue>& value, float zoom, T defaultValue) { + static std::unique_ptr< + PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2>> + create(const PossiblyEvaluatedPropertyValue>& value, float zoom, T defaultValue) { return value.match( - [&] (const Faded& constant) -> std::unique_ptr, PossiblyEvaluatedPropertyValue>, A1, A2>> { + [&](const Faded& constant) + -> std::unique_ptr< + PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2>> { return std::make_unique>(constant); }, - [&] (const style::PropertyExpression& expression) -> std::unique_ptr, PossiblyEvaluatedPropertyValue>, A1, A2>> { - return std::make_unique>(expression, zoom, defaultValue); - } - ); + [&](const style::PropertyExpression& expression) + -> std::unique_ptr< + PaintPropertyBinder, PossiblyEvaluatedPropertyValue>, A1, A2>> { + return std::make_unique>( + expression, zoom, defaultValue); + }); } }; template -std::unique_ptr> -PaintPropertyBinder::create(const PossiblyEvaluatedType& value, float zoom, T defaultValue) { +std::unique_ptr> +PaintPropertyBinder::create(const PossiblyEvaluatedType& value, + float zoom, + T defaultValue) { return CreateBinder::template create(value, zoom, defaultValue); } @@ -581,9 +605,7 @@ struct ZoomInterpolatedAttribute : public Attr { template struct InterpolationUniform { using Value = float; - static constexpr auto name() { - return concat_literals<&Attr::name, &string_literal<'_', 't'>::value>::value(); - } + static constexpr auto name() { return concat_literals<&Attr::name, &string_literal<'_', 't'>::value>::value(); } }; template @@ -603,15 +625,16 @@ class PaintPropertyBinders> { }; template - using Property = Detail; + using Property = Detail; public: template using Binder = typename Property

::Binder; - using Binders = IndexedTuple< - TypeList, - TypeList>...>>; + using Binders = IndexedTuple, TypeList>...>>; template PaintPropertyBinders(const EvaluatedProperties& properties, float z) @@ -634,22 +657,19 @@ class PaintPropertyBinders> { 0)...}); } - void updateVertexVectors(const FeatureStates& states, const GeometryTileLayer& layer, + void updateVertexVectors(const FeatureStates& states, + const GeometryTileLayer& layer, const ImagePositions& imagePositions) { util::ignore({(binders.template get()->updateVertexVectors(states, layer, imagePositions), 0)...}); } - void setPatternParameters(const std::optional& posA, const std::optional& posB, const CrossfadeParameters& crossfade) const { - util::ignore({ - (binders.template get()->setPatternParameters(posA, posB, crossfade), 0)... - }); + void setPatternParameters(const std::optional& posA, + const std::optional& posB, + const CrossfadeParameters& crossfade) const { + util::ignore({(binders.template get()->setPatternParameters(posA, posB, crossfade), 0)...}); } - void upload(gfx::UploadPass& uploadPass) { - util::ignore({ - (binders.template get()->upload(uploadPass), 0)... - }); - } + void upload(gfx::UploadPass& uploadPass) { util::ignore({(binders.template get()->upload(uploadPass), 0)...}); } template using ZoomInterpolatedAttributeList = typename Property

::ZoomInterpolatedAttributeList; @@ -661,9 +681,8 @@ class PaintPropertyBinders> { template AttributeBindings attributeBindings(const EvaluatedProperties& currentProperties) const { - return AttributeBindings { std::tuple_cat( - binders.template get()->attributeBinding(currentProperties.template get())... - ) }; + return AttributeBindings{ + std::tuple_cat(binders.template get()->attributeBinding(currentProperties.template get())...)}; } using UniformList = TypeListConcat..., typename Ps::UniformList...>; @@ -672,13 +691,11 @@ class PaintPropertyBinders> { template UniformValues uniformValues(float currentZoom, EvaluatedProperties& currentProperties) const { (void)currentZoom; // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56958 - return UniformValues ( - std::tuple_cat( - // interpolation uniform values - binders.template get()->interpolationFactor(currentZoom)..., - // uniform values - binders.template get()->uniformValue(currentProperties.template get())...) - ); + return UniformValues(std::tuple_cat( + // interpolation uniform values + binders.template get()->interpolationFactor(currentZoom)..., + // uniform values + binders.template get()->uniformValue(currentProperties.template get())...)); } template diff --git a/src/mbgl/renderer/paint_property_statistics.hpp b/src/mbgl/renderer/paint_property_statistics.hpp index 2533c4c4f34..295afeea99d 100644 --- a/src/mbgl/renderer/paint_property_statistics.hpp +++ b/src/mbgl/renderer/paint_property_statistics.hpp @@ -15,13 +15,9 @@ class PaintPropertyStatistics { template <> class PaintPropertyStatistics { public: - std::optional max() const { - return _max; - } + std::optional max() const { return _max; } - void add(float value) { - _max = _max ? std::max(*_max, value) : value; - } + void add(float value) { _max = _max ? std::max(*_max, value) : value; } private: std::optional _max; diff --git a/src/mbgl/renderer/pattern_atlas.cpp b/src/mbgl/renderer/pattern_atlas.cpp index 0c2c7a8b3e5..4a3c881c064 100644 --- a/src/mbgl/renderer/pattern_atlas.cpp +++ b/src/mbgl/renderer/pattern_atlas.cpp @@ -6,9 +6,10 @@ namespace mbgl { namespace { -// When copied into the atlas texture, image data is padded by one pixel on each side. -// Pattern images are padded with a copy of the image data wrapped from the opposite side. -// This ensures the correct behavior of GL_LINEAR texture sampling mode. +// When copied into the atlas texture, image data is padded by one pixel on each +// side. Pattern images are padded with a copy of the image data wrapped from +// the opposite side. This ensures the correct behavior of GL_LINEAR texture +// sampling mode. const uint16_t padding = 1; mapbox::ShelfPack::ShelfPackOptions shelfPackOptions() { @@ -20,8 +21,7 @@ mapbox::ShelfPack::ShelfPackOptions shelfPackOptions() { } // namespace PatternAtlas::PatternAtlas() - : shelfPack(64, 64, shelfPackOptions()) { -} + : shelfPack(64, 64, shelfPackOptions()) {} PatternAtlas::~PatternAtlas() = default; @@ -54,17 +54,17 @@ std::optional PatternAtlas::addPattern(const style::Image::Impl& const uint32_t w = src.size.width; const uint32_t h = src.size.height; - PremultipliedImage::copy(src, atlasImage, { 0, 0 }, { x, y }, { w, h }); + PremultipliedImage::copy(src, atlasImage, {0, 0}, {x, y}, {w, h}); // Add 1 pixel wrapped padding on each side of the image. - PremultipliedImage::copy(src, atlasImage, { 0, h - 1 }, { x, y - 1 }, { w, 1 }); // T - PremultipliedImage::copy(src, atlasImage, { 0, 0 }, { x, y + h }, { w, 1 }); // B - PremultipliedImage::copy(src, atlasImage, { w - 1, 0 }, { x - 1, y }, { 1, h }); // L - PremultipliedImage::copy(src, atlasImage, { 0, 0 }, { x + w, y }, { 1, h }); // R + PremultipliedImage::copy(src, atlasImage, {0, h - 1}, {x, y - 1}, {w, 1}); // T + PremultipliedImage::copy(src, atlasImage, {0, 0}, {x, y + h}, {w, 1}); // B + PremultipliedImage::copy(src, atlasImage, {w - 1, 0}, {x - 1, y}, {1, h}); // L + PremultipliedImage::copy(src, atlasImage, {0, 0}, {x + w, y}, {1, h}); // R dirty = true; - return patterns.emplace(image.id, Pattern { bin, { *bin, image } }).first->second.position; + return patterns.emplace(image.id, Pattern{bin, {*bin, image}}).first->second.position; } void PatternAtlas::removePattern(const std::string& id) { @@ -75,7 +75,7 @@ void PatternAtlas::removePattern(const std::string& id) { const uint32_t y = it->second.bin->y; const uint32_t w = it->second.bin->w; const uint32_t h = it->second.bin->h; - PremultipliedImage::clear(atlasImage, { x, y }, { w, h }); + PremultipliedImage::clear(atlasImage, {x, y}, {w, h}); shelfPack.unref(*it->second.bin); patterns.erase(it); @@ -83,10 +83,7 @@ void PatternAtlas::removePattern(const std::string& id) { } Size PatternAtlas::getPixelSize() const { - return { - static_cast(shelfPack.width()), - static_cast(shelfPack.height()) - }; + return {static_cast(shelfPack.width()), static_cast(shelfPack.height())}; } void PatternAtlas::upload(gfx::UploadPass& uploadPass) { @@ -102,7 +99,7 @@ void PatternAtlas::upload(gfx::UploadPass& uploadPass) { gfx::TextureBinding PatternAtlas::textureBinding() const { assert(atlasTexture); assert(!dirty); - return { atlasTexture->getResource(), gfx::TextureFilterType::Linear }; + return {atlasTexture->getResource(), gfx::TextureFilterType::Linear}; } } // namespace mbgl diff --git a/src/mbgl/renderer/pattern_atlas.hpp b/src/mbgl/renderer/pattern_atlas.hpp index 14c4432c366..de225eb0cef 100644 --- a/src/mbgl/renderer/pattern_atlas.hpp +++ b/src/mbgl/renderer/pattern_atlas.hpp @@ -34,9 +34,7 @@ class PatternAtlas { void upload(gfx::UploadPass&); Size getPixelSize() const; - const PremultipliedImage& getAtlasImageForTests() const { - return atlasImage; - } + const PremultipliedImage& getAtlasImageForTests() const { return atlasImage; } bool isEmpty() const { return patterns.empty(); } @@ -51,5 +49,5 @@ class PatternAtlas { std::optional atlasTexture; bool dirty = true; }; - + } // namespace mbgl diff --git a/src/mbgl/renderer/possibly_evaluated_property_value.hpp b/src/mbgl/renderer/possibly_evaluated_property_value.hpp index cf706ba3bf8..49a8aa5297b 100644 --- a/src/mbgl/renderer/possibly_evaluated_property_value.hpp +++ b/src/mbgl/renderer/possibly_evaluated_property_value.hpp @@ -12,9 +12,7 @@ namespace mbgl { template class PossiblyEvaluatedPropertyValue { private: - using Value = variant< - T, - style::PropertyExpression>; + using Value = variant>; Value value; @@ -23,19 +21,14 @@ class PossiblyEvaluatedPropertyValue { PossiblyEvaluatedPropertyValue(Value v) : value(std::move(v)) {} - bool isConstant() const { - return value.template is(); - } + bool isConstant() const { return value.template is(); } std::optional constant() const { - return value.match( - [&] (const T& t) { return std::optional(t); }, - [&] (const auto&) { return std::optional(); }); + return value.match([&](const T& t) { return std::optional(t); }, + [&](const auto&) { return std::optional(); }); } - T constantOr(const T& t) const { - return constant().value_or(t); - } + T constantOr(const T& t) const { return constant().value_or(t); } template auto match(Ts&&... ts) const { @@ -44,12 +37,10 @@ class PossiblyEvaluatedPropertyValue { template T evaluate(const Feature& feature, float zoom, T defaultValue) const { - return this->match( - [&] (const T& constant_) { return constant_; }, - [&] (const style::PropertyExpression& expression) { - return expression.evaluate(zoom, feature, defaultValue); - } - ); + return this->match([&](const T& constant_) { return constant_; }, + [&](const style::PropertyExpression& expression) { + return expression.evaluate(zoom, feature, defaultValue); + }); } template @@ -72,9 +63,7 @@ class PossiblyEvaluatedPropertyValue { template class PossiblyEvaluatedPropertyValue> { private: - using Value = variant< - Faded, - style::PropertyExpression>; + using Value = variant, style::PropertyExpression>; Value value; @@ -83,19 +72,14 @@ class PossiblyEvaluatedPropertyValue> { PossiblyEvaluatedPropertyValue(Value v) : value(std::move(v)) {} - bool isConstant() const { - return value.template is>(); - } + bool isConstant() const { return value.template is>(); } std::optional> constant() const { - return value.match( - [&] (const Faded& t) { return std::optional>(t); }, - [&] (const auto&) { return std::optional>(); }); + return value.match([&](const Faded& t) { return std::optional>(t); }, + [&](const auto&) { return std::optional>(); }); } - Faded constantOr(const Faded& t) const { - return constant().value_or(t); - } + Faded constantOr(const Faded& t) const { return constant().value_or(t); } template auto match(Ts&&... ts) const { @@ -108,25 +92,22 @@ class PossiblyEvaluatedPropertyValue> { const std::set& availableImages, const CanonicalTileID& canonical, T defaultValue) const { - return this->match( - [&] (const Faded& constant_) { return constant_; }, - [&] (const style::PropertyExpression& expression) { - if (!expression.isZoomConstant()) { - const T min = - expression.evaluate(std::floor(zoom), feature, availableImages, canonical, defaultValue); - const T max = - expression.evaluate(std::floor(zoom) + 1, feature, availableImages, canonical, defaultValue); - return Faded {min, max}; - } else { - const T evaluated = expression.evaluate(feature, availableImages, defaultValue); - return Faded {evaluated, evaluated}; - } - } - ); + return this->match([&](const Faded& constant_) { return constant_; }, + [&](const style::PropertyExpression& expression) { + if (!expression.isZoomConstant()) { + const T min = expression.evaluate( + std::floor(zoom), feature, availableImages, canonical, defaultValue); + const T max = expression.evaluate( + std::floor(zoom) + 1, feature, availableImages, canonical, defaultValue); + return Faded{min, max}; + } else { + const T evaluated = expression.evaluate(feature, availableImages, defaultValue); + return Faded{evaluated, evaluated}; + } + }); } }; - namespace util { template @@ -135,9 +116,9 @@ struct Interpolator> { const PossiblyEvaluatedPropertyValue& b, const double t) const { if (a.isConstant() && b.isConstant()) { - return { interpolate(*a.constant(), *b.constant(), t) }; + return {interpolate(*a.constant(), *b.constant(), t)}; } else { - return { a }; + return {a}; } } @@ -145,9 +126,9 @@ struct Interpolator> { const PossiblyEvaluatedPropertyValue& b, const float t) const { if (a.isConstant() && b.isConstant()) { - return { interpolate(*a.constant(), *b.constant(), t) }; + return {interpolate(*a.constant(), *b.constant(), t)}; } else { - return { a }; + return {a}; } } }; diff --git a/src/mbgl/renderer/property_evaluation_parameters.hpp b/src/mbgl/renderer/property_evaluation_parameters.hpp index d6cbf9d159f..d4e35c5b24c 100644 --- a/src/mbgl/renderer/property_evaluation_parameters.hpp +++ b/src/mbgl/renderer/property_evaluation_parameters.hpp @@ -21,18 +21,20 @@ class PropertyEvaluationParameters { defaultFadeDuration(0) {} PropertyEvaluationParameters(ZoomHistory zoomHistory_, TimePoint now_, Duration defaultFadeDuration_) - : z(zoomHistory_.lastZoom), now(now_), zoomHistory(zoomHistory_), defaultFadeDuration(defaultFadeDuration_) {} + : z(zoomHistory_.lastZoom), + now(now_), + zoomHistory(zoomHistory_), + defaultFadeDuration(defaultFadeDuration_) {} CrossfadeParameters getCrossfadeParameters() const { const float fraction = z - std::floor(z); const std::chrono::duration d = defaultFadeDuration; const float t = d != std::chrono::duration::zero() - ? std::min((now - zoomHistory.lastIntegerZoomTime) / d, 1.0f) - : 1.0f; + ? std::min((now - zoomHistory.lastIntegerZoomTime) / d, 1.0f) + : 1.0f; - return z > zoomHistory.lastIntegerZoom - ? CrossfadeParameters { 2.0f, 1.0f, fraction + (1.0f - fraction) * t } - : CrossfadeParameters { 0.5f, 1.0f, 1 - (1 - t) * fraction }; + return z > zoomHistory.lastIntegerZoom ? CrossfadeParameters{2.0f, 1.0f, fraction + (1.0f - fraction) * t} + : CrossfadeParameters{0.5f, 1.0f, 1 - (1 - t) * fraction}; } float z; diff --git a/src/mbgl/renderer/render_layer.cpp b/src/mbgl/renderer/render_layer.cpp index 27289f4d650..a0d2c39f648 100644 --- a/src/mbgl/renderer/render_layer.cpp +++ b/src/mbgl/renderer/render_layer.cpp @@ -14,8 +14,7 @@ using namespace style; RenderLayer::RenderLayer(Immutable properties) : evaluatedProperties(std::move(properties)), - baseImpl(evaluatedProperties->baseImpl) { -} + baseImpl(evaluatedProperties->baseImpl) {} void RenderLayer::transition(const TransitionParameters& parameters, Immutable newImpl) { baseImpl = std::move(newImpl); @@ -23,8 +22,8 @@ void RenderLayer::transition(const TransitionParameters& parameters, ImmutablegetTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required - && !placementData.empty(); + return baseImpl->getTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required && + !placementData.empty(); } const std::string& RenderLayer::getID() const { @@ -36,8 +35,7 @@ bool RenderLayer::hasRenderPass(RenderPass pass) const { } bool RenderLayer::needsRendering() const { - return passes != RenderPass::None - && baseImpl->visibility != style::VisibilityType::None; + return passes != RenderPass::None && baseImpl->visibility != style::VisibilityType::None; } bool RenderLayer::supportsZoom(float zoom) const { @@ -60,8 +58,7 @@ void RenderLayer::markContextDestroyed() { // no-op } -void RenderLayer::checkRenderability(const PaintParameters& parameters, - const uint32_t activeBindingCount) { +void RenderLayer::checkRenderability(const PaintParameters& parameters, const uint32_t activeBindingCount) { // Only warn once for every layer. if (hasRenderFailures) { return; @@ -69,18 +66,26 @@ void RenderLayer::checkRenderability(const PaintParameters& parameters, if (activeBindingCount > parameters.context.maximumVertexBindingCount) { Log::Error(Event::OpenGL, - "The layer '" + getID() + "' uses more data-driven properties than the current device " - "supports, and will have rendering errors. To ensure compatibility with this " - "device, use " + std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + - " fewer data driven properties in this layer."); + "The layer '" + getID() + + "' uses more data-driven properties than the current device " + "supports, and will have rendering errors. To ensure " + "compatibility with this " + "device, use " + + std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + + " fewer data driven properties in this layer."); hasRenderFailures = true; } else if (activeBindingCount > gfx::Context::minimumRequiredVertexBindingCount) { Log::Warning(Event::OpenGL, - "The layer '" + getID() + "' uses more data-driven properties than some devices may support. " - "Though it will render correctly on this device, it may have rendering errors " - "on other devices. To ensure compatibility with all devices, use " + - std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + "fewer " - "data-driven properties in this layer."); + "The layer '" + getID() + + "' uses more data-driven properties than some devices may " + "support. " + "Though it will render correctly on this device, it may have " + "rendering errors " + "on other devices. To ensure compatibility with all devices, " + "use " + + std::to_string(activeBindingCount - gfx::Context::minimumRequiredVertexBindingCount) + + "fewer " + "data-driven properties in this layer."); hasRenderFailures = true; } } @@ -101,5 +106,4 @@ const LayerRenderData* RenderLayer::getRenderDataForPass(const RenderTile& tile, return nullptr; } -} //namespace mbgl - +} // namespace mbgl diff --git a/src/mbgl/renderer/render_layer.hpp b/src/mbgl/renderer/render_layer.hpp index b4ea90e2754..b6bacb680cb 100644 --- a/src/mbgl/renderer/render_layer.hpp +++ b/src/mbgl/renderer/render_layer.hpp @@ -70,8 +70,8 @@ class RenderLayer { // Overloaded version for transitions to a new layer impl. void transition(const TransitionParameters&, Immutable newImpl); - // Fully evaluate possibly-transitioning paint properties based on a zoom level. - // Updates the contained `evaluatedProperties` member. + // Fully evaluate possibly-transitioning paint properties based on a zoom + // level. Updates the contained `evaluatedProperties` member. virtual void evaluate(const PropertyEvaluationParameters&) = 0; // Returns true if any paint properties have active transitions. @@ -102,8 +102,13 @@ class RenderLayer { // Check wether the given geometry intersects // with the feature - virtual bool queryIntersectsFeature(const GeometryCoordinates&, const GeometryTileFeature&, const float, - const TransformState&, const float, const mat4&, const FeatureState&) const { + virtual bool queryIntersectsFeature(const GeometryCoordinates&, + const GeometryTileFeature&, + const float, + const TransformState&, + const float, + const mat4&, + const FeatureState&) const { return false; }; @@ -124,8 +129,8 @@ class RenderLayer { virtual std::optional getSolidBackground() const; protected: - // Checks whether the current hardware can render this layer. If it can't, we'll show a warning - // in the console to inform the developer. + // Checks whether the current hardware can render this layer. If it can't, + // we'll show a warning in the console to inform the developer. void checkRenderability(const PaintParameters&, uint32_t activeBindingCount); void addRenderPassesFromTiles(); @@ -143,9 +148,9 @@ class RenderLayer { LayerPlacementData placementData; private: - // Some layers may not render correctly on some hardware when the vertex attribute limit of - // that GPU is exceeded. More attributes are used when adding many data driven paint properties - // to a layer. + // Some layers may not render correctly on some hardware when the vertex + // attribute limit of that GPU is exceeded. More attributes are used when + // adding many data driven paint properties to a layer. bool hasRenderFailures = false; }; diff --git a/src/mbgl/renderer/render_light.cpp b/src/mbgl/renderer/render_light.cpp index 85768cff474..a3946b329c4 100644 --- a/src/mbgl/renderer/render_light.cpp +++ b/src/mbgl/renderer/render_light.cpp @@ -4,8 +4,7 @@ namespace mbgl { RenderLight::RenderLight(Immutable impl_) : impl(std::move(impl_)), - transitioning(impl->properties.untransitioned()) { -} + transitioning(impl->properties.untransitioned()) {} void RenderLight::transition(const TransitionParameters& parameters) { transitioning = impl->properties.transitioned(parameters, std::move(transitioning)); diff --git a/src/mbgl/renderer/render_light.hpp b/src/mbgl/renderer/render_light.hpp index f13f925318d..42b49b05d46 100644 --- a/src/mbgl/renderer/render_light.hpp +++ b/src/mbgl/renderer/render_light.hpp @@ -9,7 +9,7 @@ class TransitionParameters; class PropertyEvaluationParameters; using TransitioningLight = style::LightProperties::Unevaluated; -using EvaluatedLight = style::LightProperties::PossiblyEvaluated; +using EvaluatedLight = style::LightProperties::PossiblyEvaluated; class RenderLight { public: diff --git a/src/mbgl/renderer/render_orchestrator.cpp b/src/mbgl/renderer/render_orchestrator.cpp index 4a2b018bd2a..0553ae50772 100644 --- a/src/mbgl/renderer/render_orchestrator.cpp +++ b/src/mbgl/renderer/render_orchestrator.cpp @@ -41,7 +41,9 @@ namespace { class LayerRenderItem final : public RenderItem { public: LayerRenderItem(RenderLayer& layer_, RenderSource* source_, uint32_t index_) - : layer(layer_), source(source_), index(index_) {} + : layer(layer_), + source(source_), + index(index_) {} bool operator<(const LayerRenderItem& other) const { return index < other.index; } std::reference_wrapper layer; @@ -80,9 +82,7 @@ class RenderTreeImpl final : public RenderTree { } } - RenderItems getLayerRenderItems() const override { - return { layerRenderItems.begin(), layerRenderItems.end() }; - } + RenderItems getLayerRenderItems() const override { return {layerRenderItems.begin(), layerRenderItems.end()}; } RenderItems getSourceRenderItems() const override { RenderItems result; result.reserve(sourceRenderItems.size()); @@ -101,7 +101,7 @@ class RenderTreeImpl final : public RenderTree { bool updateSymbolOpacities; }; -} // namespace +} // namespace RenderOrchestrator::RenderOrchestrator(bool backgroundLayerAsColor_, const std::optional& localFontFamily_) : observer(&nullObserver()), @@ -150,11 +150,11 @@ std::unique_ptr RenderOrchestrator::createRenderTree( } } - const bool zoomChanged = - zoomHistory.update(static_cast(updateParameters->transformState.getZoom()), updateParameters->timePoint); + const bool zoomChanged = zoomHistory.update(static_cast(updateParameters->transformState.getZoom()), + updateParameters->timePoint); - const TransitionOptions transitionOptions = - isMapModeContinuous ? updateParameters->transitionOptions : TransitionOptions(); + const TransitionOptions transitionOptions = isMapModeContinuous ? updateParameters->transitionOptions + : TransitionOptions(); const TransitionParameters transitionParameters{updateParameters->timePoint, transitionOptions}; @@ -191,7 +191,8 @@ std::unique_ptr RenderOrchestrator::createRenderTree( const ImageDifference imageDiff = diffImages(imageImpls, updateParameters->images); imageImpls = updateParameters->images; - // Only trigger tile reparse for changed images. Changed images only need a relayout when they have a different size. + // Only trigger tile reparse for changed images. Changed images only need a + // relayout when they have a different size. bool hasImageDiff = !imageDiff.removed.empty(); // Remove removed images from sprite atlas. @@ -321,8 +322,8 @@ std::unique_ptr RenderOrchestrator::createRenderTree( filteredLayersForSource.push_back(layer.evaluatedProperties); if (zoomFitsLayer) { sourceNeedsRendering = true; - renderItemsEmplaceHint = - layerRenderItems.emplace_hint(renderItemsEmplaceHint, layer, source, static_cast(index)); + renderItemsEmplaceHint = layerRenderItems.emplace_hint( + renderItemsEmplaceHint, layer, source, static_cast(index)); } } } @@ -335,18 +336,15 @@ std::unique_ptr RenderOrchestrator::createRenderTree( const auto& solidBackground = layer.getSolidBackground(); if (solidBackground) { renderTreeParameters->backgroundColor = *solidBackground; - continue; // This layer is shown with background color, and it shall not be added to render - // items. + continue; // This layer is shown with background color, + // and it shall not be added to render items. } } - renderItemsEmplaceHint = layerRenderItems.emplace_hint(renderItemsEmplaceHint, layer, nullptr, static_cast(index)); + renderItemsEmplaceHint = layerRenderItems.emplace_hint( + renderItemsEmplaceHint, layer, nullptr, static_cast(index)); } } - source->update(sourceImpl, - filteredLayersForSource, - sourceNeedsRendering, - sourceNeedsRelayout, - tileParameters); + source->update(sourceImpl, filteredLayersForSource, sourceNeedsRendering, sourceNeedsRelayout, tileParameters); filteredLayersForSource.clear(); } @@ -397,17 +395,22 @@ std::unique_ptr RenderOrchestrator::createRenderTree( if (isMapModeContinuous) { std::optional placementUpdatePeriodOverride; if (symbolBucketsAdded && !tiltedView) { - // If the view is not tilted, we want *the new* symbols to show up faster, however simple setting - // `placementChanged` to `true` would initiate placement too often as new buckets usually come from several - // rendered tiles in a row within a short period of time. Instead, we squeeze placement update period to - // coalesce buckets updates from several tiles. On contrary, with the tilted view it's more important to - // make placement rarely for performance reasons and as the new symbols are normally "far away" and the user - // is not that interested to see them ASAP. + // If the view is not tilted, we want *the new* symbols to show up + // faster, however simple setting `placementChanged` to `true` would + // initiate placement too often as new buckets usually come from + // several rendered tiles in a row within a short period of time. + // Instead, we squeeze placement update period to coalesce buckets + // updates from several tiles. On contrary, with the tilted view + // it's more important to make placement rarely for performance + // reasons and as the new symbols are normally "far away" and the + // user is not that interested to see them ASAP. placementUpdatePeriodOverride = std::optional(Milliseconds(30)); } renderTreeParameters->placementChanged = !placementController.placementIsRecent( - updateParameters->timePoint, static_cast(updateParameters->transformState.getZoom()), placementUpdatePeriodOverride); + updateParameters->timePoint, + static_cast(updateParameters->transformState.getZoom()), + placementUpdatePeriodOverride); symbolBucketsChanged |= renderTreeParameters->placementChanged; if (renderTreeParameters->placementChanged) { Mutable placement = Placement::create(updateParameters, placementController.getPlacement()); @@ -420,8 +423,8 @@ std::unique_ptr RenderOrchestrator::createRenderTree( } else { placementController.setPlacementStale(); } - renderTreeParameters->symbolFadeChange = - placementController.getPlacement()->symbolFadeChange(updateParameters->timePoint); + renderTreeParameters->symbolFadeChange = placementController.getPlacement()->symbolFadeChange( + updateParameters->timePoint); renderTreeParameters->needsRepaint = hasTransitions(updateParameters->timePoint); } else { renderTreeParameters->placementChanged = symbolBucketsChanged = !layersNeedPlacement.empty(); @@ -459,7 +462,8 @@ std::unique_ptr RenderOrchestrator::createRenderTree( symbolBucketsChanged); } -std::vector RenderOrchestrator::queryRenderedFeatures(const ScreenLineString& geometry, const RenderedQueryOptions& options) const { +std::vector RenderOrchestrator::queryRenderedFeatures(const ScreenLineString& geometry, + const RenderedQueryOptions& options) const { std::unordered_map layers; if (options.layerIDs) { for (const auto& layerID : *options.layerIDs) { @@ -477,10 +481,10 @@ std::vector RenderOrchestrator::queryRenderedFeatures(const ScreenLineS } void RenderOrchestrator::queryRenderedSymbols(std::unordered_map>& resultsByLayer, - const ScreenLineString& geometry, - const std::unordered_map& layers, - const RenderedQueryOptions& options) const { - const auto hasCrossTileIndex = [] (const auto& pair) { + const ScreenLineString& geometry, + const std::unordered_map& layers, + const RenderedQueryOptions& options) const { + const auto hasCrossTileIndex = [](const auto& pair) { return pair.second->baseImpl->getTypeInfo()->crossTileIndex == style::LayerTypeInfo::CrossTileIndex::Required; }; @@ -500,13 +504,14 @@ void RenderOrchestrator::queryRenderedSymbols(std::unordered_map RenderOrchestrator::queryRenderedFeatures(const ScreenLineString& geometry, const RenderedQueryOptions& options, const std::unordered_map& layers) const { +std::vector RenderOrchestrator::queryRenderedFeatures( + const ScreenLineString& geometry, + const RenderedQueryOptions& options, + const std::unordered_map& layers) const { std::unordered_set sourceIDs; std::unordered_map filteredLayers; for (const auto& pair : layers) { @@ -540,8 +548,10 @@ std::vector RenderOrchestrator::queryRenderedFeatures(const ScreenLineS std::unordered_map> resultsByLayer; for (const auto& sourceID : sourceIDs) { if (RenderSource* renderSource = getRenderSource(sourceID)) { - auto sourceResults = renderSource->queryRenderedFeatures(geometry, transformState, filteredLayers, options, projMatrix); - std::move(sourceResults.begin(), sourceResults.end(), std::inserter(resultsByLayer, resultsByLayer.begin())); + auto sourceResults = renderSource->queryRenderedFeatures( + geometry, transformState, filteredLayers, options, projMatrix); + std::move( + sourceResults.begin(), sourceResults.end(), std::inserter(resultsByLayer, resultsByLayer.begin())); } } @@ -575,8 +585,11 @@ std::vector RenderOrchestrator::queryShapeAnnotations(const ScreenLineS std::unordered_map shapeAnnotationLayers; RenderedQueryOptions options; for (const auto& layerImpl : *layerImpls) { - if (std::mismatch(layerImpl->id.begin(), layerImpl->id.end(), - AnnotationManager::ShapeLayerID.begin(), AnnotationManager::ShapeLayerID.end()).second == AnnotationManager::ShapeLayerID.end()) { + if (std::mismatch(layerImpl->id.begin(), + layerImpl->id.end(), + AnnotationManager::ShapeLayerID.begin(), + AnnotationManager::ShapeLayerID.end()) + .second == AnnotationManager::ShapeLayerID.end()) { if (const RenderLayer* layer = getRenderLayer(layerImpl->id)) { shapeAnnotationLayers.emplace(layer->getID(), layer); } @@ -586,32 +599,37 @@ std::vector RenderOrchestrator::queryShapeAnnotations(const ScreenLineS return queryRenderedFeatures(geometry, options, shapeAnnotationLayers); } -std::vector RenderOrchestrator::querySourceFeatures(const std::string& sourceID, const SourceQueryOptions& options) const { +std::vector RenderOrchestrator::querySourceFeatures(const std::string& sourceID, + const SourceQueryOptions& options) const { const RenderSource* source = getRenderSource(sourceID); if (!source) return {}; return source->querySourceFeatures(options); } -FeatureExtensionValue RenderOrchestrator::queryFeatureExtensions(const std::string& sourceID, - const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const { +FeatureExtensionValue RenderOrchestrator::queryFeatureExtensions( + const std::string& sourceID, + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args) const { if (RenderSource* renderSource = getRenderSource(sourceID)) { return renderSource->queryFeatureExtensions(feature, extension, extensionField, args); } return {}; } -void RenderOrchestrator::setFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::string& featureID, const FeatureState& state) { +void RenderOrchestrator::setFeatureState(const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID, + const FeatureState& state) { if (RenderSource* renderSource = getRenderSource(sourceID)) { renderSource->setFeatureState(sourceLayerID, featureID, state); } } -void RenderOrchestrator::getFeatureState(FeatureState& state, const std::string& sourceID, +void RenderOrchestrator::getFeatureState(FeatureState& state, + const std::string& sourceID, const std::optional& sourceLayerID, const std::string& featureID) const { if (RenderSource* renderSource = getRenderSource(sourceID)) { @@ -619,7 +637,8 @@ void RenderOrchestrator::getFeatureState(FeatureState& state, const std::string& } } -void RenderOrchestrator::removeFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, +void RenderOrchestrator::removeFeatureState(const std::string& sourceID, + const std::optional& sourceLayerID, const std::optional& featureID, const std::optional& stateKey) { if (RenderSource* renderSource = getRenderSource(sourceID)) { @@ -692,7 +711,7 @@ bool RenderOrchestrator::hasTransitions(TimePoint timePoint) const { } bool RenderOrchestrator::isLoaded() const { - for (const auto& entry: renderSources) { + for (const auto& entry : renderSources) { if (!entry.second->isLoaded()) { return false; } @@ -718,14 +737,20 @@ void RenderOrchestrator::clearData() { glyphManager->evict(fontStacks(*layerImpls)); } -void RenderOrchestrator::onGlyphsError(const FontStack& fontStack, const GlyphRange& glyphRange, std::exception_ptr error) { - Log::Error(Event::Style, "Failed to load glyph range " + std::to_string(glyphRange.first) + "-" + std::to_string(glyphRange.second) + - " for font stack " + fontStackToString(fontStack) + ": " + util::toString(error)); +void RenderOrchestrator::onGlyphsError(const FontStack& fontStack, + const GlyphRange& glyphRange, + std::exception_ptr error) { + Log::Error(Event::Style, + "Failed to load glyph range " + std::to_string(glyphRange.first) + "-" + + std::to_string(glyphRange.second) + " for font stack " + fontStackToString(fontStack) + ": " + + util::toString(error)); observer->onResourceError(error); } void RenderOrchestrator::onTileError(RenderSource& source, const OverscaledTileID& tileID, std::exception_ptr error) { - Log::Error(Event::Style, "Failed to load tile " + util::toString(tileID) + " for source " + source.baseImpl->id + ": " + util::toString(error)); + Log::Error(Event::Style, + "Failed to load tile " + util::toString(tileID) + " for source " + source.baseImpl->id + ": " + + util::toString(error)); observer->onResourceError(error); } diff --git a/src/mbgl/renderer/render_orchestrator.hpp b/src/mbgl/renderer/render_orchestrator.hpp index 95887e6ffb9..7cea91074a4 100644 --- a/src/mbgl/renderer/render_orchestrator.hpp +++ b/src/mbgl/renderer/render_orchestrator.hpp @@ -33,19 +33,15 @@ class CrossTileSymbolIndex; class RenderTree; namespace style { - class LayerProperties; +class LayerProperties; } // namespace style -class RenderOrchestrator final : public GlyphManagerObserver, - public ImageManagerObserver, - public RenderSourceObserver { +class RenderOrchestrator final : public GlyphManagerObserver, public ImageManagerObserver, public RenderSourceObserver { public: RenderOrchestrator(bool backgroundLayerAsColor_, const std::optional& localFontFamily_); ~RenderOrchestrator() override; - void markContextLost() { - contextLost = true; - }; + void markContextLost() { contextLost = true; }; // TODO: Introduce RenderOrchestratorObserver. void setObserver(RendererObserver*); @@ -61,14 +57,20 @@ class RenderOrchestrator final : public GlyphManagerObserver, const std::string& extensionField, const std::optional>& args) const; - void setFeatureState(const std::string& sourceID, const std::optional& layerID, - const std::string& featureID, const FeatureState& state); + void setFeatureState(const std::string& sourceID, + const std::optional& layerID, + const std::string& featureID, + const FeatureState& state); - void getFeatureState(FeatureState& state, const std::string& sourceID, const std::optional& layerID, + void getFeatureState(FeatureState& state, + const std::string& sourceID, + const std::optional& layerID, const std::string& featureID) const; - void removeFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::optional& featureID, const std::optional& stateKey); + void removeFeatureState(const std::string& sourceID, + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey); void reduceMemoryUse(); void dumpDebugLogs(); @@ -82,15 +84,17 @@ class RenderOrchestrator final : public GlyphManagerObserver, RenderSource* getRenderSource(const std::string& id) const; - RenderLayer* getRenderLayer(const std::string& id); + RenderLayer* getRenderLayer(const std::string& id); const RenderLayer* getRenderLayer(const std::string& id) const; - + void queryRenderedSymbols(std::unordered_map>& resultsByLayer, const ScreenLineString& geometry, const std::unordered_map& layers, const RenderedQueryOptions& options) const; - - std::vector queryRenderedFeatures(const ScreenLineString&, const RenderedQueryOptions&, const std::unordered_map&) const; + + std::vector queryRenderedFeatures(const ScreenLineString&, + const RenderedQueryOptions&, + const std::unordered_map&) const; // GlyphManagerObserver implementation. void onGlyphsError(const FontStack&, const GlyphRange&, std::exception_ptr) override; @@ -128,8 +132,8 @@ class RenderOrchestrator final : public GlyphManagerObserver, bool contextLost = false; bool placedSymbolDataCollected = false; - // Vectors with reserved capacity of layerImpls->size() to avoid reallocation - // on each frame. + // Vectors with reserved capacity of layerImpls->size() to avoid + // reallocation on each frame. std::vector> filteredLayersForSource; RenderLayerReferences orderedLayers; RenderLayerReferences layersNeedPlacement; diff --git a/src/mbgl/renderer/render_source.cpp b/src/mbgl/renderer/render_source.cpp index f39d3089d7c..624d89073e0 100644 --- a/src/mbgl/renderer/render_source.cpp +++ b/src/mbgl/renderer/render_source.cpp @@ -20,28 +20,28 @@ using namespace style; std::unique_ptr RenderSource::create(const Immutable& impl) { switch (impl->type) { - case SourceType::Vector: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::Raster: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::RasterDEM: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::GeoJSON: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::Video: - assert(false); - return nullptr; - case SourceType::Annotations: - if (LayerManager::annotationsEnabled) { - return std::make_unique(staticImmutableCast(impl)); - } else { + case SourceType::Vector: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::Raster: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::RasterDEM: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::GeoJSON: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::Video: assert(false); return nullptr; - } - case SourceType::Image: - return std::make_unique(staticImmutableCast(impl)); - case SourceType::CustomVector: - return std::make_unique(staticImmutableCast(impl)); + case SourceType::Annotations: + if (LayerManager::annotationsEnabled) { + return std::make_unique(staticImmutableCast(impl)); + } else { + assert(false); + return nullptr; + } + case SourceType::Image: + return std::make_unique(staticImmutableCast(impl)); + case SourceType::CustomVector: + return std::make_unique(staticImmutableCast(impl)); } // Not reachable, but placate GCC. @@ -53,8 +53,7 @@ static RenderSourceObserver nullObserver; RenderSource::RenderSource(Immutable impl) : baseImpl(std::move(impl)), - observer(&nullObserver) { -} + observer(&nullObserver) {} RenderSource::~RenderSource() = default; @@ -74,7 +73,7 @@ bool RenderSource::isEnabled() const { return enabled; } -uint8_t RenderSource::getMaxZoom() const { +uint8_t RenderSource::getMaxZoom() const { assert(false); return util::TERRAIN_RGB_MAXZOOM; } diff --git a/src/mbgl/renderer/render_source.hpp b/src/mbgl/renderer/render_source.hpp index 4ed1253f966..9df117c7751 100644 --- a/src/mbgl/renderer/render_source.hpp +++ b/src/mbgl/renderer/render_source.hpp @@ -64,32 +64,30 @@ class RenderSource : protected TileObserver { virtual void prepare(const SourcePrepareParameters&) = 0; virtual void updateFadingTiles() = 0; virtual bool hasFadingTiles() const = 0; - // If supported, returns a shared list of RenderTiles, sorted by tile id and excluding tiles hold for fade; - // returns nullptr otherwise. + // If supported, returns a shared list of RenderTiles, sorted by tile id and + // excluding tiles hold for fade; returns nullptr otherwise. virtual RenderTiles getRenderTiles() const { return nullptr; } - // If supported, returns a shared list of RenderTiles, sorted in opposite y position, so tiles with overlapping - // symbols are drawn on top of each other, with lower symbols being drawn on top of higher symbols; - // returns nullptr otherwise. + // If supported, returns a shared list of RenderTiles, sorted in opposite y + // position, so tiles with overlapping symbols are drawn on top of each other, + // with lower symbols being drawn on top of higher symbols; returns nullptr otherwise. virtual RenderTiles getRenderTilesSortedByYPosition() const { return nullptr; } // If supported, returns pointer to image data; returns nullptr otherwise. virtual const ImageSourceRenderData* getImageRenderData() const { return nullptr; } virtual const Tile* getRenderedTile(const UnwrappedTileID&) const { return nullptr; } - virtual std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const = 0; - - virtual std::vector - querySourceFeatures(const SourceQueryOptions&) const = 0; - - virtual FeatureExtensionValue - queryFeatureExtensions(const Feature&, - const std::string&, - const std::string&, - const std::optional>&) const { + virtual std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const = 0; + + virtual std::vector querySourceFeatures(const SourceQueryOptions&) const = 0; + + virtual FeatureExtensionValue queryFeatureExtensions(const Feature&, + const std::string&, + const std::string&, + const std::optional>&) const { return {}; } @@ -97,7 +95,8 @@ class RenderSource : protected TileObserver { virtual void getFeatureState(FeatureState&, const std::optional&, const std::string&) const {} - virtual void removeFeatureState(const std::optional&, const std::optional&, + virtual void removeFeatureState(const std::optional&, + const std::optional&, const std::optional&) {} virtual void reduceMemoryUse() = 0; diff --git a/src/mbgl/renderer/render_static_data.cpp b/src/mbgl/renderer/render_static_data.cpp index 2522cbaed91..9f48cfcefef 100644 --- a/src/mbgl/renderer/render_static_data.cpp +++ b/src/mbgl/renderer/render_static_data.cpp @@ -7,10 +7,10 @@ namespace mbgl { static gfx::VertexVector> tileVertices() { gfx::VertexVector> result; - result.emplace_back(gfx::Vertex({{{ 0, 0 }}})); - result.emplace_back(gfx::Vertex({{{ util::EXTENT, 0 }}})); - result.emplace_back(gfx::Vertex({{{ 0, util::EXTENT }}})); - result.emplace_back(gfx::Vertex({{{ util::EXTENT, util::EXTENT }}})); + result.emplace_back(gfx::Vertex({{{0, 0}}})); + result.emplace_back(gfx::Vertex({{{util::EXTENT, 0}}})); + result.emplace_back(gfx::Vertex({{{0, util::EXTENT}}})); + result.emplace_back(gfx::Vertex({{{util::EXTENT, util::EXTENT}}})); return result; } @@ -33,24 +33,23 @@ static gfx::IndexVector tileLineStripIndices() { static gfx::VertexVector rasterVertices() { gfx::VertexVector result; - result.emplace_back(RasterProgram::layoutVertex({ 0, 0 }, { 0, 0 })); - result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, 0 }, { util::EXTENT, 0 })); - result.emplace_back(RasterProgram::layoutVertex({ 0, util::EXTENT }, { 0, util::EXTENT })); - result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, util::EXTENT }, { util::EXTENT, util::EXTENT })); + result.emplace_back(RasterProgram::layoutVertex({0, 0}, {0, 0})); + result.emplace_back(RasterProgram::layoutVertex({util::EXTENT, 0}, {util::EXTENT, 0})); + result.emplace_back(RasterProgram::layoutVertex({0, util::EXTENT}, {0, util::EXTENT})); + result.emplace_back(RasterProgram::layoutVertex({util::EXTENT, util::EXTENT}, {util::EXTENT, util::EXTENT})); return result; } static gfx::VertexVector heatmapTextureVertices() { gfx::VertexVector result; - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 0, 0 })); - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 1, 0 })); - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 0, 1 })); - result.emplace_back(HeatmapTextureProgram::layoutVertex({ 1, 1 })); + result.emplace_back(HeatmapTextureProgram::layoutVertex({0, 0})); + result.emplace_back(HeatmapTextureProgram::layoutVertex({1, 0})); + result.emplace_back(HeatmapTextureProgram::layoutVertex({0, 1})); + result.emplace_back(HeatmapTextureProgram::layoutVertex({1, 1})); return result; } -RenderStaticData::RenderStaticData(float pixelRatio, - std::unique_ptr&& shaders_) +RenderStaticData::RenderStaticData(float pixelRatio, std::unique_ptr&& shaders_) : programs(ProgramParameters{pixelRatio, false}), shaders(std::move(shaders_)), clippingMaskSegments(tileTriangleSegments()) diff --git a/src/mbgl/renderer/render_tile.cpp b/src/mbgl/renderer/render_tile.cpp index 92a18022b53..36994f593e4 100644 --- a/src/mbgl/renderer/render_tile.cpp +++ b/src/mbgl/renderer/render_tile.cpp @@ -16,7 +16,9 @@ namespace mbgl { using namespace style; -RenderTile::RenderTile(UnwrappedTileID id_, Tile& tile_) : id(id_), tile(tile_) {} +RenderTile::RenderTile(UnwrappedTileID id_, Tile& tile_) + : id(id_), + tile(tile_) {} RenderTile::~RenderTile() = default; @@ -31,16 +33,18 @@ mat4 RenderTile::translateVtxMatrix(const mat4& tileMatrix, mat4 vtxMatrix; - const float angle = inViewportPixelUnits ? - (anchor == TranslateAnchorType::Map ? static_cast(state.getBearing()) : 0.0f) : - (anchor == TranslateAnchorType::Viewport ? static_cast(-state.getBearing()) : 0.0f); + const float angle = inViewportPixelUnits + ? (anchor == TranslateAnchorType::Map ? static_cast(state.getBearing()) : 0.0f) + : (anchor == TranslateAnchorType::Viewport ? static_cast(-state.getBearing()) + : 0.0f); - Point translate = util::rotate(Point{ translation[0], translation[1] }, angle); + Point translate = util::rotate(Point{translation[0], translation[1]}, angle); if (inViewportPixelUnits) { matrix::translate(vtxMatrix, tileMatrix, translate.x, translate.y, 0); } else { - matrix::translate(vtxMatrix, tileMatrix, + matrix::translate(vtxMatrix, + tileMatrix, id.pixelsToTileUnits(translate.x, static_cast(state.getZoom())), id.pixelsToTileUnits(translate.y, static_cast(state.getZoom())), 0); @@ -61,8 +65,12 @@ mat4 RenderTile::translatedClipMatrix(const std::array& translation, return translateVtxMatrix(nearClippedMatrix, translation, anchor, state, false); } -const OverscaledTileID& RenderTile::getOverscaledTileID() const { return tile.id; } -bool RenderTile::holdForFade() const { return tile.holdForFade(); } +const OverscaledTileID& RenderTile::getOverscaledTileID() const { + return tile.id; +} +bool RenderTile::holdForFade() const { + return tile.holdForFade(); +} Bucket* RenderTile::getBucket(const style::Layer::Impl& impl) const { assert(renderData); @@ -106,20 +114,18 @@ void RenderTile::prepare(const SourcePrepareParameters& parameters) { needsRendering = tile.usedByRenderedLayers; if (parameters.debugOptions != MapDebugOptions::NoDebug && - (!debugBucket || debugBucket->renderable != tile.isRenderable() || - debugBucket->complete != tile.isComplete() || - !(debugBucket->modified == tile.modified) || - !(debugBucket->expires == tile.expires) || + (!debugBucket || debugBucket->renderable != tile.isRenderable() || debugBucket->complete != tile.isComplete() || + !(debugBucket->modified == tile.modified) || !(debugBucket->expires == tile.expires) || debugBucket->debugMode != parameters.debugOptions)) { debugBucket = std::make_unique( - tile.id, tile.isRenderable(), tile.isComplete(), tile.modified, tile.expires, - parameters.debugOptions); + tile.id, tile.isRenderable(), tile.isComplete(), tile.modified, tile.expires, parameters.debugOptions); } else if (parameters.debugOptions == MapDebugOptions::NoDebug) { debugBucket.reset(); } - // Calculate two matrices for this tile: matrix is the standard tile matrix; nearClippedMatrix - // has near plane moved further, to enhance depth buffer precision + // Calculate two matrices for this tile: matrix is the standard tile matrix; + // nearClippedMatrix has near plane moved further, to enhance depth buffer + // precision const auto& transform = parameters.transform; transform.state.matrixFor(matrix, id); transform.state.matrixFor(nearClippedMatrix, id); @@ -128,10 +134,9 @@ void RenderTile::prepare(const SourcePrepareParameters& parameters) { } void RenderTile::finishRender(PaintParameters& parameters) const { - if (!needsRendering || parameters.debugOptions == MapDebugOptions::NoDebug) - return; + if (!needsRendering || parameters.debugOptions == MapDebugOptions::NoDebug) return; - static const style::Properties<>::PossiblyEvaluated properties {}; + static const style::Properties<>::PossiblyEvaluated properties{}; static const DebugProgram::Binders paintAttributeData(properties, 0); auto program = parameters.shaders.get(); @@ -141,48 +146,48 @@ void RenderTile::finishRender(PaintParameters& parameters) const { if (parameters.debugOptions & (MapDebugOptions::Timestamps | MapDebugOptions::ParseStatus)) { assert(debugBucket); - const auto allAttributeBindings = - DebugProgram::computeAllAttributeBindings(*debugBucket->vertexBuffer, paintAttributeData, properties); + const auto allAttributeBindings = DebugProgram::computeAllAttributeBindings( + *debugBucket->vertexBuffer, paintAttributeData, properties); program->draw(parameters.context, - *parameters.renderPass, - gfx::Lines{4.0f * parameters.pixelRatio}, - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::unblended(), - gfx::CullFaceMode::disabled(), - *debugBucket->indexBuffer, - debugBucket->segments, - DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::white()), - uniforms::overlay_scale::Value(1.0f)}, - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())), - allAttributeBindings, - DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, - "text-outline"); + *parameters.renderPass, + gfx::Lines{4.0f * parameters.pixelRatio}, + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::unblended(), + gfx::CullFaceMode::disabled(), + *debugBucket->indexBuffer, + debugBucket->segments, + DebugProgram::computeAllUniformValues( + DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::white()), + uniforms::overlay_scale::Value(1.0f)}, + paintAttributeData, + properties, + static_cast(parameters.state.getZoom())), + allAttributeBindings, + DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, + "text-outline"); program->draw(parameters.context, - *parameters.renderPass, - gfx::Lines{2.0f * parameters.pixelRatio}, - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::unblended(), - gfx::CullFaceMode::disabled(), - *debugBucket->indexBuffer, - debugBucket->segments, - DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::black()), - uniforms::overlay_scale::Value(1.0f)}, - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())), - allAttributeBindings, - DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, - "text"); + *parameters.renderPass, + gfx::Lines{2.0f * parameters.pixelRatio}, + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::unblended(), + gfx::CullFaceMode::disabled(), + *debugBucket->indexBuffer, + debugBucket->segments, + DebugProgram::computeAllUniformValues( + DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::black()), + uniforms::overlay_scale::Value(1.0f)}, + paintAttributeData, + properties, + static_cast(parameters.state.getZoom())), + allAttributeBindings, + DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, + "text"); } if (parameters.debugOptions & MapDebugOptions::TileBorders) { @@ -190,27 +195,26 @@ void RenderTile::finishRender(PaintParameters& parameters) const { if (debugBucket->tileBorderSegments.empty()) { debugBucket->tileBorderSegments = RenderStaticData::tileBorderSegments(); } - program->draw( - parameters.context, - *parameters.renderPass, - gfx::LineStrip{4.0f * parameters.pixelRatio}, - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::unblended(), - gfx::CullFaceMode::disabled(), - *parameters.staticData.tileBorderIndexBuffer, - debugBucket->tileBorderSegments, - DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::red()), - uniforms::overlay_scale::Value(1.0f)}, - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())), - DebugProgram::computeAllAttributeBindings( - *parameters.staticData.tileVertexBuffer, paintAttributeData, properties), - DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, - "border"); + program->draw(parameters.context, + *parameters.renderPass, + gfx::LineStrip{4.0f * parameters.pixelRatio}, + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::unblended(), + gfx::CullFaceMode::disabled(), + *parameters.staticData.tileBorderIndexBuffer, + debugBucket->tileBorderSegments, + DebugProgram::computeAllUniformValues( + DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::red()), + uniforms::overlay_scale::Value(1.0f)}, + paintAttributeData, + properties, + static_cast(parameters.state.getZoom())), + DebugProgram::computeAllAttributeBindings( + *parameters.staticData.tileVertexBuffer, paintAttributeData, properties), + DebugProgram::TextureBindings{textures::image::Value{debugBucket->texture->getResource()}}, + "border"); } } diff --git a/src/mbgl/renderer/render_tree.hpp b/src/mbgl/renderer/render_tree.hpp index 4c505995db8..e47fcf90401 100644 --- a/src/mbgl/renderer/render_tree.hpp +++ b/src/mbgl/renderer/render_tree.hpp @@ -23,7 +23,7 @@ class RenderItem { virtual void upload(gfx::UploadPass&) const = 0; virtual void render(PaintParameters&) const = 0; virtual bool hasRenderPass(RenderPass) const = 0; - virtual const std::string& getName() const = 0; + virtual const std::string& getName() const = 0; }; using RenderItems = std::vector>; @@ -65,9 +65,8 @@ class RenderTree { virtual LineAtlas& getLineAtlas() const = 0; virtual PatternAtlas& getPatternAtlas() const = 0; // Parameters - const RenderTreeParameters& getParameters() const { - return *parameters; - } + const RenderTreeParameters& getParameters() const { return *parameters; } + protected: RenderTree(std::unique_ptr parameters_) : parameters(std::move(parameters_)) { @@ -76,5 +75,4 @@ class RenderTree { std::unique_ptr parameters; }; - } // namespace mbgl diff --git a/src/mbgl/renderer/renderer.cpp b/src/mbgl/renderer/renderer.cpp index 5a2110b32f7..b35f9d6c339 100644 --- a/src/mbgl/renderer/renderer.cpp +++ b/src/mbgl/renderer/renderer.cpp @@ -12,7 +12,7 @@ Renderer::Renderer(gfx::RendererBackend& backend, float pixelRatio_, const std:: : impl(std::make_unique(backend, pixelRatio_, localFontFamily_)) {} Renderer::~Renderer() { - gfx::BackendScope guard { impl->backend }; + gfx::BackendScope guard{impl->backend}; impl.reset(); } @@ -33,25 +33,19 @@ void Renderer::render(const std::shared_ptr& updateParameters) } } -std::vector Renderer::queryRenderedFeatures(const ScreenLineString& geometry, const RenderedQueryOptions& options) const { +std::vector Renderer::queryRenderedFeatures(const ScreenLineString& geometry, + const RenderedQueryOptions& options) const { return impl->orchestrator.queryRenderedFeatures(geometry, options); } -std::vector Renderer::queryRenderedFeatures(const ScreenCoordinate& point, const RenderedQueryOptions& options) const { - return impl->orchestrator.queryRenderedFeatures({ point }, options); +std::vector Renderer::queryRenderedFeatures(const ScreenCoordinate& point, + const RenderedQueryOptions& options) const { + return impl->orchestrator.queryRenderedFeatures({point}, options); } std::vector Renderer::queryRenderedFeatures(const ScreenBox& box, const RenderedQueryOptions& options) const { return impl->orchestrator.queryRenderedFeatures( - { - box.min, - {box.max.x, box.min.y}, - box.max, - {box.min.x, box.max.y}, - box.min - }, - options - ); + {box.min, {box.max.x, box.min.y}, box.max, {box.min.x, box.max.y}, box.min}, options); } AnnotationIDs Renderer::queryPointAnnotations(const ScreenBox& box) const { @@ -59,7 +53,7 @@ AnnotationIDs Renderer::queryPointAnnotations(const ScreenBox& box) const { return {}; } RenderedQueryOptions options; - options.layerIDs = {{ AnnotationManager::PointLayerID }}; + options.layerIDs = {{AnnotationManager::PointLayerID}}; auto features = queryRenderedFeatures(box, options); return getAnnotationIDs(features); } @@ -68,22 +62,17 @@ AnnotationIDs Renderer::queryShapeAnnotations(const ScreenBox& box) const { if (!LayerManager::annotationsEnabled) { return {}; } - auto features = impl->orchestrator.queryShapeAnnotations({ - box.min, - {box.max.x, box.min.y}, - box.max, - {box.min.x, box.max.y}, - box.min - }); + auto features = impl->orchestrator.queryShapeAnnotations( + {box.min, {box.max.x, box.min.y}, box.max, {box.min.x, box.max.y}, box.min}); return getAnnotationIDs(features); } - + AnnotationIDs Renderer::getAnnotationIDs(const std::vector& features) const { if (!LayerManager::annotationsEnabled) { return {}; } std::set set; - for (auto &feature : features) { + for (auto& feature : features) { assert(feature.id.is()); assert(feature.id.get() <= std::numeric_limits::max()); set.insert(static_cast(feature.id.get())); @@ -94,7 +83,8 @@ AnnotationIDs Renderer::getAnnotationIDs(const std::vector& features) c return ids; } -std::vector Renderer::querySourceFeatures(const std::string& sourceID, const SourceQueryOptions& options) const { +std::vector Renderer::querySourceFeatures(const std::string& sourceID, + const SourceQueryOptions& options) const { return impl->orchestrator.querySourceFeatures(sourceID, options); } @@ -106,18 +96,24 @@ FeatureExtensionValue Renderer::queryFeatureExtensions(const std::string& source return impl->orchestrator.queryFeatureExtensions(sourceID, feature, extension, extensionField, args); } -void Renderer::setFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::string& featureID, const FeatureState& state) { +void Renderer::setFeatureState(const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID, + const FeatureState& state) { impl->orchestrator.setFeatureState(sourceID, sourceLayerID, featureID, state); } -void Renderer::getFeatureState(FeatureState& state, const std::string& sourceID, - const std::optional& sourceLayerID, const std::string& featureID) const { +void Renderer::getFeatureState(FeatureState& state, + const std::string& sourceID, + const std::optional& sourceLayerID, + const std::string& featureID) const { impl->orchestrator.getFeatureState(state, sourceID, sourceLayerID, featureID); } -void Renderer::removeFeatureState(const std::string& sourceID, const std::optional& sourceLayerID, - const std::optional& featureID, const std::optional& stateKey) { +void Renderer::removeFeatureState(const std::string& sourceID, + const std::optional& sourceLayerID, + const std::optional& featureID, + const std::optional& stateKey) { impl->orchestrator.removeFeatureState(sourceID, sourceLayerID, featureID, stateKey); } @@ -134,7 +130,7 @@ const std::vector& Renderer::getPlacedSymbolsData() const { } void Renderer::reduceMemoryUse() { - gfx::BackendScope guard { impl->backend }; + gfx::BackendScope guard{impl->backend}; impl->reduceMemoryUse(); impl->orchestrator.reduceMemoryUse(); } diff --git a/src/mbgl/renderer/renderer_impl.cpp b/src/mbgl/renderer/renderer_impl.cpp index 1c1fe7f973c..5cb47e850f7 100644 --- a/src/mbgl/renderer/renderer_impl.cpp +++ b/src/mbgl/renderer/renderer_impl.cpp @@ -25,7 +25,9 @@ static RendererObserver& nullObserver() { return observer; } -Renderer::Impl::Impl(gfx::RendererBackend& backend_, float pixelRatio_, const std::optional& localFontFamily_) +Renderer::Impl::Impl(gfx::RendererBackend& backend_, + float pixelRatio_, + const std::optional& localFontFamily_) : orchestrator(!backend_.contextIsShared(), localFontFamily_), backend(backend_), observer(&nullObserver()), @@ -48,8 +50,7 @@ void Renderer::Impl::render(const RenderTree& renderTree) { const auto& renderTreeParameters = renderTree.getParameters(); if (!staticData) { - staticData = std::make_unique(pixelRatio, - std::make_unique()); + staticData = std::make_unique(pixelRatio, std::make_unique()); staticData->programs.registerWith(*staticData->shaders); observer->onRegisterShaders(*staticData->shaders); } @@ -60,19 +61,17 @@ void Renderer::Impl::render(const RenderTree& renderTree) { // Blocks execution until the renderable is available. backend.getDefaultRenderable().wait(); - PaintParameters parameters { - context, - pixelRatio, - backend, - renderTreeParameters.light, - renderTreeParameters.mapMode, - renderTreeParameters.debugOptions, - renderTreeParameters.timePoint, - renderTreeParameters.transformParams, - *staticData, - renderTree.getLineAtlas(), - renderTree.getPatternAtlas() - }; + PaintParameters parameters{context, + pixelRatio, + backend, + renderTreeParameters.light, + renderTreeParameters.mapMode, + renderTreeParameters.debugOptions, + renderTreeParameters.timePoint, + renderTreeParameters.transformParams, + *staticData, + renderTree.getLineAtlas(), + renderTree.getPatternAtlas()}; parameters.symbolFadeChange = renderTreeParameters.symbolFadeChange; parameters.opaquePassCutoff = renderTreeParameters.opaquePassCutOff; @@ -96,9 +95,10 @@ void Renderer::Impl::render(const RenderTree& renderTree) { renderTree.getPatternAtlas().upload(*uploadPass); } - // - 3D PASS ------------------------------------------------------------------------------------- - // Renders any 3D layers bottom-to-top to unique FBOs with texture attachments, but share the same - // depth rbo between them. + // - 3D PASS + // ------------------------------------------------------------------------------------- + // Renders any 3D layers bottom-to-top to unique FBOs with texture + // attachments, but share the same depth rbo between them. if (parameters.staticData.has3D) { parameters.staticData.backendSize = parameters.backend.getDefaultRenderable().getSize(); @@ -108,7 +108,8 @@ void Renderer::Impl::render(const RenderTree& renderTree) { if (!parameters.staticData.depthRenderbuffer || parameters.staticData.depthRenderbuffer->getSize() != parameters.staticData.backendSize) { parameters.staticData.depthRenderbuffer = - parameters.context.createRenderbuffer(parameters.staticData.backendSize); + parameters.context.createRenderbuffer( + parameters.staticData.backendSize); } parameters.staticData.depthRenderbuffer->setShouldClear(true); @@ -123,9 +124,10 @@ void Renderer::Impl::render(const RenderTree& renderTree) { } } - // - CLEAR ------------------------------------------------------------------------------------- - // Renders the backdrop of the OpenGL view. This also paints in areas where we don't have any - // tiles whatsoever. + // - CLEAR + // ------------------------------------------------------------------------------------- + // Renders the backdrop of the OpenGL view. This also paints in areas where + // we don't have any tiles whatsoever. { std::optional color; if (parameters.debugOptions & MapDebugOptions::Overdraw) { @@ -133,7 +135,8 @@ void Renderer::Impl::render(const RenderTree& renderTree) { } else if (!backend.contextIsShared()) { color = renderTreeParameters.backgroundColor; } - parameters.renderPass = parameters.encoder->createRenderPass("main buffer", { parameters.backend.getDefaultRenderable(), color, 1.0f, 0 }); + parameters.renderPass = parameters.encoder->createRenderPass( + "main buffer", {parameters.backend.getDefaultRenderable(), color, 1.0f, 0}); } // Actually render the layers @@ -174,15 +177,16 @@ void Renderer::Impl::render(const RenderTree& renderTree) { } } - // - DEBUG PASS -------------------------------------------------------------------------------- + // - DEBUG PASS + // -------------------------------------------------------------------------------- // Renders debug overlays. { const auto debugGroup(parameters.renderPass->createDebugGroup("debug")); // Finalize the rendering, e.g. by calling debug render calls per tile. // This guarantees that we have at least one function per tile called. - // When only rendering layers via the stylesheet, it's possible that we don't - // ever visit a tile during rendering. + // When only rendering layers via the stylesheet, it's possible that we + // don't ever visit a tile during rendering. for (const RenderItem& renderItem : sourceRenderItems) { renderItem.render(parameters); } @@ -211,8 +215,7 @@ void Renderer::Impl::render(const RenderTree& renderTree) { observer->onDidFinishRenderingFrame( renderTreeParameters.loaded ? RendererObserver::RenderMode::Full : RendererObserver::RenderMode::Partial, renderTreeParameters.needsRepaint, - renderTreeParameters.placementChanged - ); + renderTreeParameters.placementChanged); if (!renderTreeParameters.loaded) { renderState = RenderState::Partial; diff --git a/src/mbgl/renderer/renderer_impl.hpp b/src/mbgl/renderer/renderer_impl.hpp index 4057864a779..ca137d9b376 100644 --- a/src/mbgl/renderer/renderer_impl.hpp +++ b/src/mbgl/renderer/renderer_impl.hpp @@ -23,7 +23,7 @@ class Renderer::Impl { private: friend class Renderer; - + void setObserver(RendererObserver*); void render(const RenderTree&); diff --git a/src/mbgl/renderer/source_state.cpp b/src/mbgl/renderer/source_state.cpp index 1c734225a68..65397eb6def 100644 --- a/src/mbgl/renderer/source_state.cpp +++ b/src/mbgl/renderer/source_state.cpp @@ -5,7 +5,8 @@ namespace mbgl { -void SourceFeatureState::updateState(const std::optional& sourceLayerID, const std::string& featureID, +void SourceFeatureState::updateState(const std::optional& sourceLayerID, + const std::string& featureID, const FeatureState& newState) { std::string sourceLayer = sourceLayerID.value_or(std::string()); for (const auto& state : newState) { @@ -15,7 +16,8 @@ void SourceFeatureState::updateState(const std::optional& sourceLay } } -void SourceFeatureState::getState(FeatureState& result, const std::optional& sourceLayerID, +void SourceFeatureState::getState(FeatureState& result, + const std::optional& sourceLayerID, const std::string& featureID) const { std::string sourceLayer = sourceLayerID.value_or(std::string()); FeatureState current; @@ -101,7 +103,8 @@ void SourceFeatureState::coalesceChanges(std::vector& tiles) { } } -void SourceFeatureState::removeState(const std::optional& sourceLayerID, const std::optional& featureID, +void SourceFeatureState::removeState(const std::optional& sourceLayerID, + const std::optional& featureID, const std::optional& stateKey) { std::string sourceLayer = sourceLayerID.value_or(std::string()); @@ -115,8 +118,8 @@ void SourceFeatureState::removeState(const std::optional& sourceLay deletedStates[sourceLayer][*featureID][*stateKey] = {}; } } else if (featureID) { - bool updateInQueue = - (stateChanges.count(sourceLayer) != 0U) && (stateChanges[sourceLayer].count(*featureID) != 0U); + bool updateInQueue = (stateChanges.count(sourceLayer) != 0U) && + (stateChanges[sourceLayer].count(*featureID) != 0U); if (updateInQueue) { for (const auto& changeEntry : stateChanges[sourceLayer][*featureID]) { deletedStates[sourceLayer][*featureID][changeEntry.first] = {}; diff --git a/src/mbgl/renderer/source_state.hpp b/src/mbgl/renderer/source_state.hpp index ff775fa2f86..e233bac8ffa 100644 --- a/src/mbgl/renderer/source_state.hpp +++ b/src/mbgl/renderer/source_state.hpp @@ -12,10 +12,14 @@ class SourceFeatureState { SourceFeatureState() = default; ~SourceFeatureState() = default; - void updateState(const std::optional& sourceLayerID, const std::string& featureID, + void updateState(const std::optional& sourceLayerID, + const std::string& featureID, const FeatureState& newState); - void getState(FeatureState& result, const std::optional& sourceLayerID, const std::string& featureID) const; - void removeState(const std::optional& sourceLayerID, const std::optional& featureID, + void getState(FeatureState& result, + const std::optional& sourceLayerID, + const std::string& featureID) const; + void removeState(const std::optional& sourceLayerID, + const std::optional& featureID, const std::optional& stateKey); void coalesceChanges(std::vector& tiles); diff --git a/src/mbgl/renderer/sources/render_custom_geometry_source.cpp b/src/mbgl/renderer/sources/render_custom_geometry_source.cpp index 841e3f363fc..3787d6d8b32 100644 --- a/src/mbgl/renderer/sources/render_custom_geometry_source.cpp +++ b/src/mbgl/renderer/sources/render_custom_geometry_source.cpp @@ -17,10 +17,10 @@ const style::CustomGeometrySource::Impl& RenderCustomGeometrySource::impl() cons } void RenderCustomGeometrySource::update(Immutable baseImpl_, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters) { if (baseImpl != baseImpl_) { std::swap(baseImpl, baseImpl_); diff --git a/src/mbgl/renderer/sources/render_custom_geometry_source.hpp b/src/mbgl/renderer/sources/render_custom_geometry_source.hpp index e94af0473f0..559039e245b 100644 --- a/src/mbgl/renderer/sources/render_custom_geometry_source.hpp +++ b/src/mbgl/renderer/sources/render_custom_geometry_source.hpp @@ -14,7 +14,7 @@ class RenderCustomGeometrySource final : public RenderTileSource { bool needsRendering, bool needsRelayout, const TileParameters&) override; - + private: const style::CustomGeometrySource::Impl& impl() const; }; diff --git a/src/mbgl/renderer/sources/render_geojson_source.cpp b/src/mbgl/renderer/sources/render_geojson_source.cpp index e0cb9f3b494..024e5f96044 100644 --- a/src/mbgl/renderer/sources/render_geojson_source.cpp +++ b/src/mbgl/renderer/sources/render_geojson_source.cpp @@ -12,7 +12,7 @@ using namespace style; namespace { -template +template std::optional getProperty(const C& cont, const typename C::key_type& name) { const auto it = cont.find(name); if (it == cont.end() || !(it->second.template is())) { @@ -42,9 +42,8 @@ FeatureExtensionValue getLeaves(std::shared_ptr clusterData, // Offset cannot be set without limit. if (limit) { if (offset) { - return clusterData->getLeaves(clusterID, - static_cast(*limit), - static_cast(*offset)); + return clusterData->getLeaves( + clusterID, static_cast(*limit), static_cast(*offset)); } return clusterData->getLeaves(clusterID, static_cast(*limit), 0u); } @@ -60,17 +59,14 @@ FeatureExtensionValue getClusterExpansionZoom(std::shared_ptr(clusterData->getClusterExpansionZoom(clusterID))}; } -MAPBOX_ETERNAL_CONSTEXPR const auto extensionGetters = mapbox::eternal::hash_map({ - {"children", &getChildren}, - {"leaves", &getLeaves}, - {"expansion-zoom", &getClusterExpansionZoom} -}); +MAPBOX_ETERNAL_CONSTEXPR const auto extensionGetters = + mapbox::eternal::hash_map( + {{"children", &getChildren}, {"leaves", &getLeaves}, {"expansion-zoom", &getClusterExpansionZoom}}); } // namespace RenderGeoJSONSource::RenderGeoJSONSource(Immutable impl_) - : RenderTileSource(std::move(impl_)) { -} + : RenderTileSource(std::move(impl_)) {} RenderGeoJSONSource::~RenderGeoJSONSource() = default; @@ -119,11 +115,11 @@ void RenderGeoJSONSource::update(Immutable baseImpl_, }); } -mapbox::util::variant -RenderGeoJSONSource::queryFeatureExtensions(const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const { +mapbox::util::variant RenderGeoJSONSource::queryFeatureExtensions( + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args) const { if (extension != "supercluster") { return {}; } diff --git a/src/mbgl/renderer/sources/render_geojson_source.hpp b/src/mbgl/renderer/sources/render_geojson_source.hpp index 8d3061444de..ef2b3a1e7cb 100644 --- a/src/mbgl/renderer/sources/render_geojson_source.hpp +++ b/src/mbgl/renderer/sources/render_geojson_source.hpp @@ -20,11 +20,11 @@ class RenderGeoJSONSource final : public RenderTileSource { bool needsRelayout, const TileParameters&) override; - FeatureExtensionValue - queryFeatureExtensions(const Feature& feature, - const std::string& extension, - const std::string& extensionField, - const std::optional>& args) const override; + FeatureExtensionValue queryFeatureExtensions( + const Feature& feature, + const std::string& extension, + const std::string& extensionField, + const std::optional>& args) const override; private: const style::GeoJSONSource::Impl& impl() const; diff --git a/src/mbgl/renderer/sources/render_image_source.cpp b/src/mbgl/renderer/sources/render_image_source.cpp index ce865374d1c..29a786bd9f0 100644 --- a/src/mbgl/renderer/sources/render_image_source.cpp +++ b/src/mbgl/renderer/sources/render_image_source.cpp @@ -36,7 +36,7 @@ void ImageSourceRenderData::render(PaintParameters& parameters) const { return; } assert(debugTexture); - static const style::Properties<>::PossiblyEvaluated properties {}; + static const style::Properties<>::PossiblyEvaluated properties{}; static const DebugProgram::Binders paintAttributeData(properties, 0); auto programInstance = parameters.shaders.get(); @@ -46,31 +46,30 @@ void ImageSourceRenderData::render(PaintParameters& parameters) const { for (auto matrix : matrices) { programInstance->draw(parameters.context, - *parameters.renderPass, - gfx::LineStrip{4.0f * parameters.pixelRatio}, - gfx::DepthMode::disabled(), - gfx::StencilMode::disabled(), - gfx::ColorMode::unblended(), - gfx::CullFaceMode::disabled(), - *parameters.staticData.tileBorderIndexBuffer, - RenderStaticData::tileBorderSegments(), - DebugProgram::computeAllUniformValues( - DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), - uniforms::color::Value(Color::red()), - uniforms::overlay_scale::Value(1.0f)}, - paintAttributeData, - properties, - static_cast(parameters.state.getZoom())), - DebugProgram::computeAllAttributeBindings( - *parameters.staticData.tileVertexBuffer, paintAttributeData, properties), - DebugProgram::TextureBindings{textures::image::Value{debugTexture->getResource()}}, - "image"); + *parameters.renderPass, + gfx::LineStrip{4.0f * parameters.pixelRatio}, + gfx::DepthMode::disabled(), + gfx::StencilMode::disabled(), + gfx::ColorMode::unblended(), + gfx::CullFaceMode::disabled(), + *parameters.staticData.tileBorderIndexBuffer, + RenderStaticData::tileBorderSegments(), + DebugProgram::computeAllUniformValues( + DebugProgram::LayoutUniformValues{uniforms::matrix::Value(matrix), + uniforms::color::Value(Color::red()), + uniforms::overlay_scale::Value(1.0f)}, + paintAttributeData, + properties, + static_cast(parameters.state.getZoom())), + DebugProgram::computeAllAttributeBindings( + *parameters.staticData.tileVertexBuffer, paintAttributeData, properties), + DebugProgram::TextureBindings{textures::image::Value{debugTexture->getResource()}}, + "image"); } } RenderImageSource::RenderImageSource(Immutable impl_) - : RenderSource(std::move(impl_)) { -} + : RenderSource(std::move(impl_)) {} RenderImageSource::~RenderImageSource() = default; @@ -105,13 +104,13 @@ void RenderImageSource::prepare(const SourcePrepareParameters& parameters) { renderData = std::make_unique(bucket, std::move(matrices), baseImpl->id); } -std::unordered_map> -RenderImageSource::queryRenderedFeatures(const ScreenLineString&, - const TransformState&, - const std::unordered_map&, - const RenderedQueryOptions&, - const mat4&) const { - return std::unordered_map> {}; +std::unordered_map> RenderImageSource::queryRenderedFeatures( + const ScreenLineString&, + const TransformState&, + const std::unordered_map&, + const RenderedQueryOptions&, + const mat4&) const { + return std::unordered_map>{}; } std::vector RenderImageSource::querySourceFeatures(const SourceQueryOptions&) const { @@ -140,8 +139,8 @@ void RenderImageSource::update(Immutable baseImpl_, } // Compute the z0 tile coordinates for the given LatLngs - TileCoordinatePoint nePoint = { -INFINITY, -INFINITY }; - TileCoordinatePoint swPoint = { INFINITY, INFINITY }; + TileCoordinatePoint nePoint = {-INFINITY, -INFINITY}; + TileCoordinatePoint swPoint = {INFINITY, INFINITY}; std::vector tileCoordinates; for (LatLng latLng : coords) { auto point = TileCoordinate::fromLatLng(0, latLng).p; @@ -150,7 +149,7 @@ void RenderImageSource::update(Immutable baseImpl_, nePoint.x = std::max(nePoint.x, point.x); swPoint.y = std::min(swPoint.y, point.y); nePoint.y = std::max(nePoint.y, point.y); - } + } // Calculate the optimum zoom level to determine the tile ids to use for transforms const auto dx = nePoint.x - swPoint.x; @@ -182,11 +181,9 @@ void RenderImageSource::update(Immutable baseImpl_, if (tile.wrap != 0 && tileCover[0].canonical.isChildOf(tile.canonical)) { tileIds.emplace_back(tile.wrap, tileCover[0].canonical); hasVisibleTile = true; - } - else if (!hasVisibleTile) { - for (auto coveringTile: tileCover) { - if(coveringTile.canonical == tile.canonical || - coveringTile.canonical.isChildOf(tile.canonical) || + } else if (!hasVisibleTile) { + for (auto coveringTile : tileCover) { + if (coveringTile.canonical == tile.canonical || coveringTile.canonical.isChildOf(tile.canonical) || tile.canonical.isChildOf(coveringTile.canonical)) { hasVisibleTile = true; } @@ -215,14 +212,11 @@ void RenderImageSource::update(Immutable baseImpl_, } // Set Bucket Vertices, Indices, and segments + bucket->vertices.emplace_back(RasterProgram::layoutVertex({geomCoords[0].x, geomCoords[0].y}, {0, 0})); + bucket->vertices.emplace_back(RasterProgram::layoutVertex({geomCoords[1].x, geomCoords[1].y}, {util::EXTENT, 0})); + bucket->vertices.emplace_back(RasterProgram::layoutVertex({geomCoords[3].x, geomCoords[3].y}, {0, util::EXTENT})); bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[0].x, geomCoords[0].y }, { 0, 0 })); - bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[1].x, geomCoords[1].y }, { util::EXTENT, 0 })); - bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[3].x, geomCoords[3].y }, { 0, util::EXTENT })); - bucket->vertices.emplace_back( - RasterProgram::layoutVertex({ geomCoords[2].x, geomCoords[2].y }, { util::EXTENT, util::EXTENT })); + RasterProgram::layoutVertex({geomCoords[2].x, geomCoords[2].y}, {util::EXTENT, util::EXTENT})); bucket->indices.emplace_back(0, 1, 2); bucket->indices.emplace_back(1, 2, 3); diff --git a/src/mbgl/renderer/sources/render_image_source.hpp b/src/mbgl/renderer/sources/render_image_source.hpp index 41b6e02fb59..7e461eee131 100644 --- a/src/mbgl/renderer/sources/render_image_source.hpp +++ b/src/mbgl/renderer/sources/render_image_source.hpp @@ -11,9 +11,7 @@ class RasterBucket; class ImageSourceRenderData final : public RenderItem { public: - ImageSourceRenderData(std::shared_ptr bucket_, - std::vector matrices_, - std::string name_) + ImageSourceRenderData(std::shared_ptr bucket_, std::vector matrices_, std::string name_) : bucket(std::move(bucket_)), matrices(std::move(matrices_)), name(std::move(name_)) {} @@ -48,21 +46,18 @@ class RenderImageSource final : public RenderSource { bool needsRelayout, const TileParameters&) final; - const ImageSourceRenderData* getImageRenderData() const override { - return renderData.get(); - } + const ImageSourceRenderData* getImageRenderData() const override { return renderData.get(); } - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const final; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const final; std::vector querySourceFeatures(const SourceQueryOptions&) const final; - void reduceMemoryUse() final { - } + void reduceMemoryUse() final {} void dumpDebugLogs() const final; private: diff --git a/src/mbgl/renderer/sources/render_raster_dem_source.cpp b/src/mbgl/renderer/sources/render_raster_dem_source.cpp index fd2a3e9f1d2..041127e6877 100644 --- a/src/mbgl/renderer/sources/render_raster_dem_source.cpp +++ b/src/mbgl/renderer/sources/render_raster_dem_source.cpp @@ -11,8 +11,7 @@ namespace mbgl { using namespace style; RenderRasterDEMSource::RenderRasterDEMSource(Immutable impl_) - : RenderTileSetSource(std::move(impl_)) { -} + : RenderTileSetSource(std::move(impl_)) {} const style::RasterSource::Impl& RenderRasterDEMSource::impl() const { return static_cast(*baseImpl); @@ -40,19 +39,18 @@ void RenderRasterDEMSource::updateInternal(const Tileset& tileset, algorithm::updateTileMasks(tilePyramid.getRenderedTiles()); } -void RenderRasterDEMSource::onTileChanged(Tile& tile){ +void RenderRasterDEMSource::onTileChanged(Tile& tile) { auto& demtile = static_cast(tile); std::map opposites = { - { DEMTileNeighbors::Left, DEMTileNeighbors::Right }, - { DEMTileNeighbors::Right, DEMTileNeighbors::Left }, - { DEMTileNeighbors::TopLeft, DEMTileNeighbors::BottomRight }, - { DEMTileNeighbors::TopCenter, DEMTileNeighbors::BottomCenter }, - { DEMTileNeighbors::TopRight, DEMTileNeighbors::BottomLeft }, - { DEMTileNeighbors::BottomRight, DEMTileNeighbors::TopLeft }, - { DEMTileNeighbors::BottomCenter, DEMTileNeighbors:: TopCenter }, - { DEMTileNeighbors::BottomLeft, DEMTileNeighbors::TopRight } - }; + {DEMTileNeighbors::Left, DEMTileNeighbors::Right}, + {DEMTileNeighbors::Right, DEMTileNeighbors::Left}, + {DEMTileNeighbors::TopLeft, DEMTileNeighbors::BottomRight}, + {DEMTileNeighbors::TopCenter, DEMTileNeighbors::BottomCenter}, + {DEMTileNeighbors::TopRight, DEMTileNeighbors::BottomLeft}, + {DEMTileNeighbors::BottomRight, DEMTileNeighbors::TopLeft}, + {DEMTileNeighbors::BottomCenter, DEMTileNeighbors::TopCenter}, + {DEMTileNeighbors::BottomLeft, DEMTileNeighbors::TopRight}}; if (tile.isRenderable() && demtile.neighboringTiles != DEMTileNeighbors::Complete) { const CanonicalTileID canonical = tile.id.canonical; @@ -62,30 +60,30 @@ void RenderRasterDEMSource::onTileChanged(Tile& tile){ const uint32_t nx = (canonical.x + 1 + dim) % dim; const int nxw = (canonical.x + 1 == dim) ? tile.id.wrap + 1 : tile.id.wrap; - auto getNeighbor = [&] (DEMTileNeighbors mask){ - if (mask == DEMTileNeighbors::Left){ + auto getNeighbor = [&](DEMTileNeighbors mask) { + if (mask == DEMTileNeighbors::Left) { return OverscaledTileID(tile.id.overscaledZ, pxw, canonical.z, px, canonical.y); - } else if (mask == DEMTileNeighbors::Right){ + } else if (mask == DEMTileNeighbors::Right) { return OverscaledTileID(tile.id.overscaledZ, nxw, canonical.z, nx, canonical.y); - } else if (mask == DEMTileNeighbors::TopLeft){ + } else if (mask == DEMTileNeighbors::TopLeft) { return OverscaledTileID(tile.id.overscaledZ, pxw, canonical.z, px, canonical.y - 1); - } else if (mask == DEMTileNeighbors::TopCenter){ + } else if (mask == DEMTileNeighbors::TopCenter) { return OverscaledTileID(tile.id.overscaledZ, tile.id.wrap, canonical.z, canonical.x, canonical.y - 1); - } else if (mask == DEMTileNeighbors::TopRight){ + } else if (mask == DEMTileNeighbors::TopRight) { return OverscaledTileID(tile.id.overscaledZ, nxw, canonical.z, nx, canonical.y - 1); - } else if (mask == DEMTileNeighbors::BottomLeft){ + } else if (mask == DEMTileNeighbors::BottomLeft) { return OverscaledTileID(tile.id.overscaledZ, pxw, canonical.z, px, canonical.y + 1); - } else if (mask == DEMTileNeighbors::BottomCenter){ + } else if (mask == DEMTileNeighbors::BottomCenter) { return OverscaledTileID(tile.id.overscaledZ, tile.id.wrap, canonical.z, canonical.x, canonical.y + 1); - } else if (mask == DEMTileNeighbors::BottomRight){ + } else if (mask == DEMTileNeighbors::BottomRight) { return OverscaledTileID(tile.id.overscaledZ, nxw, canonical.z, nx, canonical.y + 1); - } else{ + } else { throw std::runtime_error("mask is not a valid tile neighbor"); } }; for (uint8_t i = 0; i < 8; i++) { - auto mask = DEMTileNeighbors(std::pow(2,i)); + auto mask = DEMTileNeighbors(std::pow(2, i)); // only backfill if this neighbor has not been previously backfilled if ((demtile.neighboringTiles & mask) != mask) { OverscaledTileID neighborid = getNeighbor(mask); @@ -94,12 +92,13 @@ void RenderRasterDEMSource::onTileChanged(Tile& tile){ auto& borderTile = static_cast(*renderableNeighbor); demtile.backfillBorder(borderTile, mask); - // if the border tile has not been backfilled by a previous instance of the main - // tile, backfill its corresponding neighbor as well. + // if the border tile has not been backfilled by a previous + // instance of the main tile, backfill its corresponding + // neighbor as well. const DEMTileNeighbors& borderMask = opposites[mask]; - if ((borderTile.neighboringTiles & borderMask) != borderMask){ + if ((borderTile.neighboringTiles & borderMask) != borderMask) { borderTile.backfillBorder(demtile, borderMask); - } + } } } } @@ -107,12 +106,12 @@ void RenderRasterDEMSource::onTileChanged(Tile& tile){ RenderTileSource::onTileChanged(tile); } -std::unordered_map> -RenderRasterDEMSource::queryRenderedFeatures(const ScreenLineString&, - const TransformState&, - const std::unordered_map&, - const RenderedQueryOptions&, - const mat4&) const { +std::unordered_map> RenderRasterDEMSource::queryRenderedFeatures( + const ScreenLineString&, + const TransformState&, + const std::unordered_map&, + const RenderedQueryOptions&, + const mat4&) const { return std::unordered_map>{}; } @@ -120,5 +119,4 @@ std::vector RenderRasterDEMSource::querySourceFeatures(const SourceQuer return {}; } - } // namespace mbgl diff --git a/src/mbgl/renderer/sources/render_raster_dem_source.hpp b/src/mbgl/renderer/sources/render_raster_dem_source.hpp index 6e6d25c6746..1da7d6f14a8 100644 --- a/src/mbgl/renderer/sources/render_raster_dem_source.hpp +++ b/src/mbgl/renderer/sources/render_raster_dem_source.hpp @@ -9,15 +9,14 @@ class RenderRasterDEMSource final : public RenderTileSetSource { public: explicit RenderRasterDEMSource(Immutable); - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const override; - - std::vector - querySourceFeatures(const SourceQueryOptions&) const override; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const override; + + std::vector querySourceFeatures(const SourceQueryOptions&) const override; private: // RenderTileSetSource overrides diff --git a/src/mbgl/renderer/sources/render_raster_source.cpp b/src/mbgl/renderer/sources/render_raster_source.cpp index 6f491d6967a..2bfd6a23092 100644 --- a/src/mbgl/renderer/sources/render_raster_source.cpp +++ b/src/mbgl/renderer/sources/render_raster_source.cpp @@ -9,8 +9,7 @@ namespace mbgl { using namespace style; RenderRasterSource::RenderRasterSource(Immutable impl_) - : RenderTileSetSource(std::move(impl_)) { -} + : RenderTileSetSource(std::move(impl_)) {} inline const style::RasterSource::Impl& RenderRasterSource::impl() const { return static_cast(*baseImpl); @@ -42,12 +41,12 @@ void RenderRasterSource::prepare(const SourcePrepareParameters& parameters) { RenderTileSource::prepare(parameters); } -std::unordered_map> -RenderRasterSource::queryRenderedFeatures(const ScreenLineString&, - const TransformState&, - const std::unordered_map&, - const RenderedQueryOptions&, - const mat4&) const { +std::unordered_map> RenderRasterSource::queryRenderedFeatures( + const ScreenLineString&, + const TransformState&, + const std::unordered_map&, + const RenderedQueryOptions&, + const mat4&) const { return std::unordered_map>{}; } @@ -55,5 +54,4 @@ std::vector RenderRasterSource::querySourceFeatures(const SourceQueryOp return {}; } - } // namespace mbgl diff --git a/src/mbgl/renderer/sources/render_raster_source.hpp b/src/mbgl/renderer/sources/render_raster_source.hpp index 7675e264403..47035e41b54 100644 --- a/src/mbgl/renderer/sources/render_raster_source.hpp +++ b/src/mbgl/renderer/sources/render_raster_source.hpp @@ -12,15 +12,14 @@ class RenderRasterSource final : public RenderTileSetSource { private: void prepare(const SourcePrepareParameters&) final; - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const override; - - std::vector - querySourceFeatures(const SourceQueryOptions&) const override; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const override; + + std::vector querySourceFeatures(const SourceQueryOptions&) const override; // RenderTileSetSource overrides void updateInternal(const Tileset&, diff --git a/src/mbgl/renderer/sources/render_tile_source.cpp b/src/mbgl/renderer/sources/render_tile_source.cpp index 6d24f29f729..45b6d87b13e 100644 --- a/src/mbgl/renderer/sources/render_tile_source.cpp +++ b/src/mbgl/renderer/sources/render_tile_source.cpp @@ -17,8 +17,8 @@ using namespace style; class TileSourceRenderItem : public RenderItem { public: TileSourceRenderItem(Immutable> renderTiles_, std::string name_) - : renderTiles(std::move(renderTiles_)) - , name(std::move(name_)) {} + : renderTiles(std::move(renderTiles_)), + name(std::move(name_)) {} private: void upload(gfx::UploadPass&) const override; @@ -43,8 +43,8 @@ void TileSourceRenderItem::render(PaintParameters& parameters) const { } RenderTileSource::RenderTileSource(Immutable impl_) - : RenderSource(std::move(impl_)) - , renderTiles(makeMutable>()) { + : RenderSource(std::move(impl_)), + renderTiles(makeMutable>()) { tilePyramid.setObserver(this); } @@ -121,12 +121,12 @@ const Tile* RenderTileSource::getRenderedTile(const UnwrappedTileID& tileID) con return tilePyramid.getRenderedTile(tileID); } -std::unordered_map> -RenderTileSource::queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const { +std::unordered_map> RenderTileSource::queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const { return tilePyramid.queryRenderedFeatures(geometry, transformState, layers, options, projMatrix, featureState); } @@ -134,12 +134,14 @@ std::vector RenderTileSource::querySourceFeatures(const SourceQueryOpti return tilePyramid.querySourceFeatures(options); } -void RenderTileSource::setFeatureState(const std::optional& sourceLayerID, const std::string& featureID, +void RenderTileSource::setFeatureState(const std::optional& sourceLayerID, + const std::string& featureID, const FeatureState& state) { featureState.updateState(sourceLayerID, featureID, state); } -void RenderTileSource::getFeatureState(FeatureState& state, const std::optional& sourceLayerID, +void RenderTileSource::getFeatureState(FeatureState& state, + const std::optional& sourceLayerID, const std::string& featureID) const { featureState.getState(state, sourceLayerID, featureID); } @@ -161,8 +163,7 @@ void RenderTileSource::dumpDebugLogs() const { // RenderTileSetSource implementation RenderTileSetSource::RenderTileSetSource(Immutable impl_) - : RenderTileSource(std::move(impl_)) { -} + : RenderTileSource(std::move(impl_)) {} RenderTileSetSource::~RenderTileSetSource() = default; @@ -171,19 +172,19 @@ uint8_t RenderTileSetSource::getMaxZoom() const { } void RenderTileSetSource::update(Immutable baseImpl_, - const std::vector>& layers, - const bool needsRendering, - const bool needsRelayout, - const TileParameters& parameters) { + const std::vector>& layers, + const bool needsRendering, + const bool needsRelayout, + const TileParameters& parameters) { std::swap(baseImpl, baseImpl_); enabled = needsRendering; const auto& implTileset = getTileset(); - // In Continuous mode, keep the existing tiles if the new cachedTileset is not - // yet available, thus providing smart style transitions without flickering. - // In other modes, allow clearing the tile pyramid first, before the early - // return in order to avoid render tests being flaky. + // In Continuous mode, keep the existing tiles if the new cachedTileset is + // not yet available, thus providing smart style transitions without + // flickering. In other modes, allow clearing the tile pyramid first, before + // the early return in order to avoid render tests being flaky. bool canUpdateTileset = implTileset || parameters.mode != MapMode::Continuous; if (canUpdateTileset && cachedTileset != implTileset) { cachedTileset = implTileset; diff --git a/src/mbgl/renderer/sources/render_tile_source.hpp b/src/mbgl/renderer/sources/render_tile_source.hpp index bd929678ff7..6ca108e7a49 100644 --- a/src/mbgl/renderer/sources/render_tile_source.hpp +++ b/src/mbgl/renderer/sources/render_tile_source.hpp @@ -25,21 +25,21 @@ class RenderTileSource : public RenderSource { RenderTiles getRenderTilesSortedByYPosition() const override; const Tile* getRenderedTile(const UnwrappedTileID&) const override; - std::unordered_map> - queryRenderedFeatures(const ScreenLineString& geometry, - const TransformState& transformState, - const std::unordered_map& layers, - const RenderedQueryOptions& options, - const mat4& projMatrix) const override; + std::unordered_map> queryRenderedFeatures( + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix) const override; - std::vector - querySourceFeatures(const SourceQueryOptions&) const override; + std::vector querySourceFeatures(const SourceQueryOptions&) const override; void setFeatureState(const std::optional&, const std::string&, const FeatureState&) override; void getFeatureState(FeatureState& state, const std::optional&, const std::string&) const override; - void removeFeatureState(const std::optional&, const std::optional&, + void removeFeatureState(const std::optional&, + const std::optional&, const std::optional&) override; void reduceMemoryUse() override; diff --git a/src/mbgl/renderer/sources/render_vector_source.cpp b/src/mbgl/renderer/sources/render_vector_source.cpp index ca60d575b01..8134f4cc815 100644 --- a/src/mbgl/renderer/sources/render_vector_source.cpp +++ b/src/mbgl/renderer/sources/render_vector_source.cpp @@ -9,8 +9,7 @@ namespace mbgl { using namespace style; RenderVectorSource::RenderVectorSource(Immutable impl_) - : RenderTileSetSource(std::move(impl_)) { -} + : RenderTileSetSource(std::move(impl_)) {} const std::optional& RenderVectorSource::getTileset() const { return static_cast(*baseImpl).tileset; diff --git a/src/mbgl/renderer/sources/render_vector_source.hpp b/src/mbgl/renderer/sources/render_vector_source.hpp index 19c39e719b3..f826603c8a7 100644 --- a/src/mbgl/renderer/sources/render_vector_source.hpp +++ b/src/mbgl/renderer/sources/render_vector_source.hpp @@ -9,6 +9,7 @@ namespace mbgl { class RenderVectorSource final : public RenderTileSetSource { public: explicit RenderVectorSource(Immutable); + private: void updateInternal(const Tileset&, const std::vector>&, diff --git a/src/mbgl/renderer/style_diff.cpp b/src/mbgl/renderer/style_diff.cpp index 270c4483cdd..fbdf4513454 100644 --- a/src/mbgl/renderer/style_diff.cpp +++ b/src/mbgl/renderer/style_diff.cpp @@ -7,9 +7,7 @@ namespace mbgl { template -StyleDifference diff(const Immutable>& a, - const Immutable>& b, - const Eq& eq) { +StyleDifference diff(const Immutable>& a, const Immutable>& b, const Eq& eq) { StyleDifference result; if (a == b) { @@ -33,7 +31,7 @@ StyleDifference diff(const Immutable>& a, bIt++; } else { if (aIt->get() != bIt->get()) { - result.changed.emplace((*bIt)->id, StyleChange { *aIt, *bIt }); + result.changed.emplace((*bIt)->id, StyleChange{*aIt, *bIt}); } aIt++; bIt++; @@ -46,32 +44,27 @@ StyleDifference diff(const Immutable>& a, ImageDifference diffImages(const Immutable>& a, const Immutable>& b) { - return diff(a, b, [] (const ImmutableImage& lhs, const ImmutableImage& rhs) { - return lhs->id == rhs->id; - }); + return diff(a, b, [](const ImmutableImage& lhs, const ImmutableImage& rhs) { return lhs->id == rhs->id; }); } SourceDifference diffSources(const Immutable>& a, const Immutable>& b) { - return diff(a, b, [] (const ImmutableSource& lhs, const ImmutableSource& rhs) { - return std::tie(lhs->id, lhs->type) - == std::tie(rhs->id, rhs->type); + return diff(a, b, [](const ImmutableSource& lhs, const ImmutableSource& rhs) { + return std::tie(lhs->id, lhs->type) == std::tie(rhs->id, rhs->type); }); } LayerDifference diffLayers(const Immutable>& a, const Immutable>& b) { - return diff(a, b, [] (const ImmutableLayer& lhs, const ImmutableLayer& rhs) { + return diff(a, b, [](const ImmutableLayer& lhs, const ImmutableLayer& rhs) { return (lhs->id == rhs->id) && (lhs->getTypeInfo() == rhs->getTypeInfo()); }); } bool hasLayoutDifference(const LayerDifference& layerDiff, const std::string& layerID) { - if (layerDiff.added.count(layerID)) - return true; + if (layerDiff.added.count(layerID)) return true; const auto it = layerDiff.changed.find(layerID); - if (it == layerDiff.changed.end()) - return false; + if (it == layerDiff.changed.end()) return false; return it->second.before->hasLayoutDifference(*it->second.after); } diff --git a/src/mbgl/renderer/tile_mask.hpp b/src/mbgl/renderer/tile_mask.hpp index 5f24d63ba44..b72252b5f12 100644 --- a/src/mbgl/renderer/tile_mask.hpp +++ b/src/mbgl/renderer/tile_mask.hpp @@ -6,10 +6,11 @@ namespace mbgl { -// A TileMask is a set of TileIDs that describe what part of a tile should be rendered. It omits -// those parts of the tile that are covered by other/better tiles. If the entire tile should be -// rendered, it contains the { 0, 0, 0 } tile. If it's empty, no part of the tile will be rendered. -// TileMasks are typically generated with algorithm::updateTileMasks(). +// A TileMask is a set of TileIDs that describe what part of a tile should be +// rendered. It omits those parts of the tile that are covered by other/better +// tiles. If the entire tile should be rendered, it contains the { 0, 0, 0 } +// tile. If it's empty, no part of the tile will be rendered. TileMasks are +// typically generated with algorithm::updateTileMasks(). using TileMask = std::set; } // namespace mbgl diff --git a/src/mbgl/renderer/tile_pyramid.cpp b/src/mbgl/renderer/tile_pyramid.cpp index b4d2e5512f4..350b4dd3fe4 100644 --- a/src/mbgl/renderer/tile_pyramid.cpp +++ b/src/mbgl/renderer/tile_pyramid.cpp @@ -24,8 +24,7 @@ using namespace style; static TileObserver nullObserver; TilePyramid::TilePyramid() - : observer(&nullObserver) { -} + : observer(&nullObserver) {} TilePyramid::~TilePyramid() = default; @@ -101,18 +100,18 @@ void TilePyramid::update(const std::vector>& l if (overscaledZoom >= zoomRange.min) { int32_t idealZoom = std::min(zoomRange.max, overscaledZoom); - // Make sure we're not reparsing overzoomed raster tiles. if (type == SourceType::Raster) { tileZoom = idealZoom; } // Only attempt prefetching in continuous mode. - if (parameters.mode == MapMode::Continuous && type != style::SourceType::GeoJSON && type != style::SourceType::Annotations) { + if (parameters.mode == MapMode::Continuous && type != style::SourceType::GeoJSON && + type != style::SourceType::Annotations) { // Request lower zoom level tiles (if configured to do so) in an attempt // to show something on the screen faster at the cost of a little of bandwidth. - const uint8_t prefetchZoomDelta = - sourcePrefetchZoomDelta ? *sourcePrefetchZoomDelta : parameters.prefetchZoomDelta; + const uint8_t prefetchZoomDelta = sourcePrefetchZoomDelta ? *sourcePrefetchZoomDelta + : parameters.prefetchZoomDelta; if (prefetchZoomDelta) { panZoom = std::max(tileZoom - prefetchZoomDelta, zoomRange.min); } @@ -127,15 +126,16 @@ void TilePyramid::update(const std::vector>& l idealTiles.size() > 1) { mbgl::Log::Warning(mbgl::Event::General, "Provided camera options returned " + std::to_string(idealTiles.size()) + - " tiles, only " + util::toString(idealTiles[0]) + " is taken in Tile mode."); + " tiles, only " + util::toString(idealTiles[0]) + " is taken in Tile mode."); idealTiles = {idealTiles[0]}; } } - // Stores a list of all the tiles that we're definitely going to retain. There are two - // kinds of tiles we need: the ideal tiles determined by the tile cover. They may not yet be in - // use because they're still loading. In addition to that, we also need to retain all tiles that - // we're actively using, e.g. as a replacement for tile that aren't loaded yet. + // Stores a list of all the tiles that we're definitely going to retain. + // There are two kinds of tiles we need: the ideal tiles determined by the + // tile cover. They may not yet be in use because they're still loading. In + // addition to that, we also need to retain all tiles that we're actively + // using, e.g. as a replacement for tile that aren't loaded yet. std::set retain; auto retainTileFn = [&](Tile& tile, TileNecessity necessity) -> void { @@ -153,9 +153,9 @@ void TilePyramid::update(const std::vector>& l return it == tiles.end() ? nullptr : it->second.get(); }; - // The min and max zoom for TileRange are based on the updateRenderables algorithm. - // Tiles are created at the ideal tile zoom or at lower zoom levels. Child - // tiles are used from the cache, but not created. + // The min and max zoom for TileRange are based on the updateRenderables + // algorithm. Tiles are created at the ideal tile zoom or at lower zoom + // levels. Child tiles are used from the cache, but not created. std::optional tileRange = std::nullopt; if (bounds) { tileRange = util::TileRange::fromLatLngBounds( @@ -215,13 +215,13 @@ void TilePyramid::update(const std::vector>& l auto conservativeCacheSize = static_cast( std::max(static_cast(parameters.transformState.getSize().width) / tileSize, 1.0) * std::max(static_cast(parameters.transformState.getSize().height) / tileSize, 1.0) * - (parameters.transformState.getMaxZoom() - parameters.transformState.getMinZoom() + 1) * 0.5 - ); + (parameters.transformState.getMaxZoom() - parameters.transformState.getMinZoom() + 1) * 0.5); cache.setSize(conservativeCacheSize); } - // Remove stale tiles. This goes through the (sorted!) tiles map and retain set in lockstep - // and removes items from tiles that don't have the corresponding key in the retain set. + // Remove stale tiles. This goes through the (sorted!) tiles map and retain + // set in lockstep and removes items from tiles that don't have the + // corresponding key in the retain set. { auto tilesIt = tiles.begin(); auto retainIt = retain.begin(); @@ -303,9 +303,12 @@ void TilePyramid::handleWrapJump(float lng) { } std::unordered_map> TilePyramid::queryRenderedFeatures( - const ScreenLineString& geometry, const TransformState& transformState, - const std::unordered_map& layers, const RenderedQueryOptions& options, - const mat4& projMatrix, const SourceFeatureState& featureState) const { + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map& layers, + const RenderedQueryOptions& options, + const mat4& projMatrix, + const SourceFeatureState& featureState) const { std::unordered_map> result; if (renderedTiles.empty() || geometry.empty()) { return result; @@ -315,18 +318,19 @@ std::unordered_map> TilePyramid::queryRendered queryGeometry.reserve(geometry.size()); for (const auto& p : geometry) { - queryGeometry.push_back(TileCoordinate::fromScreenCoordinate( - transformState, 0, { p.x, transformState.getSize().height - p.y }).p); + queryGeometry.push_back( + TileCoordinate::fromScreenCoordinate(transformState, 0, {p.x, transformState.getSize().height - p.y}).p); } mapbox::geometry::box box = mapbox::geometry::envelope(queryGeometry); auto cmp = [](const UnwrappedTileID& a, const UnwrappedTileID& b) { return std::tie(a.canonical.z, a.canonical.y, a.wrap, a.canonical.x) < - std::tie(b.canonical.z, b.canonical.y, b.wrap, b.canonical.x); + std::tie(b.canonical.z, b.canonical.y, b.wrap, b.canonical.x); }; - std::map, decltype(cmp)> sortedTiles{renderedTiles.begin(), renderedTiles.end(), cmp}; + std::map, decltype(cmp)> sortedTiles{ + renderedTiles.begin(), renderedTiles.end(), cmp}; auto maxPitchScaleFactor = transformState.maxPitchScaleFactor(); @@ -334,11 +338,15 @@ std::unordered_map> TilePyramid::queryRendered const UnwrappedTileID& id = entry.first; Tile& tile = entry.second; - const auto scale = static_cast(transformState.getScale() / (1 << id.canonical.z)); // equivalent to std::pow(2, transformState.getZoom() - id.canonical.z); - auto queryPadding = maxPitchScaleFactor * tile.getQueryPadding(layers) * util::EXTENT / util::tileSize_D / scale; + const auto scale = static_cast(transformState.getScale() / + (1 << id.canonical.z)); // equivalent to std::pow(2, + // transformState.getZoom() - id.canonical.z); + auto queryPadding = maxPitchScaleFactor * tile.getQueryPadding(layers) * util::EXTENT / util::tileSize_D / + scale; GeometryCoordinate tileSpaceBoundsMin = TileCoordinate::toGeometryCoordinate(id, box.min); - if (tileSpaceBoundsMin.x - queryPadding >= util::EXTENT || tileSpaceBoundsMin.y - queryPadding >= util::EXTENT) { + if (tileSpaceBoundsMin.x - queryPadding >= util::EXTENT || + tileSpaceBoundsMin.y - queryPadding >= util::EXTENT) { continue; } @@ -353,8 +361,8 @@ std::unordered_map> TilePyramid::queryRendered tileSpaceQueryGeometry.push_back(TileCoordinate::toGeometryCoordinate(id, c)); } - tile.queryRenderedFeatures(result, tileSpaceQueryGeometry, transformState, layers, options, projMatrix, - featureState); + tile.queryRenderedFeatures( + result, tileSpaceQueryGeometry, transformState, layers, options, projMatrix, featureState); } return result; diff --git a/src/mbgl/renderer/tile_pyramid.hpp b/src/mbgl/renderer/tile_pyramid.hpp index b04d2c6bb7d..e50a0eee290 100644 --- a/src/mbgl/renderer/tile_pyramid.hpp +++ b/src/mbgl/renderer/tile_pyramid.hpp @@ -51,9 +51,12 @@ class TilePyramid { void handleWrapJump(float lng); std::unordered_map> queryRenderedFeatures( - const ScreenLineString& geometry, const TransformState& transformState, - const std::unordered_map&, const RenderedQueryOptions& options, - const mat4& projMatrix, const mbgl::SourceFeatureState& featureState) const; + const ScreenLineString& geometry, + const TransformState& transformState, + const std::unordered_map&, + const RenderedQueryOptions& options, + const mat4& projMatrix, + const mbgl::SourceFeatureState& featureState) const; std::vector querySourceFeatures(const SourceQueryOptions&) const; diff --git a/src/mbgl/renderer/tile_render_data.cpp b/src/mbgl/renderer/tile_render_data.cpp index 5f8c2498bf7..f0845381c5e 100644 --- a/src/mbgl/renderer/tile_render_data.cpp +++ b/src/mbgl/renderer/tile_render_data.cpp @@ -5,8 +5,7 @@ namespace mbgl { TileRenderData::TileRenderData() = default; TileRenderData::TileRenderData(std::shared_ptr atlasTextures_) - : atlasTextures(std::move(atlasTextures_)) { -} + : atlasTextures(std::move(atlasTextures_)) {} TileRenderData::~TileRenderData() = default; diff --git a/src/mbgl/renderer/tile_render_data.hpp b/src/mbgl/renderer/tile_render_data.hpp index 85b26754e45..b4f3de1505f 100644 --- a/src/mbgl/renderer/tile_render_data.hpp +++ b/src/mbgl/renderer/tile_render_data.hpp @@ -18,7 +18,7 @@ class LayerRenderData; class SourcePrepareParameters; class TileAtlasTextures { -public: +public: std::optional glyph; std::optional icon; }; @@ -49,9 +49,7 @@ class SharedBucketTileRenderData final : public TileRenderData { private: // TileRenderData overrides. - Bucket* getBucket(const style::Layer::Impl&) const override { - return bucket ? bucket.get() : nullptr; - } + Bucket* getBucket(const style::Layer::Impl&) const override { return bucket ? bucket.get() : nullptr; } void upload(gfx::UploadPass& uploadPass) override { if (bucket) bucket->upload(uploadPass); } diff --git a/src/mbgl/renderer/update_parameters.hpp b/src/mbgl/renderer/update_parameters.hpp index 47192b9940c..a16a2801f0b 100644 --- a/src/mbgl/renderer/update_parameters.hpp +++ b/src/mbgl/renderer/update_parameters.hpp @@ -39,7 +39,7 @@ class UpdateParameters { std::shared_ptr fileSource; const uint8_t prefetchZoomDelta; - + // For still image requests, render requested const bool stillImageRequest; diff --git a/src/mbgl/renderer/upload_parameters.hpp b/src/mbgl/renderer/upload_parameters.hpp index 74fb6a8c862..b8c6d4e91b6 100644 --- a/src/mbgl/renderer/upload_parameters.hpp +++ b/src/mbgl/renderer/upload_parameters.hpp @@ -10,11 +10,9 @@ class LineAtlas; class UploadParameters { public: - UploadParameters(const TransformState& state_, - LineAtlas& lineAtlas_) + UploadParameters(const TransformState& state_, LineAtlas& lineAtlas_) : state(state_), - lineAtlas(lineAtlas_) { - } + lineAtlas(lineAtlas_) {} const TransformState& state; LineAtlas& lineAtlas; diff --git a/src/mbgl/sprite/sprite_loader.cpp b/src/mbgl/sprite/sprite_loader.cpp index da057142429..61f5fb47a07 100644 --- a/src/mbgl/sprite/sprite_loader.cpp +++ b/src/mbgl/sprite/sprite_loader.cpp @@ -27,7 +27,9 @@ struct SpriteLoader::Data { }; SpriteLoader::SpriteLoader(float pixelRatio_) - : pixelRatio(pixelRatio_), observer(&nullObserver), threadPool(Scheduler::GetBackground()) {} + : pixelRatio(pixelRatio_), + observer(&nullObserver), + threadPool(Scheduler::GetBackground()) {} SpriteLoader::~SpriteLoader() = default; diff --git a/src/mbgl/sprite/sprite_parser.cpp b/src/mbgl/sprite/sprite_parser.cpp index 3ac93d3358d..10629b4d53d 100644 --- a/src/mbgl/sprite/sprite_parser.cpp +++ b/src/mbgl/sprite/sprite_parser.cpp @@ -33,11 +33,9 @@ std::unique_ptr createStyleImage(const std::string& id, srcX + width > static_cast(image.size.width) || srcY + height > static_cast(image.size.height)) { std::ostringstream ss; - ss << "Can't create image with invalid metrics: " - << width << "x" << height << "@" << srcX << "," << srcY - << " in " << image.size.width << "x" << image.size.height - << "@" << util::toString(ratio) << "x" - << " sprite"; + ss << "Can't create image with invalid metrics: " << width << "x" << height << "@" << srcX << "," << srcY + << " in " << image.size.width << "x" << image.size.height << "@" << util::toString(ratio) << "x" + << " sprite"; Log::Error(Event::Sprite, ss.str()); return nullptr; } @@ -66,7 +64,8 @@ uint16_t getUInt16(const JSValue& value, const char* property, const char* name, return v.GetUint(); } else { Log::Warning(Event::Sprite, - std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be an integer between 0 and 65535"); + std::string("Invalid sprite image '") + name + "': value of '" + property + + "' must be an integer between 0 and 65535"); } } @@ -79,7 +78,9 @@ double getDouble(const JSValue& value, const char* property, const char* name, c if (v.IsNumber()) { return v.GetDouble(); } else { - Log::Warning(Event::Sprite, std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a number"); + Log::Warning( + Event::Sprite, + std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a number"); } } @@ -92,7 +93,9 @@ bool getBoolean(const JSValue& value, const char* property, const char* name, co if (v.IsBool()) { return v.GetBool(); } else { - Log::Warning(Event::Sprite, std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a boolean"); + Log::Warning( + Event::Sprite, + std::string("Invalid sprite image '") + name + "': value of '" + property + "' must be a boolean"); } } @@ -113,11 +116,14 @@ style::ImageStretches getStretches(const JSValue& value, const char* property, c stretch[rapidjson::SizeType(1)].GetFloat()}); } else { Log::Warning(Event::Sprite, - "Invalid sprite image '" + std::string(name) + "': members of '" + property + "' must be an array of two numbers"); + "Invalid sprite image '" + std::string(name) + "': members of '" + property + + "' must be an array of two numbers"); } } } else { - Log::Warning(Event::Sprite, "Invalid sprite image '" + std::string(name) + "': value of '" + property + "' must be an array"); + Log::Warning( + Event::Sprite, + "Invalid sprite image '" + std::string(name) + "': value of '" + property + "' must be an array"); } } @@ -136,7 +142,8 @@ std::optional getContent(const JSValue& value, const char* content[rapidjson::SizeType(3)].GetFloat()}; } else { Log::Warning(Event::Sprite, - "Invalid sprite image '" + std::string(name) + "': value of '" + property + "' must be an array of four numbers"); + "Invalid sprite image '" + std::string(name) + "': value of '" + property + + "' must be an array of four numbers"); } } diff --git a/src/mbgl/storage/asset_file_source.hpp b/src/mbgl/storage/asset_file_source.hpp index 6d9ee3bb524..8db775592d1 100644 --- a/src/mbgl/storage/asset_file_source.hpp +++ b/src/mbgl/storage/asset_file_source.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace util { -template class Thread; +template +class Thread; } // namespace util class AssetFileSource : public FileSource { diff --git a/src/mbgl/storage/file_source_manager.cpp b/src/mbgl/storage/file_source_manager.cpp index 6e24d721089..2e21443b82a 100644 --- a/src/mbgl/storage/file_source_manager.cpp +++ b/src/mbgl/storage/file_source_manager.cpp @@ -13,7 +13,9 @@ namespace mbgl { struct FileSourceInfo { FileSourceInfo(FileSourceType type_, std::string id_, std::weak_ptr fileSource_) - : type(type_), id(std::move(id_)), fileSource(std::move(fileSource_)) {} + : type(type_), + id(std::move(id_)), + fileSource(std::move(fileSource_)) {} FileSourceType type; std::string id; @@ -27,11 +29,14 @@ class FileSourceManager::Impl { std::recursive_mutex mutex; }; -FileSourceManager::FileSourceManager() : impl(std::make_unique()) {} +FileSourceManager::FileSourceManager() + : impl(std::make_unique()) {} FileSourceManager::~FileSourceManager() = default; -std::shared_ptr FileSourceManager::getFileSource(FileSourceType type, const ResourceOptions& resourceOptions, const ClientOptions& clientOptions) noexcept { +std::shared_ptr FileSourceManager::getFileSource(FileSourceType type, + const ResourceOptions& resourceOptions, + const ClientOptions& clientOptions) noexcept { std::lock_guard lock(impl->mutex); // Remove released file sources. @@ -41,8 +46,8 @@ std::shared_ptr FileSourceManager::getFileSource(FileSourceType typ const auto context = reinterpret_cast(resourceOptions.platformContext()); std::string baseURL = resourceOptions.tileServerOptions().baseURL(); - std::string id = - baseURL + '|' + resourceOptions.apiKey() + '|' + resourceOptions.cachePath() + '|' + util::toString(context); + std::string id = baseURL + '|' + resourceOptions.apiKey() + '|' + resourceOptions.cachePath() + '|' + + util::toString(context); std::shared_ptr fileSource; auto fileSourceIt = std::find_if(impl->fileSources.begin(), impl->fileSources.end(), [type, &id](const auto& info) { diff --git a/src/mbgl/storage/local_file_source.hpp b/src/mbgl/storage/local_file_source.hpp index 3595db6499b..79a90de6720 100644 --- a/src/mbgl/storage/local_file_source.hpp +++ b/src/mbgl/storage/local_file_source.hpp @@ -7,7 +7,8 @@ namespace mbgl { namespace util { -template class Thread; +template +class Thread; } // namespace util class LocalFileSource : public FileSource { diff --git a/src/mbgl/storage/mbtiles_file_source.hpp b/src/mbgl/storage/mbtiles_file_source.hpp index a31f9002ef2..876d348c653 100644 --- a/src/mbgl/storage/mbtiles_file_source.hpp +++ b/src/mbgl/storage/mbtiles_file_source.hpp @@ -5,7 +5,6 @@ #include #include - namespace mbgl { // File source for supporting .mbtiles maps. // can only load resource URLS that are absolute paths to local files @@ -14,7 +13,7 @@ class MBTilesFileSource : public FileSource { MBTilesFileSource(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions); ~MBTilesFileSource() override; - std::unique_ptr request(const Resource &, Callback) override; + std::unique_ptr request(const Resource&, Callback) override; bool canRequest(const Resource&) const override; void setResourceOptions(ResourceOptions) override; @@ -25,7 +24,7 @@ class MBTilesFileSource : public FileSource { private: class Impl; - std::unique_ptr > thread; //impl + std::unique_ptr> thread; // impl }; } // namespace mbgl diff --git a/src/mbgl/storage/network_status.cpp b/src/mbgl/storage/network_status.cpp index 646bbf40be5..4b534b1c95b 100644 --- a/src/mbgl/storage/network_status.cpp +++ b/src/mbgl/storage/network_status.cpp @@ -4,8 +4,8 @@ // Example: Allocate a reachability object // Reachability* reach = [Reachability reachabilityForInternetConnection]; -// reach.reachableBlock = ^(Reachability* reach) { NetworkStatus::Reachable(); }; -// [reach startNotifier]; +// reach.reachableBlock = ^(Reachability* reach) { NetworkStatus::Reachable(); +// }; [reach startNotifier]; namespace mbgl { @@ -24,7 +24,7 @@ NetworkStatus::Status NetworkStatus::Get() { void NetworkStatus::Set(Status status) { if (status == Status::Offline) { online = false; - } else if(!online) { + } else if (!online) { online = true; Reachable(); } diff --git a/src/mbgl/storage/resource.cpp b/src/mbgl/storage/resource.cpp index 7461364a84f..acf785313c1 100644 --- a/src/mbgl/storage/resource.cpp +++ b/src/mbgl/storage/resource.cpp @@ -35,60 +35,49 @@ static std::string getTileBBox(int32_t x, int32_t y, int8_t z) { auto min = getMercCoord(x * 256, y * 256, z); auto max = getMercCoord((x + 1) * 256, (y + 1) * 256, z); - return (util::toString(min.x) + "," + util::toString(min.y) + "," + - util::toString(max.x) + "," + util::toString(max.y)); + return (util::toString(min.x) + "," + util::toString(min.y) + "," + util::toString(max.x) + "," + + util::toString(max.y)); } Resource Resource::style(const std::string& url) { - return Resource { - Resource::Kind::Style, - url - }; + return Resource{Resource::Kind::Style, url}; } Resource Resource::source(const std::string& url) { - return Resource { - Resource::Kind::Source, - url - }; + return Resource{Resource::Kind::Source, url}; } Resource Resource::image(const std::string& url) { - return Resource { - Resource::Kind::Image, - url - }; + return Resource{Resource::Kind::Image, url}; } Resource Resource::spriteImage(const std::string& base, float pixelRatio) { util::URL url(base); - return Resource{ Resource::Kind::SpriteImage, - base.substr(0, url.path.first + url.path.second) + - (pixelRatio > 1 ? "@2x" : "") + ".png" + - base.substr(url.query.first, url.query.second)}; + return Resource{Resource::Kind::SpriteImage, + base.substr(0, url.path.first + url.path.second) + (pixelRatio > 1 ? "@2x" : "") + ".png" + + base.substr(url.query.first, url.query.second)}; } Resource Resource::spriteJSON(const std::string& base, float pixelRatio) { util::URL url(base); - return Resource{ Resource::Kind::SpriteJSON, - base.substr(0, url.path.first + url.path.second) + - (pixelRatio > 1 ? "@2x" : "") + ".json" + - base.substr(url.query.first, url.query.second)}; + return Resource{Resource::Kind::SpriteJSON, + base.substr(0, url.path.first + url.path.second) + (pixelRatio > 1 ? "@2x" : "") + ".json" + + base.substr(url.query.first, url.query.second)}; } -Resource Resource::glyphs(const std::string& urlTemplate, const FontStack& fontStack, const std::pair& glyphRange) { - return Resource { - Resource::Kind::Glyphs, - util::replaceTokens(urlTemplate, [&](const std::string& token) -> std::optional { - if (token == "fontstack") { - return util::percentEncode(fontStackToString(fontStack)); - } else if (token == "range") { - return util::toString(glyphRange.first) + "-" + util::toString(glyphRange.second); - } else { - return {}; - } - }) - }; +Resource Resource::glyphs(const std::string& urlTemplate, + const FontStack& fontStack, + const std::pair& glyphRange) { + return Resource{Resource::Kind::Glyphs, + util::replaceTokens(urlTemplate, [&](const std::string& token) -> std::optional { + if (token == "fontstack") { + return util::percentEncode(fontStackToString(fontStack)); + } else if (token == "range") { + return util::toString(glyphRange.first) + "-" + util::toString(glyphRange.second); + } else { + return {}; + } + })}; } Resource Resource::tile(const std::string& urlTemplate, @@ -102,39 +91,32 @@ Resource Resource::tile(const std::string& urlTemplate, if (scheme == Tileset::Scheme::TMS) { y = (1 << z) - y - 1; } - return Resource { - Resource::Kind::Tile, - util::replaceTokens(urlTemplate, [&](const std::string& token) -> std::optional { - if (token == "z") { - return util::toString(z); - } else if (token == "x") { - return util::toString(x); - } else if (token == "y") { - return util::toString(y); - } else if (token == "quadkey") { - return getQuadKey(x, y, z); - } else if (token == "bbox-epsg-3857") { - return getTileBBox(x, y, z); - } else if (token == "prefix") { - return {{ - "0123456789abcdef"[x % 16], - "0123456789abcdef"[y % 16], - }}; - } else if (token == "ratio") { - return std::string(pixelRatio > 1.0 ? "@2x" : ""); - } else { - return {}; - } - }), - Resource::TileData { - urlTemplate, - uint8_t(supportsRatio && pixelRatio > 1.0 ? 2 : 1), - x, - y, - z - }, - loadingMethod - }; + return Resource{Resource::Kind::Tile, + util::replaceTokens(urlTemplate, + [&](const std::string& token) -> std::optional { + if (token == "z") { + return util::toString(z); + } else if (token == "x") { + return util::toString(x); + } else if (token == "y") { + return util::toString(y); + } else if (token == "quadkey") { + return getQuadKey(x, y, z); + } else if (token == "bbox-epsg-3857") { + return getTileBBox(x, y, z); + } else if (token == "prefix") { + return {{ + "0123456789abcdef"[x % 16], + "0123456789abcdef"[y % 16], + }}; + } else if (token == "ratio") { + return std::string(pixelRatio > 1.0 ? "@2x" : ""); + } else { + return {}; + } + }), + Resource::TileData{urlTemplate, uint8_t(supportsRatio && pixelRatio > 1.0 ? 2 : 1), x, y, z}, + loadingMethod}; } } // namespace mbgl diff --git a/src/mbgl/storage/resource_options.cpp b/src/mbgl/storage/resource_options.cpp index f1e1275d595..2aec7afa4ec 100644 --- a/src/mbgl/storage/resource_options.cpp +++ b/src/mbgl/storage/resource_options.cpp @@ -15,12 +15,20 @@ class ResourceOptions::Impl { }; // These requires the complete type of Impl. -ResourceOptions::ResourceOptions() : impl_(std::make_unique()) {} +ResourceOptions::ResourceOptions() + : impl_(std::make_unique()) {} ResourceOptions::~ResourceOptions() = default; ResourceOptions::ResourceOptions(ResourceOptions&&) noexcept = default; -ResourceOptions::ResourceOptions(const ResourceOptions& other) : impl_(std::make_unique(*other.impl_)) {} -ResourceOptions& ResourceOptions::operator=(const ResourceOptions& other) {impl_ = std::make_unique(*other.impl_); return *this; } -ResourceOptions& ResourceOptions::operator=(ResourceOptions&& options) {swap(impl_, options.impl_); return *this; } +ResourceOptions::ResourceOptions(const ResourceOptions& other) + : impl_(std::make_unique(*other.impl_)) {} +ResourceOptions& ResourceOptions::operator=(const ResourceOptions& other) { + impl_ = std::make_unique(*other.impl_); + return *this; +} +ResourceOptions& ResourceOptions::operator=(ResourceOptions&& options) { + swap(impl_, options.impl_); + return *this; +} ResourceOptions ResourceOptions::clone() const { return ResourceOptions(*this); @@ -81,8 +89,9 @@ void* ResourceOptions::platformContext() const { } ResourceOptions ResourceOptions::Default() { - ResourceOptions resourceOptions = ResourceOptions().withTileServerOptions(TileServerOptions::DefaultConfiguration()); + ResourceOptions resourceOptions = ResourceOptions().withTileServerOptions( + TileServerOptions::DefaultConfiguration()); return resourceOptions; } -} // namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/storage/resource_transform.cpp b/src/mbgl/storage/resource_transform.cpp index eaf10c93fdd..b2b4208643b 100644 --- a/src/mbgl/storage/resource_transform.cpp +++ b/src/mbgl/storage/resource_transform.cpp @@ -2,7 +2,8 @@ namespace mbgl { -ResourceTransform::ResourceTransform(TransformCallback callback) : transformCallback(std::move(callback)) {} +ResourceTransform::ResourceTransform(TransformCallback callback) + : transformCallback(std::move(callback)) {} void ResourceTransform::transform(Resource::Kind kind, const std::string& url, FinishedCallback finished) { assert(finished); diff --git a/src/mbgl/storage/response.cpp b/src/mbgl/storage/response.cpp index 1922d319c84..9bc6958caf9 100644 --- a/src/mbgl/storage/response.cpp +++ b/src/mbgl/storage/response.cpp @@ -19,7 +19,8 @@ Response& Response::operator=(const Response& res) { } Response::Error::Error(Reason reason_, std::string message_, std::optional retryAfter_) - : reason(reason_), message(std::move(message_)), retryAfter(std::move(retryAfter_)) { -} + : reason(reason_), + message(std::move(message_)), + retryAfter(std::move(retryAfter_)) {} } // namespace mbgl diff --git a/src/mbgl/style/collection.hpp b/src/mbgl/style/collection.hpp index 36d5176d4c4..6602ea126c6 100644 --- a/src/mbgl/style/collection.hpp +++ b/src/mbgl/style/collection.hpp @@ -10,10 +10,11 @@ namespace mbgl { namespace style { /* - Manages an ordered collection of elements and their `Immutable`s. The latter is - itself stored in an Immutable container. Using immutability at the collection level - allows us to short-circuit significant portions of the RenderStyle update logic via - a simple pointer equality check, greatly improving performance. + Manages an ordered collection of elements and their `Immutable`s. The + latter is itself stored in an Immutable container. Using immutability at the + collection level allows us to short-circuit significant portions of the + RenderStyle update logic via a simple pointer equality check, greatly + improving performance. Element types are required to have: @@ -45,9 +46,9 @@ class CollectionBase { std::size_t index(const std::string&) const; T* add(std::size_t wrapperIndex, std::size_t implIndex, std::unique_ptr wrapper); std::unique_ptr remove(std::size_t wrapperIndex, std::size_t implIndex); - // Must be called whenever an element of the collection is internally mutated. - // Typically, each element permits registration of an observer, and the observer - // should call this method. + // Must be called whenever an element of the collection is internally + // mutated. Typically, each element permits registration of an observer, and + // the observer should call this method. void update(std::size_t implIndex, const T&); WrapperVector wrappers; @@ -99,7 +100,8 @@ template using CollectionWithPersistentOrder = Collection; template -CollectionBase::CollectionBase() : impls(makeMutable>>()) {} +CollectionBase::CollectionBase() + : impls(makeMutable>>()) {} template std::size_t CollectionBase::size() const { @@ -108,9 +110,8 @@ std::size_t CollectionBase::size() const { template std::size_t CollectionBase::index(const std::string& id) const { - return std::find_if(wrappers.begin(), wrappers.end(), [&](const auto& e) { - return e->getID() == id; - }) - wrappers.begin(); + return std::find_if(wrappers.begin(), wrappers.end(), [&](const auto& e) { return e->getID() == id; }) - + wrappers.begin(); } template @@ -133,9 +134,7 @@ std::vector CollectionBase::getWrappers() const { template void CollectionBase::clear() { - mutate(impls, [&] (auto& impls_) { - impls_.clear(); - }); + mutate(impls, [&](auto& impls_) { impls_.clear(); }); wrappers.clear(); } diff --git a/src/mbgl/style/conversion/color_ramp_property_value.cpp b/src/mbgl/style/conversion/color_ramp_property_value.cpp index f31ad47b602..c2d91ffb9d2 100644 --- a/src/mbgl/style/conversion/color_ramp_property_value.cpp +++ b/src/mbgl/style/conversion/color_ramp_property_value.cpp @@ -10,7 +10,10 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, Error& error, bool, bool) const { +std::optional Converter::operator()(const Convertible& value, + Error& error, + bool, + bool) const { using namespace mbgl::style::expression; if (isUndefined(value)) { return ColorRampPropertyValue(); diff --git a/src/mbgl/style/conversion/constant.cpp b/src/mbgl/style/conversion/constant.cpp index 6e82047ac2d..910e5a04735 100644 --- a/src/mbgl/style/conversion/constant.cpp +++ b/src/mbgl/style/conversion/constant.cpp @@ -33,7 +33,8 @@ std::optional Converter::operator()(const Convertible& } template -std::optional Converter>>::operator()(const Convertible& value, Error& error) const { +std::optional Converter>>::operator()(const Convertible& value, + Error& error) const { std::optional string = toString(value); if (!string) { error.message = "value must be a string"; @@ -50,7 +51,9 @@ std::optional Converter>>::ope } template -auto Converter, typename std::enable_if_t>>::operator()(const Convertible& value, Error& error) const -> std::optional> { +auto Converter, typename std::enable_if_t>>::operator()(const Convertible& value, + Error& error) const + -> std::optional> { if (!isArray(value)) { error.message = "value must be an array"; return std::nullopt; @@ -71,22 +74,29 @@ auto Converter, typename std::enable_if_t>>::op } template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, + Error&) const; +template std::optional Converter::operator()( + const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, + Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, + Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional Converter::operator()(const Convertible&, Error&) const; +template std::optional Converter::operator()(const Convertible&, + Error&) const; template std::optional Converter::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; +template std::optional> Converter>::operator()( + const Convertible&, Error&) const; +template std::optional> Converter>::operator()( + const Convertible&, Error&) const; std::optional Converter::operator()(const Convertible& value, Error& error) const { std::optional string = toString(value); @@ -105,7 +115,8 @@ std::optional Converter::operator()(const Convertible& value, Erro } template -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()(const Convertible& value, + Error& error) const { if (!isArray(value) || arrayLength(value) != N) { error.message = "value must be an array of " + util::toString(N) + " numbers"; return std::nullopt; @@ -123,13 +134,16 @@ std::optional> Converter>::operator()( return result; } -template std::optional> Converter>::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; -template std::optional> Converter>::operator()(const Convertible&, Error&) const; +template std::optional> Converter>::operator()(const Convertible&, + Error&) const; +template std::optional> Converter>::operator()(const Convertible&, + Error&) const; +template std::optional> Converter>::operator()(const Convertible&, + Error&) const; template std::optional> Converter>::operator()(const Convertible& value, - Error& error) const { + Error& error) const { if (!isArray(value) || arrayLength(value) != N) { error.message = "value must be an array of " + util::toString(N) + " numbers"; return std::nullopt; @@ -147,9 +161,11 @@ std::optional> Converter>::operator( return result; } -template std::optional> Converter>::operator()(const Convertible&, Error&) const; +template std::optional> Converter>::operator()(const Convertible&, + Error&) const; -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()(const Convertible& value, + Error& error) const { if (!isArray(value)) { error.message = "value must be an array"; return std::nullopt; @@ -170,7 +186,8 @@ std::optional> Converter>::operator()(cons return result; } -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()(const Convertible& value, + Error& error) const { if (!isArray(value)) { error.message = "value must be an array"; return std::nullopt; diff --git a/src/mbgl/style/conversion/coordinate.cpp b/src/mbgl/style/conversion/coordinate.cpp index 9f554518b4d..5609d52f4b5 100644 --- a/src/mbgl/style/conversion/coordinate.cpp +++ b/src/mbgl/style/conversion/coordinate.cpp @@ -5,20 +5,24 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator() (const Convertible& value, Error& error) const { - if (!isArray(value) || arrayLength(value) < 2 ) { - error.message = "coordinate array must contain numeric longitude and latitude values"; +std::optional Converter::operator()(const Convertible& value, Error& error) const { + if (!isArray(value) || arrayLength(value) < 2) { + error.message = + "coordinate array must contain numeric longitude and latitude " + "values"; return std::nullopt; } - //Style spec uses GeoJSON convention for specifying coordinates + // Style spec uses GeoJSON convention for specifying coordinates std::optional latitude = toDouble(arrayMember(value, 1)); std::optional longitude = toDouble(arrayMember(value, 0)); if (!latitude || !longitude) { - error.message = "coordinate array must contain numeric longitude and latitude values"; + error.message = + "coordinate array must contain numeric longitude and latitude " + "values"; return std::nullopt; } - if (*latitude < -90 || *latitude > 90 ){ + if (*latitude < -90 || *latitude > 90) { error.message = "coordinate latitude must be between -90 and 90"; return std::nullopt; } diff --git a/src/mbgl/style/conversion/custom_geometry_source_options.cpp b/src/mbgl/style/conversion/custom_geometry_source_options.cpp index 4b0f715c03d..00be385184d 100644 --- a/src/mbgl/style/conversion/custom_geometry_source_options.cpp +++ b/src/mbgl/style/conversion/custom_geometry_source_options.cpp @@ -5,7 +5,8 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, Error& error) const { +std::optional Converter::operator()( + const Convertible& value, Error& error) const { CustomGeometrySource::Options options; const auto minzoomValue = objectMember(value, "minzoom"); diff --git a/src/mbgl/style/conversion/filter.cpp b/src/mbgl/style/conversion/filter.cpp index d354d23e846..d72d64c3174 100644 --- a/src/mbgl/style/conversion/filter.cpp +++ b/src/mbgl/style/conversion/filter.cpp @@ -26,7 +26,7 @@ std::optional Converter::operator()(const Convertible& value, Er error.message = parsingContext.getCombinedErrors(); return std::nullopt; } else { - return { Filter(std::move(parseResult)) }; + return {Filter(std::move(parseResult))}; } } else { ParseResult expression = convertLegacyFilter(value, error); @@ -38,7 +38,8 @@ std::optional Converter::operator()(const Convertible& value, Er } } -// This is a port from https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/feature_filter/index.js +// This is a port from +// https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/feature_filter/index.js bool isExpression(const Convertible& filter) { if (!isArray(filter) || arrayLength(filter) == 0) { return false; @@ -83,9 +84,7 @@ ParseResult createExpression(const std::string& op, std::optional>> args, Error& error) { if (!args) return {}; - assert(std::all_of(args->begin(), args->end(), [](const std::unique_ptr &e) { - return bool(e.get()); - })); + assert(std::all_of(args->begin(), args->end(), [](const std::unique_ptr& e) { return bool(e.get()); })); if (op == "any") { return {std::make_unique(std::move(*args))}; @@ -124,7 +123,9 @@ ParseResult convertLiteral(const Convertible& convertible, Error& error) { } } -std::optional>> convertLiteralArray(const Convertible &input, Error& error, std::size_t startIndex = 0) { +std::optional>> convertLiteralArray(const Convertible& input, + Error& error, + std::size_t startIndex = 0) { std::vector> output; output.reserve(arrayLength(input)); for (std::size_t i = startIndex; i < arrayLength(input); ++i) { @@ -187,7 +188,9 @@ ParseResult convertLegacyInFilter(const Convertible& values, Error& error) { } } -std::optional>> convertLegacyFilterArray(const Convertible &input, Error& error, std::size_t startIndex = 0) { +std::optional>> convertLegacyFilterArray(const Convertible& input, + Error& error, + std::size_t startIndex = 0) { std::vector> output; output.reserve(arrayLength(input)); for (std::size_t i = startIndex; i < arrayLength(input); ++i) { @@ -206,8 +209,8 @@ ParseResult convertLegacyFilter(const Convertible& values, Error& error) { } if (!isArray(values) || arrayLength(values) == 0) { - error.message = "filter value must be a non empty array"; - return std::nullopt; + error.message = "filter value must be a non empty array"; + return std::nullopt; } std::optional op = toString(arrayMember(values, 0)); @@ -221,22 +224,19 @@ ParseResult convertLegacyFilter(const Convertible& values, Error& error) { expression::ParsingContext ctx; return ctx.parseExpression(values); } else { - return { - *op == "==" || - *op == "<" || - *op == ">" || - *op == "<=" || - *op == ">=" ? convertLegacyComparisonFilter(values, error) : - *op == "!=" ? createExpression("!", convertLegacyComparisonFilter(values, error, {"=="}), error) : - *op == "any" ? createExpression("any", convertLegacyFilterArray(values, error, 1), error) : - *op == "all" ? createExpression("all", convertLegacyFilterArray(values, error, 1), error) : - *op == "none" ? createExpression("!", createExpression("any", convertLegacyFilterArray(values, error, 1), error), error) : - *op == "in" ? convertLegacyInFilter(values, error) : - *op == "!in" ? createExpression("!", convertLegacyInFilter(values, error), error) : - *op == "has" ? convertLegacyHasFilter(values, error) : - *op == "!has" ? createExpression("!", convertLegacyHasFilter(values, error), error) : - ParseResult(std::make_unique(true)) - }; + return {*op == "==" || *op == "<" || *op == ">" || *op == "<=" || *op == ">=" + ? convertLegacyComparisonFilter(values, error) + : *op == "!=" ? createExpression("!", convertLegacyComparisonFilter(values, error, {"=="}), error) + : *op == "any" ? createExpression("any", convertLegacyFilterArray(values, error, 1), error) + : *op == "all" ? createExpression("all", convertLegacyFilterArray(values, error, 1), error) + : *op == "none" + ? createExpression( + "!", createExpression("any", convertLegacyFilterArray(values, error, 1), error), error) + : *op == "in" ? convertLegacyInFilter(values, error) + : *op == "!in" ? createExpression("!", convertLegacyInFilter(values, error), error) + : *op == "has" ? convertLegacyHasFilter(values, error) + : *op == "!has" ? createExpression("!", convertLegacyHasFilter(values, error), error) + : ParseResult(std::make_unique(true))}; } } diff --git a/src/mbgl/style/conversion/function.cpp b/src/mbgl/style/conversion/function.cpp index 8824aeed8fb..39a7654aec8 100644 --- a/src/mbgl/style/conversion/function.cpp +++ b/src/mbgl/style/conversion/function.cpp @@ -30,9 +30,9 @@ bool hasTokens(const std::string& source) { while (pos != end) { auto brace = std::find(pos, end, '{'); - if (brace == end) - return false; - for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++); + if (brace == end) return false; + for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++) + ; if (brace != end && *brace == '}') { return true; } @@ -41,7 +41,7 @@ bool hasTokens(const std::string& source) { return false; } - + std::unique_ptr convertTokenStringToFormatExpression(const std::string& source) { auto textExpression = convertTokenStringToExpression(source); std::vector sections{FormatExpressionSection(std::move(textExpression))}; @@ -65,7 +65,8 @@ std::unique_ptr convertTokenStringToExpression(const std::string& so } pos = brace; if (pos != end) { - for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++); + for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++) + ; if (brace != end && *brace == '}') { inputs.push_back(get(literal(std::string(pos + 1, brace)))); pos = brace + 1; @@ -77,18 +78,21 @@ std::unique_ptr convertTokenStringToExpression(const std::string& so } switch (inputs.size()) { - case 0: - return literal(source); - case 1: - return expression::dsl::toString(std::move(inputs[0])); - default: - return concat(std::move(inputs)); + case 0: + return literal(source); + case 1: + return expression::dsl::toString(std::move(inputs[0])); + default: + return concat(std::move(inputs)); } } template -std::optional> convertFunctionToExpression(const Convertible& value, Error& error, bool convertTokens) { - auto expression = convertFunctionToExpression(expression::valueTypeToExpressionType(), value, error, convertTokens); +std::optional> convertFunctionToExpression(const Convertible& value, + Error& error, + bool convertTokens) { + auto expression = convertFunctionToExpression( + expression::valueTypeToExpressionType(), value, error, convertTokens); if (!expression) { return std::nullopt; } @@ -107,64 +111,69 @@ std::optional> convertFunctionToExpression(const Convertib return PropertyExpression(std::move(*expression), defaultValue); } -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression(const Convertible&, + Error&, + bool); +template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); +convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression(const Convertible&, + Error&, + bool); +template std::optional> convertFunctionToExpression(const Convertible&, + Error&, + bool); +template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression(const Convertible&, + Error&, + bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional>> convertFunctionToExpression>( + const Convertible&, Error&, bool); +template std::optional>> convertFunctionToExpression>( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression(const Convertible&, + Error&, + bool); +template std::optional>> convertFunctionToExpression>( + const Convertible&, Error&, bool); template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); +convertFunctionToExpression>(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> - convertFunctionToExpression(const Convertible&, Error&, bool); +convertFunctionToExpression>(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression( + const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression(const Convertible&, + Error&, + bool); template std::optional>> - convertFunctionToExpression>(const Convertible&, Error&, bool); +convertFunctionToExpression>(const Convertible&, Error&, bool); template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); -template std::optional> convertFunctionToExpression(const Convertible&, Error&, bool); +template std::optional> convertFunctionToExpression(const Convertible&, + Error&, + bool); -// Ad-hoc Converters for double and int64_t. We should replace float with double wholesale, -// and promote the int64_t Converter to general use (and it should check that the input is -// an integer). +// Ad-hoc Converters for double and int64_t. We should replace float with double +// wholesale, and promote the int64_t Converter to general use (and it should +// check that the input is an integer). template <> struct Converter { std::optional operator()(const Convertible& value, Error& error) const { @@ -196,23 +205,16 @@ enum class FunctionType { }; static bool interpolatable(type::Type type) { - return type.match( - [&] (const type::NumberType&) { - return true; - }, - [&] (const type::ColorType&) { - return true; - }, - [&] (const type::Array& array) { - return array.N && array.itemType == type::Number; - }, - [&] (const auto&) { - return false; - } - ); + return type.match([&](const type::NumberType&) { return true; }, + [&](const type::ColorType&) { return true; }, + [&](const type::Array& array) { return array.N && array.itemType == type::Number; }, + [&](const auto&) { return false; }); } -static std::optional> convertLiteral(type::Type type, const Convertible& value, Error& error, bool convertTokens = false) { +static std::optional> convertLiteral(type::Type type, + const Convertible& value, + Error& error, + bool convertTokens = false) { return type.match( [&](const type::NumberType&) -> std::optional> { auto result = convert(value, error); @@ -252,7 +254,7 @@ static std::optional> convertLiteral(type::Type type return std::nullopt; } return array.itemType.match( - [&] (const type::NumberType&) -> std::optional> { + [&](const type::NumberType&) -> std::optional> { std::vector result; result.reserve(arrayLength(value)); for (std::size_t i = 0; i < arrayLength(value); ++i) { @@ -265,7 +267,7 @@ static std::optional> convertLiteral(type::Type type } return literal(result); }, - [&] (const type::StringType&) -> std::optional> { + [&](const type::StringType&) -> std::optional> { std::vector result; result.reserve(arrayLength(value)); for (std::size_t i = 0; i < arrayLength(value); ++i) { @@ -278,11 +280,10 @@ static std::optional> convertLiteral(type::Type type } return literal(result); }, - [&] (const auto&) -> std::optional> { + [&](const auto&) -> std::optional> { assert(false); // No properties use this type. return std::nullopt; - } - ); + }); }, [&](const type::NullType&) -> std::optional> { assert(false); // No properties use this type. @@ -309,9 +310,7 @@ static std::optional> convertLiteral(type::Type type if (!result) { return std::nullopt; } - return convertTokens ? - convertTokenStringToFormatExpression(*result) : - literal(Formatted(result->c_str())); + return convertTokens ? convertTokenStringToFormatExpression(*result) : literal(Formatted(result->c_str())); }, [&](const type::ImageType&) -> std::optional> { auto result = convert(value, error); @@ -324,9 +323,9 @@ static std::optional> convertLiteral(type::Type type } static std::optional>> convertStops(const type::Type& type, - const Convertible& value, - Error& error, - bool convertTokens) { + const Convertible& value, + Error& error, + bool convertTokens) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { error.message = "function value must specify stops"; @@ -362,7 +361,8 @@ static std::optional>> convertStops return std::nullopt; } - std::optional> e = convertLiteral(type, arrayMember(stopValue, 1), error, convertTokens); + std::optional> e = convertLiteral( + type, arrayMember(stopValue, 1), error, convertTokens); if (!e) { return std::nullopt; } @@ -370,7 +370,7 @@ static std::optional>> convertStops stops.emplace(*t, std::move(*e)); } - return { std::move(stops) }; + return {std::move(stops)}; } static void omitFirstStop(std::map>& stops) { @@ -386,8 +386,8 @@ static void omitFirstStop(std::map>& stops) template std::optional>> convertBranches(const type::Type& type, - const Convertible& value, - Error& error) { + const Convertible& value, + Error& error) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { error.message = "function value must specify stops"; @@ -423,7 +423,7 @@ std::optional>> convertBranches(const ty return std::nullopt; } - std::optional> e = convertLiteral(type, arrayMember(stopValue, 1), error); + std::optional> e = convertLiteral(type, arrayMember(stopValue, 1), error); if (!e) { return std::nullopt; } @@ -431,7 +431,7 @@ std::optional>> convertBranches(const ty stops.emplace(*t, std::move(*e)); } - return { std::move(stops) }; + return {std::move(stops)}; } static std::optional convertBase(const Convertible& value, Error& error) { @@ -456,7 +456,10 @@ static std::unique_ptr step(const type::Type& type, return std::make_unique(type, std::move(input), std::move(stops)); } -static std::unique_ptr interpolate(type::Type type, Interpolator interpolator, std::unique_ptr input, std::map> stops) { +static std::unique_ptr interpolate(type::Type type, + Interpolator interpolator, + std::unique_ptr input, + std::map> stops) { ParsingContext ctx; auto result = createInterpolate(std::move(type), std::move(interpolator), std::move(input), std::move(stops), ctx); if (!result) { @@ -487,21 +490,19 @@ std::unique_ptr categorical(const type::Type& type, std::map> branches, std::unique_ptr def) { auto it = branches.find(true); - std::unique_ptr trueCase = it == branches.end() ? - error("replaced with default") : - std::move(it->second); + std::unique_ptr trueCase = it == branches.end() ? error("replaced with default") + : std::move(it->second); it = branches.find(false); - std::unique_ptr falseCase = it == branches.end() ? - error("replaced with default") : - std::move(it->second); + std::unique_ptr falseCase = it == branches.end() ? error("replaced with default") + : std::move(it->second); std::vector convertedBranches; convertedBranches.emplace_back(eq(get(literal(property)), literal(Value(true))), std::move(trueCase)); convertedBranches.emplace_back(eq(get(literal(property)), literal(Value(false))), std::move(falseCase)); - return std::make_unique(type, std::move(convertedBranches), - def ? std::move(def) : error("replaced with default")); + return std::make_unique( + type, std::move(convertedBranches), def ? std::move(def) : error("replaced with default")); } static std::unique_ptr numberOrDefault(const type::Type& type, @@ -513,8 +514,7 @@ static std::unique_ptr numberOrDefault(const type::Type& type, } std::vector branches; - branches.emplace_back(eq(compound("typeof", std::move(get)), literal("number")), - std::move(expr)); + branches.emplace_back(eq(compound("typeof", std::move(get)), literal("number")), std::move(expr)); return std::make_unique(type, std::move(branches), std::move(def)); } @@ -531,10 +531,7 @@ static std::optional> convertIntervalFunction( } omitFirstStop(*stops); - return numberOrDefault(type, - makeInput(false), - step(type, makeInput(true), std::move(*stops)), - std::move(def)); + return numberOrDefault(type, makeInput(false), step(type, makeInput(true), std::move(*stops)), std::move(def)); } static std::optional> convertExponentialFunction( @@ -560,10 +557,10 @@ static std::optional> convertExponentialFunction( } static std::optional> convertCategoricalFunction(const type::Type& type, - const Convertible& value, - Error& err, - const std::string& property, - std::unique_ptr def) { + const Convertible& value, + Error& err, + const std::string& property, + std::unique_ptr def) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { err.message = "function value must specify stops"; @@ -622,9 +619,9 @@ static std::optional> convertCategoricalFunction(con template std::optional> composite(type::Type type, - const Convertible& value, - Error& error, - const Fn& makeInnerExpression) { + const Convertible& value, + Error& error, + const Fn& makeInnerExpression) { auto base = convertBase(value, error); if (!base) { return std::nullopt; @@ -702,9 +699,9 @@ std::optional> composite(type::Type type, } std::optional> convertFunctionToExpression(type::Type type, - const Convertible& value, - Error& err, - bool convertTokens) { + const Convertible& value, + Error& err, + bool convertTokens) { if (!isObject(value)) { err.message = "function must be an object"; return std::nullopt; @@ -718,14 +715,10 @@ std::optional> convertFunctionToExpression(type::Typ } else { auto string = toString(*typeValue); if (string) { - if (*string == "interval") - functionType = FunctionType::Interval; - if (*string == "exponential" && interpolatable(type)) - functionType = FunctionType::Exponential; - if (*string == "categorical") - functionType = FunctionType::Categorical; - if (*string == "identity") - functionType = FunctionType::Identity; + if (*string == "interval") functionType = FunctionType::Interval; + if (*string == "exponential" && interpolatable(type)) functionType = FunctionType::Exponential; + if (*string == "categorical") functionType = FunctionType::Categorical; + if (*string == "identity") functionType = FunctionType::Identity; } } @@ -743,13 +736,15 @@ std::optional> convertFunctionToExpression(type::Typ if (!objectMember(value, "property")) { // Camera function. switch (functionType) { - case FunctionType::Interval: - return convertIntervalFunction(type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens); - case FunctionType::Exponential: - return convertExponentialFunction(type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Interval: + return convertIntervalFunction( + type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens); + case FunctionType::Exponential: + return convertExponentialFunction( + type, value, err, [](bool) { return zoom(); }, defaultExpr(), convertTokens); + default: + err.message = "unsupported function type"; + return std::nullopt; } } @@ -835,15 +830,15 @@ std::optional> convertFunctionToExpression(type::Typ if (!isObject(stop)) { // Source function. switch (functionType) { - case FunctionType::Interval: - return convertIntervalFunction(type, value, err, getProperty, defaultExpr()); - case FunctionType::Exponential: - return convertExponentialFunction(type, value, err, getProperty, defaultExpr()); - case FunctionType::Categorical: - return convertCategoricalFunction(type, value, err, *property, defaultExpr()); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Interval: + return convertIntervalFunction(type, value, err, getProperty, defaultExpr()); + case FunctionType::Exponential: + return convertExponentialFunction(type, value, err, getProperty, defaultExpr()); + case FunctionType::Categorical: + return convertCategoricalFunction(type, value, err, *property, defaultExpr()); + default: + err.message = "unsupported function type"; + return std::nullopt; } } else { // Composite function. @@ -855,71 +850,73 @@ std::optional> convertFunctionToExpression(type::Typ if (toBool(*sourceValue)) { switch (functionType) { - case FunctionType::Categorical: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - return categorical(type_, *property, std::move(stops), defaultExpr()); - }); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Categorical: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + return categorical(type_, *property, std::move(stops), defaultExpr()); + }); + default: + err.message = "unsupported function type"; + return std::nullopt; } } if (toNumber(*sourceValue)) { switch (functionType) { - case FunctionType::Interval: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - omitFirstStop(stops); - return numberOrDefault( - type, getProperty(false), step(type_, getProperty(true), std::move(stops)), defaultExpr()); - }); - case FunctionType::Exponential: - return composite( - type, - value, - err, - [&](type::Type type_, double base, std::map> stops) { - return numberOrDefault( - type, - getProperty(false), - interpolate(std::move(type_), exponential(base), getProperty(true), std::move(stops)), - defaultExpr()); - }); - case FunctionType::Categorical: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - return categorical(type_, *property, std::move(stops), defaultExpr()); - }); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Interval: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + omitFirstStop(stops); + return numberOrDefault(type, + getProperty(false), + step(type_, getProperty(true), std::move(stops)), + defaultExpr()); + }); + case FunctionType::Exponential: + return composite( + type, + value, + err, + [&](type::Type type_, double base, std::map> stops) { + return numberOrDefault( + type, + getProperty(false), + interpolate(std::move(type_), exponential(base), getProperty(true), std::move(stops)), + defaultExpr()); + }); + case FunctionType::Categorical: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + return categorical(type_, *property, std::move(stops), defaultExpr()); + }); + default: + err.message = "unsupported function type"; + return std::nullopt; } } if (toString(*sourceValue)) { switch (functionType) { - case FunctionType::Categorical: - return composite( - type, - value, - err, - [&](const type::Type& type_, double, std::map> stops) { - return categorical(type_, *property, std::move(stops), defaultExpr()); - }); - default: - err.message = "unsupported function type"; - return std::nullopt; + case FunctionType::Categorical: + return composite( + type, + value, + err, + [&](const type::Type& type_, double, std::map> stops) { + return categorical(type_, *property, std::move(stops), defaultExpr()); + }); + default: + err.message = "unsupported function type"; + return std::nullopt; } } diff --git a/src/mbgl/style/conversion/geojson_options.cpp b/src/mbgl/style/conversion/geojson_options.cpp index 6aad28d15ac..7a7ceb97df3 100644 --- a/src/mbgl/style/conversion/geojson_options.cpp +++ b/src/mbgl/style/conversion/geojson_options.cpp @@ -8,8 +8,7 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, - Error& error) const { +std::optional Converter::operator()(const Convertible& value, Error& error) const { GeoJSONOptions options; const auto minzoomValue = objectMember(value, "minzoom"); @@ -100,58 +99,63 @@ std::optional Converter::operator()(const Conver } GeoJSONOptions::ClusterProperties result; assert(error.message.empty()); - eachMember( - *clusterProperties, - [&](const std::string& k, - const mbgl::style::conversion::Convertible& v) -> std::optional { - // Each property shall be formed as ["key" : [operator, [mapExpression]]] - // or ["key" : [[operator, ['accumulated'], ['get', key]], [mapExpression]]] - if (!isArray(v) || arrayLength(v) != 2) { - error.message = - "GeoJSON source clusterProperties member must be an array with length of 2"; - return std::nullopt; - } - auto map = expression::dsl::createExpression(arrayMember(v, 1)); - if (!map) { - error.message = - "Failed to convert GeoJSON source clusterProperties map expression"; - return std::nullopt; - } - std::unique_ptr reduce; - if (isArray(arrayMember(v, 0))) { - reduce = expression::dsl::createExpression(arrayMember(v, 0)); - } else { - auto reduceOp = toString(arrayMember(v, 0)); - if (!reduceOp) { - error.message = - "GeoJSON source clusterProperties member must contain a valid operator"; - return std::nullopt; - } - std::stringstream ss; - // Reformulate reduce expression to [operator, ['accumulated'], ['get', key]] - // The reason to create expression via parsing string instead of invoking function - // createCompoundExpression is due to expression type disunity can’t be resolved - // with current logic of createCompoundExpression - ss << std::string(R"([")") << *reduceOp - << std::string(R"(", ["accumulated"], ["get", ")") << k - << std::string(R"("]])"); - reduce = expression::dsl::createExpression(ss.str().c_str()); - } - if (!reduce) { - error.message = - "Failed to convert GeoJSON source clusterProperties reduce expression"; - return std::nullopt; - } - result.emplace(k, std::make_pair(std::move(map), std::move(reduce))); - return std::nullopt; - }); + eachMember(*clusterProperties, + [&](const std::string& k, + const mbgl::style::conversion::Convertible& v) -> std::optional { + // Each property shall be formed as ["key" : [operator, + // [mapExpression]]] or ["key" : [[operator, ['accumulated'], + // ['get', key]], [mapExpression]]] + if (!isArray(v) || arrayLength(v) != 2) { + error.message = + "GeoJSON source clusterProperties member must be an " + "array with length of 2"; + return std::nullopt; + } + auto map = expression::dsl::createExpression(arrayMember(v, 1)); + if (!map) { + error.message = + "Failed to convert GeoJSON source clusterProperties " + "map expression"; + return std::nullopt; + } + std::unique_ptr reduce; + if (isArray(arrayMember(v, 0))) { + reduce = expression::dsl::createExpression(arrayMember(v, 0)); + } else { + auto reduceOp = toString(arrayMember(v, 0)); + if (!reduceOp) { + error.message = + "GeoJSON source clusterProperties member must " + "contain a valid operator"; + return std::nullopt; + } + std::stringstream ss; + // Reformulate reduce expression to [operator, + // ['accumulated'], ['get', key]] The reason to create + // expression via parsing string instead of invoking + // function createCompoundExpression is due to expression + // type disunity can’t be resolved with current logic of + // createCompoundExpression + ss << std::string(R"([")") << *reduceOp << std::string(R"(", ["accumulated"], ["get", ")") + << k << std::string(R"("]])"); + reduce = expression::dsl::createExpression(ss.str().c_str()); + } + if (!reduce) { + error.message = + "Failed to convert GeoJSON source clusterProperties " + "reduce expression"; + return std::nullopt; + } + result.emplace(k, std::make_pair(std::move(map), std::move(reduce))); + return std::nullopt; + }); if (!error.message.empty()) { return std::nullopt; } options.clusterProperties = std::move(result); } - return { std::move(options) }; + return {std::move(options)}; } } // namespace conversion diff --git a/src/mbgl/style/conversion/json.hpp b/src/mbgl/style/conversion/json.hpp index f10da67abf4..f9858b017e7 100644 --- a/src/mbgl/style/conversion/json.hpp +++ b/src/mbgl/style/conversion/json.hpp @@ -9,13 +9,13 @@ namespace mbgl { namespace style { namespace conversion { -template -std::optional convertJSON(const std::string& json, Error& error, Args&&...args) { +template +std::optional convertJSON(const std::string& json, Error& error, Args&&... args) { JSDocument document; document.Parse<0>(json.c_str()); if (document.HasParseError()) { - error = { formatJSONParseError(document) }; + error = {formatJSONParseError(document)}; return {}; } diff --git a/src/mbgl/style/conversion/layer.cpp b/src/mbgl/style/conversion/layer.cpp index 8842cc2ac11..71dbf83766f 100644 --- a/src/mbgl/style/conversion/layer.cpp +++ b/src/mbgl/style/conversion/layer.cpp @@ -27,12 +27,13 @@ std::optional setPaintProperties(Layer& layer, const Convertible& value) return std::nullopt; } if (!isObject(*paintValue)) { - return { { "paint must be an object" } }; + return {{"paint must be an object"}}; } return eachMember(*paintValue, [&](const std::string& k, const Convertible& v) { return layer.setProperty(k, v); }); } -std::optional> Converter>::operator()(const Convertible& value, Error& error) const { +std::optional> Converter>::operator()(const Convertible& value, + Error& error) const { if (!isObject(value)) { error.message = "layer must be an object"; return std::nullopt; @@ -78,8 +79,8 @@ std::optional> Converter>::operato error.message = "layout must be an object"; return std::nullopt; } - auto error_ = eachMember( - *layoutValue, [&](const std::string& k, const Convertible& v) { return layer->setProperty(k, v); }); + auto error_ = eachMember(*layoutValue, + [&](const std::string& k, const Convertible& v) { return layer->setProperty(k, v); }); if (error_) { error = *error_; return std::nullopt; diff --git a/src/mbgl/style/conversion/light.cpp b/src/mbgl/style/conversion/light.cpp index e003ea05279..33759b57ad1 100644 --- a/src/mbgl/style/conversion/light.cpp +++ b/src/mbgl/style/conversion/light.cpp @@ -99,7 +99,7 @@ std::optional Converter::operator()(const Convertible& value, Erro } } - return { std::move(light) }; + return {std::move(light)}; } } // namespace conversion diff --git a/src/mbgl/style/conversion/property_value.cpp b/src/mbgl/style/conversion/property_value.cpp index 2357a304083..e7cac3b4221 100644 --- a/src/mbgl/style/conversion/property_value.cpp +++ b/src/mbgl/style/conversion/property_value.cpp @@ -8,7 +8,10 @@ namespace style { namespace conversion { template -std::optional> Converter>::operator()(const Convertible& value, Error& error, bool allowDataExpressions, bool convertTokens) const { +std::optional> Converter>::operator()(const Convertible& value, + Error& error, + bool allowDataExpressions, + bool convertTokens) const { using namespace mbgl::style::expression; if (isUndefined(value)) { @@ -42,7 +45,7 @@ std::optional> Converter>::operator()(const Co return std::nullopt; } else if (!(*expression).isFeatureConstant() || !(*expression).isZoomConstant() || !(*expression).isRuntimeConstant()) { - return { std::move(*expression) }; + return {std::move(*expression)}; } else if ((*expression).getExpression().getKind() == Kind::Literal) { std::optional constant = fromExpressionValue( static_cast((*expression).getExpression()).getValue()); @@ -57,32 +60,79 @@ std::optional> Converter>::operator()(const Co } } -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; -template std::optional>> Converter>>::operator()(conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; +template std::optional> Converter>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; +template std::optional>> Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional>> Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional>> Converter>>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional>> +Converter>>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> +Converter>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional>> +Converter>>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> Converter>::operator()( + conversion::Convertible const&, conversion::Error&, bool, bool) const; +template std::optional> +Converter>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; +template std::optional>> +Converter>>::operator()(conversion::Convertible const&, + conversion::Error&, + bool, + bool) const; template std::optional> Converter>::operator()(conversion::Convertible const&, conversion::Error&, diff --git a/src/mbgl/style/conversion/source.cpp b/src/mbgl/style/conversion/source.cpp index 55223a2a9a7..75c22c84928 100644 --- a/src/mbgl/style/conversion/source.cpp +++ b/src/mbgl/style/conversion/source.cpp @@ -23,7 +23,7 @@ static std::optional> convertURLOrTileset(const Co if (!tileset) { return std::nullopt; } - return { *tileset }; + return {*tileset}; } std::optional url = toString(*urlVal); @@ -32,12 +32,12 @@ static std::optional> convertURLOrTileset(const Co return std::nullopt; } - return { *url }; + return {*url}; } static std::optional> convertRasterSource(const std::string& id, - const Convertible& value, - Error& error) { + const Convertible& value, + Error& error) { std::optional> urlOrTileset = convertURLOrTileset(value, error); if (!urlOrTileset) { return std::nullopt; @@ -54,12 +54,12 @@ static std::optional> convertRasterSource(const std::str tileSize = static_cast(*size); } - return { std::make_unique(id, std::move(*urlOrTileset), tileSize) }; + return {std::make_unique(id, std::move(*urlOrTileset), tileSize)}; } static std::optional> convertRasterDEMSource(const std::string& id, - const Convertible& value, - Error& error) { + const Convertible& value, + Error& error) { std::optional> urlOrTileset = convertURLOrTileset(value, error); if (!urlOrTileset) { return std::nullopt; @@ -76,12 +76,12 @@ static std::optional> convertRasterDEMSource(const std:: tileSize = static_cast(*size); } - return { std::make_unique(id, std::move(*urlOrTileset), tileSize) }; + return {std::make_unique(id, std::move(*urlOrTileset), tileSize)}; } static std::optional> convertVectorSource(const std::string& id, - const Convertible& value, - Error& error) { + const Convertible& value, + Error& error) { std::optional> urlOrTileset = convertURLOrTileset(value, error); if (!urlOrTileset) { return std::nullopt; @@ -108,8 +108,8 @@ static std::optional> convertVectorSource(const std::str } static std::optional> convertGeoJSONSource(const std::string& id, - const Convertible& value, - Error& error) { + const Convertible& value, + Error& error) { auto dataValue = objectMember(value, "data"); if (!dataValue) { error.message = "GeoJSON source must have a data value"; @@ -136,12 +136,12 @@ static std::optional> convertGeoJSONSource(const std::st return std::nullopt; } - return { std::move(result) }; + return {std::move(result)}; } static std::optional> convertImageSource(const std::string& id, - const Convertible& value, - Error& error) { + const Convertible& value, + Error& error) { auto urlValue = objectMember(value, "url"); if (!urlValue) { error.message = "Image source must have a url value"; @@ -161,13 +161,15 @@ static std::optional> convertImageSource(const std::stri } if (!isArray(*coordinatesValue) || arrayLength(*coordinatesValue) != 4) { - error.message = "Image coordinates must be an array of four longitude latitude pairs"; + error.message = + "Image coordinates must be an array of four longitude latitude " + "pairs"; return std::nullopt; } std::array coordinates; - for (std::size_t i=0; i < 4; i++) { - auto latLng = conversion::convert(arrayMember(*coordinatesValue,i), error); + for (std::size_t i = 0; i < 4; i++) { + auto latLng = conversion::convert(arrayMember(*coordinatesValue, i), error); if (!latLng) { return std::nullopt; } @@ -176,10 +178,12 @@ static std::optional> convertImageSource(const std::stri auto result = std::make_unique(id, coordinates); result->setURL(*urlString); - return { std::move(result) }; + return {std::move(result)}; } -std::optional> Converter>::operator()(const Convertible& value, Error& error, const std::string& id) const { +std::optional> Converter>::operator()(const Convertible& value, + Error& error, + const std::string& id) const { if (!isObject(value)) { error.message = "source must be an object"; return std::nullopt; diff --git a/src/mbgl/style/conversion/stringify.hpp b/src/mbgl/style/conversion/stringify.hpp index b3072b4dbac..cd7c968b58f 100644 --- a/src/mbgl/style/conversion/stringify.hpp +++ b/src/mbgl/style/conversion/stringify.hpp @@ -109,39 +109,40 @@ void stringify(Writer& writer, const std::unordered_map& m) { template void stringify(Writer& writer, const Value& v) { - Value::visit(v, [&] (const auto& v_) { stringify(writer, v_); }); + Value::visit(v, [&](const auto& v_) { stringify(writer, v_); }); } template void stringify(Writer& writer, FeatureType type) { switch (type) { - case FeatureType::Unknown: - writer.String("Unknown"); - break; - case FeatureType::Point: - writer.String("Point"); - break; - case FeatureType::LineString: - writer.String("LineString"); - break; - case FeatureType::Polygon: - writer.String("Polygon"); - break; + case FeatureType::Unknown: + writer.String("Unknown"); + break; + case FeatureType::Point: + writer.String("Point"); + break; + case FeatureType::LineString: + writer.String("LineString"); + break; + case FeatureType::Polygon: + writer.String("Polygon"); + break; } } template void stringify(Writer& writer, const FeatureIdentifier& id) { - FeatureIdentifier::visit(id, [&] (const auto& id_) { stringify(writer, id_); }); + FeatureIdentifier::visit(id, [&](const auto& id_) { stringify(writer, id_); }); } template void stringify(Writer& writer, const Filter& filter) { - if (!filter.expression) writer.Null(); - else stringify(writer, (*filter.expression)->serialize()); + if (!filter.expression) + writer.Null(); + else + stringify(writer, (*filter.expression)->serialize()); } - - + template void stringify(Writer& writer, const expression::Formatted& v) { // Convert to mbgl::Value and then use the existing stringify @@ -168,7 +169,7 @@ void stringify(Writer& writer, const PropertyExpression& fn) { template void stringify(Writer& writer, const PropertyValue& v) { - v.evaluate([&] (const auto& v_) { stringify(writer, v_); }); + v.evaluate([&](const auto& v_) { stringify(writer, v_); }); } template diff --git a/src/mbgl/style/conversion/tileset.cpp b/src/mbgl/style/conversion/tileset.cpp index a64f2f9617f..417842f0f4a 100644 --- a/src/mbgl/style/conversion/tileset.cpp +++ b/src/mbgl/style/conversion/tileset.cpp @@ -44,7 +44,9 @@ std::optional Converter::operator()(const Convertible& value, if (encoding && *encoding == "terrarium") { result.encoding = Tileset::DEMEncoding::Terrarium; } else if (encoding && *encoding != "mapbox") { - error.message = "invalid raster-dem encoding type - valid types are 'mapbox' and 'terrarium' "; + error.message = + "invalid raster-dem encoding type - valid types are 'mapbox' " + "and 'terrarium' "; } } @@ -81,7 +83,9 @@ std::optional Converter::operator()(const Convertible& value, auto boundsValue = objectMember(value, "bounds"); if (boundsValue) { if (!isArray(*boundsValue) || arrayLength(*boundsValue) != 4) { - error.message = "bounds must be an array with left, bottom, top, and right values"; + error.message = + "bounds must be an array with left, bottom, top, and right " + "values"; return std::nullopt; } std::optional left = toDouble(arrayMember(*boundsValue, 0)); @@ -90,24 +94,30 @@ std::optional Converter::operator()(const Convertible& value, std::optional top = toDouble(arrayMember(*boundsValue, 3)); if (!left || !right || !bottom || !top) { - error.message = "bounds array must contain numeric longitude and latitude values"; + error.message = + "bounds array must contain numeric longitude and latitude " + "values"; return std::nullopt; } bottom = util::clamp(*bottom, -90.0, 90.0); top = util::clamp(*top, -90.0, 90.0); - if (*top < *bottom){ - error.message = "bounds bottom latitude must be less than or equal to top latitude"; + if (*top < *bottom) { + error.message = + "bounds bottom latitude must be less than or equal to top " + "latitude"; return std::nullopt; } - if(*left > *right) { - error.message = "bounds left longitude must be less than or equal to right longitude"; + if (*left > *right) { + error.message = + "bounds left longitude must be less than or equal to right " + "longitude"; return std::nullopt; } left = util::max(-180.0, *left); right = util::min(180.0, *right); - result.bounds = LatLngBounds::hull({ *bottom, *left }, { *top, *right }); + result.bounds = LatLngBounds::hull({*bottom, *left}, {*top, *right}); } return result; diff --git a/src/mbgl/style/conversion/transition_options.cpp b/src/mbgl/style/conversion/transition_options.cpp index f41e138006a..69d39eac073 100644 --- a/src/mbgl/style/conversion/transition_options.cpp +++ b/src/mbgl/style/conversion/transition_options.cpp @@ -5,7 +5,8 @@ namespace mbgl { namespace style { namespace conversion { -std::optional Converter::operator()(const Convertible& value, Error& error) const { +std::optional Converter::operator()(const Convertible& value, + Error& error) const { if (!isObject(value)) { error.message = "transition must be an object"; return std::nullopt; @@ -20,7 +21,7 @@ std::optional Converter::operator()(const error.message = "duration must be a number"; return std::nullopt; } - result->duration = { std::chrono::milliseconds(int64_t(*number)) }; + result->duration = {std::chrono::milliseconds(int64_t(*number))}; } auto delay = objectMember(value, "delay"); @@ -30,7 +31,7 @@ std::optional Converter::operator()(const error.message = "delay must be a number"; return std::nullopt; } - result->delay = { std::chrono::milliseconds(int64_t(*number)) }; + result->delay = {std::chrono::milliseconds(int64_t(*number))}; } return result; diff --git a/src/mbgl/style/custom_tile_loader.cpp b/src/mbgl/style/custom_tile_loader.cpp index eb17640dc89..a86635e4a73 100644 --- a/src/mbgl/style/custom_tile_loader.cpp +++ b/src/mbgl/style/custom_tile_loader.cpp @@ -19,10 +19,10 @@ void CustomTileLoader::fetchTile(const OverscaledTileID& tileID, const ActorRef< auto tileCallbacks = tileCallbackMap.find(tileID.canonical); if (tileCallbacks == tileCallbackMap.end()) { auto tuple = std::make_tuple(tileID.overscaledZ, tileID.wrap, tileRef); - tileCallbackMap.insert({ tileID.canonical, std::vector(1, tuple) }); + tileCallbackMap.insert({tileID.canonical, std::vector(1, tuple)}); } else { for (auto& iter : tileCallbacks->second) { - if (std::get<0>(iter) == tileID.overscaledZ && std::get<1>(iter) == tileID.wrap ) { + if (std::get<0>(iter) == tileID.overscaledZ && std::get<1>(iter) == tileID.wrap) { std::get<2>(iter) = tileRef; return; } @@ -46,7 +46,7 @@ void CustomTileLoader::removeTile(const OverscaledTileID& tileID) { auto tileCallbacks = tileCallbackMap.find(tileID.canonical); if (tileCallbacks == tileCallbackMap.end()) return; for (auto iter = tileCallbacks->second.begin(); iter != tileCallbacks->second.end(); iter++) { - if (std::get<0>(*iter) == tileID.overscaledZ && std::get<1>(*iter) == tileID.wrap ) { + if (std::get<0>(*iter) == tileID.overscaledZ && std::get<1>(*iter) == tileID.wrap) { tileCallbacks->second.erase(iter); invokeTileCancel(tileID.canonical); break; @@ -73,7 +73,9 @@ void CustomTileLoader::setTileData(const CanonicalTileID& tileID, const GeoJSON& void CustomTileLoader::invalidateTile(const CanonicalTileID& tileID) { std::lock_guard guard(dataMutex); auto tileCallbacks = tileCallbackMap.find(tileID); - if (tileCallbacks == tileCallbackMap.end()) { return; } + if (tileCallbacks == tileCallbackMap.end()) { + return; + } for (auto& iter : tileCallbacks->second) { auto actor = std::get<2>(iter); actor.invoke(&CustomGeometryTile::invalidateTileData); @@ -83,13 +85,13 @@ void CustomTileLoader::invalidateTile(const CanonicalTileID& tileID) { dataCache.erase(tileID); } -void CustomTileLoader::invalidateRegion(const LatLngBounds& bounds, Range ) { +void CustomTileLoader::invalidateRegion(const LatLngBounds& bounds, Range) { std::lock_guard guard(dataMutex); std::map tileRanges; for (auto& idtuple : tileCallbackMap) { auto zoom = idtuple.first.z; auto tileRange = tileRanges.find(zoom); - if(tileRange == tileRanges.end()) { + if (tileRange == tileRanges.end()) { tileRange = tileRanges.emplace(std::make_pair(zoom, util::TileRange::fromLatLngBounds(bounds, zoom))).first; } if (tileRange->second.contains(idtuple.first)) { diff --git a/src/mbgl/style/expression/assertion.cpp b/src/mbgl/style/expression/assertion.cpp index 982557aed9c..3dfa71ddf96 100644 --- a/src/mbgl/style/expression/assertion.cpp +++ b/src/mbgl/style/expression/assertion.cpp @@ -10,7 +10,8 @@ namespace expression { using namespace mbgl::style::conversion; Assertion::Assertion(type::Type type_, std::vector> inputs_) - : Expression(Kind::Assertion, std::move(type_)), inputs(std::move(inputs_)) { + : Expression(Kind::Assertion, std::move(type_)), + inputs(std::move(inputs_)) { assert(!inputs.empty()); } @@ -39,10 +40,7 @@ ParseResult Assertion::parse(const Convertible& value, ParsingContext& ctx) { std::optional itemTypeName = toString(arrayMember(value, 1)); auto it = itemTypeName ? types.find(*itemTypeName) : types.end(); if (it == types.end() || it->second == type::Object) { - ctx.error( - R"(The item type argument of "array" must be one of string, number, boolean)", - 1 - ); + ctx.error(R"(The item type argument of "array" must be one of string, number, boolean)", 1); return ParseResult(); } itemType = it->second; @@ -55,12 +53,8 @@ ParseResult Assertion::parse(const Convertible& value, ParsingContext& ctx) { if (length > 3) { auto m = arrayMember(value, 2); std::optional n = toNumber(m); - if (!isUndefined(m) && - (!n || *n < 0 || *n != std::floor(*n))) { - ctx.error( - R"(The length argument to "array" must be a positive integer literal.)", - 2 - ); + if (!isUndefined(m) && (!n || *n < 0 || *n != std::floor(*n))) { + ctx.error(R"(The length argument to "array" must be a positive integer literal.)", 2); return ParseResult(); } if (n) { @@ -96,19 +90,17 @@ EvaluationResult Assertion::evaluate(const EvaluationContext& params) const { if (!type::checkSubtype(getType(), typeOf(*value))) { return value; } else if (i == inputs.size() - 1) { - return EvaluationError { - "Expected value to be of type " + toString(getType()) + - ", but found " + toString(typeOf(*value)) + " instead." - }; + return EvaluationError{"Expected value to be of type " + toString(getType()) + ", but found " + + toString(typeOf(*value)) + " instead."}; } } assert(false); - return EvaluationError { "Unreachable" }; + return EvaluationError{"Unreachable"}; }; void Assertion::eachChild(const std::function& visit) const { - for(const std::unique_ptr& input : inputs) { + for (const std::unique_ptr& input : inputs) { visit(*input); } }; @@ -137,9 +129,8 @@ mbgl::Value Assertion::serialize() const { if (getType().is()) { const auto array = getType().get(); - if (array.itemType.is() - || array.itemType.is() - || array.itemType.is()) { + if (array.itemType.is() || array.itemType.is() || + array.itemType.is()) { serialized.emplace_back(type::toString(array.itemType)); if (array.N) { serialized.emplace_back(uint64_t(*array.N)); @@ -159,5 +150,3 @@ mbgl::Value Assertion::serialize() const { } // namespace expression } // namespace style } // namespace mbgl - - diff --git a/src/mbgl/style/expression/at.cpp b/src/mbgl/style/expression/at.cpp index 648f247830f..03112221e4f 100644 --- a/src/mbgl/style/expression/at.cpp +++ b/src/mbgl/style/expression/at.cpp @@ -2,7 +2,6 @@ #include #include - namespace mbgl { namespace style { namespace expression { @@ -16,26 +15,20 @@ EvaluationResult At::evaluate(const EvaluationContext& params) const { if (!evaluatedInput) { return evaluatedInput.error(); } - + const auto i = evaluatedIndex->get(); const auto inputArray = evaluatedInput->get>(); - + if (i < 0) { - return EvaluationError { - "Array index out of bounds: " + util::toString(i) + " < 0." - }; + return EvaluationError{"Array index out of bounds: " + util::toString(i) + " < 0."}; } - + if (i >= inputArray.size()) { - return EvaluationError { - "Array index out of bounds: " + util::toString(i) + - " > " + util::toString(inputArray.size() - 1) + "." - }; + return EvaluationError{"Array index out of bounds: " + util::toString(i) + " > " + + util::toString(inputArray.size() - 1) + "."}; } if (i != std::floor(i)) { - return EvaluationError { - "Array index must be an integer, but found " + util::toString(i) + " instead." - }; + return EvaluationError{"Array index must be an integer, but found " + util::toString(i) + " instead."}; } return inputArray[static_cast(i)]; } @@ -56,14 +49,13 @@ ParseResult At::parse(const Convertible& value, ParsingContext& ctx) { } ParseResult index = ctx.parse(arrayMember(value, 1), 1, {type::Number}); - + type::Type inputType = type::Array(ctx.getExpected() ? *ctx.getExpected() : type::Value); ParseResult input = ctx.parse(arrayMember(value, 2), 2, {inputType}); if (!index || !input) return ParseResult(); return ParseResult(std::make_unique(std::move(*index), std::move(*input))); - } } // namespace expression diff --git a/src/mbgl/style/expression/boolean_operator.cpp b/src/mbgl/style/expression/boolean_operator.cpp index 37ebc02c7b4..ea2a75af15a 100644 --- a/src/mbgl/style/expression/boolean_operator.cpp +++ b/src/mbgl/style/expression/boolean_operator.cpp @@ -29,10 +29,9 @@ bool Any::operator==(const Expression& e) const { } std::vector> Any::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } - EvaluationResult All::evaluate(const EvaluationContext& params) const { for (const auto& input : inputs) { EvaluationResult result = input->evaluate(params); @@ -57,29 +56,28 @@ bool All::operator==(const Expression& e) const { } std::vector> All::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } using namespace mbgl::style::conversion; template ParseResult parseBooleanOp(const Convertible& value, ParsingContext& ctx) { - assert(isArray(value)); auto length = arrayLength(value); - + std::vector> parsedInputs; - + parsedInputs.reserve(length - 1); for (std::size_t i = 1; i < length; i++) { auto parsed = ctx.parse(arrayMember(value, i), i, {type::Boolean}); if (!parsed) { return parsed; } - + parsedInputs.push_back(std::move(*parsed)); } - + return ParseResult(std::make_unique(std::move(parsedInputs))); } @@ -91,8 +89,6 @@ ParseResult All::parse(const Convertible& value, ParsingContext& ctx) { return parseBooleanOp(value, ctx); } - } // namespace expression } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/case.cpp b/src/mbgl/style/expression/case.cpp index e8e7c64b7cf..90818a3d950 100644 --- a/src/mbgl/style/expression/case.cpp +++ b/src/mbgl/style/expression/case.cpp @@ -16,7 +16,7 @@ EvaluationResult Case::evaluate(const EvaluationContext& params) const { return branch.second->evaluate(params); } } - + return otherwise->evaluate(params); } @@ -81,7 +81,7 @@ ParseResult Case::parse(const Convertible& value, ParsingContext& ctx) { if (!output) { return output; } - + if (!outputType) { outputType = (*output)->getType(); } @@ -96,9 +96,7 @@ ParseResult Case::parse(const Convertible& value, ParsingContext& ctx) { return otherwise; } - return ParseResult(std::make_unique(*outputType, - std::move(branches), - std::move(*otherwise))); + return ParseResult(std::make_unique(*outputType, std::move(branches), std::move(*otherwise))); } } // namespace expression diff --git a/src/mbgl/style/expression/check_subtype.cpp b/src/mbgl/style/expression/check_subtype.cpp index 9f868676505..356c9061bbf 100644 --- a/src/mbgl/style/expression/check_subtype.cpp +++ b/src/mbgl/style/expression/check_subtype.cpp @@ -12,9 +12,9 @@ std::string errorMessage(const Type& expected, const Type& t) { std::optional checkSubtype(const Type& expected, const Type& t) { if (t.is()) return {}; - + std::optional result = expected.match( - [&] (const Array& expectedArray) -> std::optional { + [&](const Array& expectedArray) -> std::optional { if (!t.is()) { return {errorMessage(expected, t)}; } @@ -22,15 +22,15 @@ std::optional checkSubtype(const Type& expected, const Type& t) { if (!actualArray.N || *actualArray.N != 0 || actualArray.itemType != type::Value) { const auto err = checkSubtype(expectedArray.itemType, actualArray.itemType); if (err) { - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; } } if (expectedArray.N && expectedArray.N != actualArray.N) { - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; } return {}; }, - [&] (const ValueType&) -> std::optional { + [&](const ValueType&) -> std::optional { if (t.is()) return {}; const Type members[] = {Null, Boolean, Number, String, Object, Color, Formatted, Image, Array(Value)}; @@ -41,16 +41,15 @@ std::optional checkSubtype(const Type& expected, const Type& t) { return {}; } } - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; }, - [&] (const auto&) -> std::optional { + [&](const auto&) -> std::optional { if (expected != t) { - return { errorMessage(expected, t) }; + return {errorMessage(expected, t)}; } return {}; - } - ); - + }); + return result; } diff --git a/src/mbgl/style/expression/coalesce.cpp b/src/mbgl/style/expression/coalesce.cpp index 71cb9ae0ed4..aff148c24b9 100644 --- a/src/mbgl/style/expression/coalesce.cpp +++ b/src/mbgl/style/expression/coalesce.cpp @@ -61,7 +61,7 @@ ParseResult Coalesce::parse(const Convertible& value, ParsingContext& ctx) { ctx.error("Expected at least one argument."); return ParseResult(); } - + std::optional outputType; std::optional expectedType = ctx.getExpected(); if (expectedType && *expectedType != type::Value) { @@ -87,10 +87,9 @@ ParseResult Coalesce::parse(const Convertible& value, ParsingContext& ctx) { // preempt the desired null-coalescing behavior. // Thus, if any of our arguments would have needed an annotation, we // need to wrap the enclosing coalesce expression with it instead. - bool needsAnnotation = expectedType && - std::any_of(args.begin(), args.end(), [&] (const auto& arg) { - return type::checkSubtype(*expectedType, arg->getType()); - }); + bool needsAnnotation = expectedType && std::any_of(args.begin(), args.end(), [&](const auto& arg) { + return type::checkSubtype(*expectedType, arg->getType()); + }); return ParseResult(std::make_unique(needsAnnotation ? type::Value : *outputType, std::move(args))); } diff --git a/src/mbgl/style/expression/coercion.cpp b/src/mbgl/style/expression/coercion.cpp index e04a86d0383..0236b8eefb1 100644 --- a/src/mbgl/style/expression/coercion.cpp +++ b/src/mbgl/style/expression/coercion.cpp @@ -18,39 +18,31 @@ EvaluationResult toBoolean(const Value& v) { } EvaluationResult toNumber(const Value& v) { - std::optional result = v.match( - [](NullValue) -> std::optional { return 0.0; }, - [](const double f) -> std::optional { return f; }, - [](const std::string& s) -> std::optional { - try { - return util::stof(s); - } catch (...) { - return {}; - } - }, - [](const auto&) { return std::optional(); } - ); + std::optional result = v.match([](NullValue) -> std::optional { return 0.0; }, + [](const double f) -> std::optional { return f; }, + [](const std::string& s) -> std::optional { + try { + return util::stof(s); + } catch (...) { + return {}; + } + }, + [](const auto&) { return std::optional(); }); if (!result) { - return EvaluationError { - "Could not convert " + stringify(v) + " to number." - }; + return EvaluationError{"Could not convert " + stringify(v) + " to number."}; } return *result; } EvaluationResult toColor(const Value& colorValue) { return colorValue.match( - [&](const Color& color) -> EvaluationResult { - return color; - }, + [&](const Color& color) -> EvaluationResult { return color; }, [&](const std::string& colorString) -> EvaluationResult { const std::optional result = Color::parse(colorString); if (result) { return *result; } else { - return EvaluationError{ - "Could not parse color from value '" + colorString + "'" - }; + return EvaluationError{"Could not parse color from value '" + colorString + "'"}; } }, [&colorValue](const std::vector& components) -> EvaluationResult { @@ -59,26 +51,21 @@ EvaluationResult toColor(const Value& colorValue) { return item.template is(); }); if ((len == 3 || len == 4) && isNumeric) { - Result c = {rgba( - components[0].template get(), - components[1].template get(), - components[2].template get(), - len == 4 ? components[3].template get() : 1.0 - )}; + Result c = {rgba(components[0].template get(), + components[1].template get(), + components[2].template get(), + len == 4 ? components[3].template get() : 1.0)}; if (!c) return c.error(); return *c; } else { - return EvaluationError{ - "Invalid rbga value " + stringify(colorValue) + ": expected an array containing either three or four numeric values." - }; + return EvaluationError{"Invalid rbga value " + stringify(colorValue) + + ": expected an array containing either three or four " + "numeric values."}; } }, [&](const auto&) -> EvaluationResult { - return EvaluationError{ - "Could not parse color from value '" + stringify(colorValue) + "'" - }; - } - ); + return EvaluationError{"Could not parse color from value '" + stringify(colorValue) + "'"}; + }); } EvaluationResult toFormatted(const Value& formattedValue) { @@ -89,10 +76,9 @@ EvaluationResult toImage(const Value& imageValue) { return Image(toString(imageValue).c_str()); } -Coercion::Coercion(type::Type type_, std::vector> inputs_) : - Expression(Kind::Coercion, std::move(type_)), - inputs(std::move(inputs_)) -{ +Coercion::Coercion(type::Type type_, std::vector> inputs_) + : Expression(Kind::Coercion, std::move(type_)), + inputs(std::move(inputs_)) { assert(!inputs.empty()); type::Type t = getType(); if (t.is()) { @@ -102,7 +88,9 @@ Coercion::Coercion(type::Type type_, std::vector> in } else if (t.is()) { coerceSingleValue = toNumber; } else if (t.is()) { - coerceSingleValue = [] (const Value& v) -> EvaluationResult { return toString(v); }; + coerceSingleValue = [](const Value& v) -> EvaluationResult { + return toString(v); + }; } else if (t.is()) { coerceSingleValue = toFormatted; } else if (t.is()) { @@ -114,9 +102,10 @@ Coercion::Coercion(type::Type type_, std::vector> in mbgl::Value Coercion::serialize() const { if (getType().is()) { - // Since there's no explicit "to-formatted" coercion, the only coercions should be created - // by string expressions that get implicitly coerced to "formatted". - std::vector serialized{{ std::string("format") }}; + // Since there's no explicit "to-formatted" coercion, the only coercions + // should be created by string expressions that get implicitly coerced + // to "formatted". + std::vector serialized{{std::string("format")}}; serialized.push_back(inputs[0]->serialize()); serialized.emplace_back(std::unordered_map()); return serialized; @@ -126,24 +115,24 @@ mbgl::Value Coercion::serialize() const { return Expression::serialize(); } }; - + std::string Coercion::getOperator() const { - return getType().match( - [](const type::BooleanType&) { return "to-boolean"; }, - [](const type::ColorType&) { return "to-color"; }, - [](const type::NumberType&) { return "to-number"; }, - [](const type::StringType&) { return "to-string"; }, - [](const auto&) { assert(false); return ""; }); + return getType().match([](const type::BooleanType&) { return "to-boolean"; }, + [](const type::ColorType&) { return "to-color"; }, + [](const type::NumberType&) { return "to-number"; }, + [](const type::StringType&) { return "to-string"; }, + [](const auto&) { + assert(false); + return ""; + }); } using namespace mbgl::style::conversion; ParseResult Coercion::parse(const Convertible& value, ParsingContext& ctx) { - static std::unordered_map types { - {"to-boolean", type::Boolean}, - {"to-color", type::Color}, - {"to-number", type::Number}, - {"to-string", type::String} - }; + static std::unordered_map types{{"to-boolean", type::Boolean}, + {"to-color", type::Color}, + {"to-number", type::Number}, + {"to-string", type::String}}; std::size_t length = arrayLength(value); @@ -164,8 +153,8 @@ ParseResult Coercion::parse(const Convertible& value, ParsingContext& ctx) { /** * Special form for error-coalescing coercion expressions "to-number", - * "to-color". Since these coercions can fail at runtime, they accept multiple - * arguments, only evaluating one at a time until one succeeds. + * "to-color". Since these coercions can fail at runtime, they accept + * multiple arguments, only evaluating one at a time until one succeeds. */ std::vector> parsed; @@ -190,11 +179,11 @@ EvaluationResult Coercion::evaluate(const EvaluationContext& params) const { } assert(false); - return EvaluationError { "Unreachable" }; + return EvaluationError{"Unreachable"}; }; void Coercion::eachChild(const std::function& visit) const { - for(const std::unique_ptr& input : inputs) { + for (const std::unique_ptr& input : inputs) { visit(*input); } }; diff --git a/src/mbgl/style/expression/collator_expression.cpp b/src/mbgl/style/expression/collator_expression.cpp index 5e489c51402..397e2c8b077 100644 --- a/src/mbgl/style/expression/collator_expression.cpp +++ b/src/mbgl/style/expression/collator_expression.cpp @@ -7,15 +7,14 @@ namespace mbgl { namespace style { namespace expression { - + CollatorExpression::CollatorExpression(std::unique_ptr caseSensitive_, - std::unique_ptr diacriticSensitive_, - std::optional> locale_) - : Expression(Kind::CollatorExpression, type::Collator) - , caseSensitive(std::move(caseSensitive_)) - , diacriticSensitive(std::move(diacriticSensitive_)) - , locale(std::move(locale_)) -{} + std::unique_ptr diacriticSensitive_, + std::optional> locale_) + : Expression(Kind::CollatorExpression, type::Collator), + caseSensitive(std::move(caseSensitive_)), + diacriticSensitive(std::move(diacriticSensitive_)), + locale(std::move(locale_)) {} using namespace mbgl::style::conversion; @@ -30,13 +29,13 @@ ParseResult CollatorExpression::parse(const Convertible& value, ParsingContext& ctx.error("Collator options argument must be an object."); return ParseResult(); } - + const std::optional caseSensitiveOption = objectMember(options, "case-sensitive"); ParseResult caseSensitive; if (caseSensitiveOption) { caseSensitive = ctx.parse(*caseSensitiveOption, 1, {type::Boolean}); } else { - caseSensitive = { std::make_unique(false) }; + caseSensitive = {std::make_unique(false)}; } if (!caseSensitive) { return ParseResult(); @@ -47,12 +46,12 @@ ParseResult CollatorExpression::parse(const Convertible& value, ParsingContext& if (diacriticSensitiveOption) { diacriticSensitive = ctx.parse(*diacriticSensitiveOption, 1, {type::Boolean}); } else { - diacriticSensitive = { std::make_unique(false) }; + diacriticSensitive = {std::make_unique(false)}; } if (!diacriticSensitive) { return ParseResult(); } - + const std::optional localeOption = objectMember(options, "locale"); ParseResult locale; if (localeOption) { @@ -61,10 +60,11 @@ ParseResult CollatorExpression::parse(const Convertible& value, ParsingContext& return ParseResult(); } } - - return ParseResult(std::make_unique(std::move(*caseSensitive), std::move(*diacriticSensitive), std::move(locale))); + + return ParseResult(std::make_unique( + std::move(*caseSensitive), std::move(*diacriticSensitive), std::move(locale))); } - + void CollatorExpression::eachChild(const std::function& fn) const { fn(*caseSensitive); fn(*diacriticSensitive); @@ -72,16 +72,14 @@ void CollatorExpression::eachChild(const std::function& fn(**locale); } } - + bool CollatorExpression::operator==(const Expression& e) const { if (e.getKind() == Kind::CollatorExpression) { auto rhs = static_cast(&e); - if ((locale && (!rhs->locale || **locale != **(rhs->locale))) || - (!locale && rhs->locale)) { + if ((locale && (!rhs->locale || **locale != **(rhs->locale))) || (!locale && rhs->locale)) { return false; } - return *caseSensitive == *(rhs->caseSensitive) && - *diacriticSensitive == *(rhs->diacriticSensitive); + return *caseSensitive == *(rhs->caseSensitive) && *diacriticSensitive == *(rhs->diacriticSensitive); } return false; } @@ -93,9 +91,9 @@ mbgl::Value CollatorExpression::serialize() const { if (locale) { options["locale"] = (*locale)->serialize(); } - return std::vector{{ std::string("collator"), options }}; + return std::vector{{std::string("collator"), options}}; } - + EvaluationResult CollatorExpression::evaluate(const EvaluationContext& params) const { auto caseSensitiveResult = caseSensitive->evaluate(params); if (!caseSensitiveResult) { @@ -105,13 +103,14 @@ EvaluationResult CollatorExpression::evaluate(const EvaluationContext& params) c if (!diacriticSensitiveResult) { return diacriticSensitiveResult.error(); } - + if (locale) { auto localeResult = (*locale)->evaluate(params); if (!localeResult) { return localeResult.error(); } - return Collator(caseSensitiveResult->get(), diacriticSensitiveResult->get(), localeResult->get()); + return Collator( + caseSensitiveResult->get(), diacriticSensitiveResult->get(), localeResult->get()); } else { return Collator(caseSensitiveResult->get(), diacriticSensitiveResult->get()); } diff --git a/src/mbgl/style/expression/comparison.cpp b/src/mbgl/style/expression/comparison.cpp index 4fe4c5899f1..38c12a4438d 100644 --- a/src/mbgl/style/expression/comparison.cpp +++ b/src/mbgl/style/expression/comparison.cpp @@ -10,15 +10,10 @@ namespace expression { static bool isComparableType(const std::string& op, const type::Type& type) { if (op == "==" || op == "!=") { - return type == type::String || - type == type::Number || - type == type::Boolean || - type == type::Null || - type == type::Value; + return type == type::String || type == type::Number || type == type::Boolean || type == type::Null || + type == type::Value; } else { - return type == type::String || - type == type::Number || - type == type::Value; + return type == type::String || type == type::Number || type == type::Value; } } @@ -29,32 +24,36 @@ bool neq(const Value& a, const Value& b) { return a != b; } bool lt(const Value& lhs, const Value& rhs) { - return lhs.match( - [&](const std::string& a) { return a < rhs.get(); }, - [&](double a) { return a < rhs.get(); }, - [&](const auto&) { assert(false); return false; } - ); + return lhs.match([&](const std::string& a) { return a < rhs.get(); }, + [&](double a) { return a < rhs.get(); }, + [&](const auto&) { + assert(false); + return false; + }); } bool gt(const Value& lhs, const Value& rhs) { - return lhs.match( - [&](const std::string& a) { return a > rhs.get(); }, - [&](double a) { return a > rhs.get(); }, - [&](const auto&) { assert(false); return false; } - ); + return lhs.match([&](const std::string& a) { return a > rhs.get(); }, + [&](double a) { return a > rhs.get(); }, + [&](const auto&) { + assert(false); + return false; + }); } bool lteq(const Value& lhs, const Value& rhs) { - return lhs.match( - [&](const std::string& a) { return a <= rhs.get(); }, - [&](double a) { return a <= rhs.get(); }, - [&](const auto&) { assert(false); return false; } - ); + return lhs.match([&](const std::string& a) { return a <= rhs.get(); }, + [&](double a) { return a <= rhs.get(); }, + [&](const auto&) { + assert(false); + return false; + }); } bool gteq(const Value& lhs, const Value& rhs) { - return lhs.match( - [&](const std::string& a) { return a >= rhs.get(); }, - [&](double a) { return a >= rhs.get(); }, - [&](const auto&) { assert(false); return false; } - ); + return lhs.match([&](const std::string& a) { return a >= rhs.get(); }, + [&](double a) { return a >= rhs.get(); }, + [&](const auto&) { + assert(false); + return false; + }); } bool eqCollate(const std::string& a, const std::string& b, const Collator& c) { @@ -77,33 +76,40 @@ bool gteqCollate(const std::string& a, const std::string& b, const Collator& c) } static BasicComparison::CompareFunctionType getBasicCompareFunction(const std::string& op) { - if (op == "==") return eq; - else if (op == "!=") return neq; - else if (op == ">") return gt; - else if (op == "<") return lt; - else if (op == ">=") return gteq; - else if (op == "<=") return lteq; + if (op == "==") + return eq; + else if (op == "!=") + return neq; + else if (op == ">") + return gt; + else if (op == "<") + return lt; + else if (op == ">=") + return gteq; + else if (op == "<=") + return lteq; assert(false); return nullptr; } static CollatorComparison::CompareFunctionType getCollatorComparisonFunction(const std::string& op) { - if (op == "==") return eqCollate; - else if (op == "!=") return neqCollate; - else if (op == ">") return gtCollate; - else if (op == "<") return ltCollate; - else if (op == ">=") return gteqCollate; - else if (op == "<=") return lteqCollate; + if (op == "==") + return eqCollate; + else if (op == "!=") + return neqCollate; + else if (op == ">") + return gtCollate; + else if (op == "<") + return ltCollate; + else if (op == ">=") + return gteqCollate; + else if (op == "<=") + return lteqCollate; assert(false); return nullptr; - } - -BasicComparison::BasicComparison( - std::string op_, - std::unique_ptr lhs_, - std::unique_ptr rhs_) +BasicComparison::BasicComparison(std::string op_, std::unique_ptr lhs_, std::unique_ptr rhs_) : Expression(Kind::Comparison, type::Boolean), op(std::move(op_)), compare(getBasicCompareFunction(op)), @@ -111,9 +117,9 @@ BasicComparison::BasicComparison( rhs(std::move(rhs_)) { assert(isComparableType(op, lhs->getType()) && isComparableType(op, rhs->getType())); assert(lhs->getType() == rhs->getType() || lhs->getType() == type::Value || rhs->getType() == type::Value); - + needsRuntimeTypeCheck = (op != "==" && op != "!=") && - (lhs->getType() == type::Value || rhs->getType() == type::Value); + (lhs->getType() == type::Value || rhs->getType() == type::Value); } EvaluationResult BasicComparison::evaluate(const EvaluationContext& params) const { @@ -122,20 +128,18 @@ EvaluationResult BasicComparison::evaluate(const EvaluationContext& params) cons EvaluationResult rhsResult = rhs->evaluate(params); if (!rhsResult) return rhsResult; - + if (needsRuntimeTypeCheck) { type::Type lhsType = typeOf(*lhsResult); type::Type rhsType = typeOf(*rhsResult); // check that type is string or number, and equal if (lhsType != rhsType || !(lhsType == type::String || lhsType == type::Number)) { - return EvaluationError { - R"(Expected arguments for ")" + op + R"(")" + - " to be (string, string) or (number, number), but found (" + toString(lhsType) + ", " + - toString(rhsType) + ") instead." - }; + return EvaluationError{R"(Expected arguments for ")" + op + R"(")" + + " to be (string, string) or (number, number), but found (" + toString(lhsType) + + ", " + toString(rhsType) + ") instead."}; } } - + return compare(*lhsResult, *rhsResult); } @@ -144,27 +148,26 @@ void BasicComparison::eachChild(const std::function& vi visit(*rhs); } -std::string BasicComparison::getOperator() const { return op; } +std::string BasicComparison::getOperator() const { + return op; +} bool BasicComparison::operator==(const Expression& e) const { if (e.getKind() == Kind::Comparison) { auto comp = static_cast(&e); - return comp->op == op && - *comp->lhs == *lhs && - *comp->rhs == *rhs; + return comp->op == op && *comp->lhs == *lhs && *comp->rhs == *rhs; } return false; } std::vector> BasicComparison::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } -CollatorComparison::CollatorComparison( - std::string op_, - std::unique_ptr lhs_, - std::unique_ptr rhs_, - std::unique_ptr collator_) +CollatorComparison::CollatorComparison(std::string op_, + std::unique_ptr lhs_, + std::unique_ptr rhs_, + std::unique_ptr collator_) : Expression(Kind::Comparison, type::Boolean), op(std::move(op_)), compare(getCollatorComparisonFunction(op)), @@ -175,7 +178,7 @@ CollatorComparison::CollatorComparison( assert(lhs->getType() == rhs->getType() || lhs->getType() == type::Value || rhs->getType() == type::Value); needsRuntimeTypeCheck = (op == "==" || op == "!=") && - (lhs->getType() == type::Value || rhs->getType() == type::Value); + (lhs->getType() == type::Value || rhs->getType() == type::Value); } EvaluationResult CollatorComparison::evaluate(const EvaluationContext& params) const { @@ -184,16 +187,16 @@ EvaluationResult CollatorComparison::evaluate(const EvaluationContext& params) c EvaluationResult rhsResult = rhs->evaluate(params); if (!rhsResult) return lhsResult; - + if (needsRuntimeTypeCheck) { if (typeOf(*lhsResult) != type::String || typeOf(*rhsResult) != type::String) { return getBasicCompareFunction(op)(*lhsResult, *rhsResult); } } - + auto collatorResult = collator->evaluate(params); if (!collatorResult) return collatorResult; - + const Collator& c = collatorResult->get(); return compare(lhsResult->get(), rhsResult->get(), c); } @@ -204,21 +207,20 @@ void CollatorComparison::eachChild(const std::function& visit(*collator); } -std::string CollatorComparison::getOperator() const { return op; } +std::string CollatorComparison::getOperator() const { + return op; +} bool CollatorComparison::operator==(const Expression& e) const { if (e.getKind() == Kind::Comparison) { auto comp = static_cast(&e); - return comp->op == op && - *comp->collator == *collator && - *comp->lhs == *lhs && - *comp->rhs == *rhs; + return comp->op == op && *comp->collator == *collator && *comp->lhs == *lhs && *comp->rhs == *rhs; } return false; } std::vector> CollatorComparison::possibleOutputs() const { - return {{ true }, { false }}; + return {{true}, {false}}; } using namespace mbgl::style::conversion; @@ -229,9 +231,9 @@ ParseResult parseComparison(const Convertible& value, ParsingContext& ctx) { ctx.error("Expected two or three arguments."); return ParseResult(); } - + std::string op = *toString(arrayMember(value, 0)); - + assert(getBasicCompareFunction(op)); ParseResult lhs = ctx.parse(arrayMember(value, 1), 1, {type::Value}); @@ -250,15 +252,11 @@ ParseResult parseComparison(const Convertible& value, ParsingContext& ctx) { return ParseResult(); } - if ( - lhsType != rhsType && - lhsType != type::Value && - rhsType != type::Value - ) { + if (lhsType != rhsType && lhsType != type::Value && rhsType != type::Value) { ctx.error("Cannot compare types '" + toString(lhsType) + "' and '" + toString(rhsType) + "'."); return ParseResult(); } - + if (op != "==" && op != "!=") { // typing rules specific to less/greater than operators if (lhsType == type::Value && rhsType != type::Value) { @@ -269,22 +267,18 @@ ParseResult parseComparison(const Convertible& value, ParsingContext& ctx) { rhs = dsl::assertion(lhsType, std::move(*rhs)); } } - + if (length == 4) { - if ( - lhsType != type::String && - rhsType != type::String && - lhsType != type::Value && - rhsType != type::Value - ) { + if (lhsType != type::String && rhsType != type::String && lhsType != type::Value && rhsType != type::Value) { ctx.error("Cannot use collator to compare non-string types."); return ParseResult(); } ParseResult collatorParseResult = ctx.parse(arrayMember(value, 3), 3, {type::Collator}); if (!collatorParseResult) return ParseResult(); - return ParseResult(std::make_unique(op, std::move(*lhs), std::move(*rhs), std::move(*collatorParseResult))); + return ParseResult(std::make_unique( + op, std::move(*lhs), std::move(*rhs), std::move(*collatorParseResult))); } - + return ParseResult(std::make_unique(op, std::move(*lhs), std::move(*rhs))); } diff --git a/src/mbgl/style/expression/compound_expression.cpp b/src/mbgl/style/expression/compound_expression.cpp index a814343c911..e1430979afa 100644 --- a/src/mbgl/style/expression/compound_expression.cpp +++ b/src/mbgl/style/expression/compound_expression.cpp @@ -25,7 +25,9 @@ namespace expression { Represents the parameter list for an expression that takes an arbitrary number of arguments (of a specific type). */ -struct VarargsType { type::Type type; }; +struct VarargsType { + type::Type type; +}; bool operator==(const VarargsType& lhs, const VarargsType& rhs) { return lhs.type == rhs.type; @@ -34,7 +36,8 @@ bool operator==(const VarargsType& lhs, const VarargsType& rhs) { template struct Varargs : std::vector { template - explicit Varargs(Args&&... args) : std::vector(std::forward(args)...) {} + explicit Varargs(Args&&... args) + : std::vector(std::forward(args)...) {} }; namespace detail { @@ -44,11 +47,10 @@ namespace detail { struct SignatureBase { using Args = std::vector>; - SignatureBase(type::Type result_, variant, VarargsType> params_, std::string name_) : - result(std::move(result_)), - params(std::move(params_)), - name(std::move(name_)) - {} + SignatureBase(type::Type result_, variant, VarargsType> params_, std::string name_) + : result(std::move(result_)), + params(std::move(params_)), + name(std::move(name_)) {} virtual ~SignatureBase() = default; virtual EvaluationResult apply(const EvaluationContext&, const Args&) const = 0; @@ -62,20 +64,20 @@ struct SignatureBase { The Signature structs are wrappers around an "evaluate()" function whose purpose is to extract the necessary Type data from the evaluate function's type. There are three key (partial) specializations: - + Signature: Wraps a simple evaluate function (const T0&, const T1&, ...) -> Result - + Signature&)>: Wraps an evaluate function that takes an arbitrary number of arguments (via a Varargs, which is just an alias for std::vector). - + Signature: Wraps an evaluate function that needs to access the expression evaluation parameters in addition to its subexpressions, i.e., (const EvaluationParams&, const T0&, const T1&, ...) -> Result. Needed for expressions like ["zoom"], ["get", key], etc. - + In each of the above evaluate signatures, T0, T1, etc. are the types of the successfully evaluated subexpressions. */ @@ -84,7 +86,7 @@ struct Signature; // Simple evaluate function (const T0&, const T1&, ...) -> Result template -struct Signature : SignatureBase { +struct Signature : SignatureBase { Signature(R (*evaluate_)(Params...), const std::string& name_) : SignatureBase(valueTypeToExpressionType>(), std::vector{valueTypeToExpressionType>()...}, @@ -98,8 +100,10 @@ struct Signature : SignatureBase { R (*evaluate)(Params...); private: - template - EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence) const { + template + EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, + const Args& args, + std::index_sequence) const { std::array evaluated; for (int i = 0; i < int(sizeof...(Params)); ++i) { const EvaluationResult evaluatedArg = args.at(i)->evaluate(evaluationParameters); @@ -114,7 +118,7 @@ struct Signature : SignatureBase { // Varargs evaluate function (const Varargs&) -> Result template -struct Signature&)> : SignatureBase { +struct Signature&)> : SignatureBase { Signature(R (*evaluate_)(const Varargs&), const std::string& name_) : SignatureBase(valueTypeToExpressionType>(), VarargsType{valueTypeToExpressionType()}, @@ -126,7 +130,7 @@ struct Signature&)> : SignatureBase { evaluated.reserve(args.size()); for (const auto& arg : args) { const EvaluationResult evaluatedArg = arg->evaluate(evaluationParameters); - if(!evaluatedArg) return evaluatedArg.error(); + if (!evaluatedArg) return evaluatedArg.error(); evaluated.push_back(*fromExpressionValue>(*evaluatedArg)); } const R value = evaluate(evaluated); @@ -140,7 +144,7 @@ struct Signature&)> : SignatureBase { // Evaluate function needing parameter access, // (const EvaluationParams&, const T0&, const T1&, ...) -> Result template -struct Signature : SignatureBase { +struct Signature : SignatureBase { Signature(R (*evaluate_)(const EvaluationContext&, Params...), const std::string& name_) : SignatureBase(valueTypeToExpressionType>(), std::vector{valueTypeToExpressionType>()...}, @@ -152,8 +156,10 @@ struct Signature : SignatureBase { } private: - template - EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, const Args& args, std::index_sequence) const { + template + EvaluationResult applyImpl(const EvaluationContext& evaluationParameters, + const Args& args, + std::index_sequence) const { std::array evaluated; for (int i = 0; i < int(sizeof...(Params)); ++i) { const EvaluationResult evaluatedArg = args.at(i)->evaluate(evaluationParameters); @@ -167,11 +173,11 @@ struct Signature : SignatureBase { R (*evaluate)(const EvaluationContext&, Params...); }; - + // Evaluate function needing EvaluationContext and Varargs // (const EvaluationContext&, const Varargs&) -> Result template -struct Signature&)> : SignatureBase { +struct Signature&)> : SignatureBase { Signature(R (*evaluate_)(const EvaluationContext&, const Varargs&), const std::string& name_) : SignatureBase(valueTypeToExpressionType>(), VarargsType{valueTypeToExpressionType()}, @@ -183,7 +189,7 @@ struct Signature&)> : SignatureBas evaluated.reserve(args.size()); for (const auto& arg : args) { const EvaluationResult evaluatedArg = arg->evaluate(evaluationParameters); - if(!evaluatedArg) return evaluatedArg.error(); + if (!evaluatedArg) return evaluatedArg.error(); evaluated.push_back(*fromExpressionValue>(*evaluatedArg)); } const R value = evaluate(evaluationParameters, evaluated); @@ -199,12 +205,14 @@ template struct SignatureType; template -struct SignatureType -{ using Type = R (Params...); }; +struct SignatureType { + using Type = R(Params...); +}; template -struct SignatureType>> -{ using Type = typename SignatureType::Type; }; +struct SignatureType>> { + using Type = typename SignatureType::Type; +}; template static std::unique_ptr makeSignature(std::string name, Fn evaluateFunction) { @@ -217,9 +225,7 @@ Value featureIdAsExpressionValue(const EvaluationContext& params) { assert(params.feature); auto id = params.feature->getID(); if (id.is()) return Null; - return id.match([](const auto& idid) { - return toExpressionValue(mbgl::Value(idid)); - }); + return id.match([](const auto& idid) { return toExpressionValue(mbgl::Value(idid)); }); }; std::optional featurePropertyAsExpressionValue(const EvaluationContext& params, const std::string& key) { @@ -229,17 +235,17 @@ std::optional featurePropertyAsExpressionValue(const EvaluationContext& p }; std::optional featureTypeAsString(FeatureType type) { - switch(type) { - case FeatureType::Point: - return std::optional("Point"); - case FeatureType::LineString: - return std::optional("LineString"); - case FeatureType::Polygon: - return std::optional("Polygon"); - case FeatureType::Unknown: - return std::optional("Unknown"); - default: - return {}; + switch (type) { + case FeatureType::Point: + return std::optional("Point"); + case FeatureType::LineString: + return std::optional("LineString"); + case FeatureType::Polygon: + return std::optional("Polygon"); + case FeatureType::Unknown: + return std::optional("Unknown"); + default: + return {}; } }; @@ -292,33 +298,35 @@ const auto& ln2CompoundExpression() { } const auto& typeofCompoundExpression() { - static auto signature = detail::makeSignature("typeof", [](const Value& v) -> Result { return toString(typeOf(v)); }); + static auto signature = detail::makeSignature( + "typeof", [](const Value& v) -> Result { return toString(typeOf(v)); }); return signature; } const auto& toRgbaCompoundExpression() { - static auto signature = detail::makeSignature("to-rgba", [](const Color& color) -> Result> { - return color.toArray(); - }); + static auto signature = detail::makeSignature( + "to-rgba", [](const Color& color) -> Result> { return color.toArray(); }); return signature; } const auto& rgbaCompoundExpression() { - static auto signature = detail::makeSignature("rgba", [](double r, double g, double b, double a) { return rgba(r, g, b, a); }); + static auto signature = detail::makeSignature( + "rgba", [](double r, double g, double b, double a) { return rgba(r, g, b, a); }); return signature; } const auto& rgbCompoundExpression() { - static auto signature = detail::makeSignature("rgb", [](double r, double g, double b) { return rgba(r, g, b, 1.0f); }); + static auto signature = detail::makeSignature("rgb", + [](double r, double g, double b) { return rgba(r, g, b, 1.0f); }); return signature; } const auto& zoomCompoundExpression() { static auto signature = detail::makeSignature("zoom", [](const EvaluationContext& params) -> Result { if (!params.zoom) { - return EvaluationError { - "The 'zoom' expression is unavailable in the current evaluation context." - }; + return EvaluationError{ + "The 'zoom' expression is unavailable in the current " + "evaluation context."}; } return *(params.zoom); }); @@ -326,142 +334,147 @@ const auto& zoomCompoundExpression() { } const auto& heatmapDensityCompoundExpression() { - static auto signature = detail::makeSignature("heatmap-density", [](const EvaluationContext& params) -> Result { - if (!params.colorRampParameter) { - return EvaluationError { - "The 'heatmap-density' expression is unavailable in the current evaluation context." - }; - } - return *(params.colorRampParameter); - }); + static auto signature = detail::makeSignature("heatmap-density", + [](const EvaluationContext& params) -> Result { + if (!params.colorRampParameter) { + return EvaluationError{ + "The 'heatmap-density' expression is unavailable in the " + "current evaluation context."}; + } + return *(params.colorRampParameter); + }); return signature; } const auto& lineProgressCompoundExpression() { - static auto signature = detail::makeSignature("line-progress", [](const EvaluationContext& params) -> Result { - if (!params.colorRampParameter) { - return EvaluationError { - "The 'line-progress' expression is unavailable in the current evaluation context." - }; - } - return *(params.colorRampParameter); - }); + static auto signature = detail::makeSignature("line-progress", + [](const EvaluationContext& params) -> Result { + if (!params.colorRampParameter) { + return EvaluationError{ + "The 'line-progress' expression is unavailable in the " + "current evaluation context."}; + } + return *(params.colorRampParameter); + }); return signature; } const auto& accumulatedCompoundExpression() { - const static auto signature = detail::makeSignature("accumulated", [](const EvaluationContext& params) -> Result { - if (!params.accumulated) { - return EvaluationError { - "The 'accumulated' expression is unavailable in the current evaluation context." - }; - } - return Value(toExpressionValue(*params.accumulated)); - }); + const static auto signature = detail::makeSignature( + "accumulated", [](const EvaluationContext& params) -> Result { + if (!params.accumulated) { + return EvaluationError{ + "The 'accumulated' expression is unavailable in the " + "current evaluation context."}; + } + return Value(toExpressionValue(*params.accumulated)); + }); return signature; } - + const auto& hasContextCompoundExpression() { - static auto signature = detail::makeSignature("has", [](const EvaluationContext& params, const std::string& key) -> Result { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } + static auto signature = detail::makeSignature( + "has", [](const EvaluationContext& params, const std::string& key) -> Result { + if (!params.feature) { + return EvaluationError{ + "Feature data is unavailable in the current evaluation " + "context."}; + } - return static_cast(params.feature->getValue(key)); - }); + return static_cast(params.feature->getValue(key)); + }); return signature; } const auto& hasObjectCompoundExpression() { - static auto signature = detail::makeSignature("has", [](const std::string& key, const std::unordered_map& object) -> Result { - return object.find(key) != object.end(); - }); + static auto signature = detail::makeSignature( + "has", [](const std::string& key, const std::unordered_map& object) -> Result { + return object.find(key) != object.end(); + }); return signature; } const auto& getContextCompoundExpression() { - static auto signature = detail::makeSignature("get", [](const EvaluationContext& params, const std::string& key) -> Result { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } + static auto signature = detail::makeSignature( + "get", [](const EvaluationContext& params, const std::string& key) -> Result { + if (!params.feature) { + return EvaluationError{ + "Feature data is unavailable in the current evaluation " + "context."}; + } - auto propertyValue = params.feature->getValue(key); - if (!propertyValue) { - return Null; - } - return Value(toExpressionValue(*propertyValue)); - }); + auto propertyValue = params.feature->getValue(key); + if (!propertyValue) { + return Null; + } + return Value(toExpressionValue(*propertyValue)); + }); return signature; } const auto& getObjectCompoundExpression() { - static auto signature = detail::makeSignature("get", [](const std::string& key, const std::unordered_map& object) -> Result { - if (object.find(key) == object.end()) { - return Null; - } - return object.at(key); - }); + static auto signature = detail::makeSignature( + "get", [](const std::string& key, const std::unordered_map& object) -> Result { + if (object.find(key) == object.end()) { + return Null; + } + return object.at(key); + }); return signature; } const auto& propertiesCompoundExpression() { - static auto signature = detail::makeSignature("properties", [](const EvaluationContext& params) -> Result> { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } - std::unordered_map result; - const PropertyMap& properties = params.feature->getProperties(); - result.reserve(properties.size()); - for (const auto& entry : properties) { - result[entry.first] = toExpressionValue(entry.second); - } - return result; - }); + static auto signature = detail::makeSignature( + "properties", [](const EvaluationContext& params) -> Result> { + if (!params.feature) { + return EvaluationError{ + "Feature data is unavailable in the current evaluation " + "context."}; + } + std::unordered_map result; + const PropertyMap& properties = params.feature->getProperties(); + result.reserve(properties.size()); + for (const auto& entry : properties) { + result[entry.first] = toExpressionValue(entry.second); + } + return result; + }); return signature; } const auto& geometryTypeCompoundExpression() { - static auto signature = detail::makeSignature("geometry-type", [](const EvaluationContext& params) -> Result { - if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; - } - - auto type = params.feature->getType(); - if (type == FeatureType::Point) { - return "Point"; - } else if (type == FeatureType::LineString) { - return "LineString"; - } else if (type == FeatureType::Polygon) { - return "Polygon"; - } else { - return "Unknown"; - } - }); + static auto signature = detail::makeSignature("geometry-type", + [](const EvaluationContext& params) -> Result { + if (!params.feature) { + return EvaluationError{ + "Feature data is unavailable in the current evaluation " + "context."}; + } + + auto type = params.feature->getType(); + if (type == FeatureType::Point) { + return "Point"; + } else if (type == FeatureType::LineString) { + return "LineString"; + } else if (type == FeatureType::Polygon) { + return "Polygon"; + } else { + return "Unknown"; + } + }); return signature; } const auto& idCompoundExpression() { static auto signature = detail::makeSignature("id", [](const EvaluationContext& params) -> Result { if (!params.feature) { - return EvaluationError { - "Feature data is unavailable in the current evaluation context." - }; + return EvaluationError{ + "Feature data is unavailable in the current evaluation " + "context."}; } auto id = params.feature->getID(); - return id.match( - [](const auto& idValue) { - return toExpressionValue(mbgl::Value(idValue)); - } - ); + return id.match([](const auto& idValue) { return toExpressionValue(mbgl::Value(idValue)); }); }); return signature; } @@ -626,16 +639,14 @@ const auto& isSupportedScriptCompoundExpression() { } const auto& upcaseCompoundExpression() { - static auto signature = detail::makeSignature("upcase", [](const std::string& input) -> Result { - return platform::uppercase(input); - }); + static auto signature = detail::makeSignature( + "upcase", [](const std::string& input) -> Result { return platform::uppercase(input); }); return signature; } const auto& downcaseCompoundExpression() { - static auto signature = detail::makeSignature("downcase", [](const std::string& input) -> Result { - return platform::lowercase(input); - }); + static auto signature = detail::makeSignature( + "downcase", [](const std::string& input) -> Result { return platform::lowercase(input); }); return signature; } @@ -651,16 +662,14 @@ const auto& concatCompoundExpression() { } const auto& resolvedLocaleCompoundExpression() { - static auto signature = detail::makeSignature("resolved-locale", [](const Collator& collator) -> Result { - return collator.resolvedLocale(); - }); + static auto signature = detail::makeSignature( + "resolved-locale", [](const Collator& collator) -> Result { return collator.resolvedLocale(); }); return signature; } const auto& errorCompoundExpression() { - static auto signature = detail::makeSignature("error", [](const std::string& input) -> Result { - return EvaluationError { input }; - }); + static auto signature = detail::makeSignature( + "error", [](const std::string& input) -> Result { return EvaluationError{input}; }); return signature; } @@ -681,33 +690,37 @@ const auto& featureStateCompoundExpression() { // Legacy Filters const auto& filterEqualsCompoundExpression() { - static auto signature = detail::makeSignature("filter-==", [](const EvaluationContext& params, const std::string& key, const Value &lhs) -> Result { - const auto rhs = featurePropertyAsExpressionValue(params, key); - return rhs ? lhs == *rhs : false; - }); + static auto signature = detail::makeSignature( + "filter-==", [](const EvaluationContext& params, const std::string& key, const Value& lhs) -> Result { + const auto rhs = featurePropertyAsExpressionValue(params, key); + return rhs ? lhs == *rhs : false; + }); return signature; } const auto& filterIdEqualsCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-==", [](const EvaluationContext& params, const Value &lhs) -> Result { - return lhs == featureIdAsExpressionValue(params); - }); + static auto signature = detail::makeSignature( + "filter-id-==", [](const EvaluationContext& params, const Value& lhs) -> Result { + return lhs == featureIdAsExpressionValue(params); + }); return signature; } const auto& filterTypeEqualsCompoundExpression() { - static auto signature = detail::makeSignature("filter-type-==", [](const EvaluationContext& params, const std::string &lhs) -> Result { - if (!params.feature) return false; - return featureTypeAsString(params.feature->getType()) == lhs; - }); + static auto signature = detail::makeSignature( + "filter-type-==", [](const EvaluationContext& params, const std::string& lhs) -> Result { + if (!params.feature) return false; + return featureTypeAsString(params.feature->getType()) == lhs; + }); return signature; } const auto& filterLessThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-<", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs < lhs : false; - }); + static auto signature = detail::makeSignature( + "filter-<", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs < lhs : false; + }); return signature; } @@ -722,10 +735,11 @@ const auto& filterLessThanStringCompoundExpression() { } const auto& filterIdLessThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-<", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs < lhs : false; - }); + static auto signature = detail::makeSignature("filter-id-<", + [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs < lhs : false; + }); return signature; } @@ -739,10 +753,11 @@ const auto& filterIdLessThanStringCompoundExpression() { } const auto& filterMoreThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter->", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs > lhs : false; - }); + static auto signature = detail::makeSignature( + "filter->", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs > lhs : false; + }); return signature; } @@ -757,10 +772,11 @@ const auto& filterMoreThanStringCompoundExpression() { } const auto& filterIdMoreThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id->", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs > lhs : false; - }); + static auto signature = detail::makeSignature("filter-id->", + [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs > lhs : false; + }); return signature; } @@ -774,10 +790,11 @@ const auto& filterIdMoreThanStringCompoundExpression() { } const auto& filterLessOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-<=", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs <= lhs : false; - }); + static auto signature = detail::makeSignature( + "filter-<=", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs <= lhs : false; + }); return signature; } @@ -792,10 +809,11 @@ const auto& filterLessOrEqualThanStringCompoundExpression() { } const auto& filterIdLessOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-<=", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs <= lhs : false; - }); + static auto signature = detail::makeSignature( + "filter-id-<=", [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs <= lhs : false; + }); return signature; } @@ -809,10 +827,11 @@ const auto& filterIdLessOrEqualThanStringCompoundExpression() { } const auto& filterGreaterOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter->=", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { - auto rhs = featurePropertyAsDouble(params, key); - return rhs ? rhs >= lhs : false; - }); + static auto signature = detail::makeSignature( + "filter->=", [](const EvaluationContext& params, const std::string& key, double lhs) -> Result { + auto rhs = featurePropertyAsDouble(params, key); + return rhs ? rhs >= lhs : false; + }); return signature; } @@ -827,10 +846,11 @@ const auto& filterGreaterOrEqualThanStringCompoundExpression() { } const auto& filterIdGreaterOrEqualThanNumberCompoundExpression() { - static auto signature = detail::makeSignature("filter-id->=", [](const EvaluationContext& params, double lhs) -> Result { - auto rhs = featureIdAsDouble(params); - return rhs ? rhs >= lhs : false; - }); + static auto signature = detail::makeSignature( + "filter-id->=", [](const EvaluationContext& params, double lhs) -> Result { + auto rhs = featureIdAsDouble(params); + return rhs ? rhs >= lhs : false; + }); return signature; } @@ -844,10 +864,11 @@ const auto& filterIdGreaterOrEqualThanStringCompoundExpression() { } const auto& filterHasCompoundExpression() { - static auto signature = detail::makeSignature("filter-has", [](const EvaluationContext& params, const std::string& key) -> Result { - assert(params.feature); - return bool(params.feature->getValue(key)); - }); + static auto signature = detail::makeSignature( + "filter-has", [](const EvaluationContext& params, const std::string& key) -> Result { + assert(params.feature); + return bool(params.feature->getValue(key)); + }); return signature; } @@ -860,30 +881,32 @@ const auto& filterHasIdCompoundExpression() { } const auto& filterTypeInCompoundExpression() { - static auto signature = detail::makeSignature("filter-type-in", [](const EvaluationContext& params, const Varargs& types) -> Result { - assert(params.feature); - std::optional type = featureTypeAsString(params.feature->getType()); - return std::find(types.begin(), types.end(), type) != types.end(); - }); + static auto signature = detail::makeSignature( + "filter-type-in", [](const EvaluationContext& params, const Varargs& types) -> Result { + assert(params.feature); + std::optional type = featureTypeAsString(params.feature->getType()); + return std::find(types.begin(), types.end(), type) != types.end(); + }); return signature; } const auto& filterIdInCompoundExpression() { - static auto signature = detail::makeSignature("filter-id-in", [](const EvaluationContext& params, const Varargs& ids) -> Result { - auto id = featureIdAsExpressionValue(params); - return std::find(ids.begin(), ids.end(), id) != ids.end(); - }); + static auto signature = detail::makeSignature( + "filter-id-in", [](const EvaluationContext& params, const Varargs& ids) -> Result { + auto id = featureIdAsExpressionValue(params); + return std::find(ids.begin(), ids.end(), id) != ids.end(); + }); return signature; } - const auto& filterInCompoundExpression() { - static auto signature = detail::makeSignature("filter-in", [](const EvaluationContext& params, const Varargs& varargs) -> Result { - if (varargs.size() < 2) return false; - assert(varargs[0].is()); - auto value = featurePropertyAsExpressionValue(params, varargs[0].get()); - return value ? std::find(varargs.begin() + 1, varargs.end(), *value) != varargs.end() : false; - }); + static auto signature = detail::makeSignature( + "filter-in", [](const EvaluationContext& params, const Varargs& varargs) -> Result { + if (varargs.size() < 2) return false; + assert(varargs[0].is()); + auto value = featurePropertyAsExpressionValue(params, varargs[0].get()); + return value ? std::find(varargs.begin() + 1, varargs.end(), *value) != varargs.end() : false; + }); return signature; } @@ -971,38 +994,36 @@ using namespace mbgl::style::conversion; using DefinitionIterator = decltype(compoundExpressionRegistry)::const_iterator; using Definitions = std::pair; -std::string expectedTypesError(const Definitions& definitions, - const std::vector>& args) { - std::vector availableOverloads; // Only used if there are no overloads with matching number of args +std::string expectedTypesError(const Definitions& definitions, const std::vector>& args) { + std::vector availableOverloads; // Only used if there are no overloads + // with matching number of args std::vector overloads; for (auto it = definitions.first; it != definitions.second; ++it) { const auto& signature = it->second(); signature->params.match( - [&](const VarargsType& varargs) { - std::string overload = "(" + toString(varargs.type) + ")"; - overloads.push_back(overload); - }, - [&](const std::vector& params) { - std::string overload = "("; - bool first = true; - for (const type::Type& param : params) { - if (!first) overload += ", "; - overload += toString(param); - first = false; - } - overload += ")"; - if (params.size() == args.size()) { + [&](const VarargsType& varargs) { + std::string overload = "(" + toString(varargs.type) + ")"; overloads.push_back(overload); - } else { - availableOverloads.push_back(overload); - } - } - ); + }, + [&](const std::vector& params) { + std::string overload = "("; + bool first = true; + for (const type::Type& param : params) { + if (!first) overload += ", "; + overload += toString(param); + first = false; + } + overload += ")"; + if (params.size() == args.size()) { + overloads.push_back(overload); + } else { + availableOverloads.push_back(overload); + } + }); } - std::string signatures = overloads.empty() ? - boost::algorithm::join(availableOverloads, " | ") : - boost::algorithm::join(overloads, " | "); - + std::string signatures = overloads.empty() ? boost::algorithm::join(availableOverloads, " | ") + : boost::algorithm::join(overloads, " | "); + std::string actualTypes; for (const auto& arg : args) { if (!actualTypes.empty()) { @@ -1010,14 +1031,13 @@ std::string expectedTypesError(const Definitions& definitions, } actualTypes += toString(arg->getType()); } - + return "Expected arguments of type " + signatures + ", but found (" + actualTypes + ") instead."; } static ParseResult createCompoundExpression(const Definitions& definitions, std::vector> args, - ParsingContext& ctx) -{ + ParsingContext& ctx) { ParsingContext signatureContext(ctx.getKey()); for (auto it = definitions.first; it != definitions.second; ++it) { @@ -1027,10 +1047,8 @@ static ParseResult createCompoundExpression(const Definitions& definitions, if (signature->params.is>()) { const std::vector& params = signature->params.get>(); if (params.size() != args.size()) { - signatureContext.error( - "Expected " + util::toString(params.size()) + - " arguments, but found " + util::toString(args.size()) + " instead." - ); + signatureContext.error("Expected " + util::toString(params.size()) + " arguments, but found " + + util::toString(args.size()) + " instead."); continue; } @@ -1071,22 +1089,17 @@ ParseResult parseCompoundExpression(const std::string& name, const Convertible& const auto definitions = compoundExpressionRegistry.equal_range(name.c_str()); if (definitions.first == definitions.second) { - ctx.error( - R"(Unknown expression ")" + name + R"(". If you wanted a literal array, use ["literal", [...]].)", - 0 - ); + ctx.error(R"(Unknown expression ")" + name + R"(". If you wanted a literal array, use ["literal", [...]].)", 0); return ParseResult(); } auto length = arrayLength(value); - + for (auto it = definitions.first; it != definitions.second; ++it) { const auto& signature = it->second(); - if ( - signature->params.is() || - signature->params.get>().size() == length - 1 - ) { + if (signature->params.is() || + signature->params.get>().size() == length - 1) { // First parse all the args, potentially coercing to the // types expected by this overload. ctx.clearErrors(); @@ -1097,8 +1110,7 @@ ParseResult parseCompoundExpression(const std::string& name, const Convertible& for (std::size_t i = 1; i < length; i++) { std::optional expected = signature->params.match( [](const VarargsType& varargs) { return varargs.type; }, - [&](const std::vector& params_) { return params_[i - 1]; } - ); + [&](const std::vector& params_) { return params_[i - 1]; }); auto parsed = ctx.parse(arrayMember(value, i), i, expected); if (!parsed) { @@ -1124,7 +1136,7 @@ ParseResult parseCompoundExpression(const std::string& name, const Convertible& ctx.clearErrors(); std::vector> args; args.reserve(length - 1); - + for (std::size_t i = 1; i < length; i++) { auto parsed = ctx.parse(arrayMember(value, i), i); if (!parsed) { @@ -1140,16 +1152,15 @@ ParseResult parseCompoundExpression(const std::string& name, const Convertible& ParseResult createCompoundExpression(const std::string& name, std::vector> args, - ParsingContext& ctx) -{ + ParsingContext& ctx) { return createCompoundExpression(compoundExpressionRegistry.equal_range(name.c_str()), std::move(args), ctx); } -CompoundExpression::CompoundExpression(const detail::SignatureBase& signature_, std::vector> args_) : - Expression(Kind::CompoundExpression, signature_.result), - signature(signature_), - args(std::move(args_)) -{} +CompoundExpression::CompoundExpression(const detail::SignatureBase& signature_, + std::vector> args_) + : Expression(Kind::CompoundExpression, signature_.result), + signature(signature_), + args(std::move(args_)) {} std::string CompoundExpression::getOperator() const { return signature.name; @@ -1160,12 +1171,13 @@ EvaluationResult CompoundExpression::evaluate(const EvaluationContext& evaluatio } std::optional CompoundExpression::getParameterCount() const { - return signature.params.match([&](const VarargsType&) -> std::optional { return std::nullopt; }, - [&](const std::vector& p) -> std::optional { return p.size(); }); + return signature.params.match( + [&](const VarargsType&) -> std::optional { return std::nullopt; }, + [&](const std::vector& p) -> std::optional { return p.size(); }); } std::vector> CompoundExpression::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } void CompoundExpression::eachChild(const std::function& visit) const { @@ -1177,10 +1189,8 @@ void CompoundExpression::eachChild(const std::function& bool CompoundExpression::operator==(const Expression& e) const { if (e.getKind() == Kind::CompoundExpression) { auto rhs = static_cast(&e); - return signature.name == rhs->signature.name && - signature.result == rhs->signature.result && - signature.params == rhs->signature.params && - Expression::childrenEqual(args, rhs->args); + return signature.name == rhs->signature.name && signature.result == rhs->signature.result && + signature.params == rhs->signature.params && Expression::childrenEqual(args, rhs->args); } return false; } diff --git a/src/mbgl/style/expression/distance.cpp b/src/mbgl/style/expression/distance.cpp index d5cbdfd9ff0..099b1c87c82 100644 --- a/src/mbgl/style/expression/distance.cpp +++ b/src/mbgl/style/expression/distance.cpp @@ -117,7 +117,9 @@ bool isPolygonValid(const mapbox::geometry::polygon& polygon) { } for (const auto& ring : polygon) { if (ring.size() < 3) { - mbgl::Log::Error(mbgl::Event::Style, "Invalid Polygon with ring having fewer than 3 geometry points"); + mbgl::Log::Error(mbgl::Event::Style, + "Invalid Polygon with ring having fewer than 3 " + "geometry points"); return false; } } @@ -125,8 +127,8 @@ bool isPolygonValid(const mapbox::geometry::polygon& polygon) { } // Calculate the distance between two bounding boxes. -// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} and {dx, dy} to calculate the distance. -// Distance will be 0.0 if bounding box are overlapping. +// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} +// and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping. double bboxToBBoxDistance(const DistanceBBox& bbox1, const DistanceBBox& bbox2, mapbox::cheap_ruler::CheapRuler& ruler) { @@ -256,7 +258,8 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, return dist; } -// TODO: Currently the time complexity for polygon to polygon distance is quadratic, performance improvement is needed. +// TODO: Currently the time complexity for polygon to polygon distance is +// quadratic, performance improvement is needed. double polygonToPolygonDistance(const mapbox::geometry::polygon& polygon1, const mapbox::geometry::polygon& polygon2, mapbox::cheap_ruler::CheapRuler& ruler, @@ -307,8 +310,8 @@ struct Comparator { // The priority queue will ensure the top element would always be the pair that has the biggest distance using DistQueue = std::priority_queue, Comparator>; -// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force O(n*n) -// Most of the time, use index for in-place processing. +// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force +// O(n*n) Most of the time, use index for in-place processing. double pointsToPolygonDistance(const mapbox::geometry::multi_point& points, const mapbox::geometry::polygon& polygon, @@ -343,8 +346,9 @@ double pointsToPolygonDistance(const mapbox::geometry::multi_point& poin [&distQueue, &miniDist, &ruler, &points, &polyBBox](std::optional& rangeA) { if (!rangeA) return; auto tempDist = bboxToBBoxDistance(getBBox(points, *rangeA), polyBBox, ruler); - // Insert new pair to the queue if the bbox distance is less than miniDist, - // The pair with biggest distance will be at the top + // Insert new pair to the queue if the bbox distance is less + // than miniDist, The pair with biggest distance will be at + // the top if (tempDist < miniDist) distQueue.push(std::make_tuple(tempDist, std::move(*rangeA), IndexRange(0, 0))); }; @@ -383,8 +387,9 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, [&distQueue, &miniDist, &ruler, &line, &polyBBox](std::optional& rangeA) { if (!rangeA) return; auto tempDist = bboxToBBoxDistance(getBBox(line, *rangeA), polyBBox, ruler); - // Insert new pair to the queue if the bbox distance is less than miniDist, - // The pair with biggest distance will be at the top + // Insert new pair to the queue if the bbox distance is less + // than miniDist, The pair with biggest distance will be at + // the top if (tempDist < miniDist) distQueue.push(std::make_tuple(tempDist, std::move(*rangeA), IndexRange(0, 0))); }; @@ -424,8 +429,9 @@ double lineToLineDistance(const mapbox::geometry::line_string& line1, std::optional& range1, std::optional& range2) { if (!range1 || !range2) return; auto tempDist = bboxToBBoxDistance(getBBox(line1, *range1), getBBox(line2, *range2), ruler); - // Insert new pair to the queue if the bbox distance is less than miniDist, - // The pair with biggest distance will be at the top + // Insert new pair to the queue if the bbox distance is less + // than miniDist, The pair with biggest distance will be at + // the top if (tempDist < miniDist) distQueue.push(std::make_tuple(tempDist, std::move(*range1), std::move(*range2))); }; @@ -468,8 +474,9 @@ double pointsToPointsDistance(const mapbox::geometry::multi_point& point std::optional& range1, std::optional& range2) { if (!range1 || !range2) return; auto tempDist = bboxToBBoxDistance(getBBox(pointSet1, *range1), getBBox(pointSet2, *range2), ruler); - // Insert new pair to the queue if the bbox distance is less than miniDist, - // The pair with biggest distance will be at the top + // Insert new pair to the queue if the bbox distance is less + // than miniDist, The pair with biggest distance will be at + // the top if (tempDist < miniDist) distQueue.push(std::make_tuple(tempDist, std::move(*range1), std::move(*range2))); }; @@ -505,8 +512,8 @@ double pointsToLineDistance(const mapbox::geometry::multi_point& points, mbgl::Log::Error(mbgl::Event::Style, "Index is out of range"); return InvalidDistance; } - auto subLine = - mapbox::geometry::multi_point(line.begin() + rangeB.first, line.begin() + rangeB.second + 1); + auto subLine = mapbox::geometry::multi_point(line.begin() + rangeB.first, + line.begin() + rangeB.second + 1); for (std::size_t i = rangeA.first; i <= rangeA.second; ++i) { miniDist = std::min(miniDist, pointToLineDistance(points[i], subLine, ruler)); if (miniDist == 0.0) return 0.0; @@ -518,8 +525,9 @@ double pointsToLineDistance(const mapbox::geometry::multi_point& points, std::optional& range1, std::optional& range2) { if (!range1 || !range2) return; auto tempDist = bboxToBBoxDistance(getBBox(points, *range1), getBBox(line, *range2), ruler); - // Insert new pair to the queue if the bbox distance is less than miniDist, - // The pair with biggest distance will be at the top + // Insert new pair to the queue if the bbox distance is less + // than miniDist, The pair with biggest distance will be at + // the top if (tempDist < miniDist) distQueue.push(std::make_tuple(tempDist, std::move(*range1), std::move(*range2))); }; @@ -739,17 +747,21 @@ std::optional parseValue(const style::conversion::Convertible& value, s ctx.error(error.message); } } - ctx.error("'distance' expression needs to be an array with format [\"distance\", GeoJSONObj]."); + ctx.error( + "'distance' expression needs to be an array with format [\"distance\", " + "GeoJSONObj]."); return std::nullopt; } -std::optional getGeometry(const Feature& feature, mbgl::style::expression::ParsingContext& ctx) { +std::optional getGeometry(const Feature& feature, + mbgl::style::expression::ParsingContext& ctx) { const auto type = apply_visitor(ToFeatureType(), feature.geometry); if (type == FeatureType::Point || type == FeatureType::LineString || type == FeatureType::Polygon) { return feature.geometry; } ctx.error( - "'distance' expression requires valid geojson object with valid geometry type: Point, LineString or Polygon."); + "'distance' expression requires valid geojson object with valid " + "geometry type: Point, LineString or Polygon."); return std::nullopt; } } // namespace @@ -758,7 +770,9 @@ namespace style { namespace expression { Distance::Distance(GeoJSON geojson, Feature::geometry_type geometries_) - : Expression(Kind::Distance, type::Number), geoJSONSource(std::move(geojson)), geometries(std::move(geometries_)) {} + : Expression(Kind::Distance, type::Number), + geoJSONSource(std::move(geojson)), + geometries(std::move(geometries_)) {} Distance::~Distance() = default; @@ -766,7 +780,9 @@ using namespace mbgl::style::conversion; EvaluationResult Distance::evaluate(const EvaluationContext& params) const { if (!params.feature || !params.canonical) { - return EvaluationError{"distance expression requirs valid feature and canonical information."}; + return EvaluationError{ + "distance expression requirs valid feature and canonical " + "information."}; } auto geometryType = params.feature->getType(); if (geometryType == FeatureType::Point || geometryType == FeatureType::LineString || @@ -777,7 +793,9 @@ EvaluationResult Distance::evaluate(const EvaluationContext& params) const { return distance; } } - return EvaluationError{"distance expression currently only evaluates valid Point/LineString/Polygon geometries."}; + return EvaluationError{ + "distance expression currently only evaluates valid " + "Point/LineString/Polygon geometries."}; } ParseResult Distance::parse(const Convertible& value, ParsingContext& ctx) { @@ -809,7 +827,8 @@ ParseResult Distance::parse(const Convertible& value, ParsingContext& ctx) { }, [&ctx](const auto&) { ctx.error( - "'distance' expression requires valid geojson that contains Point/LineString/Polygon geometries."); + "'distance' expression requires valid geojson that contains " + "Point/LineString/Polygon geometries."); return ParseResult(); }); @@ -857,7 +876,8 @@ mbgl::Value Distance::serialize() const { } } else { mbgl::Log::Error(mbgl::Event::Style, - "Failed to serialize 'distance' expression, converted rapidJSON is not an object"); + "Failed to serialize 'distance' expression, converted rapidJSON is " + "not an object"); } return std::vector{{getOperator(), serialized}}; } @@ -871,7 +891,7 @@ bool Distance::operator==(const Expression& e) const { } std::vector> Distance::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } std::string Distance::getOperator() const { diff --git a/src/mbgl/style/expression/dsl.cpp b/src/mbgl/style/expression/dsl.cpp index d8c105633f9..f9215c1c898 100644 --- a/src/mbgl/style/expression/dsl.cpp +++ b/src/mbgl/style/expression/dsl.cpp @@ -23,11 +23,11 @@ namespace dsl { std::unique_ptr compound(const char* op, std::vector> args) { ParsingContext ctx; - ParseResult result = createCompoundExpression(op, std::move(args), ctx); + ParseResult result = createCompoundExpression(op, std::move(args), ctx); assert(result); return std::move(*result); } - + std::unique_ptr createExpression(const char* expr) { using JSValue = rapidjson::GenericValue, rapidjson::CrtAllocator>; rapidjson::GenericDocument, rapidjson::CrtAllocator> document; @@ -36,8 +36,7 @@ std::unique_ptr createExpression(const char* expr) { const JSValue* expression = &document; expression::ParsingContext ctx; - expression::ParseResult parsed = - ctx.parseExpression(mbgl::style::conversion::Convertible(expression)); + expression::ParseResult parsed = ctx.parseExpression(mbgl::style::conversion::Convertible(expression)); return parsed ? std::move(*parsed) : nullptr; } @@ -67,7 +66,7 @@ std::unique_ptr literal(std::initializer_list value) { return literal(values); } -std::unique_ptr literal(std::initializer_list value) { +std::unique_ptr literal(std::initializer_list value) { std::vector values; for (auto i : value) { values.emplace_back(std::string(i)); @@ -78,25 +77,22 @@ std::unique_ptr literal(std::initializer_list value) { std::unique_ptr assertion(const type::Type& type, std::unique_ptr value, std::unique_ptr def) { - std::vector> v = vec(std::move(value)); + std::vector> v = vec(std::move(value)); if (def) { v.push_back(std::move(def)); } return std::make_unique(type, std::move(v)); } -std::unique_ptr number(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr number(std::unique_ptr value, std::unique_ptr def) { return assertion(type::Number, std::move(value), std::move(def)); } -std::unique_ptr string(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr string(std::unique_ptr value, std::unique_ptr def) { return assertion(type::String, std::move(value), std::move(def)); } -std::unique_ptr boolean(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr boolean(std::unique_ptr value, std::unique_ptr def) { return assertion(type::Boolean, std::move(value), std::move(def)); } @@ -110,18 +106,15 @@ std::unique_ptr coercion(const type::Type& type, return std::make_unique(type, std::move(v)); } -std::unique_ptr toColor(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr toColor(std::unique_ptr value, std::unique_ptr def) { return coercion(type::Color, std::move(value), std::move(def)); } -std::unique_ptr toString(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr toString(std::unique_ptr value, std::unique_ptr def) { return coercion(type::String, std::move(value), std::move(def)); } -std::unique_ptr toFormatted(std::unique_ptr value, - std::unique_ptr def) { +std::unique_ptr toFormatted(std::unique_ptr value, std::unique_ptr def) { return coercion(type::Formatted, std::move(value), std::move(def)); } @@ -145,29 +138,26 @@ std::unique_ptr zoom() { return compound("zoom"); } -std::unique_ptr eq(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr eq(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique("==", std::move(lhs), std::move(rhs)); } -std::unique_ptr ne(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr ne(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique("!=", std::move(lhs), std::move(rhs)); } -std::unique_ptr gt(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr gt(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique(">", std::move(lhs), std::move(rhs)); } -std::unique_ptr lt(std::unique_ptr lhs, - std::unique_ptr rhs) { +std::unique_ptr lt(std::unique_ptr lhs, std::unique_ptr rhs) { return std::make_unique("<", std::move(lhs), std::move(rhs)); } std::unique_ptr step(std::unique_ptr input, std::unique_ptr output0, - double input1, std::unique_ptr output1) { + double input1, + std::unique_ptr output1) { type::Type type = output0->getType(); std::map> stops; stops[-std::numeric_limits::infinity()] = std::move(output0); @@ -189,7 +179,8 @@ Interpolator cubicBezier(double x1, double y1, double x2, double y2) { std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr input, - double input1, std::unique_ptr output1) { + double input1, + std::unique_ptr output1) { type::Type type = output1->getType(); std::map> stops; stops[input1] = std::move(output1); @@ -201,8 +192,10 @@ std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2) { + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2) { type::Type type = output1->getType(); std::map> stops; stops[input1] = std::move(output1); @@ -215,9 +208,12 @@ std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr input, - double input1, std::unique_ptr output1, - double input2, std::unique_ptr output2, - double input3, std::unique_ptr output3) { + double input1, + std::unique_ptr output1, + double input2, + std::unique_ptr output2, + double input3, + std::unique_ptr output3) { type::Type type = output1->getType(); std::map> stops; stops[input1] = std::move(output1); diff --git a/src/mbgl/style/expression/expression.cpp b/src/mbgl/style/expression/expression.cpp index ce07d46436d..224e0264c79 100644 --- a/src/mbgl/style/expression/expression.cpp +++ b/src/mbgl/style/expression/expression.cpp @@ -12,8 +12,10 @@ class GeoJSONFeature : public GeometryTileFeature { const Feature& feature; mutable std::optional geometry; - explicit GeoJSONFeature(const Feature& feature_) : feature(feature_) {} - GeoJSONFeature(const Feature& feature_, const CanonicalTileID& canonical) : feature(feature_) { + explicit GeoJSONFeature(const Feature& feature_) + : feature(feature_) {} + GeoJSONFeature(const Feature& feature_, const CanonicalTileID& canonical) + : feature(feature_) { geometry = convertGeometry(feature.geometry, canonical); // https://github.com/mapbox/geojson-vt-cpp/issues/44 if (getTypeImpl() == FeatureType::Polygon) { diff --git a/src/mbgl/style/expression/find_zoom_curve.cpp b/src/mbgl/style/expression/find_zoom_curve.cpp index d888272dd46..1a7a91704a0 100644 --- a/src/mbgl/style/expression/find_zoom_curve.cpp +++ b/src/mbgl/style/expression/find_zoom_curve.cpp @@ -14,65 +14,64 @@ namespace expression { std::optional> findZoomCurve(const expression::Expression* e) { std::optional> result; - + switch (e->getKind()) { - case Kind::Let: { - auto let = static_cast(e); - result = findZoomCurve(let->getResult()); - break; - } - case Kind::Coalesce: { - auto coalesce = static_cast(e); - std::size_t length = coalesce->getLength(); - for (std::size_t i = 0; i < length; i++) { - result = findZoomCurve(coalesce->getChild(i)); - if (result) { - break; + case Kind::Let: { + auto let = static_cast(e); + result = findZoomCurve(let->getResult()); + break; + } + case Kind::Coalesce: { + auto coalesce = static_cast(e); + std::size_t length = coalesce->getLength(); + for (std::size_t i = 0; i < length; i++) { + result = findZoomCurve(coalesce->getChild(i)); + if (result) { + break; + } } + break; } - break; - } - case Kind::Interpolate: { - auto curve = static_cast(e); - if (curve->getInput()->getKind() == Kind::CompoundExpression) { - auto z = static_cast(curve->getInput().get()); - if (z && z->getOperator() == "zoom") { - result = {curve}; + case Kind::Interpolate: { + auto curve = static_cast(e); + if (curve->getInput()->getKind() == Kind::CompoundExpression) { + auto z = static_cast(curve->getInput().get()); + if (z && z->getOperator() == "zoom") { + result = {curve}; + } } + break; } - break; - } - case Kind::Step: { - auto step = static_cast(e); - if (step->getInput()->getKind() == Kind::CompoundExpression) { - auto z = static_cast(step->getInput().get()); - if (z && z->getOperator() == "zoom") { - result = {step}; + case Kind::Step: { + auto step = static_cast(e); + if (step->getInput()->getKind() == Kind::CompoundExpression) { + auto z = static_cast(step->getInput().get()); + if (z && z->getOperator() == "zoom") { + result = {step}; + } } + break; } - break; + default: + break; } - default: - break; - } - + if (result && result->is()) { return result; } - + e->eachChild([&](const Expression& child) { std::optional> childResult(findZoomCurve(&child)); if (childResult) { if (childResult->is()) { result = childResult; } else if (!result && childResult) { - result = {ParsingError { - R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", "" - }}; + result = {ParsingError{ + R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", + ""}}; } else if (result && childResult && result != childResult) { - result = {ParsingError { - R"(Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.)", "" - }}; + result = {ParsingError{ + R"(Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.)", ""}}; } } }); @@ -89,10 +88,7 @@ variant findZoomCurveChecked(co assert(false); return nullptr; }, - [](auto zoomCurve) -> variant { - return zoomCurve; - } - ); + [](auto zoomCurve) -> variant { return zoomCurve; }); } } // namespace expression diff --git a/src/mbgl/style/expression/format_expression.cpp b/src/mbgl/style/expression/format_expression.cpp index f88096f844e..9999cad8cde 100644 --- a/src/mbgl/style/expression/format_expression.cpp +++ b/src/mbgl/style/expression/format_expression.cpp @@ -6,7 +6,8 @@ namespace mbgl { namespace style { namespace expression { -FormatExpressionSection::FormatExpressionSection(std::unique_ptr content_) : content(std::move(content_)) {} +FormatExpressionSection::FormatExpressionSection(std::unique_ptr content_) + : content(std::move(content_)) {} void FormatExpressionSection::setTextSectionOptions(std::optional> fontScale_, std::optional> textFont_, @@ -28,9 +29,8 @@ void FormatExpressionSection::setTextSectionOptions(std::optional sections_) - : Expression(Kind::FormatExpression, type::Formatted) - , sections(std::move(sections_)) -{} + : Expression(Kind::FormatExpression, type::Formatted), + sections(std::move(sections_)) {} using namespace mbgl::style::conversion; @@ -142,7 +142,7 @@ bool FormatExpression::operator==(const Expression& e) const { } mbgl::Value FormatExpression::serialize() const { - std::vector serialized{{ getOperator() }}; + std::vector serialized{{getOperator()}}; for (const auto& section : sections) { serialized.push_back(section.content->serialize()); std::unordered_map options; @@ -180,7 +180,9 @@ EvaluationResult FormatExpression::evaluate(const EvaluationContext& params) con } else { evaluatedText = toString(*contentResult); if (!evaluatedText) { - return EvaluationError({"Could not coerce format expression text input to string."}); + return EvaluationError( + {"Could not coerce format expression text input to " + "string."}); } } @@ -201,7 +203,9 @@ EvaluationResult FormatExpression::evaluate(const EvaluationContext& params) con } auto textFontValue = ValueConverter>::fromExpressionValue(*textFontResult); if (!textFontValue) { - return EvaluationError { "Format text-font option must evaluate to an array of strings" }; + return EvaluationError{ + "Format text-font option must evaluate to an array of " + "strings"}; } evaluatedTextFont = *textFontValue; } @@ -215,7 +219,7 @@ EvaluationResult FormatExpression::evaluate(const EvaluationContext& params) con evaluatedTextColor = fromExpressionValue(*textColorResult); if (!evaluatedTextColor) { - return EvaluationError { "Format text-color option must evaluate to Color" }; + return EvaluationError{"Format text-color option must evaluate to Color"}; } } evaluatedSections.emplace_back(*evaluatedText, evaluatedFontScale, evaluatedTextFont, evaluatedTextColor); @@ -226,4 +230,3 @@ EvaluationResult FormatExpression::evaluate(const EvaluationContext& params) con } // namespace expression } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/formatted.cpp b/src/mbgl/style/expression/formatted.cpp index 5ad34a578cf..43efbebe7da 100644 --- a/src/mbgl/style/expression/formatted.cpp +++ b/src/mbgl/style/expression/formatted.cpp @@ -77,7 +77,7 @@ mbgl::Value Formatted::toObject() const { } // namespace expression namespace conversion { - + using namespace mbgl::style::expression; std::optional Converter::operator()(const Convertible& value, Error& error) const { @@ -89,7 +89,9 @@ std::optional Converter::operator()(const Convertible& val const Convertible& section = arrayMember(value, i); std::size_t sectionLength = arrayLength(section); if (sectionLength < 1) { - error.message = "Section has to contain a text and std::optional parameters or an image."; + error.message = + "Section has to contain a text and std::optional " + "parameters or an image."; return std::nullopt; } @@ -102,13 +104,17 @@ std::optional Converter::operator()(const Convertible& val std::optional imageOp = toString(arrayMember(firstElement, 0)); if (!imageOp || *imageOp != "image") { - error.message = "Serialized image section has to contain 'image' operator."; + error.message = + "Serialized image section has to contain 'image' " + "operator."; return std::nullopt; } std::optional imageArg = toString(arrayMember(firstElement, 1)); if (!imageArg) { - error.message = "Serialized image section agument has to be of a String type."; + error.message = + "Serialized image section agument has to be of a " + "String type."; return std::nullopt; } @@ -180,4 +186,3 @@ std::optional Converter::operator()(const Convertible& val } // namespace conversion } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/get_covering_stops.cpp b/src/mbgl/style/expression/get_covering_stops.cpp index c9f87d93ac5..1f4b08408a0 100644 --- a/src/mbgl/style/expression/get_covering_stops.cpp +++ b/src/mbgl/style/expression/get_covering_stops.cpp @@ -5,7 +5,8 @@ namespace style { namespace expression { Range getCoveringStops(const std::map>& stops, - const double lower, const double upper) { + const double lower, + const double upper) { assert(!stops.empty()); auto minIt = stops.lower_bound(lower); auto maxIt = stops.lower_bound(upper); @@ -15,10 +16,8 @@ Range getCoveringStops(const std::map if (minIt != stops.begin() && minIt != stops.end() && minIt->first > lower) { minIt--; } - return Range { - static_cast(minIt == stops.end() ? stops.rbegin()->first : minIt->first), - static_cast(maxIt == stops.end() ? stops.rbegin()->first : maxIt->first) - }; + return Range{static_cast(minIt == stops.end() ? stops.rbegin()->first : minIt->first), + static_cast(maxIt == stops.end() ? stops.rbegin()->first : maxIt->first)}; } } // namespace expression diff --git a/src/mbgl/style/expression/image.cpp b/src/mbgl/style/expression/image.cpp index d8c5d98188a..79b3ac6c997 100644 --- a/src/mbgl/style/expression/image.cpp +++ b/src/mbgl/style/expression/image.cpp @@ -6,11 +6,15 @@ namespace mbgl { namespace style { namespace expression { -Image::Image(std::string imageID_, bool available_) : imageID(std::move(imageID_)), available(available_) {} +Image::Image(std::string imageID_, bool available_) + : imageID(std::move(imageID_)), + available(available_) {} -Image::Image(std::string imageID_) : Image(std::move(imageID_), false) {} +Image::Image(std::string imageID_) + : Image(std::move(imageID_), false) {} -Image::Image(const char* imageID_) : Image(std::string(imageID_)) { +Image::Image(const char* imageID_) + : Image(std::string(imageID_)) { assert(imageID_); } diff --git a/src/mbgl/style/expression/image_expression.cpp b/src/mbgl/style/expression/image_expression.cpp index ed3a4f3bd0c..b49a195511d 100644 --- a/src/mbgl/style/expression/image_expression.cpp +++ b/src/mbgl/style/expression/image_expression.cpp @@ -7,7 +7,8 @@ namespace style { namespace expression { ImageExpression::ImageExpression(std::unique_ptr imageID_) - : Expression(Kind::ImageExpression, type::Image), imageID(std::move(imageID_)) { + : Expression(Kind::ImageExpression, type::Image), + imageID(std::move(imageID_)) { assert(imageID); } diff --git a/src/mbgl/style/expression/in.cpp b/src/mbgl/style/expression/in.cpp index 2fa1a69d3bf..99b21528825 100644 --- a/src/mbgl/style/expression/in.cpp +++ b/src/mbgl/style/expression/in.cpp @@ -29,7 +29,9 @@ bool isSearchableRuntimeType(const type::Type& type) { } // namespace In::In(std::unique_ptr needle_, std::unique_ptr haystack_) - : Expression(Kind::In, type::Boolean), needle(std::move(needle_)), haystack(std::move(haystack_)) { + : Expression(Kind::In, type::Boolean), + needle(std::move(needle_)), + haystack(std::move(haystack_)) { assert(isComparableType(needle->getType())); assert(isSearchableType(haystack->getType())); } @@ -47,14 +49,18 @@ EvaluationResult In::evaluate(const EvaluationContext& params) const { type::Type evaluatedNeedleType = typeOf(*evaluatedNeedle); if (!isComparableRuntimeType(evaluatedNeedleType)) { - return EvaluationError{"Expected first argument to be of type boolean, string or number, but found " + - toString(evaluatedNeedleType) + " instead."}; + return EvaluationError{ + "Expected first argument to be of type boolean, string or number, " + "but found " + + toString(evaluatedNeedleType) + " instead."}; } type::Type evaluatedHaystackType = typeOf(*evaluatedHaystack); if (!isSearchableRuntimeType(evaluatedHaystackType)) { - return EvaluationError{"Expected second argument to be of type array or string, but found " + - toString(evaluatedHaystackType) + " instead."}; + return EvaluationError{ + "Expected second argument to be of type array or string, but " + "found " + + toString(evaluatedHaystackType) + " instead."}; } if (evaluatedNeedleType == type::Null || evaluatedHaystackType == type::Null) { @@ -97,14 +103,18 @@ ParseResult In::parse(const Convertible& value, ParsingContext& ctx) { type::Type haystackType = (*haystack)->getType(); if (!isComparableType(needleType)) { - ctx.error("Expected first argument to be of type boolean, string or number, but found " + toString(needleType) + - " instead."); + ctx.error( + "Expected first argument to be of type boolean, string or number, " + "but found " + + toString(needleType) + " instead."); return ParseResult(); } if (!isSearchableType(haystackType)) { - ctx.error("Expected second argument to be of type array or string, but found " + toString(haystackType) + - " instead."); + ctx.error( + "Expected second argument to be of type array or string, but " + "found " + + toString(haystackType) + " instead."); return ParseResult(); } return ParseResult(std::make_unique(std::move(*needle), std::move(*haystack))); diff --git a/src/mbgl/style/expression/interpolate.cpp b/src/mbgl/style/expression/interpolate.cpp index cec6e941429..8cde78dc6f5 100644 --- a/src/mbgl/style/expression/interpolate.cpp +++ b/src/mbgl/style/expression/interpolate.cpp @@ -28,11 +28,11 @@ class InterpolateImpl : public Interpolate { float x = *fromExpressionValue(*evaluatedInput); if (std::isnan(x)) { - return EvaluationError { "Input is not a number." }; + return EvaluationError{"Input is not a number."}; } if (stops.empty()) { - return EvaluationError { "No stops in exponential curve." }; + return EvaluationError{"No stops in exponential curve."}; } auto it = stops.upper_bound(x); @@ -41,7 +41,7 @@ class InterpolateImpl : public Interpolate { } else if (it == stops.begin()) { return stops.begin()->second->evaluate(params); } else { - double t = interpolationFactor({ std::prev(it)->first, it->first }, x); + double t = interpolationFactor({std::prev(it)->first, it->first}, x); if (t == 0.0) { return std::prev(it)->second->evaluate(params); @@ -60,17 +60,13 @@ class InterpolateImpl : public Interpolate { } if (!lower->is()) { - return EvaluationError { - "Expected value to be of type " + toString(valueTypeToExpressionType()) + - ", but found " + toString(typeOf(*lower)) + " instead." - }; + return EvaluationError{"Expected value to be of type " + toString(valueTypeToExpressionType()) + + ", but found " + toString(typeOf(*lower)) + " instead."}; } if (!upper->is()) { - return EvaluationError { - "Expected value to be of type " + toString(valueTypeToExpressionType()) + - ", but found " + toString(typeOf(*upper)) + " instead." - }; + return EvaluationError{"Expected value to be of type " + toString(valueTypeToExpressionType()) + + ", but found " + toString(typeOf(*upper)) + " instead."}; } return util::interpolate(lower->get(), upper->get(), t); } @@ -94,7 +90,7 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { } std::optional interpolator; - + const std::optional interpName = toString(arrayMember(interp, 0)); if (interpName && *interpName == "linear") { interpolator = {ExponentialInterpolator(1.0)}; @@ -119,37 +115,34 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { x2 = toDouble(arrayMember(interp, 3)); y2 = toDouble(arrayMember(interp, 4)); } - if ( - !x1 || !y1 || !x2 || !y2 || - *x1 < 0 || *x1 > 1 || - *y1 < 0 || *y1 > 1 || - *x2 < 0 || *x2 > 1 || - *y2 < 0 || *y2 > 1 - ) { - ctx.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.", 1); + if (!x1 || !y1 || !x2 || !y2 || *x1 < 0 || *x1 > 1 || *y1 < 0 || *y1 > 1 || *x2 < 0 || *x2 > 1 || *y2 < 0 || + *y2 > 1) { + ctx.error( + "Cubic bezier interpolation requires four numeric arguments " + "with values between 0 and 1.", + 1); return ParseResult(); - } interpolator = {CubicBezierInterpolator(*x1, *y1, *x2, *y2)}; } - + if (!interpolator) { ctx.error("Unknown interpolation type " + (interpName ? *interpName : ""), 1, 0); return ParseResult(); } - + std::size_t minArgs = 4; if (length - 1 < minArgs) { ctx.error("Expected at least 4 arguments, but found only " + util::toString(length - 1) + "."); return ParseResult(); } - + // [interpolation, interp_type, input, 2 * (n pairs)...] if ((length - 1) % 2 != 0) { ctx.error("Expected an even number of arguments."); return ParseResult(); } - + ParseResult input = ctx.parse(arrayMember(value, 2), 2, {type::Number}); if (!input) { return input; @@ -160,9 +153,9 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { if (ctx.getExpected() && *ctx.getExpected() != type::Value) { outputType = ctx.getExpected(); } - - double previous = - std::numeric_limits::infinity(); - + + double previous = -std::numeric_limits::infinity(); + for (std::size_t i = 3; i + 1 < length; i += 2) { const std::optional labelValue = toValue(arrayMember(value, i)); std::optional label; @@ -190,25 +183,25 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { label = std::optional{n}; } }, - [&](const auto&) {} - ); + [&](const auto&) {}); } if (!label) { - ctx.error(labelError ? *labelError : - R"(Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", + ctx.error( + labelError + ? *labelError + : R"(Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", i); return ParseResult(); } - + if (*label <= previous) { ctx.error( R"(Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.)", - i - ); + i); return ParseResult(); } previous = *label; - + auto output = ctx.parse(arrayMember(value, i + 1), i + 1, outputType); if (!output) { return ParseResult(); @@ -219,14 +212,10 @@ ParseResult parseInterpolate(const Convertible& value, ParsingContext& ctx) { stops.emplace(*label, std::move(*output)); } - + assert(outputType); - return createInterpolate(*outputType, - *interpolator, - std::move(*input), - std::move(stops), - ctx); + return createInterpolate(*outputType, *interpolator, std::move(*input), std::move(stops), ctx); } ParseResult createInterpolate(type::Type type, @@ -236,14 +225,12 @@ ParseResult createInterpolate(type::Type type, ParsingContext& ctx) { return type.match( [&](const type::NumberType&) -> ParseResult { - return ParseResult(std::make_unique>( - type, interpolator, std::move(input), std::move(stops) - )); + return ParseResult( + std::make_unique>(type, interpolator, std::move(input), std::move(stops))); }, [&](const type::ColorType&) -> ParseResult { - return ParseResult(std::make_unique>( - type, interpolator, std::move(input), std::move(stops) - )); + return ParseResult( + std::make_unique>(type, interpolator, std::move(input), std::move(stops))); }, [&](const type::Array& arrayType) -> ParseResult { if (arrayType.itemType != type::Number || !arrayType.N) { @@ -251,24 +238,22 @@ ParseResult createInterpolate(type::Type type, return ParseResult(); } return ParseResult(std::make_unique>>( - type, interpolator, std::move(input), std::move(stops) - )); + type, interpolator, std::move(input), std::move(stops))); }, [&](const auto&) { ctx.error("Type " + toString(type) + " is not interpolatable."); return ParseResult(); - } - ); + }); } Interpolate::Interpolate(const type::Type& type_, Interpolator interpolator_, std::unique_ptr input_, std::map> stops_) - : Expression(Kind::Interpolate, type_), - interpolator(std::move(interpolator_)), - input(std::move(input_)), - stops(std::move(stops_)) { + : Expression(Kind::Interpolate, type_), + interpolator(std::move(interpolator_)), + input(std::move(input_)), + stops(std::move(stops_)) { assert(input->getType() == type::Number); } @@ -285,22 +270,22 @@ std::vector> Interpolate::possibleOutputs() const { mbgl::Value Interpolate::serialize() const { std::vector serialized; serialized.emplace_back(getOperator()); - + interpolator.match( [&](const ExponentialInterpolator& exponential) { if (exponential.base == 1) { - serialized.emplace_back(std::vector{{ std::string("linear") }}); + serialized.emplace_back(std::vector{{std::string("linear")}}); } else { - serialized.emplace_back(std::vector{{ std::string("exponential"), exponential.base }}); + serialized.emplace_back(std::vector{{std::string("exponential"), exponential.base}}); } }, [&](const CubicBezierInterpolator& cubicBezier) { static const std::string cubicBezierTag("cubic-bezier"); auto p1 = cubicBezier.ub.getP1(); auto p2 = cubicBezier.ub.getP2(); - serialized.emplace_back(std::vector{{ cubicBezierTag, p1.first, p1.second, p2.first, p2.second }}); - } - ); + serialized.emplace_back( + std::vector{{cubicBezierTag, p1.first, p1.second, p2.first, p2.second}}); + }); serialized.emplace_back(input->serialize()); for (auto& entry : stops) { serialized.emplace_back(entry.first); diff --git a/src/mbgl/style/expression/is_constant.cpp b/src/mbgl/style/expression/is_constant.cpp index 4ae2c182922..1c946230cbe 100644 --- a/src/mbgl/style/expression/is_constant.cpp +++ b/src/mbgl/style/expression/is_constant.cpp @@ -1,7 +1,6 @@ #include #include - namespace mbgl { namespace style { namespace expression { diff --git a/src/mbgl/style/expression/is_expression.cpp b/src/mbgl/style/expression/is_expression.cpp index 245dd38313b..d071edd3a73 100644 --- a/src/mbgl/style/expression/is_expression.cpp +++ b/src/mbgl/style/expression/is_expression.cpp @@ -15,11 +15,10 @@ bool isExpression(const Convertible& value) { if (!isArray(value) || arrayLength(value) == 0) return false; std::optional name = toString(arrayMember(value, 0)); if (!name) return false; - + return isExpression(*name) || CompoundExpression::exists(*name); } - } // namespace expression } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/expression/length.cpp b/src/mbgl/style/expression/length.cpp index 2ce7fa90155..1e3432f42d7 100644 --- a/src/mbgl/style/expression/length.cpp +++ b/src/mbgl/style/expression/length.cpp @@ -8,22 +8,17 @@ namespace expression { Length::Length(std::unique_ptr input_) : Expression(Kind::Length, type::Number), - input(std::move(input_)) { -} + input(std::move(input_)) {} EvaluationResult Length::evaluate(const EvaluationContext& params) const { EvaluationResult value = input->evaluate(params); if (!value) return value; - return value->match( - [] (const std::string& s) { - return EvaluationResult { static_cast(s.size()) }; - }, - [] (const std::vector& v) { - return EvaluationResult { static_cast(v.size()) }; - }, - [&] (const auto&) -> EvaluationResult { - return EvaluationError { "Expected value to be of type string or array, but found " + toString(typeOf(*value)) + " instead." }; - }); + return value->match([](const std::string& s) { return EvaluationResult{static_cast(s.size())}; }, + [](const std::vector& v) { return EvaluationResult{static_cast(v.size())}; }, + [&](const auto&) -> EvaluationResult { + return EvaluationError{"Expected value to be of type string or array, but found " + + toString(typeOf(*value)) + " instead."}; + }); } void Length::eachChild(const std::function& visit) const { @@ -39,7 +34,7 @@ bool Length::operator==(const Expression& e) const { } std::vector> Length::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } using namespace mbgl::style::conversion; diff --git a/src/mbgl/style/expression/let.cpp b/src/mbgl/style/expression/let.cpp index cb3ca68c39c..254c5dcf7e4 100644 --- a/src/mbgl/style/expression/let.cpp +++ b/src/mbgl/style/expression/let.cpp @@ -35,26 +35,28 @@ ParseResult Let::parse(const Convertible& value, ParsingContext& ctx) { } std::map> bindings_; - for(std::size_t i = 1; i < length - 1; i += 2) { + for (std::size_t i = 1; i < length - 1; i += 2) { std::optional name = toString(arrayMember(value, i)); if (!name) { ctx.error("Expected string, but found " + getJSONType(arrayMember(value, i)) + " instead.", i); return ParseResult(); } - - bool isValidName = std::all_of(name->begin(), name->end(), [](unsigned char c) { - return ::isalnum(c) || c == '_'; - }); + + bool isValidName = std::all_of( + name->begin(), name->end(), [](unsigned char c) { return ::isalnum(c) || c == '_'; }); if (!isValidName) { - ctx.error("Variable names must contain only alphanumeric characters or '_'.", 1); + ctx.error( + "Variable names must contain only alphanumeric characters or " + "'_'.", + 1); return ParseResult(); } - + ParseResult bindingValue = ctx.parse(arrayMember(value, i + 1), i + 1); if (!bindingValue) { return ParseResult(); } - + bindings_.emplace(*name, std::move(*bindingValue)); } @@ -84,7 +86,7 @@ EvaluationResult Var::evaluate(const EvaluationContext& params) const { void Var::eachChild(const std::function&) const {} std::vector> Var::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } ParseResult Var::parse(const Convertible& value_, ParsingContext& ctx) { @@ -99,8 +101,9 @@ ParseResult Var::parse(const Convertible& value_, ParsingContext& ctx) { std::optional> bindingValue = ctx.getBinding(name_); if (!bindingValue) { - ctx.error(R"(Unknown variable ")" + name_ + R"(". Make sure ")" + - name_ + R"(" has been bound in an enclosing "let" expression before using it.)", 1); + ctx.error(R"(Unknown variable ")" + name_ + R"(". Make sure ")" + name_ + + R"(" has been bound in an enclosing "let" expression before using it.)", + 1); return ParseResult(); } @@ -108,7 +111,7 @@ ParseResult Var::parse(const Convertible& value_, ParsingContext& ctx) { } mbgl::Value Var::serialize() const { - return std::vector{{ getOperator(), name }}; + return std::vector{{getOperator(), name}}; } } // namespace expression diff --git a/src/mbgl/style/expression/literal.cpp b/src/mbgl/style/expression/literal.cpp index 9b07131404a..f980acf9fc6 100644 --- a/src/mbgl/style/expression/literal.cpp +++ b/src/mbgl/style/expression/literal.cpp @@ -21,24 +21,26 @@ std::optional parseValue(const Convertible& value, ParsingContext& ctx) { if (isObject(value)) { std::unordered_map result; bool error = false; - eachMember(value, [&] (const std::string& k, const mbgl::style::conversion::Convertible& v) -> std::optional { - if (!error) { - std::optional memberValue = parseValue(v, ctx); - if (memberValue) { - result.emplace(k, *memberValue); - } else { - error = true; - } - } - return {}; - }); + eachMember(value, + [&](const std::string& k, + const mbgl::style::conversion::Convertible& v) -> std::optional { + if (!error) { + std::optional memberValue = parseValue(v, ctx); + if (memberValue) { + result.emplace(k, *memberValue); + } else { + error = true; + } + } + return {}; + }); return error ? std::optional() : std::optional(result); } - + if (isArray(value)) { std::vector result; const auto length = arrayLength(value); - for(std::size_t i = 0; i < length; i++) { + for (std::size_t i = 0; i < length; i++) { std::optional item = parseValue(arrayMember(value, i), ctx); if (item) { result.emplace_back(*item); @@ -48,20 +50,16 @@ std::optional parseValue(const Convertible& value, ParsingContext& ctx) { } return std::optional(result); } - + std::optional v = toValue(value); // since value represents a JSON value, if it's not undefined, object, or // array, it must be convertible to mbgl::Value assert(v); - - return v->match( - [&](uint64_t n) { return checkNumber(n); }, - [&](int64_t n) { return checkNumber(n); }, - [&](double n) { return checkNumber(n); }, - [&](const auto&) { - return std::optional(toExpressionValue(*v)); - } - ); + + return v->match([&](uint64_t n) { return checkNumber(n); }, + [&](int64_t n) { return checkNumber(n); }, + [&](double n) { return checkNumber(n); }, + [&](const auto&) { return std::optional(toExpressionValue(*v)); }); } ParseResult Literal::parse(const Convertible& value, ParsingContext& ctx) { @@ -71,30 +69,28 @@ ParseResult Literal::parse(const Convertible& value, ParsingContext& ctx) { } else if (isArray(value)) { // object or array value, quoted with ["literal", value] if (arrayLength(value) != 2) { - ctx.error("'literal' expression requires exactly one argument, but found " + util::toString(arrayLength(value) - 1) + " instead."); + ctx.error( + "'literal' expression requires exactly one argument, but " + "found " + + util::toString(arrayLength(value) - 1) + " instead."); return ParseResult(); } const std::optional parsedValue = parseValue(arrayMember(value, 1), ctx); if (!parsedValue) { return ParseResult(); } - + // special case: infer the item type if possible for zero-length arrays - if ( - ctx.getExpected() && - ctx.getExpected()->template is() && - parsedValue->template is>() - ) { + if (ctx.getExpected() && ctx.getExpected()->template is() && + parsedValue->template is>()) { auto type = typeOf(*parsedValue).template get(); auto expected = ctx.getExpected()->template get(); - if ( - type.N && (*type.N == 0) && - (!expected.N || (*expected.N == 0)) - ) { - return ParseResult(std::make_unique(expected, parsedValue->template get>())); + if (type.N && (*type.N == 0) && (!expected.N || (*expected.N == 0))) { + return ParseResult( + std::make_unique(expected, parsedValue->template get>())); } } - + return ParseResult(std::make_unique(*parsedValue)); } else { // bare primitive value (string, number, boolean, null) @@ -105,7 +101,7 @@ ParseResult Literal::parse(const Convertible& value, ParsingContext& ctx) { mbgl::Value Literal::serialize() const { if (getType().is() || getType().is()) { - return std::vector{{ getOperator(), *fromExpressionValue(value) }}; + return std::vector{{getOperator(), *fromExpressionValue(value)}}; } else { return *fromExpressionValue(value); } diff --git a/src/mbgl/style/expression/match.cpp b/src/mbgl/style/expression/match.cpp index e2a825c1764..949ad881ec7 100644 --- a/src/mbgl/style/expression/match.cpp +++ b/src/mbgl/style/expression/match.cpp @@ -21,8 +21,7 @@ template bool Match::operator==(const Expression& e) const { if (e.getKind() == Kind::Match) { auto rhs = static_cast(&e); - return (*input == *(rhs->input) && - *otherwise == *(rhs->otherwise) && + return (*input == *(rhs->input) && *otherwise == *(rhs->otherwise) && Expression::childrenEqual(branches, rhs->branches)); } return false; @@ -47,12 +46,13 @@ mbgl::Value Match::serialize() const { std::vector serialized; serialized.emplace_back(getOperator()); serialized.emplace_back(input->serialize()); - - // Sort so serialization has an arbitrary defined order, even though branch order doesn't affect evaluation + + // Sort so serialization has an arbitrary defined order, even though branch + // order doesn't affect evaluation std::map> sortedBranches(branches.begin(), branches.end()); - // Group branches by unique match expression to support condensed serializations - // of the form [case1, case2, ...] -> matchExpression + // Group branches by unique match expression to support condensed + // serializations of the form [case1, case2, ...] -> matchExpression std::map outputLookup; std::vector>> groupedByOutput; for (auto& entry : sortedBranches) { @@ -66,20 +66,20 @@ mbgl::Value Match::serialize() const { groupedByOutput[outputIndex->second].second.emplace_back(entry.first); } }; - + for (auto& entry : groupedByOutput) { entry.second.size() == 1 - ? serialized.emplace_back(entry.second[0]) // Only a single label matches this output expression - : serialized.emplace_back(entry.second); // Array of literal labels pointing to this output expression - serialized.emplace_back(entry.first->serialize()); // The output expression itself + ? serialized.emplace_back(entry.second[0]) // Only a single label matches this output expression + : serialized.emplace_back(entry.second); // Array of literal labels pointing to this output expression + serialized.emplace_back(entry.first->serialize()); // The output expression itself } - + serialized.emplace_back(otherwise->serialize()); return serialized; } - -template<> EvaluationResult Match::evaluate(const EvaluationContext& params) const { +template <> +EvaluationResult Match::evaluate(const EvaluationContext& params) const { const EvaluationResult inputValue = input->evaluate(params); if (!inputValue) { return inputValue.error(); @@ -97,7 +97,8 @@ template<> EvaluationResult Match::evaluate(const EvaluationContext return otherwise->evaluate(params); } -template<> EvaluationResult Match::evaluate(const EvaluationContext& params) const { +template <> +EvaluationResult Match::evaluate(const EvaluationContext& params) const { const EvaluationResult inputValue = input->evaluate(params); if (!inputValue) { return inputValue.error(); @@ -115,7 +116,7 @@ template<> EvaluationResult Match::evaluate(const EvaluationContext& pa return (*it).second->evaluate(params); } } - + return otherwise->evaluate(params); } @@ -125,7 +126,10 @@ template class Match; using InputType = variant; using namespace mbgl::style::conversion; -std::optional parseInputValue(const Convertible& input, ParsingContext& parentContext, std::size_t index, std::optional& inputType) { +std::optional parseInputValue(const Convertible& input, + ParsingContext& parentContext, + std::size_t index, + std::optional& inputType) { using namespace mbgl::style::conversion; std::optional result; std::optional type; @@ -134,25 +138,31 @@ std::optional parseInputValue(const Convertible& input, ParsingContex if (value) { value->match( - [&] (uint64_t n) { + [&](uint64_t n) { if (!Value::isSafeInteger(n)) { - parentContext.error("Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + ".", index); + parentContext.error("Branch labels must be integers no larger than " + + util::toString(Value::maxSafeInteger()) + ".", + index); } else { type = {type::Number}; result = std::optional{static_cast(n)}; } }, - [&] (int64_t n) { + [&](int64_t n) { if (!Value::isSafeInteger(n)) { - parentContext.error("Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + ".", index); + parentContext.error("Branch labels must be integers no larger than " + + util::toString(Value::maxSafeInteger()) + ".", + index); } else { type = {type::Number}; result = std::optional{n}; } }, - [&] (double n) { + [&](double n) { if (!Value::isSafeInteger(n)) { - parentContext.error("Branch labels must be integers no larger than " + util::toString(Value::maxSafeInteger()) + ".", index); + parentContext.error("Branch labels must be integers no larger than " + + util::toString(Value::maxSafeInteger()) + ".", + index); } else if (n != std::floor(n)) { parentContext.error("Numeric branch labels must be integer values.", index); } else { @@ -160,14 +170,11 @@ std::optional parseInputValue(const Convertible& input, ParsingContex result = std::optional{static_cast(n)}; } }, - [&] (const std::string& s) { + [&](const std::string& s) { type = {type::String}; result = {s}; }, - [&] (const auto&) { - parentContext.error("Branch labels must be numbers or strings.", index); - } - ); + [&](const auto&) { parentContext.error("Branch labels must be numbers or strings.", index); }); } else { parentContext.error("Branch labels must be numbers or strings.", index); } @@ -191,18 +198,16 @@ std::optional parseInputValue(const Convertible& input, ParsingContex template static ParseResult create(type::Type outputType, - std::unique_ptrinput, - std::vector, - std::unique_ptr>> branches, + std::unique_ptr input, + std::vector, std::unique_ptr>> branches, std::unique_ptr otherwise, ParsingContext& ctx) { typename Match::Branches typedBranches; - + std::size_t index = 2; typedBranches.reserve(branches.size()); - for (std::pair, - std::unique_ptr>& pair : branches) { + for (std::pair, std::unique_ptr>& pair : branches) { std::shared_ptr result = std::move(pair.second); for (const InputType& label : pair.first) { const auto& typedLabel = label.template get(); @@ -212,24 +217,18 @@ static ParseResult create(type::Type outputType, } typedBranches.emplace(typedLabel, result); } - + index += 2; } - return ParseResult(std::make_unique>( - outputType, - std::move(input), - std::move(typedBranches), - std::move(otherwise) - )); + return ParseResult( + std::make_unique>(outputType, std::move(input), std::move(typedBranches), std::move(otherwise))); } ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { assert(isArray(value)); auto length = arrayLength(value); if (length < 5) { - ctx.error( - "Expected at least 4 arguments, but found only " + util::toString(length - 1) + "." - ); + ctx.error("Expected at least 4 arguments, but found only " + util::toString(length - 1) + "."); return ParseResult(); } @@ -245,8 +244,7 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { outputType = ctx.getExpected(); } - std::vector, - std::unique_ptr>> branches; + std::vector, std::unique_ptr>> branches; branches.reserve((length - 3) / 2); for (size_t i = 2; i + 1 < length; i += 2) { @@ -261,7 +259,7 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { ctx.error("Expected at least one branch label.", i); return ParseResult(); } - + labels.reserve(groupLength); for (size_t j = 0; j < groupLength; j++) { const std::optional inputValue = parseInputValue(arrayMember(label, j), ctx, i, inputType); @@ -277,16 +275,16 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { } labels.push_back(*inputValue); } - + ParseResult output = ctx.parse(arrayMember(value, i + 1), i + 1, outputType); if (!output) { return ParseResult(); } - + if (!outputType) { outputType = (*output)->getType(); } - + branches.emplace_back(std::move(labels), std::move(*output)); } @@ -321,8 +319,7 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { // accepts string and (integer) numeric values. assert(false); return ParseResult(); - } - ); + }); } } // namespace expression diff --git a/src/mbgl/style/expression/number_format.cpp b/src/mbgl/style/expression/number_format.cpp index 13082fffc2e..b5864e495c0 100644 --- a/src/mbgl/style/expression/number_format.cpp +++ b/src/mbgl/style/expression/number_format.cpp @@ -21,8 +21,7 @@ NumberFormat::NumberFormat(std::unique_ptr number_, locale(std::move(locale_)), currency(std::move(currency_)), minFractionDigits(std::move(minFractionDigits_)), - maxFractionDigits(std::move(maxFractionDigits_)) -{} + maxFractionDigits(std::move(maxFractionDigits_)) {} NumberFormat::~NumberFormat() = default; @@ -32,7 +31,7 @@ EvaluationResult NumberFormat::evaluate(const EvaluationContext& params) const { return numberResult.error(); } double evaluatedNumber = numberResult->get(); - + std::string evaluatedLocale; if (locale) { auto localeResult = locale->evaluate(params); @@ -70,11 +69,8 @@ EvaluationResult NumberFormat::evaluate(const EvaluationContext& params) const { } std::string output; - output = platform::formatNumber(evaluatedNumber, - evaluatedLocale, - evaluatedCurrency, - evaluatedMinFractionDigits, - evaluatedMaxFractionDigits); + output = platform::formatNumber( + evaluatedNumber, evaluatedLocale, evaluatedCurrency, evaluatedMinFractionDigits, evaluatedMaxFractionDigits); return output; } @@ -89,12 +85,10 @@ void NumberFormat::eachChild(const std::function& visit bool NumberFormat::operator==(const Expression& e) const { if (e.getKind() == Kind::NumberFormat) { auto rhs = static_cast(&e); - if ((locale && (!rhs->locale || *locale != *rhs->locale)) || - (!locale && rhs->locale)) { + if ((locale && (!rhs->locale || *locale != *rhs->locale)) || (!locale && rhs->locale)) { return false; } - if ((currency && (!rhs->currency || *currency != *rhs->currency)) || - (!currency && rhs->currency)) { + if ((currency && (!rhs->currency || *currency != *rhs->currency)) || (!currency && rhs->currency)) { return false; } if ((minFractionDigits && (!rhs->minFractionDigits || *minFractionDigits != *rhs->minFractionDigits)) || @@ -111,7 +105,7 @@ bool NumberFormat::operator==(const Expression& e) const { } std::vector> NumberFormat::possibleOutputs() const { - return { std::nullopt }; + return {std::nullopt}; } using namespace mbgl::style::conversion; @@ -181,15 +175,16 @@ ParseResult NumberFormat::parse(const Convertible& value, ParsingContext& ctx) { } } - return ParseResult(std::make_unique(std::move(*numberResult), - localeResult ? std::move(*localeResult) : nullptr, - currencyResult? std::move(*currencyResult) : nullptr, - minFractionDigitsResult ? std::move(*minFractionDigitsResult) : nullptr, - maxFractionDigitsResult ? std::move(*maxFractionDigitsResult) : nullptr)); + return ParseResult( + std::make_unique(std::move(*numberResult), + localeResult ? std::move(*localeResult) : nullptr, + currencyResult ? std::move(*currencyResult) : nullptr, + minFractionDigitsResult ? std::move(*minFractionDigitsResult) : nullptr, + maxFractionDigitsResult ? std::move(*maxFractionDigitsResult) : nullptr)); } mbgl::Value NumberFormat::serialize() const { - std::vector serialized{{ getOperator() }}; + std::vector serialized{{getOperator()}}; serialized.emplace_back(number->serialize()); std::unordered_map options; diff --git a/src/mbgl/style/expression/parsing_context.cpp b/src/mbgl/style/expression/parsing_context.cpp index 47d98ade08a..f91ed1105ca 100644 --- a/src/mbgl/style/expression/parsing_context.cpp +++ b/src/mbgl/style/expression/parsing_context.cpp @@ -54,9 +54,8 @@ bool isConstant(const Expression& expression) { } } - bool isTypeAnnotation = expression.getKind() == Kind::Coercion || - expression.getKind() == Kind::Assertion; - + bool isTypeAnnotation = expression.getKind() == Kind::Coercion || expression.getKind() == Kind::Assertion; + bool childrenConstant = true; expression.eachChild([&](const Expression& child) { // We can _almost_ assume that if `expressions` children are constant, @@ -75,11 +74,11 @@ bool isConstant(const Expression& expression) { if (!childrenConstant) { return false; } - + return isFeatureConstant(expression) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "heatmap-density"}}) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "line-progress"}}) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "accumulated"}}); + isGlobalPropertyConstant(expression, std::array{{"zoom", "heatmap-density"}}) && + isGlobalPropertyConstant(expression, std::array{{"zoom", "line-progress"}}) && + isGlobalPropertyConstant(expression, std::array{{"zoom", "accumulated"}}); } using namespace mbgl::style::conversion; @@ -88,14 +87,13 @@ ParseResult ParsingContext::parse(const Convertible& value, std::size_t index_, std::optional expected_, const std::optional& typeAnnotationOption) { - ParsingContext child(key + "[" + util::toString(index_) + "]", - errors, - std::move(expected_), - scope); + ParsingContext child(key + "[" + util::toString(index_) + "]", errors, std::move(expected_), scope); return child.parse(value, typeAnnotationOption); } -ParseResult ParsingContext::parse(const Convertible& value, std::size_t index_, std::optional expected_, +ParseResult ParsingContext::parse(const Convertible& value, + std::size_t index_, + std::optional expected_, const std::map>& bindings) { ParsingContext child(key + "[" + util::toString(index_) + "]", errors, @@ -150,24 +148,23 @@ bool isExpression(const std::string& name) { ParseResult ParsingContext::parse(const Convertible& value, const std::optional& typeAnnotationOption) { ParseResult parsed; - + if (isArray(value)) { const std::size_t length = arrayLength(value); if (length == 0) { - error(R"(Expected an array with at least one element. If you wanted a literal array, use ["literal", []].)"); + error( + R"(Expected an array with at least one element. If you wanted a literal array, use ["literal", []].)"); return ParseResult(); } - + const std::optional op = toString(arrayMember(value, 0)); if (!op) { - error( - "Expression name must be a string, but found " + getJSONType(arrayMember(value, 0)) + - R"( instead. If you wanted a literal array, use ["literal", [...]].)", - 0 - ); + error("Expression name must be a string, but found " + getJSONType(arrayMember(value, 0)) + + R"( instead. If you wanted a literal array, use ["literal", [...]].)", + 0); return ParseResult(); } - + auto parseFunction = expressionRegistry.find(op->c_str()); if (parseFunction != expressionRegistry.end()) { parsed = parseFunction->second(value, *this); @@ -202,11 +199,15 @@ ParseResult ParsingContext::parse(const Convertible& value, if (expected) { const type::Type actual = (*parsed)->getType(); - if ((*expected == type::String || *expected == type::Number || *expected == type::Boolean || *expected == type::Object || expected->is()) && actual == type::Value) { - parsed = { annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::assert)) }; + if ((*expected == type::String || *expected == type::Number || *expected == type::Boolean || + *expected == type::Object || expected->is()) && + actual == type::Value) { + parsed = { + annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::assert))}; } else if ((*expected == type::Color || *expected == type::Formatted || *expected == type::Image) && (actual == type::Value || actual == type::String)) { - parsed = { annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::coerce)) }; + parsed = { + annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::coerce))}; } else { checkType((*parsed)->getType()); if (!errors->empty()) { @@ -226,15 +227,13 @@ ParseResult ParsingContext::parse(const Convertible& value, error(evaluated.error().message); return ParseResult(); } - + const type::Type type = (*parsed)->getType(); if (type.is()) { // keep the original expression's array type, even if the evaluated // type is more specific. - return ParseResult(std::make_unique( - type.get(), - evaluated->get>()) - ); + return ParseResult( + std::make_unique(type.get(), evaluated->get>())); } else { return ParseResult(std::make_unique(*evaluated)); } diff --git a/src/mbgl/style/expression/step.cpp b/src/mbgl/style/expression/step.cpp index 7f75135e180..72f54d0fc75 100644 --- a/src/mbgl/style/expression/step.cpp +++ b/src/mbgl/style/expression/step.cpp @@ -12,10 +12,9 @@ namespace expression { Step::Step(const type::Type& type_, std::unique_ptr input_, std::map> stops_) - : Expression(Kind::Step, type_), - input(std::move(input_)), - stops(std::move(stops_)) -{ + : Expression(Kind::Step, type_), + input(std::move(input_)), + stops(std::move(stops_)) { assert(input->getType() == type::Number); } @@ -27,11 +26,11 @@ EvaluationResult Step::evaluate(const EvaluationContext& params) const { float x = *fromExpressionValue(*evaluatedInput); if (std::isnan(x)) { - return EvaluationError { "Input is not a number." }; + return EvaluationError{"Input is not a number."}; } if (stops.empty()) { - return EvaluationError { "No stops in step curve." }; + return EvaluationError{"No stops in step curve."}; } auto it = stops.upper_bound(x); @@ -79,7 +78,6 @@ Range Step::getCoveringStops(const double lower, const double upper) cons return ::mbgl::style::expression::getCoveringStops(stops, lower, upper); } - ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx) { assert(isArray(value)); @@ -89,28 +87,28 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi ctx.error("Expected at least 4 arguments, but found only " + util::toString(length - 1) + "."); return ParseResult(); } - + // [step, input, firstOutput_value, 2 * (n pairs)...] if ((length - 1) % 2 != 0) { ctx.error("Expected an even number of arguments."); return ParseResult(); } - + ParseResult input = ctx.parse(arrayMember(value, 1), 1, {type::Number}); if (!input) { return input; } - + std::map> stops; std::optional outputType; if (ctx.getExpected() && *ctx.getExpected() != type::Value) { outputType = ctx.getExpected(); } - - double previous = - std::numeric_limits::infinity(); - - // consume the first output value, which doesn't have a corresponding input value, - // before proceeding into the "stops" loop below. + + double previous = -std::numeric_limits::infinity(); + + // consume the first output value, which doesn't have a corresponding input + // value, before proceeding into the "stops" loop below. auto firstOutput = ctx.parse(arrayMember(value, 2), 2, outputType); if (!firstOutput) { return ParseResult(); @@ -119,8 +117,7 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi outputType = (*firstOutput)->getType(); } stops.emplace(-std::numeric_limits::infinity(), std::move(*firstOutput)); - - + for (std::size_t i = 3; i + 1 < length; i += 2) { const auto labelValue = toValue(arrayMember(value, i)); std::optional label; @@ -147,23 +144,23 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi label = std::optional{n}; } }, - [&](const auto&) {} - ); + [&](const auto&) {}); } if (!label) { - ctx.error(R"(Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", i); + ctx.error( + R"(Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.)", + i); return ParseResult(); } - + if (*label <= previous) { ctx.error( R"(Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.)", - i - ); + i); return ParseResult(); } previous = *label; - + auto output = ctx.parse(arrayMember(value, i + 1), i + 1, outputType); if (!output) { return ParseResult(); @@ -174,9 +171,9 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi stops.emplace(*label, std::move(*output)); } - + assert(outputType); - + return ParseResult(std::make_unique(*outputType, std::move(*input), std::move(stops))); } @@ -196,4 +193,3 @@ mbgl::Value Step::serialize() const { } // namespace expression } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/expression/util.cpp b/src/mbgl/style/expression/util.cpp index f1a8117b341..4e6d456206f 100644 --- a/src/mbgl/style/expression/util.cpp +++ b/src/mbgl/style/expression/util.cpp @@ -6,30 +6,21 @@ namespace style { namespace expression { std::string stringifyColor(double r, double g, double b, double a) { - return stringify(r) + ", " + - stringify(g) + ", " + - stringify(b) + ", " + - stringify(a); + return stringify(r) + ", " + stringify(g) + ", " + stringify(b) + ", " + stringify(a); } Result rgba(double r, double g, double b, double a) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { - return EvaluationError { - "Invalid rgba value [" + stringifyColor(r, g, b, a) + - "]: 'r', 'g', and 'b' must be between 0 and 255." - }; + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { + return EvaluationError{"Invalid rgba value [" + stringifyColor(r, g, b, a) + + "]: 'r', 'g', and 'b' must be between 0 and 255."}; } if (a < 0 || a > 1) { - return EvaluationError { - "Invalid rgba value [" + stringifyColor(r, g, b, a) + - "]: 'a' must be between 0 and 1." - }; + return EvaluationError{"Invalid rgba value [" + stringifyColor(r, g, b, a) + "]: 'a' must be between 0 and 1."}; } - return Color(static_cast(r / 255 * a), static_cast(g / 255 * a), static_cast(b / 255 * a), static_cast(a)); + return Color(static_cast(r / 255 * a), + static_cast(g / 255 * a), + static_cast(b / 255 * a), + static_cast(a)); } } // namespace expression diff --git a/src/mbgl/style/expression/value.cpp b/src/mbgl/style/expression/value.cpp index 1955a626ef9..a06923916e4 100644 --- a/src/mbgl/style/expression/value.cpp +++ b/src/mbgl/style/expression/value.cpp @@ -59,9 +59,9 @@ void writeJSON(rapidjson::Writer& writer, const Value& assert(false); }, [&](const Formatted& f) { - // `stringify` in turns calls ValueConverter::fromExpressionValue below - // Serialization strategy for Formatted objects is to return the constant - // expression that would generate them. + // `stringify` in turns calls ValueConverter::fromExpressionValue + // below Serialization strategy for Formatted objects is to return + // the constant expression that would generate them. mbgl::style::conversion::stringify(writer, f); }, [&](const Image& i) { mbgl::style::conversion::stringify(writer, i); }, @@ -93,31 +93,27 @@ struct FromMBGLValue { Value operator()(const std::vector& v) { std::vector result; result.reserve(v.size()); - for(const auto& item : v) { + for (const auto& item : v) { result.emplace_back(toExpressionValue(item)); } return result; } - + Value operator()(const std::unordered_map& v) { std::unordered_map result; result.reserve(v.size()); - for(const auto& entry : v) { + for (const auto& entry : v) { result.emplace(entry.first, toExpressionValue(entry.second)); } return result; } - + Value operator()(const std::string& s) { return s; } Value operator()(const bool b) { return b; } Value operator()(const NullValue) { return Null; } Value operator()(const double v) { return v; } - Value operator()(const uint64_t& v) { - return static_cast(v); - } - Value operator()(const int64_t& v) { - return static_cast(v); - } + Value operator()(const uint64_t& v) { return static_cast(v); } + Value operator()(const int64_t& v) { return static_cast(v); } }; Value ValueConverter::toExpressionValue(const mbgl::Value& value) { @@ -134,8 +130,8 @@ mbgl::Value ValueConverter::fromExpressionValue(const Value& value) return mbgl::Value(); }, [&](const Formatted& formatted) -> mbgl::Value { - // Serialization strategy for Formatted objects is to return the constant - // expression that would generate them. + // Serialization strategy for Formatted objects is to return the + // constant expression that would generate them. std::vector serialized; static std::string formatOperator("format"); serialized.emplace_back(formatOperator); @@ -147,7 +143,7 @@ mbgl::Value ValueConverter::fromExpressionValue(const Value& value) serialized.emplace_back(section.text); std::unordered_map options; - + if (section.fontScale) { options.emplace("font-scale", *section.fontScale); } @@ -157,7 +153,7 @@ mbgl::Value ValueConverter::fromExpressionValue(const Value& value) for (const auto& font : *section.fontStack) { fontStack.emplace_back(font); } - options.emplace("text-font", std::vector{ std::string("literal"), fontStack }); + options.emplace("text-font", std::vector{std::string("literal"), fontStack}); } if (section.textColor) { @@ -180,7 +176,7 @@ mbgl::Value ValueConverter::fromExpressionValue(const Value& value) [&](const std::unordered_map& values) -> mbgl::Value { std::unordered_map converted; converted.reserve(values.size()); - for(const auto& entry : values) { + for (const auto& entry : values) { converted.emplace(entry.first, fromExpressionValue(entry.second)); } return converted; @@ -193,12 +189,9 @@ Value ValueConverter::toExpressionValue(const float value) { } std::optional ValueConverter::fromExpressionValue(const Value& value) { - return value.template is() - ? static_cast(value.template get()) - : std::optional(); + return value.template is() ? static_cast(value.template get()) : std::optional(); } - template std::vector toArrayValue(const Container& value) { std::vector result; @@ -217,25 +210,23 @@ Value ValueConverter>::toExpressionValue(const std::array template std::optional> ValueConverter>::fromExpressionValue(const Value& value) { return value.match( - [&] (const std::vector& v) -> std::optional> { + [&](const std::vector& v) -> std::optional> { if (v.size() != N) return std::optional>(); - std::array result; - auto it = result.begin(); - for(const Value& item : v) { - std::optional convertedItem = ValueConverter::fromExpressionValue(item); - if (!convertedItem) { - return std::optional>(); - } - *it = *convertedItem; - it = std::next(it); + std::array result; + auto it = result.begin(); + for (const Value& item : v) { + std::optional convertedItem = ValueConverter::fromExpressionValue(item); + if (!convertedItem) { + return std::optional>(); } - return result; + *it = *convertedItem; + it = std::next(it); + } + return result; }, - [&] (const auto&) { return std::optional>(); } - ); + [&](const auto&) { return std::optional>(); }); } - template Value ValueConverter>::toExpressionValue(const std::vector& value) { return toArrayValue(value); @@ -244,10 +235,10 @@ Value ValueConverter>::toExpressionValue(const std::vector& va template std::optional> ValueConverter>::fromExpressionValue(const Value& value) { return value.match( - [&] (const std::vector& v) -> std::optional> { + [&](const std::vector& v) -> std::optional> { std::vector result; result.reserve(v.size()); - for(const Value& item : v) { + for (const Value& item : v) { std::optional convertedItem = ValueConverter::fromExpressionValue(item); if (!convertedItem) { return std::optional>(); @@ -256,8 +247,7 @@ std::optional> ValueConverter>::fromExpressionValu } return result; }, - [&] (const auto&) { return std::optional>(); } - ); + [&](const auto&) { return std::optional>(); }); } Value ValueConverter::toExpressionValue(const mbgl::style::Position& value) { @@ -279,16 +269,14 @@ std::optional ValueConverter::fromExpressionValue(const Valu } template -Value ValueConverter>>::toExpressionValue(const T& value) { +Value ValueConverter>>::toExpressionValue(const T& value) { return std::string(Enum::toString(value)); } template std::optional ValueConverter>>::fromExpressionValue(const Value& value) { - return value.match( - [&] (const std::string& v) { return Enum::toEnum(v); }, - [&] (const auto&) { return std::optional(); } - ); + return value.match([&](const std::string& v) { return Enum::toEnum(v); }, + [&](const auto&) { return std::optional(); }); } template @@ -296,24 +284,56 @@ type::Type valueTypeToExpressionType() { return ValueConverter::expressionType(); } -template <> type::Type valueTypeToExpressionType() { return type::Value; } -template <> type::Type valueTypeToExpressionType() { return type::Null; } -template <> type::Type valueTypeToExpressionType() { return type::Boolean; } -template <> type::Type valueTypeToExpressionType() { return type::Number; } -template <> type::Type valueTypeToExpressionType() { return type::String; } -template <> type::Type valueTypeToExpressionType() { return type::Color; } -template <> type::Type valueTypeToExpressionType() { return type::Collator; } -template <> type::Type valueTypeToExpressionType() { return type::Formatted; } +template <> +type::Type valueTypeToExpressionType() { + return type::Value; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Null; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Boolean; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Number; +} +template <> +type::Type valueTypeToExpressionType() { + return type::String; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Color; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Collator; +} +template <> +type::Type valueTypeToExpressionType() { + return type::Formatted; +} template <> type::Type valueTypeToExpressionType() { return type::Image; } -template <> type::Type valueTypeToExpressionType>() { return type::Object; } -template <> type::Type valueTypeToExpressionType>() { return type::Array(type::Value); } +template <> +type::Type valueTypeToExpressionType>() { + return type::Object; +} +template <> +type::Type valueTypeToExpressionType>() { + return type::Array(type::Value); +} // used only for the special (and private) "error" expression -template <> type::Type valueTypeToExpressionType() { return type::Error; } - +template <> +type::Type valueTypeToExpressionType() { + return type::Error; +} // for to_rgba expression template type::Type valueTypeToExpressionType>(); @@ -360,7 +380,7 @@ template struct ValueConverter; template type::Type valueTypeToExpressionType(); template struct ValueConverter; - + template type::Type valueTypeToExpressionType(); template struct ValueConverter; diff --git a/src/mbgl/style/expression/within.cpp b/src/mbgl/style/expression/within.cpp index f56e95aa160..1b2f5a0a0d5 100644 --- a/src/mbgl/style/expression/within.cpp +++ b/src/mbgl/style/expression/within.cpp @@ -20,13 +20,15 @@ Point latLonToTileCoodinates(const Point& point, const mbgl::Ca const double size = util::EXTENT * std::pow(2, canonical.z); auto x = (point.x + util::LONGITUDE_MAX) * size / util::DEGREES_MAX; - auto y = - (util::LONGITUDE_MAX - util::rad2deg(std::log(std::tan(point.y * M_PI / util::DEGREES_MAX + M_PI / 4.0)))) * - size / util::DEGREES_MAX; + auto y = (util::LONGITUDE_MAX - + util::rad2deg(std::log(std::tan(point.y * M_PI / util::DEGREES_MAX + M_PI / 4.0)))) * + size / util::DEGREES_MAX; Point p; - p.x = (util::clamp(static_cast(x), std::numeric_limits::min(), std::numeric_limits::max())); - p.y = (util::clamp(static_cast(y), std::numeric_limits::min(), std::numeric_limits::max())); + p.x = (util::clamp( + static_cast(x), std::numeric_limits::min(), std::numeric_limits::max())); + p.y = (util::clamp( + static_cast(y), std::numeric_limits::min(), std::numeric_limits::max())); return p; }; @@ -171,7 +173,7 @@ bool featureWithinPolygons(const GeometryTileFeature& feature, } std::optional parseValue(const mbgl::style::conversion::Convertible& value_, - mbgl::style::expression::ParsingContext& ctx) { + mbgl::style::expression::ParsingContext& ctx) { if (isObject(value_)) { mbgl::style::conversion::Error error; auto geojson = toGeoJSON(value_, error); @@ -181,17 +183,21 @@ std::optional parseValue(const mbgl::style::conversion::Convertib ctx.error(error.message); } - ctx.error("'within' expression requires valid geojson source that contains polygon geometry type."); + ctx.error( + "'within' expression requires valid geojson source that contains " + "polygon geometry type."); return std::nullopt; } std::optional getPolygonInfo(const Feature& polyFeature, - mbgl::style::expression::ParsingContext& ctx) { + mbgl::style::expression::ParsingContext& ctx) { const auto type = apply_visitor(ToFeatureType(), polyFeature.geometry); if (type == FeatureType::Polygon) { return polyFeature.geometry; } - ctx.error("'within' expression requires valid geojson source that contains polygon geometry type."); + ctx.error( + "'within' expression requires valid geojson source that contains " + "polygon geometry type."); return std::nullopt; } } // namespace @@ -200,7 +206,9 @@ namespace style { namespace expression { Within::Within(GeoJSON geojson, Feature::geometry_type geometries_) - : Expression(Kind::Within, type::Boolean), geoJSONSource(std::move(geojson)), geometries(std::move(geometries_)) {} + : Expression(Kind::Within, type::Boolean), + geoJSONSource(std::move(geojson)), + geometries(std::move(geometries_)) {} Within::~Within() = default; @@ -216,7 +224,8 @@ EvaluationResult Within::evaluate(const EvaluationContext& params) const { return featureWithinPolygons(*params.feature, *params.canonical, geometries); } mbgl::Log::Warning(mbgl::Event::General, - "within expression currently only support Point/LineString geometry type."); + "within expression currently only support Point/LineString geometry " + "type."); return false; } @@ -225,8 +234,10 @@ ParseResult Within::parse(const Convertible& value, ParsingContext& ctx) { if (isArray(value)) { // object value, quoted with ["within", value] if (arrayLength(value) != 2) { - ctx.error("'within' expression requires exactly one argument, but found " + - util::toString(arrayLength(value) - 1) + " instead."); + ctx.error( + "'within' expression requires exactly one argument, but " + "found " + + util::toString(arrayLength(value) - 1) + " instead."); return ParseResult(); } @@ -257,7 +268,9 @@ ParseResult Within::parse(const Convertible& value, ParsingContext& ctx) { return ParseResult(); }, [&ctx](const auto&) { - ctx.error("'within' expression requires valid geojson source that contains polygon geometry type."); + ctx.error( + "'within' expression requires valid geojson source that " + "contains polygon geometry type."); return ParseResult(); }); } @@ -306,7 +319,8 @@ mbgl::Value Within::serialize() const { } } else { mbgl::Log::Error(mbgl::Event::General, - "Failed to serialize 'within' expression, converted rapidJSON is not an object"); + "Failed to serialize 'within' expression, converted rapidJSON is " + "not an object"); } return std::vector{{getOperator(), serialized}}; } diff --git a/src/mbgl/style/filter.cpp b/src/mbgl/style/filter.cpp index 7b5ad8d9fc3..ba97cda252e 100644 --- a/src/mbgl/style/filter.cpp +++ b/src/mbgl/style/filter.cpp @@ -5,9 +5,8 @@ namespace mbgl { namespace style { bool Filter::operator()(const expression::EvaluationContext &context) const { - if (!this->expression) return true; - + const expression::EvaluationResult result = (*this->expression)->evaluate(context); if (result) { const std::optional typed = expression::fromExpressionValue(*result); diff --git a/src/mbgl/style/layer.cpp b/src/mbgl/style/layer.cpp index 348edcff93d..3b94aa9d9ed 100644 --- a/src/mbgl/style/layer.cpp +++ b/src/mbgl/style/layer.cpp @@ -23,8 +23,7 @@ static LayerObserver nullObserver; Layer::Layer(Immutable impl) : baseImpl(std::move(impl)), - observer(&nullObserver) { -} + observer(&nullObserver) {} Layer::~Layer() = default; @@ -71,8 +70,7 @@ VisibilityType Layer::getVisibility() const { } void Layer::setVisibility(VisibilityType value) { - if (value == getVisibility()) - return; + if (value == getVisibility()) return; auto impl_ = mutableBaseImpl(); impl_->visibility = value; baseImpl = std::move(impl_); @@ -180,7 +178,8 @@ std::optional Layer::setProperty(const std::string& name, con if (getTypeInfo()->source != LayerTypeInfo::Source::Required) { Log::Warning(mbgl::Event::General, "'source-layer' property cannot be set to" - "the layer " + baseImpl->id); + "the layer " + + baseImpl->id); return std::nullopt; } setSourceLayer(*sourceLayer); @@ -191,7 +190,8 @@ std::optional Layer::setProperty(const std::string& name, con if (getTypeInfo()->source != LayerTypeInfo::Source::Required) { Log::Warning(mbgl::Event::General, "'source' property cannot be set to" - "the layer " + baseImpl->id); + "the layer " + + baseImpl->id); return std::nullopt; } setSourceID(*sourceID); diff --git a/src/mbgl/style/layer_impl.cpp b/src/mbgl/style/layer_impl.cpp index b6ab1450124..7b59ead8442 100644 --- a/src/mbgl/style/layer_impl.cpp +++ b/src/mbgl/style/layer_impl.cpp @@ -5,8 +5,7 @@ namespace style { Layer::Impl::Impl(std::string layerID, std::string sourceID) : id(std::move(layerID)), - source(std::move(sourceID)) { -} + source(std::move(sourceID)) {} void Layer::Impl::populateFontStack(std::set&) const {} diff --git a/src/mbgl/style/layer_impl.hpp b/src/mbgl/style/layer_impl.hpp index 53dd1320bde..a7012bb79f6 100644 --- a/src/mbgl/style/layer_impl.hpp +++ b/src/mbgl/style/layer_impl.hpp @@ -15,15 +15,17 @@ namespace mbgl { namespace style { /** - * `Layer::Impl` contains the internal implementation of `Layer`: the details that need to be accessible to other parts - * of the code, but hidden from the public API. Like `Layer`, it is an abstract base class, with derived classes for - * each layer type. + * `Layer::Impl` contains the internal implementation of `Layer`: the details + * that need to be accessible to other parts of the code, but hidden from the + * public API. Like `Layer`, it is an abstract base class, with derived classes + * for each layer type. * * Members that are public in `Layer` are part of the public API for all layers. - * Members that are public in `FooLayer` are part of the public API for "foo" layers. - * Members that are public in `Layer::Impl` are part of the internal API for all layers. - * Members that are public in `FooLayer::Impl` are part of the internal API for "foo" layers. - * Members that are private in `FooLayer::Impl` are internal to "foo" layers. + * Members that are public in `FooLayer` are part of the public API for "foo" + * layers. Members that are public in `Layer::Impl` are part of the internal API + * for all layers. Members that are public in `FooLayer::Impl` are part of the + * internal API for "foo" layers. Members that are private in `FooLayer::Impl` + * are internal to "foo" layers. */ class Layer::Impl { public: @@ -32,8 +34,8 @@ class Layer::Impl { Impl& operator=(const Impl&) = delete; - // Returns true buckets if properties affecting layout have changed: i.e. filter, - // visibility, layout properties, or data-driven paint properties. + // Returns true buckets if properties affecting layout have changed: i.e. + // filter, visibility, layout properties, or data-driven paint properties. virtual bool hasLayoutDifference(const Layer::Impl&) const = 0; // Utility function for automatic layer grouping. @@ -58,9 +60,11 @@ class Layer::Impl { }; // To be used in the inherited classes. -#define DECLARE_LAYER_TYPE_INFO \ -const LayerTypeInfo* getTypeInfo() const noexcept final { return staticTypeInfo(); } \ -static const LayerTypeInfo* staticTypeInfo() noexcept +#define DECLARE_LAYER_TYPE_INFO \ + const LayerTypeInfo* getTypeInfo() const noexcept final { \ + return staticTypeInfo(); \ + } \ + static const LayerTypeInfo* staticTypeInfo() noexcept } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp b/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp index 18eea1f7fca..8452c7b1f55 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp +++ b/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp @@ -6,9 +6,7 @@ namespace style { bool FillExtrusionLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - paint.hasDataDrivenPropertyDifference(impl.paint); + return filter != impl.filter || visibility != impl.visibility || paint.hasDataDrivenPropertyDifference(impl.paint); } } // namespace style diff --git a/src/mbgl/style/layers/heatmap_layer_impl.cpp b/src/mbgl/style/layers/heatmap_layer_impl.cpp index dd5baaeb449..48deee27e3a 100644 --- a/src/mbgl/style/layers/heatmap_layer_impl.cpp +++ b/src/mbgl/style/layers/heatmap_layer_impl.cpp @@ -6,9 +6,7 @@ namespace style { bool HeatmapLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - paint.hasDataDrivenPropertyDifference(impl.paint); + return filter != impl.filter || visibility != impl.visibility || paint.hasDataDrivenPropertyDifference(impl.paint); } } // namespace style diff --git a/src/mbgl/style/layers/line_layer_impl.cpp b/src/mbgl/style/layers/line_layer_impl.cpp index b5183ba9aee..e459c7d3b4d 100644 --- a/src/mbgl/style/layers/line_layer_impl.cpp +++ b/src/mbgl/style/layers/line_layer_impl.cpp @@ -6,9 +6,7 @@ namespace style { bool LineLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - layout != impl.layout || + return filter != impl.filter || visibility != impl.visibility || layout != impl.layout || paint.hasDataDrivenPropertyDifference(impl.paint); } diff --git a/src/mbgl/style/layers/symbol_layer_impl.cpp b/src/mbgl/style/layers/symbol_layer_impl.cpp index 18e5f1cd857..09b386e6358 100644 --- a/src/mbgl/style/layers/symbol_layer_impl.cpp +++ b/src/mbgl/style/layers/symbol_layer_impl.cpp @@ -14,11 +14,10 @@ bool SymbolLayer::Impl::hasFormatSectionOverrides() const { bool SymbolLayer::Impl::hasLayoutDifference(const Layer::Impl& other) const { assert(other.getTypeInfo() == getTypeInfo()); const auto& impl = static_cast(other); - return filter != impl.filter || - visibility != impl.visibility || - layout != impl.layout || + return filter != impl.filter || visibility != impl.visibility || layout != impl.layout || paint.hasDataDrivenPropertyDifference(impl.paint) || - (hasFormatSectionOverrides() && SymbolLayerPaintPropertyOverrides::hasPaintPropertyDifference(paint, impl.paint)); + (hasFormatSectionOverrides() && + SymbolLayerPaintPropertyOverrides::hasPaintPropertyDifference(paint, impl.paint)); } void SymbolLayer::Impl::populateFontStack(std::set& fontStack) const { @@ -36,7 +35,12 @@ void SymbolLayer::Impl::populateFontStack(std::set& fontStack) const if (value) { fontStack.insert(*value); } else { - Log::Warning(Event::ParseStyle, "Layer '" + id + "' has an invalid value for text-font and will not render text. Output values must be contained as literals within the expression."); + Log::Warning(Event::ParseStyle, + "Layer '" + id + + "' has an invalid value for text-font and will not " + "render text. Output values " + "must be contained as literals within the " + "expression."); break; } } diff --git a/src/mbgl/style/layers/symbol_layer_impl.hpp b/src/mbgl/style/layers/symbol_layer_impl.hpp index 826f444e173..c99bf335f4a 100644 --- a/src/mbgl/style/layers/symbol_layer_impl.hpp +++ b/src/mbgl/style/layers/symbol_layer_impl.hpp @@ -12,77 +12,72 @@ namespace mbgl { namespace style { -template +template struct FormatSectionOverrides; -template +template struct FormatSectionOverrides> { - template + template static void setOverride(const T& overrides, U& overridable) { if (hasOverride(overrides.template get())) { - auto override = - std::make_unique>(Property::expressionType(), - std::move(overridable.template get()), - Property::name()); + auto override = std::make_unique>( + Property::expressionType(), std::move(overridable.template get()), Property::name()); PropertyExpression expr(std::move(override)); - overridable.template get() = PossiblyEvaluatedPropertyValue(std::move(expr)); + overridable.template get() = PossiblyEvaluatedPropertyValue( + std::move(expr)); } } - template + template static void setOverrides(const T& overrides, U& overridable) { util::ignore({(setOverride(overrides, overridable), 0)...}); } - template + template static void updateOverride(T& evaluated, U& updated) { auto property = evaluated.template get(); if (!property.isConstant()) { const bool hasFormatSectionOverride = property.match( - [] (const style::PropertyExpression& e) { - return e.getExpression().getKind() == expression::Kind::FormatSectionOverride; - }, - [] (const auto&) { - return false; - }); + [](const style::PropertyExpression& e) { + return e.getExpression().getKind() == expression::Kind::FormatSectionOverride; + }, + [](const auto&) { return false; }); if (hasFormatSectionOverride) { updated.template get() = std::move(property); } } } - template + template static void updateOverrides(T& evaluated, U& updated) { util::ignore({(updateOverride(evaluated, updated), 0)...}); } - template + template static bool hasOverride(const FormattedProperty& formatted) { - - const auto checkLiteral = [] (const TextField::Type& literal) { + const auto checkLiteral = [](const TextField::Type& literal) { for (const auto& section : literal.sections) { - if (Property::hasOverride(section)) { - return true; - } + if (Property::hasOverride(section)) { + return true; + } } return false; }; return formatted.match( - [&checkLiteral] (const TextField::Type& literal) { - return checkLiteral(literal); - }, - [&checkLiteral] (const PropertyExpression& property) { - bool expressionHasOverrides = false; - const std::function checkExpression = [&](const expression::Expression& e) { + [&checkLiteral](const TextField::Type& literal) { return checkLiteral(literal); }, + [&checkLiteral](const PropertyExpression& property) { + bool expressionHasOverrides = false; + const std::function checkExpression = + [&](const expression::Expression& e) { if (expressionHasOverrides) { return; } - if (e.getKind() == expression::Kind::Literal && - e.getType() == expression::type::Formatted) { + if (e.getKind() == expression::Kind::Literal && e.getType() == expression::type::Formatted) { const auto* literalExpr = static_cast(&e); - const auto formattedValue = expression::fromExpressionValue(literalExpr->getValue()); + const auto formattedValue = expression::fromExpressionValue( + literalExpr->getValue()); if (formattedValue && checkLiteral(*formattedValue)) { expressionHasOverrides = true; } @@ -100,28 +95,26 @@ struct FormatSectionOverrides> { } }; - checkExpression(property.getExpression()); - return expressionHasOverrides; - }, - [] (const auto&) { - return false; - } - ); + checkExpression(property.getExpression()); + return expressionHasOverrides; + }, + [](const auto&) { return false; }); } template static bool hasOverrides(const FormattedProperty& formatted) { bool result = false; - util::ignore({ (result |= hasOverride(formatted))... }); + util::ignore({(result |= hasOverride(formatted))...}); return result; } template static bool hasPaintPropertyDifference(const PaintProperties& lhs, const PaintProperties& rhs) { bool result = false; - util::ignore({ (result |= lhs.template get().value.isConstant() && - rhs.template get().value.isConstant() && - (lhs.template get().value.asConstant() != rhs.template get().value.asConstant()))... }); + util::ignore({(result |= lhs.template get().value.isConstant() && + rhs.template get().value.isConstant() && + (lhs.template get().value.asConstant() != + rhs.template get().value.asConstant()))...}); return result; } }; diff --git a/src/mbgl/style/light.cpp b/src/mbgl/style/light.cpp index bd46474391d..c045879a3cb 100644 --- a/src/mbgl/style/light.cpp +++ b/src/mbgl/style/light.cpp @@ -19,9 +19,12 @@ namespace style { static LightObserver nullObserver; -Light::Light(Immutable impl_) : impl(std::move(impl_)), observer(&nullObserver) {} +Light::Light(Immutable impl_) + : impl(std::move(impl_)), + observer(&nullObserver) {} -Light::Light() : Light(makeMutable()) {} +Light::Light() + : Light(makeMutable()) {} Light::~Light() = default; @@ -68,89 +71,84 @@ MAPBOX_ETERNAL_CONSTEXPR const auto properties = mapbox::eternal::hash_map Light::setProperty(const std::string& name, const Convertible& value) { const auto it = properties.find(name.c_str()); if (it == properties.end()) { - return Error { "light doesn't support this property" }; + return Error{"light doesn't support this property"}; } auto property = static_cast(it->second); - if (property == Property::Anchor) { Error error; - std::optional> typedValue = convert>(value, error, false, false); + std::optional> typedValue = convert>( + value, error, false, false); if (!typedValue) { return error; } - + setAnchor(*typedValue); return std::nullopt; - } - + if (property == Property::Color) { Error error; std::optional> typedValue = convert>(value, error, false, false); if (!typedValue) { return error; } - + setColor(*typedValue); return std::nullopt; - } - + if (property == Property::Intensity) { Error error; std::optional> typedValue = convert>(value, error, false, false); if (!typedValue) { return error; } - + setIntensity(*typedValue); return std::nullopt; - } - + if (property == Property::Position) { Error error; - std::optional> typedValue = convert>(value, error, false, false); + std::optional> typedValue = convert>( + value, error, false, false); if (!typedValue) { return error; } - + setPosition(*typedValue); return std::nullopt; - } - Error error; std::optional transition = convert(value, error); if (!transition) { return error; } - + if (property == Property::AnchorTransition) { setAnchorTransition(*transition); return std::nullopt; } - + if (property == Property::ColorTransition) { setColorTransition(*transition); return std::nullopt; } - + if (property == Property::IntensityTransition) { setIntensityTransition(*transition); return std::nullopt; } - + if (property == Property::PositionTransition) { setPositionTransition(*transition); return std::nullopt; } - - return Error { "light doesn't support this property" }; + return Error{"light doesn't support this property"}; } StyleProperty Light::getProperty(const std::string& name) const { @@ -284,6 +282,5 @@ TransitionOptions Light::getPositionTransition() const { return impl->properties.template get().options; } - } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/light_impl.cpp b/src/mbgl/style/light_impl.cpp index 619d115f02d..6f21185c104 100644 --- a/src/mbgl/style/light_impl.cpp +++ b/src/mbgl/style/light_impl.cpp @@ -1,7 +1,5 @@ #include namespace mbgl { -namespace style { - -} // namespace style +namespace style {} // namespace style } // namespace mbgl diff --git a/src/mbgl/style/light_impl.hpp b/src/mbgl/style/light_impl.hpp index db75db84ff5..7c066848a40 100644 --- a/src/mbgl/style/light_impl.hpp +++ b/src/mbgl/style/light_impl.hpp @@ -25,28 +25,22 @@ class LightProperty { }; struct LightAnchor : LightProperty { - static LightAnchorType defaultValue() { - return LightAnchorType::Viewport; - } + static LightAnchorType defaultValue() { return LightAnchorType::Viewport; } }; struct LightPosition : LightProperty { static Position defaultValue() { - std::array default_ = { { 1.15f, 210.f, 30.f } }; - return Position{ { default_ } }; + std::array default_ = {{1.15f, 210.f, 30.f}}; + return Position{{default_}}; } }; struct LightColor : LightProperty { - static Color defaultValue() { - return Color::white(); - } + static Color defaultValue() { return Color::white(); } }; struct LightIntensity : LightProperty { - static float defaultValue() { - return 0.5; - } + static float defaultValue() { return 0.5; } }; using LightProperties = Properties; diff --git a/src/mbgl/style/parser.cpp b/src/mbgl/style/parser.cpp index 4dbaaa15256..461cedc7b91 100644 --- a/src/mbgl/style/parser.cpp +++ b/src/mbgl/style/parser.cpp @@ -40,14 +40,17 @@ StyleParseResult Parser::parse(const std::string& json) { const JSValue& versionValue = document["version"]; const int version = versionValue.IsNumber() ? versionValue.GetInt() : 0; if (version != 8) { - Log::Warning(Event::ParseStyle, "current renderer implementation only supports style spec version 8; using an outdated style will cause rendering errors"); + Log::Warning(Event::ParseStyle, + "current renderer implementation only supports style spec " + "version 8; using an outdated style " + "will cause rendering errors"); } } if (document.HasMember("name")) { const JSValue& value = document["name"]; if (value.IsString()) { - name = { value.GetString(), value.GetStringLength() }; + name = {value.GetString(), value.GetStringLength()}; } } @@ -102,14 +105,14 @@ StyleParseResult Parser::parse(const std::string& json) { if (document.HasMember("sprite")) { const JSValue& sprite = document["sprite"]; if (sprite.IsString()) { - spriteURL = { sprite.GetString(), sprite.GetStringLength() }; + spriteURL = {sprite.GetString(), sprite.GetStringLength()}; } } if (document.HasMember("glyphs")) { const JSValue& glyphs = document["glyphs"]; if (glyphs.IsString()) { - glyphURL = { glyphs.GetString(), glyphs.GetStringLength() }; + glyphURL = {glyphs.GetString(), glyphs.GetStringLength()}; } } @@ -148,11 +151,11 @@ void Parser::parseSources(const JSValue& value) { } for (const auto& property : value.GetObject()) { - std::string id { property.name.GetString(), property.name.GetStringLength() }; + std::string id{property.name.GetString(), property.name.GetStringLength()}; conversion::Error error; - std::optional> source = - conversion::convert>(property.value, error, id); + std::optional> source = conversion::convert>( + property.value, error, id); if (!source) { Log::Warning(Event::ParseStyle, error.message); continue; @@ -187,22 +190,20 @@ void Parser::parseLayers(const JSValue& value) { continue; } - const std::string layerID = { id.GetString(), id.GetStringLength() }; + const std::string layerID = {id.GetString(), id.GetStringLength()}; if (layersMap.find(layerID) != layersMap.end()) { Log::Warning(Event::ParseStyle, "duplicate layer id " + layerID); continue; } - layersMap.emplace(layerID, std::pair> { layerValue, nullptr }); + layersMap.emplace(layerID, std::pair>{layerValue, nullptr}); ids.push_back(layerID); } for (const auto& id : ids) { auto it = layersMap.find(id); - parseLayer(it->first, - it->second.first, - it->second.second); + parseLayer(it->first, it->second.first, it->second.second); } for (const auto& id : ids) { @@ -230,11 +231,11 @@ void Parser::parseLayer(const std::string& id, const JSValue& value, std::unique // This layer is referencing another layer. Recursively parse that layer. const JSValue& refVal = value["ref"]; if (!refVal.IsString()) { - Log::Warning(Event::ParseStyle, "layer ref of '" + id + "' must be a string"); + Log::Warning(Event::ParseStyle, "layer ref of '" + id + "' must be a string"); return; } - const std::string ref { refVal.GetString(), refVal.GetStringLength() }; + const std::string ref{refVal.GetString(), refVal.GetStringLength()}; auto it = layersMap.find(ref); if (it == layersMap.end()) { Log::Warning(Event::ParseStyle, "layer '" + id + "' references unknown layer " + ref); @@ -243,9 +244,7 @@ void Parser::parseLayer(const std::string& id, const JSValue& value, std::unique // Recursively parse the referenced layer. stack.push_front(id); - parseLayer(it->first, - it->second.first, - it->second.second); + parseLayer(it->first, it->second.first, it->second.second); stack.pop_front(); Layer* reference = it->second.second.get(); diff --git a/src/mbgl/style/parser.hpp b/src/mbgl/style/parser.hpp index f25e85fbf7c..ab9d2df7387 100644 --- a/src/mbgl/style/parser.hpp +++ b/src/mbgl/style/parser.hpp @@ -33,7 +33,7 @@ class Parser { std::vector> sources; std::vector> layers; - TransitionOptions transition { { util::DEFAULT_TRANSITION_DURATION } }; + TransitionOptions transition{{util::DEFAULT_TRANSITION_DURATION}}; Light light; std::string name; diff --git a/src/mbgl/style/properties.hpp b/src/mbgl/style/properties.hpp index 7860dd3d9ef..4a2c63b6bb4 100644 --- a/src/mbgl/style/properties.hpp +++ b/src/mbgl/style/properties.hpp @@ -22,15 +22,14 @@ class Transitioning { Transitioning() = default; explicit Transitioning(Value value_) - : value(std::move(value_)) { - } + : value(std::move(value_)) {} Transitioning(Value value_, Transitioning prior_, const TransitionOptions& transition, TimePoint now) : begin(now + transition.delay.value_or(Duration::zero())), end(begin + transition.duration.value_or(Duration::zero())), value(std::move(value_)) { if (transition.isDefined()) { - prior = { std::move(prior_) }; + prior = {std::move(prior_)}; } } @@ -46,8 +45,9 @@ class Transitioning { return finalValue; } else if (value.isDataDriven()) { // Transitions to data-driven properties are not supported. - // We snap immediately to the data-driven value so that, when we perform layout, - // we see the data-driven function and can use it to populate vertex buffers. + // We snap immediately to the data-driven value so that, when we + // perform layout, we see the data-driven function and can use it to + // populate vertex buffers. prior = {}; return finalValue; } else if (now < begin) { @@ -56,22 +56,17 @@ class Transitioning { } else { // Interpolate between recursively-calculated prior value and final. float t = std::chrono::duration(now - begin) / (end - begin); - return util::interpolate(prior->get().evaluate(evaluator, now), finalValue, + return util::interpolate(prior->get().evaluate(evaluator, now), + finalValue, static_cast(util::DEFAULT_TRANSITION_EASE.solve(t, 0.001))); } } - bool hasTransition() const { - return bool(prior); - } + bool hasTransition() const { return bool(prior); } - bool isUndefined() const { - return value.isUndefined(); - } + bool isUndefined() const { return value.isUndefined(); } - const Value& getValue() const { - return value; - } + const Value& getValue() const { return value; } private: mutable std::optional>> prior; @@ -87,10 +82,7 @@ class Transitionable { TransitionOptions options; Transitioning transition(const TransitionParameters& params, Transitioning prior) const { - return Transitioning(value, - std::move(prior), - options.reverseMerge(params.transition), - params.now); + return Transitioning(value, std::move(prior), options.reverseMerge(params.transition), params.now); } }; @@ -107,11 +99,8 @@ template struct ConstantsMask> { template static unsigned long getMask(const Properties& properties) { - std::bitset result; - util::ignore({ - result.set(TypeIndex::value, - properties.template get().isConstant())... - }); + std::bitset result; + util::ignore({result.set(TypeIndex::value, properties.template get().isConstant())...}); return result.to_ulong(); } }; @@ -120,23 +109,26 @@ template class Properties { public: /* - For style properties we implement a two step evaluation process: if you have a zoom level, - you can evaluate a set of unevaluated property values, producing a set of possibly evaluated - values, where undefined, constant, or camera function values have been fully evaluated, and - source or composite function values have not. - - Once you also have a particular feature, you can evaluate that set of possibly evaluated values - fully, producing a set of fully evaluated values. - - This is in theory maximally efficient in terms of avoiding repeated evaluation of camera - functions, though it's more of a historical accident than a purposeful optimization. + For style properties we implement a two step evaluation process: if you + have a zoom level, you can evaluate a set of unevaluated property values, + producing a set of possibly evaluated values, where undefined, constant, + or camera function values have been fully evaluated, and source or + composite function values have not. + + Once you also have a particular feature, you can evaluate that set of + possibly evaluated values fully, producing a set of fully evaluated + values. + + This is in theory maximally efficient in terms of avoiding repeated + evaluation of camera functions, though it's more of a historical accident + than a purposeful optimization. */ - using PropertyTypes = TypeList; - using TransitionableTypes = TypeList; - using UnevaluatedTypes = TypeList; + using PropertyTypes = TypeList; + using TransitionableTypes = TypeList; + using UnevaluatedTypes = TypeList; using PossiblyEvaluatedTypes = TypeList; - using EvaluatedTypes = TypeList; + using EvaluatedTypes = TypeList; using DataDrivenProperties = FilteredTypeList; using OverridableProperties = FilteredTypeList; @@ -148,16 +140,14 @@ class Properties { public: template Evaluated(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} }; class PossiblyEvaluated : public Tuple { public: template PossiblyEvaluated(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} template static T evaluate(float, const GeometryTileFeature&, const T& t, const T&) { @@ -174,13 +164,8 @@ class Properties { const GeometryTileFeature& feature, const PossiblyEvaluatedPropertyValue& v, const T& defaultValue) { - return v.match( - [&] (const T& t) { - return t; - }, - [&] (const PropertyExpression& t) { - return t.evaluate(z, feature, defaultValue); - }); + return v.match([&](const T& t) { return t; }, + [&](const PropertyExpression& t) { return t.evaluate(z, feature, defaultValue); }); } template @@ -219,8 +204,11 @@ class Properties { } template - static T evaluate(float z, const GeometryTileFeature& feature, const FeatureState& state, - const PossiblyEvaluatedPropertyValue& v, const T& defaultValue) { + static T evaluate(float z, + const GeometryTileFeature& feature, + const FeatureState& state, + const PossiblyEvaluatedPropertyValue& v, + const T& defaultValue) { return v.match([&](const T& t) { return t; }, [&](const PropertyExpression& t) { return t.evaluate(z, feature, state, defaultValue); }); } @@ -254,46 +242,38 @@ class Properties { } Evaluated evaluate(float z, const GeometryTileFeature& feature) const { - return Evaluated { - evaluate(z, feature)... - }; + return Evaluated{evaluate(z, feature)...}; } - unsigned long constantsMask() const { - return ConstantsMask::getMask(*this); - } + unsigned long constantsMask() const { return ConstantsMask::getMask(*this); } }; class Unevaluated : public Tuple { public: template Unevaluated(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} bool hasTransition() const { bool result = false; - util::ignore({ result |= this->template get().hasTransition()... }); + util::ignore({result |= this->template get().hasTransition()...}); return result; } template auto evaluate(const PropertyEvaluationParameters& parameters) const { using Evaluator = typename P::EvaluatorType; - return this->template get

() - .evaluate(Evaluator(parameters, P::defaultValue()), parameters.now); + return this->template get

().evaluate(Evaluator(parameters, P::defaultValue()), parameters.now); } PossiblyEvaluated evaluate(const PropertyEvaluationParameters& parameters) const { - return PossiblyEvaluated { - evaluate(parameters)... - }; + return PossiblyEvaluated{evaluate(parameters)...}; } template void stringify(Writer& writer) const { writer.StartObject(); - util::ignore({ (conversion::stringify(writer, this->template get()), 0)... }); + util::ignore({(conversion::stringify(writer, this->template get()), 0)...}); writer.EndObject(); } }; @@ -302,25 +282,20 @@ class Properties { public: template Transitionable(Us&&... us) - : Tuple(std::forward(us)...) { - } + : Tuple(std::forward(us)...) {} Unevaluated transitioned(const TransitionParameters& parameters, Unevaluated&& prior) const { - return Unevaluated { - this->template get() - .transition(parameters, std::move(prior.template get()))... - }; + return Unevaluated{this->template get().transition(parameters, std::move(prior.template get()))...}; } Unevaluated untransitioned() const { - return Unevaluated { - typename Ps::UnevaluatedType(this->template get().value)... - }; + return Unevaluated{typename Ps::UnevaluatedType(this->template get().value)...}; } bool hasDataDrivenPropertyDifference(const Transitionable& other) const { bool result = false; - util::ignore({ (result |= this->template get().value.hasDataDrivenPropertyDifference(other.template get().value))... }); + util::ignore({(result |= this->template get().value.hasDataDrivenPropertyDifference( + other.template get().value))...}); return result; } }; diff --git a/src/mbgl/style/property_expression.cpp b/src/mbgl/style/property_expression.cpp index 290009514ee..a6e0b471291 100644 --- a/src/mbgl/style/property_expression.cpp +++ b/src/mbgl/style/property_expression.cpp @@ -23,19 +23,17 @@ bool PropertyExpressionBase::isRuntimeConstant() const noexcept { return isRuntimeConstant_; } -float PropertyExpressionBase::interpolationFactor(const Range& inputLevels, const float inputValue) const noexcept { +float PropertyExpressionBase::interpolationFactor(const Range& inputLevels, + const float inputValue) const noexcept { return zoomCurve.match( [](std::nullptr_t) { assert(false); return 0.0f; }, [&](const expression::Interpolate* z) { - return z->interpolationFactor(Range { inputLevels.min, inputLevels.max }, inputValue); + return z->interpolationFactor(Range{inputLevels.min, inputLevels.max}, inputValue); }, - [](const expression::Step*) { - return 0.0f; - } - ); + [](const expression::Step*) { return 0.0f; }); } Range PropertyExpressionBase::getCoveringStops(const float lower, const float upper) const noexcept { diff --git a/src/mbgl/style/rapidjson_conversion.hpp b/src/mbgl/style/rapidjson_conversion.hpp index 2e34376a610..38682e82f82 100644 --- a/src/mbgl/style/rapidjson_conversion.hpp +++ b/src/mbgl/style/rapidjson_conversion.hpp @@ -13,27 +13,17 @@ namespace conversion { template <> class ConversionTraits { public: - static bool isUndefined(const JSValue* value) { - return value->IsNull(); - } + static bool isUndefined(const JSValue* value) { return value->IsNull(); } - static bool isArray(const JSValue* value) { - return value->IsArray(); - } + static bool isArray(const JSValue* value) { return value->IsArray(); } - static std::size_t arrayLength(const JSValue* value) { - return value->Size(); - } + static std::size_t arrayLength(const JSValue* value) { return value->Size(); } - static const JSValue* arrayMember(const JSValue* value, std::size_t i) { - return &(*value)[rapidjson::SizeType(i)]; - } + static const JSValue* arrayMember(const JSValue* value, std::size_t i) { return &(*value)[rapidjson::SizeType(i)]; } - static bool isObject(const JSValue* value) { - return value->IsObject(); - } + static bool isObject(const JSValue* value) { return value->IsObject(); } - static std::optional objectMember(const JSValue* value, const char * name) { + static std::optional objectMember(const JSValue* value, const char* name) { if (!value->HasMember(name)) { return {}; } @@ -45,8 +35,8 @@ class ConversionTraits { static std::optional eachMember(const JSValue* value, Fn&& fn) { assert(value->IsObject()); for (const auto& property : value->GetObject()) { - std::optional result = - fn({ property.name.GetString(), property.name.GetStringLength() }, &property.value); + std::optional result = fn({property.name.GetString(), property.name.GetStringLength()}, + &property.value); if (result) { return result; } @@ -79,25 +69,25 @@ class ConversionTraits { if (!value->IsString()) { return {}; } - return {{ value->GetString(), value->GetStringLength() }}; + return {{value->GetString(), value->GetStringLength()}}; } static std::optional toValue(const JSValue* value) { switch (value->GetType()) { case rapidjson::kNullType: case rapidjson::kFalseType: - return { false }; + return {false}; case rapidjson::kTrueType: - return { true }; + return {true}; case rapidjson::kStringType: - return { std::string { value->GetString(), value->GetStringLength() } }; + return {std::string{value->GetString(), value->GetStringLength()}}; case rapidjson::kNumberType: - if (value->IsUint64()) return { value->GetUint64() }; - if (value->IsInt64()) return { value->GetInt64() }; - return { value->GetDouble() }; + if (value->IsUint64()) return {value->GetUint64()}; + if (value->IsInt64()) return {value->GetInt64()}; + return {value->GetDouble()}; default: return {}; @@ -108,18 +98,17 @@ class ConversionTraits { try { return mapbox::geojson::convert(*value); } catch (const std::exception& ex) { - error = { ex.what() }; + error = {ex.what()}; return {}; } } }; -template -std::optional convert(const JSValue& value, Error& error, Args&&...args) { +template +std::optional convert(const JSValue& value, Error& error, Args&&... args) { return convert(Convertible(&value), error, std::forward(args)...); } } // namespace conversion } // namespace style } // namespace mbgl - diff --git a/src/mbgl/style/source.cpp b/src/mbgl/style/source.cpp index 1a8efc08b70..0574125a40f 100644 --- a/src/mbgl/style/source.cpp +++ b/src/mbgl/style/source.cpp @@ -10,8 +10,7 @@ static SourceObserver nullObserver; Source::Source(Immutable impl) : baseImpl(std::move(impl)), - observer(&nullObserver) { -} + observer(&nullObserver) {} Source::~Source() = default; diff --git a/src/mbgl/style/source_impl.cpp b/src/mbgl/style/source_impl.cpp index 0407b730cc5..7089773d700 100644 --- a/src/mbgl/style/source_impl.cpp +++ b/src/mbgl/style/source_impl.cpp @@ -6,18 +6,19 @@ namespace mbgl { namespace style { namespace { -void WarnIfOverscaleFactorCapsPrefetchDelta(const std::optional& overscale, const std::optional& prefetch) { +void WarnIfOverscaleFactorCapsPrefetchDelta(const std::optional& overscale, + const std::optional& prefetch) { const uint8_t prefetchDelta = std::max(util::DEFAULT_PREFETCH_ZOOM_DELTA, prefetch.value_or(0u)); if (overscale && *overscale < prefetchDelta) { - Log::Warning(Event::Style, "Parent tile overscale factor will cap prefetch delta to " + std::to_string(int(*overscale))); + Log::Warning(Event::Style, + "Parent tile overscale factor will cap prefetch delta to " + std::to_string(int(*overscale))); } } } // namespace Source::Impl::Impl(SourceType type_, std::string id_) : type(type_), - id(std::move(id_)) { -} + id(std::move(id_)) {} void Source::Impl::setPrefetchZoomDelta(std::optional delta) noexcept { prefetchZoomDelta = std::move(delta); diff --git a/src/mbgl/style/sources/custom_geometry_source.cpp b/src/mbgl/style/sources/custom_geometry_source.cpp index 9d3a58c1511..11a0af2be7e 100644 --- a/src/mbgl/style/sources/custom_geometry_source.cpp +++ b/src/mbgl/style/sources/custom_geometry_source.cpp @@ -35,8 +35,7 @@ bool CustomGeometrySource::supportsLayerType(const mbgl::style::LayerTypeInfo* i return mbgl::underlying_type(Tile::Kind::Geometry) == mbgl::underlying_type(info->tileKind); } -void CustomGeometrySource::setTileData(const CanonicalTileID& tileID, - const GeoJSON& data) { +void CustomGeometrySource::setTileData(const CanonicalTileID& tileID, const GeoJSON& data) { loader->self().invoke(&CustomTileLoader::setTileData, tileID, data); } diff --git a/src/mbgl/style/sources/custom_geometry_source_impl.cpp b/src/mbgl/style/sources/custom_geometry_source_impl.cpp index fbaa2521743..026e14540ea 100644 --- a/src/mbgl/style/sources/custom_geometry_source_impl.cpp +++ b/src/mbgl/style/sources/custom_geometry_source_impl.cpp @@ -11,7 +11,10 @@ CustomGeometrySource::Impl::Impl(std::string id_, const CustomGeometrySource::Op loaderRef({}) {} CustomGeometrySource::Impl::Impl(const Impl& impl, const ActorRef& loaderRef_) - : Source::Impl(impl), tileOptions(impl.tileOptions), zoomRange(impl.zoomRange), loaderRef(loaderRef_) {} + : Source::Impl(impl), + tileOptions(impl.tileOptions), + zoomRange(impl.zoomRange), + loaderRef(loaderRef_) {} bool CustomGeometrySource::Impl::operator!=(const Impl& other) const noexcept { return tileOptions != other.tileOptions || zoomRange != other.zoomRange || bool(loaderRef) != bool(other.loaderRef); diff --git a/src/mbgl/style/sources/geojson_source.cpp b/src/mbgl/style/sources/geojson_source.cpp index 86c504f940a..11d323a0be2 100644 --- a/src/mbgl/style/sources/geojson_source.cpp +++ b/src/mbgl/style/sources/geojson_source.cpp @@ -20,7 +20,8 @@ Immutable GeoJSONOptions::defaultOptions() { } GeoJSONSource::GeoJSONSource(std::string id, Immutable options) - : Source(makeMutable(std::move(id), std::move(options))), threadPool(Scheduler::GetBackground()) {} + : Source(makeMutable(std::move(id), std::move(options))), + threadPool(Scheduler::GetBackground()) {} GeoJSONSource::~GeoJSONSource() = default; @@ -81,13 +82,11 @@ void GeoJSONSource::loadDescription(FileSource& fileSource) { req = fileSource.request(Resource::source(*url), [this](const Response& res) { if (res.error) { - observer->onSourceError( - *this, std::make_exception_ptr(std::runtime_error(res.error->message))); + observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error(res.error->message))); } else if (res.notModified) { return; } else if (res.noContent) { - observer->onSourceError( - *this, std::make_exception_ptr(std::runtime_error("unexpectedly empty GeoJSON"))); + observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error("unexpectedly empty GeoJSON"))); } else { auto makeImplInBackground = [currentImpl = baseImpl, data = res.data]() -> Immutable { assert(data); @@ -97,7 +96,8 @@ void GeoJSONSource::loadDescription(FileSource& fileSource) { if (std::optional geoJSON = conversion::convertJSON(*data, error)) { geoJSONData = createGeoJSONData(*geoJSON, current); } else { - // Create an empty GeoJSON VT object to make sure we're not infinitely waiting for tiles to load. + // Create an empty GeoJSON VT object to make sure we're not + // infinitely waiting for tiles to load. Log::Error(Event::ParseStyle, "Failed to parse GeoJSON data: " + error.message); } return makeMutable(current, std::move(geoJSONData)); diff --git a/src/mbgl/style/sources/geojson_source_impl.cpp b/src/mbgl/style/sources/geojson_source_impl.cpp index 42f273c02ce..dfb1b08732f 100644 --- a/src/mbgl/style/sources/geojson_source_impl.cpp +++ b/src/mbgl/style/sources/geojson_source_impl.cpp @@ -33,9 +33,7 @@ class GeoJSONVTData final : public GeoJSONData { Features getLeaves(const std::uint32_t, const std::uint32_t, const std::uint32_t) final { return {}; } - std::uint8_t getClusterExpansionZoom(std::uint32_t) final { - return 0; - } + std::uint8_t getClusterExpansionZoom(std::uint32_t) final { return 0; } std::shared_ptr getScheduler() final { return scheduler; } @@ -43,7 +41,8 @@ class GeoJSONVTData final : public GeoJSONData { GeoJSONVTData(const GeoJSON& geoJSON, const mapbox::geojsonvt::Options& options, std::shared_ptr scheduler_) - : impl(std::make_shared(geoJSON, options)), scheduler(std::move(scheduler_)) { + : impl(std::make_shared(geoJSON, options)), + scheduler(std::move(scheduler_)) { assert(scheduler); } @@ -131,10 +130,13 @@ std::shared_ptr GeoJSONData::create(const GeoJSON& geoJSON, } GeoJSONSource::Impl::Impl(std::string id_, Immutable options_) - : Source::Impl(SourceType::GeoJSON, std::move(id_)), options(std::move(options_)) {} + : Source::Impl(SourceType::GeoJSON, std::move(id_)), + options(std::move(options_)) {} GeoJSONSource::Impl::Impl(const GeoJSONSource::Impl& other, std::shared_ptr data_) - : Source::Impl(other), options(other.options), data(std::move(data_)) {} + : Source::Impl(other), + options(other.options), + data(std::move(data_)) {} GeoJSONSource::Impl::~Impl() = default; diff --git a/src/mbgl/style/sources/image_source.cpp b/src/mbgl/style/sources/image_source.cpp index dd64d155c2d..3f0aa43951a 100644 --- a/src/mbgl/style/sources/image_source.cpp +++ b/src/mbgl/style/sources/image_source.cpp @@ -12,8 +12,7 @@ namespace mbgl { namespace style { ImageSource::ImageSource(std::string id, const std::array coords_) - : Source(makeMutable(std::move(id), coords_)) { -} + : Source(makeMutable(std::move(id), coords_)) {} ImageSource::~ImageSource() = default; @@ -59,10 +58,10 @@ void ImageSource::loadDescription(FileSource& fileSource) { loaded = true; } - if (req || loaded) { + if (req || loaded) { return; } - const Resource imageResource { Resource::Image, *url, {} }; + const Resource imageResource{Resource::Image, *url, {}}; req = fileSource.request(imageResource, [this](const Response& res) { if (res.error) { diff --git a/src/mbgl/style/sources/image_source_impl.cpp b/src/mbgl/style/sources/image_source_impl.cpp index 176bbd70a98..1031a3c1d81 100644 --- a/src/mbgl/style/sources/image_source_impl.cpp +++ b/src/mbgl/style/sources/image_source_impl.cpp @@ -4,16 +4,18 @@ namespace mbgl { namespace style { ImageSource::Impl::Impl(std::string id_, std::array coords_) - : Source::Impl(SourceType::Image, std::move(id_)), coords(coords_) {} + : Source::Impl(SourceType::Image, std::move(id_)), + coords(coords_) {} ImageSource::Impl::Impl(const Impl& other, std::array coords_) - : Source::Impl(other), coords(coords_), image(other.image) {} + : Source::Impl(other), + coords(coords_), + image(other.image) {} ImageSource::Impl::Impl(const Impl& rhs, PremultipliedImage&& image_) : Source::Impl(rhs), - coords(rhs.coords), - image(std::make_shared(std::move(image_))) { -} + coords(rhs.coords), + image(std::make_shared(std::move(image_))) {} ImageSource::Impl::~Impl() = default; diff --git a/src/mbgl/style/sources/image_source_impl.hpp b/src/mbgl/style/sources/image_source_impl.hpp index 4bf1472ca1e..bf55be6fcd3 100644 --- a/src/mbgl/style/sources/image_source_impl.hpp +++ b/src/mbgl/style/sources/image_source_impl.hpp @@ -23,6 +23,7 @@ class ImageSource::Impl final : public Source::Impl { std::array getCoordinates() const; std::optional getAttribution() const final; + private: std::array coords; std::shared_ptr image; diff --git a/src/mbgl/style/sources/raster_source.cpp b/src/mbgl/style/sources/raster_source.cpp index 415e5152b65..5aa3048264d 100644 --- a/src/mbgl/style/sources/raster_source.cpp +++ b/src/mbgl/style/sources/raster_source.cpp @@ -13,10 +13,12 @@ namespace mbgl { namespace style { -RasterSource::RasterSource(std::string id, variant urlOrTileset_, uint16_t tileSize, SourceType sourceType) +RasterSource::RasterSource(std::string id, + variant urlOrTileset_, + uint16_t tileSize, + SourceType sourceType) : Source(makeMutable(sourceType, std::move(id), tileSize)), - urlOrTileset(std::move(urlOrTileset_)) { -} + urlOrTileset(std::move(urlOrTileset_)) {} RasterSource::~RasterSource() = default; @@ -54,7 +56,7 @@ void RasterSource::loadDescription(FileSource& fileSource) { const auto& rawURL = urlOrTileset.get(); const auto& url = util::mapbox::canonicalizeSourceURL(fileSource.getResourceOptions().tileServerOptions(), rawURL); - + req = fileSource.request(Resource::source(url), [this, url, &fileSource](const Response& res) { if (res.error) { observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error(res.error->message))); diff --git a/src/mbgl/style/sources/raster_source_impl.cpp b/src/mbgl/style/sources/raster_source_impl.cpp index 62fa71710d0..6836507925f 100644 --- a/src/mbgl/style/sources/raster_source_impl.cpp +++ b/src/mbgl/style/sources/raster_source_impl.cpp @@ -5,14 +5,12 @@ namespace style { RasterSource::Impl::Impl(SourceType sourceType, std::string id_, uint16_t tileSize_) : Source::Impl(sourceType, std::move(id_)), - tileSize(tileSize_) { -} + tileSize(tileSize_) {} RasterSource::Impl::Impl(const Impl& other, Tileset tileset_) : Source::Impl(other), tileset(std::move(tileset_)), - tileSize(other.tileSize) { -} + tileSize(other.tileSize) {} uint16_t RasterSource::Impl::getTileSize() const { return tileSize; diff --git a/src/mbgl/style/sources/vector_source.cpp b/src/mbgl/style/sources/vector_source.cpp index 35b656c5b8a..b3ad9513c3c 100644 --- a/src/mbgl/style/sources/vector_source.cpp +++ b/src/mbgl/style/sources/vector_source.cpp @@ -14,7 +14,9 @@ namespace mbgl { namespace style { -VectorSource::VectorSource(std::string id, variant urlOrTileset_, std::optional maxZoom_, +VectorSource::VectorSource(std::string id, + variant urlOrTileset_, + std::optional maxZoom_, std::optional minZoom_) : Source(makeMutable(std::move(id))), urlOrTileset(std::move(urlOrTileset_)), @@ -53,7 +55,7 @@ void VectorSource::loadDescription(FileSource& fileSource) { const auto& rawURL = urlOrTileset.get(); const auto& url = util::mapbox::canonicalizeSourceURL(fileSource.getResourceOptions().tileServerOptions(), rawURL); - + req = fileSource.request(Resource::source(url), [this, url, &fileSource](const Response& res) { if (res.error) { observer->onSourceError(*this, std::make_exception_ptr(std::runtime_error(res.error->message))); diff --git a/src/mbgl/style/sources/vector_source_impl.cpp b/src/mbgl/style/sources/vector_source_impl.cpp index c46dab20696..3f202d0e14a 100644 --- a/src/mbgl/style/sources/vector_source_impl.cpp +++ b/src/mbgl/style/sources/vector_source_impl.cpp @@ -4,13 +4,11 @@ namespace mbgl { namespace style { VectorSource::Impl::Impl(std::string id_) - : Source::Impl(SourceType::Vector, std::move(id_)) { -} + : Source::Impl(SourceType::Vector, std::move(id_)) {} VectorSource::Impl::Impl(const Impl& other, Tileset tileset_) : Source::Impl(other), - tileset(std::move(tileset_)) { -} + tileset(std::move(tileset_)) {} std::optional VectorSource::Impl::getAttribution() const { if (!tileset) { diff --git a/src/mbgl/style/style_impl.cpp b/src/mbgl/style/style_impl.cpp index 8bba8220c44..aff1d3b5771 100644 --- a/src/mbgl/style/style_impl.cpp +++ b/src/mbgl/style/style_impl.cpp @@ -161,7 +161,7 @@ void Style::Impl::addSource(std::unique_ptr source) { std::unique_ptr Style::Impl::removeSource(const std::string& id) { // Check if source is in use - for (const auto& layer: layers) { + for (const auto& layer : layers) { if (layer->getSourceID() == id) { Log::Warning(Event::General, "Source '" + id + "' is in use, cannot remove"); return nullptr; @@ -264,7 +264,7 @@ bool Style::Impl::isLoaded() const { return false; } - for (const auto& source: sources) { + for (const auto& source : sources) { if (!source->loaded) { return false; } @@ -275,8 +275,8 @@ bool Style::Impl::isLoaded() const { void Style::Impl::addImage(std::unique_ptr image) { auto newImages = makeMutable(*images); - auto it = - std::lower_bound(newImages->begin(), newImages->end(), image->getID(), [](const auto& a, const std::string& b) { + auto it = std::lower_bound( + newImages->begin(), newImages->end(), image->getID(), [](const auto& a, const std::string& b) { return a->id < b; }); if (it != newImages->end() && (*it)->id == image->getID()) { @@ -291,8 +291,8 @@ void Style::Impl::addImage(std::unique_ptr image) { void Style::Impl::removeImage(const std::string& id) { auto newImages = makeMutable(*images); - auto found = - std::find_if(newImages->begin(), newImages->end(), [&id](const auto& image) { return image->id == id; }); + auto found = std::find_if( + newImages->begin(), newImages->end(), [&id](const auto& image) { return image->id == id; }); if (found == newImages->end()) { Log::Warning(Event::General, "Image '" + id + "' is not present in style, cannot remove"); return; diff --git a/src/mbgl/style/style_impl.hpp b/src/mbgl/style/style_impl.hpp index 69e82f530be..ed943e24054 100644 --- a/src/mbgl/style/style_impl.hpp +++ b/src/mbgl/style/style_impl.hpp @@ -49,18 +49,16 @@ class Style::Impl : public SpriteLoaderObserver, bool isLoaded() const; - std::exception_ptr getLastError() const { - return lastError; - } + std::exception_ptr getLastError() const { return lastError; } - std::vector< Source*> getSources(); + std::vector getSources(); std::vector getSources() const; Source* getSource(const std::string& id) const; void addSource(std::unique_ptr); std::unique_ptr removeSource(const std::string& sourceID); - std::vector< Layer*> getLayers(); + std::vector getLayers(); std::vector getLayers() const; Layer* getLayer(const std::string& id) const; diff --git a/src/mbgl/style/types.cpp b/src/mbgl/style/types.cpp index c4a7b76b664..dd4d191cc33 100644 --- a/src/mbgl/style/types.cpp +++ b/src/mbgl/style/types.cpp @@ -5,118 +5,123 @@ namespace mbgl { using namespace style; -MBGL_DEFINE_ENUM(SourceType, { - { SourceType::Vector, "vector" }, - { SourceType::Raster, "raster" }, - { SourceType::GeoJSON, "geojson" }, - { SourceType::Video, "video" }, - { SourceType::Annotations, "annotations" }, - { SourceType::Image, "image" }, - { SourceType::CustomVector, "customvector" } -}); - -MBGL_DEFINE_ENUM(VisibilityType, { - { VisibilityType::Visible, "visible" }, - { VisibilityType::None, "none" }, -}); - -MBGL_DEFINE_ENUM(TranslateAnchorType, { - { TranslateAnchorType::Map, "map" }, - { TranslateAnchorType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(RasterResamplingType, { - { RasterResamplingType::Linear, "linear" }, - { RasterResamplingType::Nearest, "nearest" }, -}); - -MBGL_DEFINE_ENUM(HillshadeIlluminationAnchorType, { - { HillshadeIlluminationAnchorType::Map, "map" }, - { HillshadeIlluminationAnchorType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(RotateAnchorType, { - { RotateAnchorType::Map, "map" }, - { RotateAnchorType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(CirclePitchScaleType, { - { CirclePitchScaleType::Map, "map" }, - { CirclePitchScaleType::Viewport, "viewport" }, -}); - -MBGL_DEFINE_ENUM(LineCapType, { - { LineCapType::Round, "round" }, - { LineCapType::Butt, "butt" }, - { LineCapType::Square, "square" }, -}); - -MBGL_DEFINE_ENUM(LineJoinType, { - { LineJoinType::Miter, "miter" }, - { LineJoinType::Bevel, "bevel" }, - { LineJoinType::Round, "round" }, - { LineJoinType::FakeRound, "fakeround" }, - { LineJoinType::FlipBevel, "flipbevel" }, -}); - -MBGL_DEFINE_ENUM(SymbolPlacementType, { - { SymbolPlacementType::Point, "point" }, - { SymbolPlacementType::Line, "line" }, - { SymbolPlacementType::LineCenter, "line-center" }, -}); - -MBGL_DEFINE_ENUM(SymbolAnchorType, { - { SymbolAnchorType::Center, "center" }, - { SymbolAnchorType::Left, "left" }, - { SymbolAnchorType::Right, "right" }, - { SymbolAnchorType::Top, "top" }, - { SymbolAnchorType::Bottom, "bottom" }, - { SymbolAnchorType::TopLeft, "top-left" }, - { SymbolAnchorType::TopRight, "top-right" }, - { SymbolAnchorType::BottomLeft, "bottom-left" }, - { SymbolAnchorType::BottomRight, "bottom-right" } -}); - -MBGL_DEFINE_ENUM(SymbolZOrderType, { - { SymbolZOrderType::Auto, "auto" }, - { SymbolZOrderType::ViewportY, "viewport-y" }, - { SymbolZOrderType::Source, "source" } -}); - -MBGL_DEFINE_ENUM(TextJustifyType, { - { TextJustifyType::Auto, "auto" }, - { TextJustifyType::Center, "center" }, - { TextJustifyType::Left, "left" }, - { TextJustifyType::Right, "right" }, -}); - -MBGL_DEFINE_ENUM(TextTransformType, { - { TextTransformType::None, "none" }, - { TextTransformType::Uppercase, "uppercase" }, - { TextTransformType::Lowercase, "lowercase" }, -}); - -MBGL_DEFINE_ENUM(TextWritingModeType, { - { TextWritingModeType::Horizontal, "horizontal" }, - { TextWritingModeType::Vertical, "vertical" } -}); - -MBGL_DEFINE_ENUM(AlignmentType, { - { AlignmentType::Map, "map" }, - { AlignmentType::Viewport, "viewport" }, - { AlignmentType::Auto, "auto" }, -}); - -MBGL_DEFINE_ENUM(IconTextFitType, { - { IconTextFitType::None, "none" }, - { IconTextFitType::Both, "both" }, - { IconTextFitType::Width, "width" }, - { IconTextFitType::Height, "height" }, -}); - -MBGL_DEFINE_ENUM(LightAnchorType, { - { LightAnchorType::Map, "map" }, - { LightAnchorType::Viewport, "viewport" } -}); +MBGL_DEFINE_ENUM(SourceType, + {{SourceType::Vector, "vector"}, + {SourceType::Raster, "raster"}, + {SourceType::GeoJSON, "geojson"}, + {SourceType::Video, "video"}, + {SourceType::Annotations, "annotations"}, + {SourceType::Image, "image"}, + {SourceType::CustomVector, "customvector"}}); + +MBGL_DEFINE_ENUM(VisibilityType, + { + {VisibilityType::Visible, "visible"}, + {VisibilityType::None, "none"}, + }); + +MBGL_DEFINE_ENUM(TranslateAnchorType, + { + {TranslateAnchorType::Map, "map"}, + {TranslateAnchorType::Viewport, "viewport"}, + }); + +MBGL_DEFINE_ENUM(RasterResamplingType, + { + {RasterResamplingType::Linear, "linear"}, + {RasterResamplingType::Nearest, "nearest"}, + }); + +MBGL_DEFINE_ENUM(HillshadeIlluminationAnchorType, + { + {HillshadeIlluminationAnchorType::Map, "map"}, + {HillshadeIlluminationAnchorType::Viewport, "viewport"}, + }); + +MBGL_DEFINE_ENUM(RotateAnchorType, + { + {RotateAnchorType::Map, "map"}, + {RotateAnchorType::Viewport, "viewport"}, + }); + +MBGL_DEFINE_ENUM(CirclePitchScaleType, + { + {CirclePitchScaleType::Map, "map"}, + {CirclePitchScaleType::Viewport, "viewport"}, + }); + +MBGL_DEFINE_ENUM(LineCapType, + { + {LineCapType::Round, "round"}, + {LineCapType::Butt, "butt"}, + {LineCapType::Square, "square"}, + }); + +MBGL_DEFINE_ENUM(LineJoinType, + { + {LineJoinType::Miter, "miter"}, + {LineJoinType::Bevel, "bevel"}, + {LineJoinType::Round, "round"}, + {LineJoinType::FakeRound, "fakeround"}, + {LineJoinType::FlipBevel, "flipbevel"}, + }); + +MBGL_DEFINE_ENUM(SymbolPlacementType, + { + {SymbolPlacementType::Point, "point"}, + {SymbolPlacementType::Line, "line"}, + {SymbolPlacementType::LineCenter, "line-center"}, + }); + +MBGL_DEFINE_ENUM(SymbolAnchorType, + {{SymbolAnchorType::Center, "center"}, + {SymbolAnchorType::Left, "left"}, + {SymbolAnchorType::Right, "right"}, + {SymbolAnchorType::Top, "top"}, + {SymbolAnchorType::Bottom, "bottom"}, + {SymbolAnchorType::TopLeft, "top-left"}, + {SymbolAnchorType::TopRight, "top-right"}, + {SymbolAnchorType::BottomLeft, "bottom-left"}, + {SymbolAnchorType::BottomRight, "bottom-right"}}); + +MBGL_DEFINE_ENUM(SymbolZOrderType, + {{SymbolZOrderType::Auto, "auto"}, + {SymbolZOrderType::ViewportY, "viewport-y"}, + {SymbolZOrderType::Source, "source"}}); + +MBGL_DEFINE_ENUM(TextJustifyType, + { + {TextJustifyType::Auto, "auto"}, + {TextJustifyType::Center, "center"}, + {TextJustifyType::Left, "left"}, + {TextJustifyType::Right, "right"}, + }); + +MBGL_DEFINE_ENUM(TextTransformType, + { + {TextTransformType::None, "none"}, + {TextTransformType::Uppercase, "uppercase"}, + {TextTransformType::Lowercase, "lowercase"}, + }); + +MBGL_DEFINE_ENUM(TextWritingModeType, + {{TextWritingModeType::Horizontal, "horizontal"}, {TextWritingModeType::Vertical, "vertical"}}); + +MBGL_DEFINE_ENUM(AlignmentType, + { + {AlignmentType::Map, "map"}, + {AlignmentType::Viewport, "viewport"}, + {AlignmentType::Auto, "auto"}, + }); + +MBGL_DEFINE_ENUM(IconTextFitType, + { + {IconTextFitType::None, "none"}, + {IconTextFitType::Both, "both"}, + {IconTextFitType::Width, "width"}, + {IconTextFitType::Height, "height"}, + }); + +MBGL_DEFINE_ENUM(LightAnchorType, {{LightAnchorType::Map, "map"}, {LightAnchorType::Viewport, "viewport"}}); } // namespace mbgl diff --git a/src/mbgl/text/bidi.hpp b/src/mbgl/text/bidi.hpp index 5ce2887db86..1f03ab91d56 100644 --- a/src/mbgl/text/bidi.hpp +++ b/src/mbgl/text/bidi.hpp @@ -19,7 +19,7 @@ std::u16string applyArabicShaping(const std::u16string&); // The data structure is intended to accomodate the reordering/interleaving // of formatting that can happen when BiDi rearranges inputs using StyledText = std::pair>; - + class BiDi : private util::noncopyable { public: BiDi(); diff --git a/src/mbgl/text/check_max_angle.cpp b/src/mbgl/text/check_max_angle.cpp index 75267d4e98c..36241394f77 100644 --- a/src/mbgl/text/check_max_angle.cpp +++ b/src/mbgl/text/check_max_angle.cpp @@ -4,11 +4,12 @@ #include -namespace mbgl{ +namespace mbgl { struct Corner { - Corner(float _distance, float _angleDelta) : - distance(_distance), angleDelta(_angleDelta) {} + Corner(float _distance, float _angleDelta) + : distance(_distance), + angleDelta(_angleDelta) {} float distance; float angleDelta; }; @@ -22,7 +23,7 @@ bool checkMaxAngle(const GeometryCoordinates& line, if (!anchor.segment) return true; GeometryCoordinate anchorPoint = convertPoint(anchor.point); - GeometryCoordinate &p = anchorPoint; + GeometryCoordinate& p = anchorPoint; std::size_t index = *anchor.segment + 1; float anchorDistance = 0; @@ -43,9 +44,8 @@ bool checkMaxAngle(const GeometryCoordinates& line, std::queue recentCorners; float recentAngleDelta = 0; - // move forwards by the length of the label and check angles along the way + // move forwards by the length of the label and check angles along the way while (anchorDistance < labelLength / 2) { - // there isn't enough room for the label before the end of the line if (index + 1 >= line.size()) return false; @@ -58,7 +58,7 @@ bool checkMaxAngle(const GeometryCoordinates& line, angleDelta = std::fabs(std::fmod(angleDelta + 3 * M_PI, M_PI * 2) - M_PI); recentCorners.emplace(anchorDistance, static_cast(angleDelta)); - recentAngleDelta += static_cast(angleDelta); + recentAngleDelta += static_cast(angleDelta); // remove corners that are far enough away from the list of recent anchors while (anchorDistance - recentCorners.front().distance > windowSize) { diff --git a/src/mbgl/text/collision_feature.cpp b/src/mbgl/text/collision_feature.cpp index f5201596e3f..2b11507713e 100644 --- a/src/mbgl/text/collision_feature.cpp +++ b/src/mbgl/text/collision_feature.cpp @@ -18,7 +18,8 @@ CollisionFeature::CollisionFeature(const GeometryCoordinates& line, IndexedSubfeature indexedFeature_, const float overscaling, const float rotate) - : indexedFeature(std::move(indexedFeature_)), alongLine(placement != style::SymbolPlacementType::Point) { + : indexedFeature(std::move(indexedFeature_)), + alongLine(placement != style::SymbolPlacementType::Point) { if (top == 0 && bottom == 0 && left == 0 && right == 0) return; float y1 = top * boxScale - padding; @@ -53,7 +54,7 @@ CollisionFeature::CollisionFeature(const GeometryCoordinates& line, const Point tr = util::rotate(Point(x2, y1), rotateRadians); const Point bl = util::rotate(Point(x1, y2), rotateRadians); const Point br = util::rotate(Point(x2, y2), rotateRadians); - + // Collision features require an "on-axis" geometry, // so take the envelope of the rotated geometry // (may be quite large for wide labels rotated 45 degrees) @@ -61,7 +62,7 @@ CollisionFeature::CollisionFeature(const GeometryCoordinates& line, const float xMax = std::max({tl.x, tr.x, bl.x, br.x}); const float yMin = std::min({tl.y, tr.y, bl.y, br.y}); const float yMax = std::max({tl.y, tr.y, bl.y, br.y}); - + boxes.emplace_back(anchor.point, xMin, yMin, xMax, yMax); } else { boxes.emplace_back(anchor.point, x1, y1, x2, y2); @@ -78,14 +79,13 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, const float step = boxSize / 2; const int nBoxes = std::max(static_cast(std::floor(labelLength / step)), 1); - // We calculate line collision circles out to 300% of what would normally be our - // max size, to allow collision detection to work on labels that expand as - // they move into the distance - // Vertically oriented labels in the distant field can extend past this padding - // This is a noticeable problem in overscaled tiles where the pitch 0-based - // symbol spacing will put labels very close together in a pitched map. - // To reduce the cost of adding extra collision circles, we slowly increase - // them for overscaled tiles. + // We calculate line collision circles out to 300% of what would normally be + // our max size, to allow collision detection to work on labels that expand + // as they move into the distance Vertically oriented labels in the distant + // field can extend past this padding This is a noticeable problem in + // overscaled tiles where the pitch 0-based symbol spacing will put labels + // very close together in a pitched map. To reduce the cost of adding extra + // collision circles, we slowly increase them for overscaled tiles. const double overscalingPaddingFactor = 1 + .4 * util::log2(static_cast(overscaling)); const int nPitchPaddingBoxes = static_cast(std::floor(nBoxes * overscalingPaddingFactor / 2)); @@ -93,7 +93,7 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, // box is at the edge of the label. const float firstBoxOffset = -boxSize / 2; - GeometryCoordinate &p = anchorPoint; + GeometryCoordinate& p = anchorPoint; std::size_t index = segment + 1; float anchorDistance = firstBoxOffset; const float labelStartDistance = -labelLength / 2; @@ -103,8 +103,8 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, do { if (index == 0u) { if (anchorDistance > labelStartDistance) { - // there isn't enough room for the label after the beginning of the line - // checkMaxAngle should have already caught this + // there isn't enough room for the label after the beginning of + // the line checkMaxAngle should have already caught this return; } else { // The line doesn't extend far enough back for all of our padding, @@ -126,9 +126,9 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, const float boxOffset = i * step; float boxDistanceToAnchor = labelStartDistance + boxOffset; - // make the distance between pitch padding boxes bigger - if (boxOffset < 0) boxDistanceToAnchor += boxOffset; - if (boxOffset > labelLength) boxDistanceToAnchor += boxOffset - labelLength; + // make the distance between pitch padding boxes bigger + if (boxOffset < 0) boxDistanceToAnchor += boxOffset; + if (boxOffset > labelLength) boxDistanceToAnchor += boxOffset - labelLength; if (boxDistanceToAnchor < anchorDistance) { // The line doesn't extend far enough back for this box, skip it @@ -153,18 +153,16 @@ void CollisionFeature::bboxifyLabel(const GeometryCoordinates& line, const auto& p0 = line[index]; const auto& p1 = line[index + 1]; - Point boxAnchor = { - p0.x + segmentBoxDistance / segmentLength * (p1.x - p0.x), - p0.y + segmentBoxDistance / segmentLength * (p1.y - p0.y) - }; - + Point boxAnchor = {p0.x + segmentBoxDistance / segmentLength * (p1.x - p0.x), + p0.y + segmentBoxDistance / segmentLength * (p1.y - p0.y)}; + // If the box is within boxSize of the anchor, force the box to be used // (so even 0-width labels use at least one box) // Otherwise, the .8 multiplication gives us a little bit of conservative // padding in choosing which boxes to use (see CollisionIndex#placedCollisionCircles) - const float paddedAnchorDistance = std::abs(boxDistanceToAnchor - firstBoxOffset) < step ? - 0.0f : - (boxDistanceToAnchor - firstBoxOffset) * 0.8f; + const float paddedAnchorDistance = std::abs(boxDistanceToAnchor - firstBoxOffset) < step + ? 0.0f + : (boxDistanceToAnchor - firstBoxOffset) * 0.8f; boxes.emplace_back(boxAnchor, -boxSize / 2, -boxSize / 2, boxSize / 2, boxSize / 2, paddedAnchorDistance); } diff --git a/src/mbgl/text/collision_feature.hpp b/src/mbgl/text/collision_feature.hpp index 9fe6fa97755..dd272a48d57 100644 --- a/src/mbgl/text/collision_feature.hpp +++ b/src/mbgl/text/collision_feature.hpp @@ -18,8 +18,12 @@ class ProjectedCollisionBox { }; ProjectedCollisionBox() = default; - ProjectedCollisionBox(float x1, float y1, float x2, float y2) : geometry(x1, y1, x2, y2), type(Type::Box) {} - ProjectedCollisionBox(float x, float y, float r) : geometry(x, y, r), type(Type::Circle) {} + ProjectedCollisionBox(float x1, float y1, float x2, float y2) + : geometry(x1, y1, x2, y2), + type(Type::Box) {} + ProjectedCollisionBox(float x, float y, float r) + : geometry(x, y, r), + type(Type::Circle) {} const mapbox::geometry::box& box() const { assert(isBox()); @@ -38,8 +42,10 @@ class ProjectedCollisionBox { union Geometry { // NOLINTNEXTLINE(modernize-use-equals-default) Geometry() {} - Geometry(float x1, float y1, float x2, float y2) : box({x1, y1}, {x2, y2}) {} - Geometry(float x, float y, float r) : circle({x, y}, r) {} + Geometry(float x1, float y1, float x2, float y2) + : box({x1, y1}, {x2, y2}) {} + Geometry(float x, float y, float r) + : circle({x, y}, r) {} mapbox::geometry::box box; geometry::circle circle; } geometry; @@ -49,7 +55,12 @@ class ProjectedCollisionBox { class CollisionBox { public: CollisionBox(Point _anchor, float _x1, float _y1, float _x2, float _y2, float _signedDistanceFromAnchor = 0) - : anchor(_anchor), x1(_x1), y1(_y1), x2(_x2), y2(_y2), signedDistanceFromAnchor(_signedDistanceFromAnchor) {} + : anchor(_anchor), + x1(_x1), + y1(_y1), + x2(_x2), + y2(_y2), + signedDistanceFromAnchor(_signedDistanceFromAnchor) {} // the box is centered around the anchor point Point anchor; @@ -69,7 +80,6 @@ class CollisionBox { class CollisionFeature { public: - // for text CollisionFeature(const GeometryCoordinates& line, const Anchor& anchor, @@ -95,11 +105,13 @@ class CollisionFeature { rotate) {} // for icons - // Icons collision features are always SymbolPlacementType::Point, which means the collision feature - // will be viewport-rotation-aligned even if the icon is map-rotation-aligned (e.g. `icon-rotation-alignment: map` - // _or_ `symbol-placement: line`). We're relying on most icons being "close enough" to square that having - // incorrect rotation alignment doesn't throw off collision detection too much. - // See: https://github.com/mapbox/mapbox-gl-js/issues/4861 + // Icons collision features are always SymbolPlacementType::Point, which + // means the collision feature will be viewport-rotation-aligned even if the + // icon is map-rotation-aligned (e.g. `icon-rotation-alignment: map` _or_ + // `symbol-placement: line`). We're relying on most icons being "close + // enough" to square that having incorrect rotation alignment doesn't throw + // off collision detection too much. See: + // https://github.com/mapbox/mapbox-gl-js/issues/4861 CollisionFeature(const GeometryCoordinates& line, const Anchor& anchor, std::optional shapedIcon, diff --git a/src/mbgl/text/collision_index.cpp b/src/mbgl/text/collision_index.cpp index 4d8295ab12e..3a7512150b6 100644 --- a/src/mbgl/text/collision_index.cpp +++ b/src/mbgl/text/collision_index.cpp @@ -47,30 +47,33 @@ CollisionIndex::CollisionIndex(const TransformState& transformState_, MapMode ma screenBottomBoundary(transformState.getSize().height + viewportPadding), gridRightBoundary(transformState.getSize().width + 2 * viewportPadding), gridBottomBoundary(transformState.getSize().height + 2 * viewportPadding), - pitchFactor(static_cast(std::cos(transformState.getPitch()) * transformState.getCameraToCenterDistance())) {} + pitchFactor( + static_cast(std::cos(transformState.getPitch()) * transformState.getCameraToCenterDistance())) {} float CollisionIndex::approximateTileDistance(const TileDistance& tileDistance, const float lastSegmentAngle, const float pixelsToTileUnits, const float cameraToAnchorDistance, const bool pitchWithMap) { - // This is a quick and dirty solution for chosing which collision circles to use (since collision circles are - // laid out in tile units). Ideally, I think we should generate collision circles on the fly in viewport coordinates - // at the time we do collision detection. + // This is a quick and dirty solution for chosing which collision circles to + // use (since collision circles are laid out in tile units). Ideally, I + // think we should generate collision circles on the fly in viewport + // coordinates at the time we do collision detection. - // incidenceStretch is the ratio of how much y space a label takes up on a tile while drawn perpendicular to the viewport vs + // incidenceStretch is the ratio of how much y space a label takes up on a + // tile while drawn perpendicular to the viewport vs // how much space it would take up if it were drawn flat on the tile - // Using law of sines, camera_to_anchor/sin(ground_angle) = camera_to_center/sin(incidence_angle) - // Incidence angle 90 -> head on, sin(incidence_angle) = 1, no stretch - // Incidence angle 1 -> very oblique, sin(incidence_angle) =~ 0, lots of stretch - // ground_angle = u_pitch + PI/2 -> sin(ground_angle) = cos(u_pitch) - // incidenceStretch = 1 / sin(incidenceAngle) + // Using law of sines, camera_to_anchor/sin(ground_angle) = + // camera_to_center/sin(incidence_angle) Incidence angle 90 -> head on, + // sin(incidence_angle) = 1, no stretch Incidence angle 1 -> very oblique, + // sin(incidence_angle) =~ 0, lots of stretch ground_angle = u_pitch + PI/2 + // -> sin(ground_angle) = cos(u_pitch) incidenceStretch = 1 / + // sin(incidenceAngle) const float incidenceStretch = pitchWithMap ? 1 : cameraToAnchorDistance / pitchFactor; const float lastSegmentTile = tileDistance.lastSegmentViewportDistance * pixelsToTileUnits; - return tileDistance.prevTileDistance + - lastSegmentTile + - (incidenceStretch - 1) * lastSegmentTile * std::abs(std::sin(lastSegmentAngle)); + return tileDistance.prevTileDistance + lastSegmentTile + + (incidenceStretch - 1) * lastSegmentTile * std::abs(std::sin(lastSegmentAngle)); } bool CollisionIndex::isOffscreen(const CollisionBoundaries& boundaries) const { @@ -84,14 +87,15 @@ bool CollisionIndex::isInsideGrid(const CollisionBoundaries& boundaries) const { } CollisionBoundaries CollisionIndex::projectTileBoundaries(const mat4& posMatrix) const { - Point topLeft = projectPoint(posMatrix, { 0, 0 }); - Point bottomRight = projectPoint(posMatrix, { util::EXTENT, util::EXTENT }); + Point topLeft = projectPoint(posMatrix, {0, 0}); + Point bottomRight = projectPoint(posMatrix, {util::EXTENT, util::EXTENT}); - return {{ topLeft.x, topLeft.y, bottomRight.x, bottomRight.y }}; + return {{topLeft.x, topLeft.y, bottomRight.x, bottomRight.y}}; } -// The tile border checks below are only well defined when the tile boundaries are axis-aligned -// We are relying on it only being used in MapMode::Tile, where that is always the case +// The tile border checks below are only well defined when the tile boundaries +// are axis-aligned We are relying on it only being used in MapMode::Tile, where +// that is always the case inline bool CollisionIndex::isInsideTile(const CollisionBoundaries& boundaries, const CollisionBoundaries& tileBoundaries) const { return boundaries[0] >= tileBoundaries[0] && boundaries[1] >= tileBoundaries[1] && @@ -165,12 +169,24 @@ std::pair CollisionIndex::placeFeature( collisionBoundaries[0], collisionBoundaries[1], collisionBoundaries[2], collisionBoundaries[3]); if ((avoidEdges && !isInsideTile(collisionBoundaries, *avoidEdges)) || !isInsideGrid(collisionBoundaries) || (!allowOverlap && collisionGrid.hitTest(projectedBoxes.back().box(), collisionGroupPredicate))) { - return { false, false }; + return {false, false}; } return {true, isOffscreen(collisionBoundaries)}; } else { - return placeLineFeature(feature, posMatrix, labelPlaneMatrix, textPixelRatio, symbol, scale, fontSize, allowOverlap, pitchWithMap, collisionDebug, avoidEdges, collisionGroupPredicate, projectedBoxes); + return placeLineFeature(feature, + posMatrix, + labelPlaneMatrix, + textPixelRatio, + symbol, + scale, + fontSize, + allowOverlap, + pitchWithMap, + collisionDebug, + avoidEdges, + collisionGroupPredicate, + projectedBoxes); } } @@ -199,16 +215,15 @@ std::pair CollisionIndex::placeLineFeature( const auto labelPlaneAnchorPoint = project(tileUnitAnchorPoint, labelPlaneMatrix).first; - const auto firstAndLastGlyph = placeFirstAndLastGlyph( - fontScale, - lineOffsetX, - lineOffsetY, - /*flip*/ false, - labelPlaneAnchorPoint, - tileUnitAnchorPoint, - symbol, - labelPlaneMatrix, - /*return tile distance*/ true); + const auto firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, + lineOffsetX, + lineOffsetY, + /*flip*/ false, + labelPlaneAnchorPoint, + tileUnitAnchorPoint, + symbol, + labelPlaneMatrix, + /*return tile distance*/ true); bool collisionDetected = false; bool inGrid = false; @@ -223,8 +238,16 @@ std::pair CollisionIndex::placeLineFeature( float firstTileDistance = 0.f; float lastTileDistance = 0.f; if (firstAndLastGlyph) { - firstTileDistance = approximateTileDistance(*(firstAndLastGlyph->first.tileDistance), firstAndLastGlyph->first.angle, pixelsToTileUnits, projectedAnchor.second, pitchWithMap); - lastTileDistance = approximateTileDistance(*(firstAndLastGlyph->second.tileDistance), firstAndLastGlyph->second.angle, pixelsToTileUnits, projectedAnchor.second, pitchWithMap); + firstTileDistance = approximateTileDistance(*(firstAndLastGlyph->first.tileDistance), + firstAndLastGlyph->first.angle, + pixelsToTileUnits, + projectedAnchor.second, + pitchWithMap); + lastTileDistance = approximateTileDistance(*(firstAndLastGlyph->second.tileDistance), + firstAndLastGlyph->second.angle, + pixelsToTileUnits, + projectedAnchor.second, + pitchWithMap); } bool previousCirclePlaced = false; @@ -232,8 +255,7 @@ std::pair CollisionIndex::placeLineFeature( for (size_t i = 0; i < feature.boxes.size(); i++) { const CollisionBox& circle = feature.boxes[i]; const float boxSignedDistanceFromAnchor = circle.signedDistanceFromAnchor; - if (!firstAndLastGlyph || - (boxSignedDistanceFromAnchor < -firstTileDistance) || + if (!firstAndLastGlyph || (boxSignedDistanceFromAnchor < -firstTileDistance) || (boxSignedDistanceFromAnchor > lastTileDistance)) { // The label either doesn't fit on its line or we // don't need to use this circle because the label @@ -252,12 +274,14 @@ std::pair CollisionIndex::placeLineFeature( const auto& previousCenter = previousCircle.circle().center; const float dx = projectedPoint.x - previousCenter.x; const float dy = projectedPoint.y - previousCenter.y; - // The circle edges touch when the distance between their centers is 2x the radius - // When the distance is 1x the radius, they're doubled up, and we could remove - // every other circle while keeping them all in touch. - // We actually start removing circles when the distance is √2x the radius: - // thinning the number of circles as much as possible is a major performance win, - // and the small gaps introduced don't make a very noticeable difference. + // The circle edges touch when the distance between their centers is + // 2x the radius When the distance is 1x the radius, they're doubled + // up, and we could remove every other circle while keeping them all + // in touch. We actually start removing circles when the distance is + // √2x the radius: + // thinning the number of circles as much as possible is a major + // performance win, and the small gaps introduced don't make a very + // noticeable difference. const bool placedTooDensely = radius * radius * 2 > dx * dx + dy * dy; if (placedTooDensely) { const bool atLeastOneMoreCircle = (i + 1) < feature.boxes.size(); @@ -265,10 +289,11 @@ std::pair CollisionIndex::placeLineFeature( const CollisionBox& nextCircle = feature.boxes[i + 1]; const float nextBoxDistanceFromAnchor = nextCircle.signedDistanceFromAnchor; if ((nextBoxDistanceFromAnchor > -firstTileDistance) && - (nextBoxDistanceFromAnchor < lastTileDistance)) { - // Hide significantly overlapping circles, unless this is the last one we can - // use, in which case we want to keep it in place even if it's tightly packed - // with the one before it. + (nextBoxDistanceFromAnchor < lastTileDistance)) { + // Hide significantly overlapping circles, unless this + // is the last one we can use, in which case we want to + // keep it in place even if it's tightly packed with the + // one before it. previousCirclePlaced = false; continue; } @@ -293,8 +318,8 @@ std::pair CollisionIndex::placeLineFeature( if (!collisionDebug) { return {false, false}; } else { - // Don't early exit if we're showing the debug circles because we still want to calculate - // which circles are in use + // Don't early exit if we're showing the debug circles because + // we still want to calculate which circles are in use collisionDetected = true; } } @@ -303,7 +328,11 @@ std::pair CollisionIndex::placeLineFeature( return {!collisionDetected && firstAndLastGlyph && inGrid, entirelyOffscreen}; } -void CollisionIndex::insertFeature(const CollisionFeature& feature, const std::vector& projectedBoxes, bool ignorePlacement, uint32_t bucketInstanceId, uint16_t collisionGroupId) { +void CollisionIndex::insertFeature(const CollisionFeature& feature, + const std::vector& projectedBoxes, + bool ignorePlacement, + uint32_t bucketInstanceId, + uint16_t collisionGroupId) { if (feature.alongLine) { for (auto& circle : projectedBoxes) { if (!circle.isCircle()) { @@ -311,15 +340,11 @@ void CollisionIndex::insertFeature(const CollisionFeature& feature, const std::v } if (ignorePlacement) { - ignoredGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - circle.circle() - ); + ignoredGrid.insert(IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), + circle.circle()); } else { - collisionGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - circle.circle() - ); + collisionGrid.insert(IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), + circle.circle()); } } } else if (!projectedBoxes.empty()) { @@ -327,22 +352,19 @@ void CollisionIndex::insertFeature(const CollisionFeature& feature, const std::v auto& box = projectedBoxes[0]; assert(box.isBox()); if (ignorePlacement) { - ignoredGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - box.box() - ); + ignoredGrid.insert(IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), + box.box()); } else { - collisionGrid.insert( - IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), - box.box() - ); + collisionGrid.insert(IndexedSubfeature(feature.indexedFeature, bucketInstanceId, collisionGroupId), + box.box()); } } } bool polygonIntersectsBox(const LineString& polygon, const GridIndex::BBox& bbox) { - // This is just a wrapper that allows us to use the integer-based util::polygonIntersectsPolygon - // Conversion limits our query accuracy to single-pixel resolution + // This is just a wrapper that allows us to use the integer-based + // util::polygonIntersectsPolygon Conversion limits our query accuracy to + // single-pixel resolution GeometryCoordinates integerPolygon; for (const auto& point : polygon) { integerPolygon.push_back(convertPoint(point)); @@ -352,14 +374,13 @@ bool polygonIntersectsBox(const LineString& polygon, const GridIndex(bbox.min.y); auto maxX1 = static_cast(bbox.max.x); - auto bboxPoints = GeometryCoordinates { - { minX1, minY1 }, { maxX1, minY1 }, { maxX1, maxY1 }, { minX1, maxY1 } - }; - + auto bboxPoints = GeometryCoordinates{{minX1, minY1}, {maxX1, minY1}, {maxX1, maxY1}, {minX1, maxY1}}; + return util::polygonIntersectsPolygon(integerPolygon, bboxPoints); } -std::unordered_map> CollisionIndex::queryRenderedSymbols(const ScreenLineString& queryGeometry) const { +std::unordered_map> CollisionIndex::queryRenderedSymbols( + const ScreenLineString& queryGeometry) const { std::unordered_map> result; if (queryGeometry.empty() || (collisionGrid.empty() && ignoredGrid.empty())) { return result; @@ -367,27 +388,27 @@ std::unordered_map> CollisionIndex::que LineString gridQuery; for (const auto& point : queryGeometry) { - gridQuery.emplace_back(static_cast(point.x) + viewportPadding, static_cast(point.y) + viewportPadding); + gridQuery.emplace_back(static_cast(point.x) + viewportPadding, + static_cast(point.y) + viewportPadding); } - + auto envelope = mapbox::geometry::envelope(gridQuery); - + using QueryResult = std::pair::BBox>; - + std::vector features = collisionGrid.queryWithBoxes(envelope); std::vector ignoredFeatures = ignoredGrid.queryWithBoxes(envelope); features.insert(features.end(), ignoredFeatures.begin(), ignoredFeatures.end()); std::unordered_map> seenBuckets; - for (auto& queryResult : features) { + for (auto& queryResult : features) { auto& feature = queryResult.first; auto& bbox = queryResult.second; // Skip already seen features. auto& seenFeatures = seenBuckets[feature.bucketInstanceId]; - if (seenFeatures.find(feature.index) != seenFeatures.end()) - continue; - + if (seenFeatures.find(feature.index) != seenFeatures.end()) continue; + if (!polygonIntersectsBox(gridQuery, bbox)) { continue; } @@ -397,41 +418,34 @@ std::unordered_map> CollisionIndex::que } return result; - } -std::pair CollisionIndex::projectAnchor(const mat4& posMatrix, const Point& point) const { - vec4 p = {{ point.x, point.y, 0, 1 }}; +std::pair CollisionIndex::projectAnchor(const mat4& posMatrix, const Point& point) const { + vec4 p = {{point.x, point.y, 0, 1}}; matrix::transformMat4(p, p, posMatrix); - return std::make_pair( - 0.5f + 0.5f * (transformState.getCameraToCenterDistance() / static_cast(p[3])), - static_cast(p[3]) - ); + return std::make_pair(0.5f + 0.5f * (transformState.getCameraToCenterDistance() / static_cast(p[3])), + static_cast(p[3])); } -std::pair,float> CollisionIndex::projectAndGetPerspectiveRatio(const mat4& posMatrix, const Point& point) const { - vec4 p = {{ point.x, point.y, 0, 1 }}; +std::pair, float> CollisionIndex::projectAndGetPerspectiveRatio(const mat4& posMatrix, + const Point& point) const { + vec4 p = {{point.x, point.y, 0, 1}}; matrix::transformMat4(p, p, posMatrix); auto size = transformState.getSize(); - return std::make_pair( - Point( - static_cast(((p[0] / p[3] + 1) / 2) * size.width + viewportPadding), - static_cast(((-p[1] / p[3] + 1) / 2) * size.height + viewportPadding) - ), - // See perspective ratio comment in symbol_sdf.vertex - // We're doing collision detection in viewport space so we need - // to scale down boxes in the distance - 0.5f + 0.5f * transformState.getCameraToCenterDistance() / static_cast(p[3]) - ); + return std::make_pair(Point(static_cast(((p[0] / p[3] + 1) / 2) * size.width + viewportPadding), + static_cast(((-p[1] / p[3] + 1) / 2) * size.height + viewportPadding)), + // See perspective ratio comment in symbol_sdf.vertex + // We're doing collision detection in viewport space so we need + // to scale down boxes in the distance + 0.5f + 0.5f * transformState.getCameraToCenterDistance() / static_cast(p[3])); } Point CollisionIndex::projectPoint(const mat4& posMatrix, const Point& point) const { - vec4 p = {{ point.x, point.y, 0, 1 }}; + vec4 p = {{point.x, point.y, 0, 1}}; matrix::transformMat4(p, p, posMatrix); auto size = transformState.getSize(); - return Point { - static_cast((((p[0] / p[3] + 1) / 2) * size.width) + viewportPadding), - static_cast((((-p[1] / p[3] + 1) / 2) * size.height) + viewportPadding) }; + return Point{static_cast((((p[0] / p[3] + 1) / 2) * size.width) + viewportPadding), + static_cast((((-p[1] / p[3] + 1) / 2) * size.height) + viewportPadding)}; } CollisionBoundaries CollisionIndex::getProjectedCollisionBoundaries(const mat4& posMatrix, diff --git a/src/mbgl/text/collision_index.hpp b/src/mbgl/text/collision_index.hpp index b90242bb452..ef11a660d5e 100644 --- a/src/mbgl/text/collision_index.hpp +++ b/src/mbgl/text/collision_index.hpp @@ -16,7 +16,11 @@ struct TileDistance; using CollisionBoundaries = std::array; // [x1, y1, x2, y2] struct IntersectStatus { - enum Flags : uint8_t { None = 0, HorizontalBorders = 1 << 0, VerticalBorders = 1 << 1 }; + enum Flags : uint8_t { + None = 0, + HorizontalBorders = 1 << 0, + VerticalBorders = 1 << 1 + }; Flags flags = None; // Assuming tile border divides box in two sections int minSectionLength = 0; @@ -45,9 +49,14 @@ class CollisionIndex { bool collisionDebug, const std::optional& avoidEdges, const std::optional>& collisionGroupPredicate, - std::vector& /*out*/); + std::vector& /*out*/ + ); - void insertFeature(const CollisionFeature& feature, const std::vector&, bool ignorePlacement, uint32_t bucketInstanceId, uint16_t collisionGroupId); + void insertFeature(const CollisionFeature& feature, + const std::vector&, + bool ignorePlacement, + uint32_t bucketInstanceId, + uint16_t collisionGroupId); std::unordered_map> queryRenderedSymbols(const ScreenLineString&) const; @@ -76,7 +85,8 @@ class CollisionIndex { bool collisionDebug, const std::optional& avoidEdges, const std::optional>& collisionGroupPredicate, - std::vector& /*out*/); + std::vector& /*out*/ + ); float approximateTileDistance(const TileDistance& tileDistance, float lastSegmentAngle, @@ -84,8 +94,9 @@ class CollisionIndex { float cameraToAnchorDistance, bool pitchWithMap); - std::pair projectAnchor(const mat4& posMatrix, const Point& point) const; - std::pair,float> projectAndGetPerspectiveRatio(const mat4& posMatrix, const Point& point) const; + std::pair projectAnchor(const mat4& posMatrix, const Point& point) const; + std::pair, float> projectAndGetPerspectiveRatio(const mat4& posMatrix, + const Point& point) const; Point projectPoint(const mat4& posMatrix, const Point& point) const; CollisionBoundaries getProjectedCollisionBoundaries(const mat4& posMatrix, Point shift, @@ -97,12 +108,12 @@ class CollisionIndex { const float viewportPadding; CollisionGrid collisionGrid; CollisionGrid ignoredGrid; - + const float screenRightBoundary; const float screenBottomBoundary; const float gridRightBoundary; const float gridBottomBoundary; - + const float pitchFactor; }; diff --git a/src/mbgl/text/cross_tile_symbol_index.cpp b/src/mbgl/text/cross_tile_symbol_index.cpp index f2785dd1203..f2b137da491 100644 --- a/src/mbgl/text/cross_tile_symbol_index.cpp +++ b/src/mbgl/text/cross_tile_symbol_index.cpp @@ -10,7 +10,9 @@ TileLayerIndex::TileLayerIndex(OverscaledTileID coord_, std::vector& symbolInstances, uint32_t bucketInstanceId_, std::string bucketLeaderId_) - : coord(coord_), bucketInstanceId(bucketInstanceId_), bucketLeaderId(std::move(bucketLeaderId_)) { + : coord(coord_), + bucketInstanceId(bucketInstanceId_), + bucketLeaderId(std::move(bucketLeaderId_)) { for (SymbolInstance& symbolInstance : symbolInstances) { if (symbolInstance.crossTileID == SymbolInstance::invalidCrossTileID()) continue; indexedSymbolInstances[symbolInstance.key].emplace_back(symbolInstance.crossTileID, @@ -23,17 +25,19 @@ Point TileLayerIndex::getScaledCoordinates(SymbolInstance& symbolInstan // Round anchor positions to roughly 4 pixel grid const double roundingFactor = 512.0 / util::EXTENT / 2.0; const double scale = roundingFactor / std::pow(2, childTileCoord.canonical.z - coord.canonical.z); - return { - static_cast(std::floor((childTileCoord.canonical.x * util::EXTENT + symbolInstance.anchor.point.x) * scale)), - static_cast(std::floor((childTileCoord.canonical.y * util::EXTENT + symbolInstance.anchor.point.y) * scale)) - }; + return {static_cast( + std::floor((childTileCoord.canonical.x * util::EXTENT + symbolInstance.anchor.point.x) * scale)), + static_cast( + std::floor((childTileCoord.canonical.y * util::EXTENT + symbolInstance.anchor.point.y) * scale))}; } void TileLayerIndex::findMatches(SymbolBucket& bucket, const OverscaledTileID& newCoord, std::set& zoomCrossTileIDs) const { auto& symbolInstances = bucket.symbolInstances; - float tolerance = coord.canonical.z < newCoord.canonical.z ? 1.0f : static_cast(std::pow(2, coord.canonical.z - newCoord.canonical.z)); + float tolerance = coord.canonical.z < newCoord.canonical.z + ? 1.0f + : static_cast(std::pow(2, coord.canonical.z - newCoord.canonical.z)); if (bucket.bucketLeaderID != bucketLeaderId) return; @@ -52,14 +56,14 @@ void TileLayerIndex::findMatches(SymbolBucket& bucket, auto scaledSymbolCoord = getScaledCoordinates(symbolInstance, newCoord); for (const IndexedSymbolInstance& thisTileSymbol : it->second) { - // Return any symbol with the same keys whose coordinates are within 1 - // grid unit. (with a 4px grid, this covers a 12px by 12px area) + // Return any symbol with the same keys whose coordinates are within + // 1 grid unit. (with a 4px grid, this covers a 12px by 12px area) if (std::abs(thisTileSymbol.coord.x - scaledSymbolCoord.x) <= tolerance && std::abs(thisTileSymbol.coord.y - scaledSymbolCoord.y) <= tolerance && zoomCrossTileIDs.find(thisTileSymbol.crossTileID) == zoomCrossTileIDs.end()) { - // Once we've marked ourselves duplicate against this parent symbol, - // don't let any other symbols at the same zoom level duplicate against - // the same parent (see issue #10844) + // Once we've marked ourselves duplicate against this parent + // symbol, don't let any other symbols at the same zoom level + // duplicate against the same parent (see issue #10844) zoomCrossTileIDs.insert(thisTileSymbol.crossTileID); symbolInstance.crossTileID = thisTileSymbol.crossTileID; break; @@ -68,19 +72,20 @@ void TileLayerIndex::findMatches(SymbolBucket& bucket, } } -CrossTileSymbolLayerIndex::CrossTileSymbolLayerIndex(uint32_t& maxCrossTileID_) : maxCrossTileID(maxCrossTileID_) {} +CrossTileSymbolLayerIndex::CrossTileSymbolLayerIndex(uint32_t& maxCrossTileID_) + : maxCrossTileID(maxCrossTileID_) {} /* - * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. - * To prevent labels from flashing out and in we adjust the tileID values in the indexes - * so that they match the new wrapped version of the map. + * Sometimes when a user pans across the antimeridian the longitude value gets + * wrapped. To prevent labels from flashing out and in we adjust the tileID + * values in the indexes so that they match the new wrapped version of the map. */ void CrossTileSymbolLayerIndex::handleWrapJump(float newLng) { const auto wrapDelta = static_cast(std::round((newLng - lng) / 360.0f)); if (wrapDelta != 0) { - std::map> newIndexes; + std::map> newIndexes; for (auto& zoomIndex : indexes) { - std::map newZoomIndex; + std::map newZoomIndex; for (auto& index : zoomIndex.second) { // change the tileID's wrap and move its index index.second.coord = index.second.coord.unwrapTo(index.second.coord.wrap + wrapDelta); @@ -121,9 +126,10 @@ bool CrossTileSymbolLayerIndex::addBucket(const OverscaledTileID& tileID, return false; } else { // We're replacing this bucket with an updated version - // Remove the old bucket's "used crossTileIDs" now so that the new bucket can claim them. - // We have to keep the old index entries themselves until the end of 'addBucket' so - // that we can copy them with 'findMatches'. + // Remove the old bucket's "used crossTileIDs" now so that the new + // bucket can claim them. We have to keep the old index entries + // themselves until the end of 'addBucket' so that we can copy them + // with 'findMatches'. removeBucketCrossTileIDs(tileID.overscaledZ, previousIndex->second); } } @@ -254,4 +260,3 @@ void CrossTileSymbolIndex::reset() { } } // namespace mbgl - diff --git a/src/mbgl/text/cross_tile_symbol_index.hpp b/src/mbgl/text/cross_tile_symbol_index.hpp index 50d91123976..8869e17817f 100644 --- a/src/mbgl/text/cross_tile_symbol_index.hpp +++ b/src/mbgl/text/cross_tile_symbol_index.hpp @@ -22,8 +22,8 @@ class SymbolBucket; class IndexedSymbolInstance { public: IndexedSymbolInstance(uint32_t crossTileID_, Point coord_) - : crossTileID(crossTileID_), coord(coord_) - {} + : crossTileID(crossTileID_), + coord(coord_) {} uint32_t crossTileID; Point coord; @@ -42,7 +42,7 @@ class TileLayerIndex { OverscaledTileID coord; uint32_t bucketInstanceId; std::string bucketLeaderId; - std::map> indexedSymbolInstances; + std::map> indexedSymbolInstances; }; class CrossTileSymbolLayerIndex { @@ -51,10 +51,11 @@ class CrossTileSymbolLayerIndex { bool addBucket(const OverscaledTileID&, const mat4& tileMatrix, SymbolBucket&); bool removeStaleBuckets(const std::unordered_set& currentIDs); void handleWrapJump(float newLng); + private: void removeBucketCrossTileIDs(uint8_t zoom, const TileLayerIndex& removedBucket); - std::map> indexes; + std::map> indexes; std::map> usedCrossTileIDs; float lng = 0; uint32_t& maxCrossTileID; @@ -74,6 +75,7 @@ class CrossTileSymbolIndex { void pruneUnusedLayers(const std::set&); void reset(); + private: std::map layerIndexes; uint32_t maxCrossTileID = 0; diff --git a/src/mbgl/text/get_anchors.cpp b/src/mbgl/text/get_anchors.cpp index ab2abc1bdba..38b16816530 100644 --- a/src/mbgl/text/get_anchors.cpp +++ b/src/mbgl/text/get_anchors.cpp @@ -7,11 +7,9 @@ #include namespace mbgl { - + float getAngleWindowSize(const float textLeft, const float textRight, const float glyphSize, const float boxScale) { - return (textLeft - textRight) != 0.0f ? - 3.0f / 5.0f * glyphSize * boxScale : - 0; + return (textLeft - textRight) != 0.0f ? 3.0f / 5.0f * glyphSize * boxScale : 0; } float getLineLength(const GeometryCoordinates& line) { @@ -58,9 +56,8 @@ static Anchors resample(const GeometryCoordinates& line, // Check that the point is within the tile boundaries and that // the label would fit before the beginning and end of the line // if placed at this point. - if (x >= 0 && x < util::EXTENT && y >= 0 && y < util::EXTENT && - markedDistance - halfLabelLength >= 0.0f && - markedDistance + halfLabelLength <= lineLength) { + if (x >= 0 && x < util::EXTENT && y >= 0 && y < util::EXTENT && markedDistance - halfLabelLength >= 0.0f && + markedDistance + halfLabelLength <= lineLength) { Anchor anchor(std::round(x), std::round(y), angle, i); if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { @@ -73,11 +70,12 @@ static Anchors resample(const GeometryCoordinates& line, } if (!placeAtMiddle && anchors.empty() && !continuedLine) { - // The first attempt at finding anchors at which labels can be placed failed. - // Try again, but this time just try placing one anchor at the middle of the line. - // This has the most effect for short lines in overscaled tiles, since the - // initial offset used in overscaled tiles is calculated to align labels with positions in - // parent tiles instead of placing the label as close to the beginning as possible. + // The first attempt at finding anchors at which labels can be placed + // failed. Try again, but this time just try placing one anchor at the + // middle of the line. This has the most effect for short lines in + // overscaled tiles, since the initial offset used in overscaled tiles + // is calculated to align labels with positions in parent tiles instead + // of placing the label as close to the beginning as possible. anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, continuedLine, true); } @@ -108,7 +106,8 @@ Anchors getAnchors(const GeometryCoordinates& line, const float labelLength = shapedLabelLength * boxScale; // Is the line continued from outside the tile boundary? - const bool continuedLine = (line[0].x == 0 || line[0].x == util::EXTENT || line[0].y == 0 || line[0].y == util::EXTENT); + const bool continuedLine = (line[0].x == 0 || line[0].x == util::EXTENT || line[0].y == 0 || + line[0].y == util::EXTENT); // Is the label long, relative to the spacing? // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. @@ -117,31 +116,31 @@ Anchors getAnchors(const GeometryCoordinates& line, } // Offset the first anchor by: - // Either half the label length plus a fixed extra offset if the line is not continued - // Or half the spacing if the line is continued. + // Either half the label length plus a fixed extra offset if the line is not + // continued Or half the spacing if the line is continued. // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. const float fixedExtraOffset = glyphSize * 2; - const float offset = !continuedLine ? - std::fmod((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling, spacing) : - std::fmod(spacing / 2 * overscaling, spacing); + const float offset = !continuedLine + ? std::fmod((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling, spacing) + : std::fmod(spacing / 2 * overscaling, spacing); return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, continuedLine, false); } std::optional getCenterAnchor(const GeometryCoordinates& line, - const float maxAngle, - const float textLeft, - const float textRight, - const float iconLeft, - const float iconRight, - const float glyphSize, - const float boxScale) { + const float maxAngle, + const float textLeft, + const float textRight, + const float iconLeft, + const float iconRight, + const float glyphSize, + const float boxScale) { if (line.empty()) { return {}; } - + const float angleWindowSize = getAngleWindowSize(textLeft, textRight, glyphSize, boxScale); const float labelLength = std::fmax(textRight - textLeft, iconRight - iconLeft) * boxScale; @@ -152,9 +151,9 @@ std::optional getCenterAnchor(const GeometryCoordinates& line, for (auto it = line.begin(), end = line.end() - 1; it != end; it++, i++) { const GeometryCoordinate& a = *(it); const GeometryCoordinate& b = *(it + 1); - + const auto segmentDistance = util::dist(a, b); - + if (prevDistance + segmentDistance > centerDistance) { // The center is on this segment float t = (centerDistance - prevDistance) / segmentDistance; @@ -169,7 +168,7 @@ std::optional getCenterAnchor(const GeometryCoordinates& line, return std::nullopt; } - + prevDistance += segmentDistance; } return {}; diff --git a/src/mbgl/text/get_anchors.hpp b/src/mbgl/text/get_anchors.hpp index 357ece3dfdf..7161cccbd77 100644 --- a/src/mbgl/text/get_anchors.hpp +++ b/src/mbgl/text/get_anchors.hpp @@ -18,12 +18,12 @@ Anchors getAnchors(const GeometryCoordinates& line, float overscaling); std::optional getCenterAnchor(const GeometryCoordinates& line, - float maxAngle, - float textLeft, - float textRight, - float iconLeft, - float iconRight, - float glyphSize, - float boxScale); + float maxAngle, + float textLeft, + float textRight, + float iconLeft, + float iconRight, + float glyphSize, + float boxScale); } // namespace mbgl diff --git a/src/mbgl/text/glyph.cpp b/src/mbgl/text/glyph.cpp index 74863d7435c..8c879cbe4dd 100644 --- a/src/mbgl/text/glyph.cpp +++ b/src/mbgl/text/glyph.cpp @@ -4,11 +4,11 @@ namespace mbgl { // Note: this only works for the BMP GlyphRange getGlyphRange(GlyphID glyph) { - unsigned start = (glyph/256) * 256; + unsigned start = (glyph / 256) * 256; unsigned end = (start + 255); if (start > 65280) start = 65280; if (end > 65535) end = 65535; - return { start, end }; + return {start, end}; } } // namespace mbgl diff --git a/src/mbgl/text/glyph.hpp b/src/mbgl/text/glyph.hpp index d1d1bd4cb41..36383c0a1eb 100644 --- a/src/mbgl/text/glyph.hpp +++ b/src/mbgl/text/glyph.hpp @@ -32,17 +32,14 @@ struct GlyphMetrics { }; inline bool operator==(const GlyphMetrics& lhs, const GlyphMetrics& rhs) { - return lhs.width == rhs.width && - lhs.height == rhs.height && - lhs.left == rhs.left && - lhs.top == rhs.top && - lhs.advance == rhs.advance; + return lhs.width == rhs.width && lhs.height == rhs.height && lhs.left == rhs.left && lhs.top == rhs.top && + lhs.advance == rhs.advance; } class Glyph { public: - // We're using this value throughout the Mapbox GL ecosystem. If this is different, the glyphs - // also need to be reencoded. + // We're using this value throughout the Mapbox GL ecosystem. If this is + // different, the glyphs also need to be reencoded. static constexpr const uint8_t borderSize = 3; GlyphID id = 0; @@ -101,10 +98,14 @@ struct PositionedLine { }; class Shaping { - public: +public: Shaping() = default; explicit Shaping(float x, float y, WritingModeType writingMode_) - : top(y), bottom(y), left(x), right(x), writingMode(writingMode_) {} + : top(y), + bottom(y), + left(x), + right(x), + writingMode(writingMode_) {} std::vector positionedLines; float top = 0; float bottom = 0; diff --git a/src/mbgl/text/glyph_atlas.cpp b/src/mbgl/text/glyph_atlas.cpp index da65aea8a9d..d2a048d659e 100644 --- a/src/mbgl/text/glyph_atlas.cpp +++ b/src/mbgl/text/glyph_atlas.cpp @@ -21,43 +21,26 @@ GlyphAtlas makeGlyphAtlas(const GlyphMap& glyphs) { if (entry.second && (*entry.second)->bitmap.valid()) { const Glyph& glyph = **entry.second; - const mapbox::Bin& bin = *pack.packOne(-1, - glyph.bitmap.size.width + 2 * padding, - glyph.bitmap.size.height + 2 * padding); + const mapbox::Bin& bin = *pack.packOne( + -1, glyph.bitmap.size.width + 2 * padding, glyph.bitmap.size.height + 2 * padding); - result.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); + result.image.resize({static_cast(pack.width()), static_cast(pack.height())}); - AlphaImage::copy(glyph.bitmap, - result.image, - { 0, 0 }, - { - bin.x + padding, - bin.y + padding - }, - glyph.bitmap.size); + AlphaImage::copy( + glyph.bitmap, result.image, {0, 0}, {bin.x + padding, bin.y + padding}, glyph.bitmap.size); positions.emplace(glyph.id, - GlyphPosition { - Rect { - static_cast(bin.x), - static_cast(bin.y), - static_cast(bin.w), - static_cast(bin.h) - }, - glyph.metrics - }); + GlyphPosition{Rect{static_cast(bin.x), + static_cast(bin.y), + static_cast(bin.w), + static_cast(bin.h)}, + glyph.metrics}); } } } pack.shrink(); - result.image.resize({ - static_cast(pack.width()), - static_cast(pack.height()) - }); + result.image.resize({static_cast(pack.width()), static_cast(pack.height())}); return result; } diff --git a/src/mbgl/text/glyph_manager.cpp b/src/mbgl/text/glyph_manager.cpp index 924e931521d..f651185b654 100644 --- a/src/mbgl/text/glyph_manager.cpp +++ b/src/mbgl/text/glyph_manager.cpp @@ -14,18 +14,18 @@ static GlyphManagerObserver nullObserver; GlyphManager::GlyphManager(std::unique_ptr localGlyphRasterizer_) : observer(&nullObserver), - localGlyphRasterizer(std::move(localGlyphRasterizer_)) { -} + localGlyphRasterizer(std::move(localGlyphRasterizer_)) {} GlyphManager::~GlyphManager() = default; void GlyphManager::getGlyphs(GlyphRequestor& requestor, GlyphDependencies glyphDependencies, FileSource& fileSource) { auto dependencies = std::make_shared(std::move(glyphDependencies)); - // Figure out which glyph ranges need to be fetched. For each range that does need to - // be fetched, record an entry mapping the requestor to a shared pointer containing the - // dependencies. When the shared pointer becomes unique, we know that all the dependencies - // for that requestor have been fetched, and can notify it of completion. + // Figure out which glyph ranges need to be fetched. For each range that + // does need to be fetched, record an entry mapping the requestor to a + // shared pointer containing the dependencies. When the shared pointer + // becomes unique, we know that all the dependencies for that requestor have + // been fetched, and can notify it of completion. for (const auto& dependency : *dependencies) { const FontStack& fontStack = dependency.first; Entry& entry = entries[fontStack]; @@ -52,8 +52,8 @@ void GlyphManager::getGlyphs(GlyphRequestor& requestor, GlyphDependencies glyphD } } - // If the shared dependencies pointer is already unique, then all dependent glyph ranges - // have already been loaded. Send a notification immediately. + // If the shared dependencies pointer is already unique, then all dependent + // glyph ranges have already been loaded. Send a notification immediately. if (dependencies.unique()) { notify(requestor, *dependencies); } @@ -65,14 +65,17 @@ Glyph GlyphManager::generateLocalSDF(const FontStack& fontStack, GlyphID glyphID return local; } -void GlyphManager::requestRange(GlyphRequest& request, const FontStack& fontStack, const GlyphRange& range, FileSource& fileSource) { +void GlyphManager::requestRange(GlyphRequest& request, + const FontStack& fontStack, + const GlyphRange& range, + FileSource& fileSource) { if (request.req) { return; } - request.req = - fileSource.request(Resource::glyphs(glyphURL, fontStack, range), - [this, fontStack, range](const Response& res) { processResponse(res, fontStack, range); }); + request.req = fileSource.request( + Resource::glyphs(glyphURL, fontStack, range), + [this, fontStack, range](const Response& res) { processResponse(res, fontStack, range); }); } void GlyphManager::processResponse(const Response& res, const FontStack& fontStack, const GlyphRange& range) { @@ -158,9 +161,7 @@ void GlyphManager::removeRequestor(GlyphRequestor& requestor) { } void GlyphManager::evict(const std::set& keep) { - util::erase_if(entries, [&] (const auto& entry) { - return keep.count(entry.first) == 0; - }); + util::erase_if(entries, [&](const auto& entry) { return keep.count(entry.first) == 0; }); } } // namespace mbgl diff --git a/src/mbgl/text/glyph_manager.hpp b/src/mbgl/text/glyph_manager.hpp index a53636d0a76..b01b630872f 100644 --- a/src/mbgl/text/glyph_manager.hpp +++ b/src/mbgl/text/glyph_manager.hpp @@ -28,20 +28,19 @@ class GlyphManager { public: GlyphManager(const GlyphManager&) = delete; GlyphManager& operator=(const GlyphManager&) = delete; - explicit GlyphManager(std::unique_ptr = std::make_unique(std::optional())); + explicit GlyphManager( + std::unique_ptr = std::make_unique(std::optional())); ~GlyphManager(); - // Workers send a `getGlyphs` message to the main thread once they have determined - // their `GlyphDependencies`. If all glyphs are already locally available, GlyphManager - // will provide them to the requestor immediately. Otherwise, it makes a request on the - // FileSource is made for each range needed, and notifies the observer when all are - // complete. + // Workers send a `getGlyphs` message to the main thread once they have + // determined their `GlyphDependencies`. If all glyphs are already locally + // available, GlyphManager will provide them to the requestor immediately. + // Otherwise, it makes a request on the FileSource is made for each range + // needed, and notifies the observer when all are complete. void getGlyphs(GlyphRequestor&, GlyphDependencies, FileSource&); void removeRequestor(GlyphRequestor&); - void setURL(const std::string& url) { - glyphURL = url; - } + void setURL(const std::string& url) { glyphURL = url; } void setObserver(GlyphManagerObserver*); @@ -68,9 +67,9 @@ class GlyphManager { void requestRange(GlyphRequest&, const FontStack&, const GlyphRange&, FileSource& fileSource); void processResponse(const Response&, const FontStack&, const GlyphRange&); void notify(GlyphRequestor&, const GlyphDependencies&); - + GlyphManagerObserver* observer = nullptr; - + std::unique_ptr localGlyphRasterizer; }; diff --git a/src/mbgl/text/glyph_pbf.cpp b/src/mbgl/text/glyph_pbf.cpp index c1cd3292926..d035c3d9ab5 100644 --- a/src/mbgl/text/glyph_pbf.cpp +++ b/src/mbgl/text/glyph_pbf.cpp @@ -27,59 +27,57 @@ std::vector parseGlyphPBF(const GlyphRange& glyphRange, const std::string while (glyph_pbf.next()) { switch (glyph_pbf.tag()) { - case 1: // id - glyph.id = glyph_pbf.get_uint32(); - hasID = true; - break; - case 2: // bitmap - glyphData = glyph_pbf.get_view(); - break; - case 3: // width - glyph.metrics.width = glyph_pbf.get_uint32(); - hasWidth = true; - break; - case 4: // height - glyph.metrics.height = glyph_pbf.get_uint32(); - hasHeight = true; - break; - case 5: // left - glyph.metrics.left = glyph_pbf.get_sint32(); - hasLeft = true; - break; - case 6: // top - glyph.metrics.top = glyph_pbf.get_sint32(); - hasTop = true; - break; - case 7: // advance - glyph.metrics.advance = glyph_pbf.get_uint32(); - hasAdvance = true; - break; - default: - glyph_pbf.skip(); - break; + case 1: // id + glyph.id = glyph_pbf.get_uint32(); + hasID = true; + break; + case 2: // bitmap + glyphData = glyph_pbf.get_view(); + break; + case 3: // width + glyph.metrics.width = glyph_pbf.get_uint32(); + hasWidth = true; + break; + case 4: // height + glyph.metrics.height = glyph_pbf.get_uint32(); + hasHeight = true; + break; + case 5: // left + glyph.metrics.left = glyph_pbf.get_sint32(); + hasLeft = true; + break; + case 6: // top + glyph.metrics.top = glyph_pbf.get_sint32(); + hasTop = true; + break; + case 7: // advance + glyph.metrics.advance = glyph_pbf.get_uint32(); + hasAdvance = true; + break; + default: + glyph_pbf.skip(); + break; } } - // Only treat this glyph as a correct glyph if it has all required fields. It also - // needs to satisfy a few metrics conditions that ensure that the glyph isn't bogus. - // All other glyphs are malformed. We're also discarding all glyphs that are outside - // the expected glyph range. - if (!hasID || !hasWidth || !hasHeight || !hasLeft || !hasTop || !hasAdvance || - glyph.metrics.width >= 256 || glyph.metrics.height >= 256 || - glyph.metrics.left < -128 || glyph.metrics.left >= 128 || - glyph.metrics.top < -128 || glyph.metrics.top >= 128 || - glyph.metrics.advance >= 256 || + // Only treat this glyph as a correct glyph if it has all required + // fields. It also needs to satisfy a few metrics conditions that + // ensure that the glyph isn't bogus. All other glyphs are + // malformed. We're also discarding all glyphs that are outside the + // expected glyph range. + if (!hasID || !hasWidth || !hasHeight || !hasLeft || !hasTop || !hasAdvance || glyph.metrics.width >= 256 || + glyph.metrics.height >= 256 || glyph.metrics.left < -128 || glyph.metrics.left >= 128 || + glyph.metrics.top < -128 || glyph.metrics.top >= 128 || glyph.metrics.advance >= 256 || glyph.id < glyphRange.first || glyph.id > glyphRange.second) { continue; } - // If the area of width/height is non-zero, we need to adjust the expected size - // with the implicit border size, otherwise we expect there to be no bitmap at all. + // If the area of width/height is non-zero, we need to adjust the + // expected size with the implicit border size, otherwise we expect + // there to be no bitmap at all. if (glyph.metrics.width && glyph.metrics.height) { - const Size size { - glyph.metrics.width + 2 * Glyph::borderSize, - glyph.metrics.height + 2 * Glyph::borderSize - }; + const Size size{glyph.metrics.width + 2 * Glyph::borderSize, + glyph.metrics.height + 2 * Glyph::borderSize}; if (size.area() != glyphData.size()) { continue; diff --git a/src/mbgl/text/glyph_range.hpp b/src/mbgl/text/glyph_range.hpp index 17dc8c82725..14c704d0e17 100644 --- a/src/mbgl/text/glyph_range.hpp +++ b/src/mbgl/text/glyph_range.hpp @@ -20,9 +20,7 @@ namespace std { template <> struct hash { - std::size_t operator()(const mbgl::GlyphRange& range) const { - return mbgl::util::hash(range.first, range.second); - } + std::size_t operator()(const mbgl::GlyphRange& range) const { return mbgl::util::hash(range.first, range.second); } }; } // namespace std diff --git a/src/mbgl/text/language_tag.cpp b/src/mbgl/text/language_tag.cpp index 02f01c3d69b..05851d18b7b 100644 --- a/src/mbgl/text/language_tag.cpp +++ b/src/mbgl/text/language_tag.cpp @@ -2,7 +2,7 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4828) +#pragma warning(disable : 4828) #endif #include @@ -100,80 +100,56 @@ namespace phoenix = boost::phoenix; namespace ascii = boost::spirit::ascii; template -struct bcp47_parser : qi::grammar -{ - bcp47_parser() : bcp47_parser::base_type(start) - { - using qi::lit; - using qi::repeat; - using qi::inf; - using qi::eoi; - using ascii::char_; - using ascii::no_case; - using ascii::digit; +struct bcp47_parser : qi::grammar { + bcp47_parser() + : bcp47_parser::base_type(start) { using ascii::alnum; using ascii::alpha; + using ascii::char_; + using ascii::digit; + using ascii::no_case; + using qi::eoi; + using qi::inf; + using qi::lit; + using qi::repeat; using boost::spirit::qi::_1; start %= no_case[langtag | privateuse | grandfathered]; - langtag %= (language) [phoenix::ref(languageTag.language) = _1] - >> -("-" >> (script)[phoenix::ref(languageTag.script) = _1]) - >> -("-" >> (region)[phoenix::ref(languageTag.region) = _1]) - >> *("-" >> variant) - >> *("-" >> extension) - >> -("-" >> privateuse); + langtag %= (language)[phoenix::ref(languageTag.language) = _1] >> + -("-" >> (script)[phoenix::ref(languageTag.script) = _1]) >> + -("-" >> (region)[phoenix::ref(languageTag.region) = _1]) >> *("-" >> variant) >> + *("-" >> extension) >> -("-" >> privateuse); - language %= (repeat(2,3)[alpha] >> -("-" >> extlang)) // shortest ISO 639 code - // sometimes followed by extended language subtags - | repeat(4)[alpha] // or reserved for future use - | repeat(5,8)[alpha]; // or registered language subtag + language %= (repeat(2, 3)[alpha] >> -("-" >> extlang)) // shortest ISO 639 code + // sometimes followed by extended language subtags + | repeat(4)[alpha] // or reserved for future use + | repeat(5, 8)[alpha]; // or registered language subtag // We add lookaheads for "-"/eoi so that spurious matches on subtags don't prevent backtracking - extlang = repeat(3)[alpha] >> (&lit('-') | eoi) >> repeat(0,2)["-" >> repeat(3)[alpha] >> (&lit('-') | eoi)]; + extlang = repeat(3)[alpha] >> (&lit('-') | eoi) >> repeat(0, 2)["-" >> repeat(3)[alpha] >> (&lit('-') | eoi)]; script = repeat(4)[alpha] >> (&lit('-') | eoi); region = (repeat(2)[alpha] | repeat(3)[digit]) >> (&lit('-') | eoi); - variant = (repeat(5,8)[alnum] | (digit >> repeat(3,inf)[alnum])) >> (&lit('-') | eoi); + variant = (repeat(5, 8)[alnum] | (digit >> repeat(3, inf)[alnum])) >> (&lit('-') | eoi); - extension = singleton >> +("-" >> repeat(2,8)[alnum]) >> (&lit('-') | eoi); + extension = singleton >> +("-" >> repeat(2, 8)[alnum]) >> (&lit('-') | eoi); - singleton = digit | char_('a','w') | char_('y','z'); // "no-case" handles A-W and Y-Z + singleton = digit | char_('a', 'w') | char_('y', 'z'); // "no-case" handles A-W and Y-Z - privateuse = "x" >> +("-" >> repeat(1,8)[alnum]) >> (&lit('-') | eoi); + privateuse = "x" >> +("-" >> repeat(1, 8)[alnum]) >> (&lit('-') | eoi); grandfathered = regular | irregular; - irregular = lit("en-GB-oed") - | "i-ami" - | "i-bnn" - | "i-default" - | "i-enochian" - | "i-hak" - | "i-klingon" - | "i-lux" - | "i-mingo" - | "i-navajo" - | "i-pwn" - | "i-tao" - | "i-tay" - | "i-tsu" - | "sgn-BE-FR" - | "sgn-BE-NL" - | "sgn-CH-DE"; - - regular = lit("art-lojban") - | "cel-gaulish" - | "no-bok" - | "no-nyn" - | "zh-guoyu" - | "zh-hakka" - | "zh-min" - | "zh-min-nan" - | "zh-xiang"; + irregular = lit("en-GB-oed") | "i-ami" | "i-bnn" | "i-default" | "i-enochian" | "i-hak" | "i-klingon" | + "i-lux" | "i-mingo" | "i-navajo" | "i-pwn" | "i-tao" | "i-tay" | "i-tsu" | "sgn-BE-FR" | + "sgn-BE-NL" | "sgn-CH-DE"; + + regular = lit("art-lojban") | "cel-gaulish" | "no-bok" | "no-nyn" | "zh-guoyu" | "zh-hakka" | "zh-min" | + "zh-min-nan" | "zh-xiang"; } qi::rule start; @@ -209,17 +185,18 @@ LanguageTag LanguageTag::fromBCP47(const std::string& bcp47Tag) { } } -LanguageTag::LanguageTag(std::optional language_, std::optional script_, std::optional region_) - : language(std::move(language_)) - , script(std::move(script_)) - , region(std::move(region_)) -{} +LanguageTag::LanguageTag(std::optional language_, + std::optional script_, + std::optional region_) + : language(std::move(language_)), + script(std::move(script_)), + region(std::move(region_)) {} std::string LanguageTag::toBCP47() const { std::stringstream bcp47; if (!language) { - // BCP 47 requires a language, but we're matching implementations that accept "" - // to mean something like "default" + // BCP 47 requires a language, but we're matching implementations that + // accept "" to mean something like "default" return bcp47.str(); } else { bcp47 << *language; diff --git a/src/mbgl/text/language_tag.hpp b/src/mbgl/text/language_tag.hpp index a499cd32179..0b0017936eb 100644 --- a/src/mbgl/text/language_tag.hpp +++ b/src/mbgl/text/language_tag.hpp @@ -17,20 +17,23 @@ We're OK with not supporting extensions, but we want to succesfully parse any valid BCP 47 tag and get out the base language/script/region. - Mozilla's version: https://dxr.mozilla.org/mozilla-central/source/intl/locale/MozLocale.cpp - Looks like it actually supports a subset of BCP 47. - See https://bugzilla.mozilla.org/show_bug.cgi?id=bcp47 - - Chromium is based on ICU version: https://ssl.icu-project.org/apiref/icu4c/uloc_8h.html - Getting all the locale information is overkill for us, we just want - language/script/region. + Mozilla's version: + https://dxr.mozilla.org/mozilla-central/source/intl/locale/MozLocale.cpp + Looks like it actually supports a subset of BCP 47. See + https://bugzilla.mozilla.org/show_bug.cgi?id=bcp47 + + Chromium is based on ICU version: + https://ssl.icu-project.org/apiref/icu4c/uloc_8h.html Getting all the locale + information is overkill for us, we just want language/script/region. */ namespace mbgl { struct LanguageTag { LanguageTag() = default; - LanguageTag(std::optional language_, std::optional script_, std::optional region_); + LanguageTag(std::optional language_, + std::optional script_, + std::optional region_); static LanguageTag fromBCP47(const std::string& bcp47Tag); std::string toBCP47() const; diff --git a/src/mbgl/text/local_glyph_rasterizer.hpp b/src/mbgl/text/local_glyph_rasterizer.hpp index 4cc0c6a1820..69550b3ed8e 100644 --- a/src/mbgl/text/local_glyph_rasterizer.hpp +++ b/src/mbgl/text/local_glyph_rasterizer.hpp @@ -10,7 +10,7 @@ namespace mbgl { then generate a matching glyph object with a greyscale rasterization of the glyph and appropriate metrics. GlyphManager will then use TinySDF to transform the rasterized bitmap into an SDF. - + The JS equivalent of this functionality will only generate glyphs in the 'CJK Unified Ideographs' and 'Hangul Syllables' ranges, for which it can get away with rendering a fixed 30px square image and GlyphMetrics of: @@ -23,10 +23,10 @@ namespace mbgl { The JS equivalent also uses heuristic evaluation of the font stack name to control the font-weight it uses during rasterization. - + It is left to platform-specific implementation to decide how best to map a FontStack to a particular rasterization. - + The default implementation simply refuses to rasterize any glyphs. */ @@ -38,6 +38,7 @@ class LocalGlyphRasterizer { // virtual so that test harness can override platform-specific behavior virtual bool canRasterizeGlyph(const FontStack&, GlyphID); virtual Glyph rasterizeGlyph(const FontStack&, GlyphID); + private: class Impl; std::unique_ptr impl; diff --git a/src/mbgl/text/placement.cpp b/src/mbgl/text/placement.cpp index 0249aec59de..6a18f183f4b 100644 --- a/src/mbgl/text/placement.cpp +++ b/src/mbgl/text/placement.cpp @@ -13,31 +13,32 @@ namespace mbgl { OpacityState::OpacityState(bool placed_, bool skipFade) - : opacity((skipFade && placed_) ? 1.0f : 0.0f) - , placed(placed_) -{ -} + : opacity((skipFade && placed_) ? 1.0f : 0.0f), + placed(placed_) {} -OpacityState::OpacityState(const OpacityState& prevState, float increment, bool placed_) : - opacity(std::fmax(0.0f, std::fmin(1.0f, prevState.opacity + (prevState.placed ? increment : -increment)))), - placed(placed_) {} +OpacityState::OpacityState(const OpacityState& prevState, float increment, bool placed_) + : opacity(std::fmax(0.0f, std::fmin(1.0f, prevState.opacity + (prevState.placed ? increment : -increment)))), + placed(placed_) {} bool OpacityState::isHidden() const { return opacity == 0 && !placed; } -JointOpacityState::JointOpacityState(bool placedText, bool placedIcon, bool skipFade) : - icon(OpacityState(placedIcon, skipFade)), - text(OpacityState(placedText, skipFade)) {} +JointOpacityState::JointOpacityState(bool placedText, bool placedIcon, bool skipFade) + : icon(OpacityState(placedIcon, skipFade)), + text(OpacityState(placedText, skipFade)) {} -JointOpacityState::JointOpacityState(const JointOpacityState& prevOpacityState, float increment, bool placedText, bool placedIcon) : - icon(OpacityState(prevOpacityState.icon, increment, placedIcon)), - text(OpacityState(prevOpacityState.text, increment, placedText)) {} +JointOpacityState::JointOpacityState(const JointOpacityState& prevOpacityState, + float increment, + bool placedText, + bool placedIcon) + : icon(OpacityState(prevOpacityState.icon, increment, placedIcon)), + text(OpacityState(prevOpacityState.text, increment, placedText)) {} bool JointOpacityState::isHidden() const { return icon.isHidden() && text.isHidden(); } - + const CollisionGroups::CollisionGroup& CollisionGroups::get(const std::string& sourceID) { // The predicate/groupID mechanism allows for arbitrary grouping, // but the current interface defines one source == one group when @@ -45,12 +46,12 @@ const CollisionGroups::CollisionGroup& CollisionGroups::get(const std::string& s if (!crossSourceCollisions) { if (collisionGroups.find(sourceID) == collisionGroups.end()) { uint16_t nextGroupID = ++maxGroupID; - collisionGroups.emplace(sourceID, CollisionGroup( - nextGroupID, - std::optional([nextGroupID](const IndexedSubfeature& feature) -> bool { - return feature.collisionGroupId == nextGroupID; - }) - )); + collisionGroups.emplace( + sourceID, + CollisionGroup(nextGroupID, + std::optional([nextGroupID](const IndexedSubfeature& feature) -> bool { + return feature.collisionGroupId == nextGroupID; + }))); } return collisionGroups[sourceID]; } else { @@ -107,8 +108,8 @@ class PlacementContext { bool pitchIconWithMap = getLayout().get() == AlignmentType::Map; SymbolPlacementType placementType = getLayout().get(); - mat4 textLabelPlaneMatrix = - getLabelPlaneMatrix(renderTile.get().matrix, pitchTextWithMap, rotateTextWithMap, state, pixelsToTileUnits); + mat4 textLabelPlaneMatrix = getLabelPlaneMatrix( + renderTile.get().matrix, pitchTextWithMap, rotateTextWithMap, state, pixelsToTileUnits); mat4 iconLabelPlaneMatrix = (rotateTextWithMap == rotateIconWithMap && pitchTextWithMap == pitchIconWithMap) ? textLabelPlaneMatrix @@ -121,25 +122,26 @@ class PlacementContext { bool textAllowOverlap = getLayout().get(); bool iconAllowOverlap = getLayout().get(); - // This logic is similar to the "defaultOpacityState" logic below in updateBucketOpacities - // If we know a symbol is always supposed to show, force it to be marked visible even if - // it wasn't placed into the collision index (because some or all of it was outside the range - // of the collision grid). - // There is a subtle edge case here we're accepting: - // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false - // A's icon is outside the grid, so doesn't get placed - // A's text would be inside grid, but doesn't get placed because of icon-optional: false - // We still show A because of the allow-overlap settings. - // Symbol B has allow-overlap: false, and gets placed where A's text would be - // On panning in, there is a short period when Symbol B and Symbol A will overlap - // This is the reverse of our normal policy of "fade in on pan", but should look like any other - // collision and hopefully not be too noticeable. + // This logic is similar to the "defaultOpacityState" logic below in + // updateBucketOpacities If we know a symbol is always supposed to show, + // force it to be marked visible even if it wasn't placed into the collision + // index (because some or all of it was outside the range of the collision + // grid). There is a subtle edge case here we're accepting: + // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, + // icon-optional: false A's icon is outside the grid, so doesn't get placed + // A's text would be inside grid, but doesn't get placed because of + // icon-optional: false We still show A because of the allow-overlap + // settings. Symbol B has allow-overlap: false, and gets placed where A's + // text would be On panning in, there is a short period when Symbol B and + // Symbol A will overlap This is the reverse of our normal policy of "fade + // in on pan", but should look like any other collision and hopefully not + // be too noticeable. // See https://github.com/mapbox/mapbox-gl-native/issues/12683 - bool alwaysShowText = - textAllowOverlap && (iconAllowOverlap || !(getBucket().hasIconData() || getBucket().hasSdfIconData()) || - getLayout().get()); - bool alwaysShowIcon = - iconAllowOverlap && (textAllowOverlap || !getBucket().hasTextData() || getLayout().get()); + bool alwaysShowText = textAllowOverlap && + (iconAllowOverlap || !(getBucket().hasIconData() || getBucket().hasSdfIconData()) || + getLayout().get()); + bool alwaysShowIcon = iconAllowOverlap && + (textAllowOverlap || !getBucket().hasTextData() || getLayout().get()); bool hasIconTextFit = getLayout().get() != IconTextFitType::None; @@ -148,14 +150,17 @@ class PlacementContext { // PlacementController implemenation -PlacementController::PlacementController() : placement(makeMutable()) {} +PlacementController::PlacementController() + : placement(makeMutable()) {} void PlacementController::setPlacement(Immutable placement_) { placement = std::move(placement_); stale = false; } -bool PlacementController::placementIsRecent(TimePoint now, const float zoom, std::optional periodOverride) const { +bool PlacementController::placementIsRecent(TimePoint now, + const float zoom, + std::optional periodOverride) const { if (!placement->transitionsEnabled()) return false; auto updatePeriod = periodOverride ? *periodOverride : placement->getUpdatePeriod(zoom); @@ -188,7 +193,9 @@ Placement::Placement(std::shared_ptr updateParameters_, } } -Placement::Placement() : collisionIndex({}, MapMode::Static), collisionGroups(true) {} +Placement::Placement() + : collisionIndex({}, MapMode::Static), + collisionGroups(true) {} Placement::~Placement() = default; @@ -245,7 +252,7 @@ void Placement::placeSymbolBucket(const BucketPlacementData& params, std::setvariableOffsets.find(symbolInstance.crossTileID); if (prevOffset != getPrevPlacement()->variableOffsets.end()) { @@ -381,8 +389,8 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons } } - const bool doVariableIconPlacement = - ctx.hasIconTextFit && !ctx.iconAllowOverlap && symbolInstance.placedIconIndex; + const bool doVariableIconPlacement = ctx.hasIconTextFit && !ctx.iconAllowOverlap && + symbolInstance.placedIconIndex; const auto placeFeatureForVariableAnchors = [&](const CollisionFeature& textCollisionFeature, style::TextWritingModeType orientation, const CollisionFeature& iconCollisionFeature) { @@ -394,7 +402,8 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons const size_t anchorsSize = variableTextAnchors.size(); const size_t placementAttempts = ctx.textAllowOverlap ? anchorsSize * 2 : anchorsSize; for (size_t i = 0u; i < placementAttempts; ++i) { - // when anchorsSize is 0, placementAttempts is also 0, so this code would not be reached + // when anchorsSize is 0, placementAttempts is also 0, + // so this code would not be reached // NOLINTNEXTLINE(clang-analyzer-core.DivideZero) auto anchor = variableTextAnchors[i % anchorsSize]; const bool allowOverlap = (i >= anchorsSize); @@ -428,21 +437,21 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons textBoxes); if (doVariableIconPlacement) { - auto placedIconFeature = - collisionIndex.placeFeature(iconCollisionFeature, - shift, - posMatrix, - ctx.iconLabelPlaneMatrix, - ctx.pixelRatio, - placedSymbol, - ctx.scale, - fontSize, - ctx.iconAllowOverlap, - ctx.pitchTextWithMap, // TODO: shall it be pitchIconWithMap? - showCollisionBoxes, - ctx.avoidEdges, - collisionGroup.second, - iconBoxes); + auto placedIconFeature = collisionIndex.placeFeature( + iconCollisionFeature, + shift, + posMatrix, + ctx.iconLabelPlaneMatrix, + ctx.pixelRatio, + placedSymbol, + ctx.scale, + fontSize, + ctx.iconAllowOverlap, + ctx.pitchTextWithMap, // TODO: shall it be pitchIconWithMap? + showCollisionBoxes, + ctx.avoidEdges, + collisionGroup.second, + iconBoxes); iconBoxes.clear(); if (!placedIconFeature.first) continue; } @@ -451,8 +460,9 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons assert(symbolInstance.crossTileID != 0u); std::optional prevAnchor; - // If this label was placed in the previous placement, record the anchor position - // to allow us to animate the transition + // If this label was placed in the previous + // placement, record the anchor position to allow us + // to animate the transition if (getPrevPlacement()) { auto prevOffset = getPrevPlacement()->variableOffsets.find(symbolInstance.crossTileID); auto prevPlacements = getPrevPlacement()->placements.find(symbolInstance.crossTileID); @@ -502,8 +512,8 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons updatePreviousOrientationIfNotPlaced(placed.first); - // If we didn't get placed, we still need to copy our position from the last placement for - // fade animations + // If we didn't get placed, we still need to copy our position from + // the last placement for fade animations if (!placeText && getPrevPlacement()) { auto prevOffset = getPrevPlacement()->variableOffsets.find(symbolInstance.crossTileID); if (prevOffset != getPrevPlacement()->variableOffsets.end()) { @@ -605,8 +615,9 @@ JointPlacement Placement::placeSymbol(const SymbolInstance& symbolInstance, cons assert(symbolInstance.crossTileID != 0); if (placements.find(symbolInstance.crossTileID) != placements.end()) { - // If there's a previous placement with this ID, it comes from a tile that's fading out - // Erase it so that the placement result from the non-fading tile supersedes it + // If there's a previous placement with this ID, it comes from a tile + // that's fading out Erase it so that the placement result from the + // non-fading tile supersedes it placements.erase(symbolInstance.crossTileID); } @@ -635,27 +646,26 @@ SymbolInstanceReferences getBucketSymbols(const SymbolBucket& bucket, SymbolInstanceReferences Placement::getSortedSymbols(const BucketPlacementData& params, float) { const auto& bucket = static_cast(params.bucket.get()); - SymbolInstanceReferences sortedSymbols = - getBucketSymbols(bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing()); + SymbolInstanceReferences sortedSymbols = getBucketSymbols( + bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing()); auto* previousPlacement = getPrevPlacement(); if (previousPlacement && isTiltedView()) { - std::stable_sort( - sortedSymbols.begin(), - sortedSymbols.end(), - [previousPlacement](const SymbolInstance& a, const SymbolInstance& b) noexcept { - auto* aPlacement = previousPlacement->getSymbolPlacement(a); - auto* bPlacement = previousPlacement->getSymbolPlacement(b); - if (!aPlacement) { - // a < b, if 'a' is new and if 'b' was previously hidden. - return bPlacement && !bPlacement->placed(); - } - if (!bPlacement) { - // a < b, if 'b' is new and 'a' was previously shown. - return aPlacement && aPlacement->placed(); - } - // a < b, if 'a' was shown and 'b' was hidden. - return aPlacement->placed() && !bPlacement->placed(); - }); + std::stable_sort(sortedSymbols.begin(), + sortedSymbols.end(), + [previousPlacement](const SymbolInstance& a, const SymbolInstance& b) noexcept { + auto* aPlacement = previousPlacement->getSymbolPlacement(a); + auto* bPlacement = previousPlacement->getSymbolPlacement(b); + if (!aPlacement) { + // a < b, if 'a' is new and if 'b' was previously hidden. + return bPlacement && !bPlacement->placed(); + } + if (!bPlacement) { + // a < b, if 'b' is new and 'a' was previously shown. + return aPlacement && aPlacement->placed(); + } + // a < b, if 'a' was shown and 'b' was hidden. + return aPlacement->placed() && !bPlacement->placed(); + }); } return sortedSymbols; } @@ -666,21 +676,28 @@ void Placement::commit() { prevZoomAdjustment = getPrevPlacement()->zoomAdjustment(placementZoom); float increment = getPrevPlacement()->symbolFadeChange(commitTime); - // add the opacities from the current placement, and copy their current values from the previous placement + // add the opacities from the current placement, and copy their current + // values from the previous placement for (auto& jointPlacement : placements) { auto prevOpacity = getPrevPlacement()->opacities.find(jointPlacement.first); if (prevOpacity != getPrevPlacement()->opacities.end()) { - opacities.emplace(jointPlacement.first, JointOpacityState(prevOpacity->second, increment, jointPlacement.second.text, jointPlacement.second.icon)); - placementChanged = placementChanged || - jointPlacement.second.icon != prevOpacity->second.icon.placed || - jointPlacement.second.text != prevOpacity->second.text.placed; + opacities.emplace( + jointPlacement.first, + JointOpacityState( + prevOpacity->second, increment, jointPlacement.second.text, jointPlacement.second.icon)); + placementChanged = placementChanged || jointPlacement.second.icon != prevOpacity->second.icon.placed || + jointPlacement.second.text != prevOpacity->second.text.placed; } else { - opacities.emplace(jointPlacement.first, JointOpacityState(jointPlacement.second.text, jointPlacement.second.icon, jointPlacement.second.skipFade)); + opacities.emplace( + jointPlacement.first, + JointOpacityState( + jointPlacement.second.text, jointPlacement.second.icon, jointPlacement.second.skipFade)); placementChanged = placementChanged || jointPlacement.second.icon || jointPlacement.second.text; } } - // copy and update values from the previous placement that aren't in the current placement but haven't finished fading + // copy and update values from the previous placement that aren't in the + // current placement but haven't finished fading for (auto& prevOpacity : getPrevPlacement()->opacities) { if (opacities.find(prevOpacity.first) == opacities.end()) { JointOpacityState jointOpacity(prevOpacity.second, increment, false, false); @@ -695,7 +712,8 @@ void Placement::commit() { const uint32_t crossTileID = prevOffset.first; auto foundOffset = variableOffsets.find(crossTileID); auto foundOpacity = opacities.find(crossTileID); - if (foundOffset == variableOffsets.end() && foundOpacity != opacities.end() && !foundOpacity->second.isHidden()) { + if (foundOffset == variableOffsets.end() && foundOpacity != opacities.end() && + !foundOpacity->second.isHidden()) { variableOffsets[prevOffset.first] = prevOffset.second; } } @@ -704,7 +722,8 @@ void Placement::commit() { const uint32_t crossTileID = prevOrientation.first; auto foundOrientation = placedOrientations.find(crossTileID); auto foundOpacity = opacities.find(crossTileID); - if (foundOrientation == placedOrientations.end() && foundOpacity != opacities.end() && !foundOpacity->second.isHidden()) { + if (foundOrientation == placedOrientations.end() && foundOpacity != opacities.end() && + !foundOpacity->second.isHidden()) { placedOrientations[prevOrientation.first] = prevOrientation.second; } } @@ -722,22 +741,31 @@ void Placement::updateLayerBuckets(const RenderLayer& layer, const TransformStat } namespace { -Point calculateVariableRenderShift(style::SymbolAnchorType anchor, float width, float height, std::array textOffset, float textBoxScale, float renderTextSize) { +Point calculateVariableRenderShift(style::SymbolAnchorType anchor, + float width, + float height, + std::array textOffset, + float textBoxScale, + float renderTextSize) { AnchorAlignment alignment = AnchorAlignment::getAnchorAlignment(anchor); float shiftX = -(alignment.horizontalAlign - 0.5f) * width; float shiftY = -(alignment.verticalAlign - 0.5f) * height; auto variablOffset = SymbolLayout::evaluateVariableOffset(anchor, textOffset); - return { (shiftX / textBoxScale + variablOffset[0]) * renderTextSize, - (shiftY / textBoxScale + variablOffset[1]) * renderTextSize }; + return {(shiftX / textBoxScale + variablOffset[0]) * renderTextSize, + (shiftY / textBoxScale + variablOffset[1]) * renderTextSize}; } } // namespace -bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const TransformState& state, const RenderTile& tile) const { +bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, + const TransformState& state, + const RenderTile& tile) const { using namespace style; const auto& layout = *bucket.layout; const bool alongLine = layout.get() != SymbolPlacementType::Point; const bool hasVariableAnchors = !layout.get().empty() && bucket.hasTextData(); - const bool updateTextFitIcon = layout.get() != IconTextFitType::None && (bucket.allowVerticalPlacement || hasVariableAnchors) && (bucket.hasIconData() || bucket.hasSdfIconData()); + const bool updateTextFitIcon = layout.get() != IconTextFitType::None && + (bucket.allowVerticalPlacement || hasVariableAnchors) && + (bucket.hasIconData() || bucket.hasSdfIconData()); bool result = false; if (alongLine) { @@ -745,15 +773,27 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor const bool pitchWithMap = layout.get() == style::AlignmentType::Map; const bool keepUpright = layout.get(); if (bucket.hasSdfIconData()) { - reprojectLineLabels(bucket.sdfIcon.dynamicVertices, bucket.sdfIcon.placedSymbols, - tile.matrix, pitchWithMap, true /*rotateWithMap*/, keepUpright, - tile, *bucket.iconSizeBinder, state); + reprojectLineLabels(bucket.sdfIcon.dynamicVertices, + bucket.sdfIcon.placedSymbols, + tile.matrix, + pitchWithMap, + true /*rotateWithMap*/, + keepUpright, + tile, + *bucket.iconSizeBinder, + state); result = true; } if (bucket.hasIconData()) { - reprojectLineLabels(bucket.icon.dynamicVertices, bucket.icon.placedSymbols, - tile.matrix, pitchWithMap, true /*rotateWithMap*/, keepUpright, - tile, *bucket.iconSizeBinder, state); + reprojectLineLabels(bucket.icon.dynamicVertices, + bucket.icon.placedSymbols, + tile.matrix, + pitchWithMap, + true /*rotateWithMap*/, + keepUpright, + tile, + *bucket.iconSizeBinder, + state); result = true; } } @@ -761,9 +801,15 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor if (bucket.hasTextData() && layout.get() == AlignmentType::Map) { const bool pitchWithMap = layout.get() == style::AlignmentType::Map; const bool keepUpright = layout.get(); - reprojectLineLabels(bucket.text.dynamicVertices, bucket.text.placedSymbols, - tile.matrix, pitchWithMap, true /*rotateWithMap*/, keepUpright, - tile, *bucket.textSizeBinder, state); + reprojectLineLabels(bucket.text.dynamicVertices, + bucket.text.placedSymbols, + tile.matrix, + pitchWithMap, + true /*rotateWithMap*/, + keepUpright, + tile, + *bucket.textSizeBinder, + state); result = true; } } else if (hasVariableAnchors) { @@ -771,11 +817,13 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor bucket.hasVariablePlacement = false; const auto partiallyEvaluatedSize = bucket.textSizeBinder->evaluateForZoom(static_cast(state.getZoom())); - const auto tileScale = static_cast(std::pow(2, state.getZoom() - tile.getOverscaledTileID().overscaledZ)); + const auto tileScale = static_cast( + std::pow(2, state.getZoom() - tile.getOverscaledTileID().overscaledZ)); const bool rotateWithMap = layout.get() == AlignmentType::Map; const bool pitchWithMap = layout.get() == AlignmentType::Map; const float pixelsToTileUnits = tile.id.pixelsToTileUnits(1.0f, static_cast(state.getZoom())); - const auto labelPlaneMatrix = getLabelPlaneMatrix(tile.matrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); + const auto labelPlaneMatrix = getLabelPlaneMatrix( + tile.matrix, pitchWithMap, rotateWithMap, state, pixelsToTileUnits); std::unordered_map>> placedTextShifts; for (std::size_t i = 0; i < bucket.text.placedSymbols.size(); ++i) { @@ -791,41 +839,44 @@ bool Placement::updateBucketDynamicVertices(SymbolBucket& bucket, const Transfor } if (!variableOffset) { - // These symbols are from a justification that is not being used, or a label that wasn't placed - // so we don't need to do the extra math to figure out what incremental shift to apply. + // These symbols are from a justification that is not being + // used, or a label that wasn't placed so we don't need to do + // the extra math to figure out what incremental shift to apply. hideGlyphs(symbol.glyphOffsets.size(), bucket.text.dynamicVertices); } else { const Point tileAnchor = symbol.anchorPoint; const auto projectedAnchor = project(tileAnchor, pitchWithMap ? tile.matrix : labelPlaneMatrix); - const float perspectiveRatio = 0.5f + 0.5f * (state.getCameraToCenterDistance() / projectedAnchor.second); - float renderTextSize = evaluateSizeForFeature(partiallyEvaluatedSize, symbol) * perspectiveRatio / util::ONE_EM; + const float perspectiveRatio = 0.5f + + 0.5f * (state.getCameraToCenterDistance() / projectedAnchor.second); + float renderTextSize = evaluateSizeForFeature(partiallyEvaluatedSize, symbol) * perspectiveRatio / + util::ONE_EM; if (pitchWithMap) { // Go from size in pixels to equivalent size in tile units renderTextSize *= bucket.tilePixelRatio / tileScale; } - auto shift = calculateVariableRenderShift( - (*variableOffset).anchor, - (*variableOffset).width, - (*variableOffset).height, - (*variableOffset).offset, - (*variableOffset).textBoxScale, - renderTextSize); - - // Usual case is that we take the projected anchor and add the pixel-based shift - // calculated above. In the (somewhat weird) case of pitch-aligned text, we add an equivalent - // tile-unit based shift to the anchor before projecting to the label plane. + auto shift = calculateVariableRenderShift((*variableOffset).anchor, + (*variableOffset).width, + (*variableOffset).height, + (*variableOffset).offset, + (*variableOffset).textBoxScale, + renderTextSize); + + // Usual case is that we take the projected anchor and add the + // pixel-based shift calculated above. In the (somewhat weird) + // case of pitch-aligned text, we add an equivalent tile-unit + // based shift to the anchor before projecting to the label + // plane. Point shiftedAnchor; if (pitchWithMap) { - shiftedAnchor = project(Point(tileAnchor.x + shift.x, tileAnchor.y + shift.y), - labelPlaneMatrix).first; + shiftedAnchor = + project(Point(tileAnchor.x + shift.x, tileAnchor.y + shift.y), labelPlaneMatrix).first; } else if (rotateWithMap) { auto rotated = util::rotate(shift, -state.getPitch()); shiftedAnchor = Point(projectedAnchor.first.x + rotated.x, - projectedAnchor.first.y + rotated.y); + projectedAnchor.first.y + rotated.y); } else { - shiftedAnchor = Point(projectedAnchor.first.x + shift.x, - projectedAnchor.first.y + shift.y); + shiftedAnchor = Point(projectedAnchor.first.x + shift.x, projectedAnchor.first.y + shift.y); } if (updateTextFitIcon && symbol.placedIconIndex) { @@ -916,9 +967,12 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, // See https://github.com/mapbox/mapbox-gl-native/issues/12483 // Prevent a flickering issue when showing a symbol allowing overlap. const JointOpacityState defaultOpacityState( - bucket.justReloaded && textAllowOverlap && (iconAllowOverlap || !(bucket.hasIconData() || bucket.hasSdfIconData()) || bucket.layout->get()), - bucket.justReloaded && iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || bucket.layout->get()), - true); + bucket.justReloaded && textAllowOverlap && + (iconAllowOverlap || !(bucket.hasIconData() || bucket.hasSdfIconData()) || + bucket.layout->get()), + bucket.justReloaded && iconAllowOverlap && + (textAllowOverlap || !bucket.hasTextData() || bucket.layout->get()), + true); for (SymbolInstance& symbolInstance : bucket.symbolInstances) { bool isDuplicate = seenCrossTileIDs.count(symbolInstance.crossTileID) > 0; @@ -935,7 +989,8 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, if (symbolInstance.hasText()) { size_t textOpacityVerticesSize = 0u; - const auto& opacityVertex = SymbolSDFTextProgram::opacityVertex(opacityState.text.placed, opacityState.text.opacity); + const auto& opacityVertex = SymbolSDFTextProgram::opacityVertex(opacityState.text.placed, + opacityState.text.opacity); if (symbolInstance.placedRightTextIndex) { textOpacityVerticesSize += symbolInstance.rightJustifiedGlyphQuadsSize * 4; PlacedSymbol& placed = bucket.text.placedSymbols[*symbolInstance.placedRightTextIndex]; @@ -974,10 +1029,10 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, } if (symbolInstance.hasIcon()) { size_t iconOpacityVerticesSize = 0u; - const auto& opacityVertex = - SymbolIconProgram::opacityVertex(opacityState.icon.placed, opacityState.icon.opacity); + const auto& opacityVertex = SymbolIconProgram::opacityVertex(opacityState.icon.placed, + opacityState.icon.opacity); auto& iconBuffer = symbolInstance.hasSdfIcon() ? bucket.sdfIcon : bucket.icon; - + if (symbolInstance.placedIconIndex) { iconOpacityVerticesSize += symbolInstance.iconQuadsSize * 4; iconBuffer.placedSymbols[*symbolInstance.placedIconIndex].hidden = opacityState.isHidden(); @@ -1011,10 +1066,10 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, auto foundOffset = variableOffsets.find(symbolInstance.crossTileID); if (foundOffset != variableOffsets.end()) { const VariableOffset& variableOffset = foundOffset->second; - // This will show either the currently placed position or the last - // successfully placed position (so you can visualize what collision - // just made the symbol disappear, and the most likely place for the - // symbol to come back) + // This will show either the currently placed position or + // the last successfully placed position (so you can + // visualize what collision just made the symbol disappear, + // and the most likely place for the symbol to come back) shift = calculateVariableLayoutOffset(variableOffset.anchor, variableOffset.width, variableOffset.height, @@ -1024,9 +1079,10 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, pitchWithMap, static_cast(state.getBearing())); } else { - // No offset -> this symbol hasn't been placed since coming on-screen - // No single box is particularly meaningful and all of them would be too noisy - // Use the center box just to show something's there, but mark it "not used" + // No offset -> this symbol hasn't been placed since coming + // on-screen No single box is particularly meaningful and + // all of them would be too noisy Use the center box just to + // show something's there, but mark it "not used" used = false; } } @@ -1043,14 +1099,15 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, if (circles != collisionCircles.end()) { for (const auto& circle : circles->second) { const auto& dynamicVertex = CollisionBoxProgram::dynamicVertex(placed, !circle.isCircle(), {}); - isText ? bucket.textCollisionCircle->dynamicVertices.extend(4, dynamicVertex): - bucket.iconCollisionCircle->dynamicVertices.extend(4, dynamicVertex); + isText ? bucket.textCollisionCircle->dynamicVertices.extend(4, dynamicVertex) + : bucket.iconCollisionCircle->dynamicVertices.extend(4, dynamicVertex); } } else { - // This feature was not placed, because it was not loaded or from a fading tile. Apply default values. + // This feature was not placed, because it was not loaded or + // from a fading tile. Apply default values. static const auto dynamicVertex = CollisionBoxProgram::dynamicVertex(placed, false /*not used*/, {}); - isText ? bucket.textCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex): - bucket.iconCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex); + isText ? bucket.textCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex) + : bucket.iconCollisionCircle->dynamicVertices.extend(4 * feature.boxes.size(), dynamicVertex); } }; Point textShift{0.0f, 0.0f}; @@ -1058,13 +1115,18 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, if (bucket.hasTextCollisionBoxData()) { textShift = updateTextCollisionBox(symbolInstance.textCollisionFeature, opacityState.text.placed); if (bucket.allowVerticalPlacement && symbolInstance.verticalTextCollisionFeature) { - verticalTextShift = updateTextCollisionBox(*symbolInstance.verticalTextCollisionFeature, opacityState.text.placed); + verticalTextShift = updateTextCollisionBox(*symbolInstance.verticalTextCollisionFeature, + opacityState.text.placed); } } if (bucket.hasIconCollisionBoxData()) { - updateIconCollisionBox(symbolInstance.iconCollisionFeature, opacityState.icon.placed, hasIconTextFit ? textShift : Point{0.0f, 0.0f}); + updateIconCollisionBox(symbolInstance.iconCollisionFeature, + opacityState.icon.placed, + hasIconTextFit ? textShift : Point{0.0f, 0.0f}); if (bucket.allowVerticalPlacement && symbolInstance.verticalIconCollisionFeature) { - updateIconCollisionBox(*symbolInstance.verticalIconCollisionFeature, opacityState.text.placed, hasIconTextFit ? verticalTextShift : Point{0.0f, 0.0f}); + updateIconCollisionBox(*symbolInstance.verticalIconCollisionFeature, + opacityState.text.placed, + hasIconTextFit ? verticalTextShift : Point{0.0f, 0.0f}); } } @@ -1084,17 +1146,23 @@ void Placement::updateBucketOpacities(SymbolBucket& bucket, } namespace { -std::optional justificationToIndex(style::TextJustifyType justify, const SymbolInstance& symbolInstance, style::TextWritingModeType orientation) { +std::optional justificationToIndex(style::TextJustifyType justify, + const SymbolInstance& symbolInstance, + style::TextWritingModeType orientation) { // Vertical symbol has just one justification, style::TextJustifyType::Left. if (orientation == style::TextWritingModeType::Vertical) { return symbolInstance.placedVerticalTextIndex; } - switch(justify) { - case style::TextJustifyType::Right: return symbolInstance.placedRightTextIndex; - case style::TextJustifyType::Center: return symbolInstance.placedCenterTextIndex; - case style::TextJustifyType::Left: return symbolInstance.placedLeftTextIndex; - case style::TextJustifyType::Auto: break; + switch (justify) { + case style::TextJustifyType::Right: + return symbolInstance.placedRightTextIndex; + case style::TextJustifyType::Center: + return symbolInstance.placedCenterTextIndex; + case style::TextJustifyType::Left: + return symbolInstance.placedLeftTextIndex; + case style::TextJustifyType::Auto: + break; } assert(false); return std::nullopt; @@ -1103,7 +1171,7 @@ std::optional justificationToIndex(style::TextJustifyType justify, const const style::TextJustifyType justifyTypes[] = { style::TextJustifyType::Right, style::TextJustifyType::Center, style::TextJustifyType::Left}; -} // namespace +} // namespace void Placement::markUsedJustification(SymbolBucket& bucket, style::TextVariableAnchorType placedAnchor, @@ -1131,10 +1199,12 @@ void Placement::markUsedJustification(SymbolBucket& bucket, void Placement::markUsedOrientation(SymbolBucket& bucket, style::TextWritingModeType orientation, const SymbolInstance& symbolInstance) const { - auto horizontal = orientation == style::TextWritingModeType::Horizontal ? - std::optional(orientation) : std::nullopt; - auto vertical = orientation == style::TextWritingModeType::Vertical ? - std::optional(orientation) : std::nullopt; + auto horizontal = orientation == style::TextWritingModeType::Horizontal + ? std::optional(orientation) + : std::nullopt; + auto vertical = orientation == style::TextWritingModeType::Vertical + ? std::optional(orientation) + : std::nullopt; if (symbolInstance.placedRightTextIndex) { bucket.text.placedSymbols.at(*symbolInstance.placedRightTextIndex).placedOrientation = horizontal; @@ -1169,16 +1239,19 @@ bool Placement::isTiltedView() const { float Placement::symbolFadeChange(TimePoint now) const { if (transitionsEnabled() && transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION) > Milliseconds(0)) { - return std::chrono::duration(now - commitTime) / transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION) + prevZoomAdjustment; + return std::chrono::duration(now - commitTime) / + transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION) + + prevZoomAdjustment; } return 1.0; } float Placement::zoomAdjustment(const float zoom) const { // When zooming out labels can overlap each other quickly. This - // adjustment is used to reduce the fade duration for symbols while zooming out quickly. - // It is also used to reduce the interval between placement calculations. Reducing the - // interval between placements means collisions are discovered and eliminated sooner. + // adjustment is used to reduce the fade duration for symbols while zooming + // out quickly. It is also used to reduce the interval between placement + // calculations. Reducing the interval between placements means collisions + // are discovered and eliminated sooner. return std::max(0.0f, (placementZoom - zoom) / 1.5f); } @@ -1189,8 +1262,8 @@ const JointPlacement* Placement::getSymbolPlacement(const SymbolInstance& symbol } Duration Placement::getUpdatePeriod(const float zoom) const { - // Even if transitionOptions.duration is set to a value < 300ms, we still wait for this default transition duration - // before attempting another placement operation. + // Even if transitionOptions.duration is set to a value < 300ms, we still wait + // for this default transition duration before attempting another placement operation. const auto fadeDuration = std::max(util::DEFAULT_TRANSITION_DURATION, transitionOptions.duration.value_or(util::DEFAULT_TRANSITION_DURATION)); return std::chrono::duration_cast(fadeDuration * (1.0 - zoomAdjustment(zoom))); @@ -1214,7 +1287,7 @@ const std::vector& Placement::getPlacedSymbolsData() const { const CollisionIndex& Placement::getCollisionIndex() const { return collisionIndex; } - + const RetainedQueryData& Placement::getQueryData(uint32_t bucketInstanceId) const { auto it = retainedQueryData.find(bucketInstanceId); if (it == retainedQueryData.end()) { @@ -1249,7 +1322,10 @@ void StaticPlacement::commit() { struct Intersection { Intersection(const SymbolInstance& symbol_, PlacementContext ctx_, IntersectStatus status_, std::size_t priority_) - : symbol(symbol_), ctx(std::move(ctx_)), status(status_), priority(priority_) {} + : symbol(symbol_), + ctx(std::move(ctx_)), + status(status_), + priority(priority_) {} std::reference_wrapper symbol; PlacementContext ctx; IntersectStatus status; @@ -1374,17 +1450,20 @@ void TilePlacement::placeSymbolBucket(const BucketPlacementData& params, std::se getAvoidEdges(bucket, renderTile.matrix)}; const auto& variableTextAnchors = ctx.getVariableTextAnchors(); - // In this case we first try to place symbols, which intersects the tile borders, so that - // those symbols will remain even if each tile is handled independently. - SymbolInstanceReferences symbolInstances = - getBucketSymbols(bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing()); + // In this case we first try to place symbols, which intersects the tile + // borders, so that those symbols will remain even if each tile is handled + // independently. + SymbolInstanceReferences symbolInstances = getBucketSymbols( + bucket, params.sortKeyRange, collisionIndex.getTransformState().getBearing()); std::optional variableAnchor; if (!variableTextAnchors.empty()) variableAnchor = variableTextAnchors.front(); // Keeps the data necessary to find a feature location according to a tile. struct NeighborTileData { NeighborTileData(const CollisionIndex& collisionIndex, UnwrappedTileID id_, Point shift_) - : id(id_), shift(shift_), matrix() { + : id(id_), + shift(shift_), + matrix() { collisionIndex.getTransformState().matrixFor(matrix, id); matrix::multiply(matrix, collisionIndex.getTransformState().getProjectionMatrix(), matrix); borders = collisionIndex.projectTileBoundaries(matrix); @@ -1407,10 +1486,11 @@ void TilePlacement::placeSymbolBucket(const BucketPlacementData& params, std::se }}; auto collisionBoxIntersectsTileEdges = [&](const CollisionBox& collisionBox, - Point shift) noexcept->IntersectStatus { - IntersectStatus intersects = - collisionIndex.intersectsTileEdges(collisionBox, shift, renderTile.matrix, ctx.pixelRatio, *tileBorders); - // Check if this symbol intersects the neighbor tile borders. If so, it also shall be placed with priority. + Point shift) noexcept -> IntersectStatus { + IntersectStatus intersects = collisionIndex.intersectsTileEdges( + collisionBox, shift, renderTile.matrix, ctx.pixelRatio, *tileBorders); + // Check if this symbol intersects the neighbor tile borders. If so, it + // also shall be placed with priority. for (const auto& neighbor : neighbours) { if (intersects.flags != IntersectStatus::None) break; intersects = collisionIndex.intersectsTileEdges( @@ -1419,14 +1499,13 @@ void TilePlacement::placeSymbolBucket(const BucketPlacementData& params, std::se return intersects; }; - auto symbolIntersectsTileEdges = [ - &collisionBoxIntersectsTileEdges, - variableAnchor, - pitchTextWithMap = ctx.pitchTextWithMap, - rotateTextWithMap = ctx.rotateTextWithMap, - variableIconPlacement = ctx.hasIconTextFit && !ctx.iconAllowOverlap, - bearing = static_cast(ctx.getTransformState().getBearing()) - ](const SymbolInstance& symbol) noexcept->IntersectStatus { + auto symbolIntersectsTileEdges = [&collisionBoxIntersectsTileEdges, + variableAnchor, + pitchTextWithMap = ctx.pitchTextWithMap, + rotateTextWithMap = ctx.rotateTextWithMap, + variableIconPlacement = ctx.hasIconTextFit && !ctx.iconAllowOverlap, + bearing = static_cast(ctx.getTransformState().getBearing())]( + const SymbolInstance& symbol) noexcept -> IntersectStatus { IntersectStatus result; if (!symbol.textCollisionFeature.boxes.empty()) { const auto& textCollisionBox = symbol.textCollisionFeature.boxes.front(); @@ -1489,8 +1568,9 @@ bool TilePlacement::canPlaceAtVariableAnchor(const CollisionBox& box, if (populateIntersections) { // A variable label is only allowed to intersect tile border with the first anchor. if (anchor == anchors.front()) { - // Check, that the label would intersect the tile borders even without shift, otherwise intersection - // is not allowed (preventing cut-offs in case the shift is lager than the buffer size). + // Check, that the label would intersect the tile borders even + // without shift, otherwise intersection is not allowed (preventing + // cut-offs in case the shift is lager than the buffer size). auto status = collisionIndex.intersectsTileEdges(box, {}, posMatrix, textPixelRatio, *tileBorders); if (status.flags != IntersectStatus::None) return true; } diff --git a/src/mbgl/text/placement.hpp b/src/mbgl/text/placement.hpp index 25ebbebf918..d04a927b0ac 100644 --- a/src/mbgl/text/placement.hpp +++ b/src/mbgl/text/placement.hpp @@ -48,20 +48,21 @@ class VariableOffset { class JointPlacement { public: JointPlacement(bool text_, bool icon_, bool skipFade_) - : text(text_), icon(icon_), skipFade(skipFade_) - {} + : text(text_), + icon(icon_), + skipFade(skipFade_) {} bool placed() const { return text || icon; } const bool text; const bool icon; - // skipFade = outside viewport, but within CollisionIndex::viewportPadding px of the edge - // Because these symbols aren't onscreen yet, we can skip the "fade in" animation, - // and if a subsequent viewport change brings them into view, they'll be fully - // visible right away. + // skipFade = outside viewport, but within CollisionIndex::viewportPadding + // px of the edge Because these symbols aren't onscreen yet, we can skip the + // "fade in" animation, and if a subsequent viewport change brings them into + // view, they'll be fully visible right away. const bool skipFade; }; - + struct RetainedQueryData { uint32_t bucketInstanceId; std::shared_ptr featureIndex; @@ -69,21 +70,22 @@ struct RetainedQueryData { mutable FeatureSortOrder featureSortOrder; RetainedQueryData(uint32_t bucketInstanceId_, std::shared_ptr featureIndex_, OverscaledTileID tileID_) - : bucketInstanceId(bucketInstanceId_), featureIndex(std::move(featureIndex_)), tileID(tileID_) {} + : bucketInstanceId(bucketInstanceId_), + featureIndex(std::move(featureIndex_)), + tileID(tileID_) {} }; - + class CollisionGroups { public: using Predicate = std::function; using CollisionGroup = std::pair>; - + CollisionGroups(const bool crossSourceCollisions_) - : maxGroupID(0) - , crossSourceCollisions(crossSourceCollisions_) - {} - + : maxGroupID(0), + crossSourceCollisions(crossSourceCollisions_) {} + const CollisionGroup& get(const std::string& sourceID); - + private: std::map collisionGroups; uint16_t maxGroupID; @@ -109,7 +111,8 @@ class PlacementController { class Placement { public: /** - * @brief creates a new placement instance, from the given update parameters and the previous placement instance. + * @brief creates a new placement instance, from the given update parameters + * and the previous placement instance. * * Different placement implementations are created based on `updateParameters->mapMode`. * In Continuous map mode, `prevPlacement` must be provided. @@ -150,7 +153,8 @@ class Placement { const JointPlacement&, style::SymbolPlacementType, const std::vector& /*textBoxes*/, - const std::vector& /*iconBoxes*/) {} + const std::vector& /*iconBoxes*/ + ) {} // Implentation specific hooks, which get called during a symbol bucket placement. virtual std::optional getAvoidEdges(const SymbolBucket&, const mat4& /*posMatrix*/) { return std::nullopt; @@ -161,7 +165,8 @@ class Placement { Point /*shift*/, std::vector&, const mat4& /*posMatrix*/, - float /*textPixelRatio*/) { + float /*textPixelRatio*/ + ) { return true; } diff --git a/src/mbgl/text/quads.cpp b/src/mbgl/text/quads.cpp index 6bf2afcae24..8c2c6379fb9 100644 --- a/src/mbgl/text/quads.cpp +++ b/src/mbgl/text/quads.cpp @@ -116,22 +116,22 @@ SymbolQuads getIconQuads(const PositionedIcon& shapedIcon, } auto makeBox = [&](Cut left, Cut top, Cut right, Cut bottom) { - const float leftEm = - getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left()); + const float leftEm = getEmOffset( + left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left()); const float leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); - const float topEm = - getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top()); + const float topEm = getEmOffset( + top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top()); const float topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); - const float rightEm = - getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left()); + const float rightEm = getEmOffset( + right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left()); const float rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); - const float bottomEm = - getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top()); - const float bottomPx = - getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + const float bottomEm = getEmOffset( + bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top()); + const float bottomPx = getPxOffset( + bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); Point tl(leftEm, topEm); Point tr(rightEm, topEm); @@ -202,7 +202,8 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, const ImageMap& imageMap, bool allowVerticalPlacement) { const float textRotate = util::deg2radf(layout.get()); - const bool alongLine = layout.get() == AlignmentType::Map && placement != SymbolPlacementType::Point; + const bool alongLine = layout.get() == AlignmentType::Map && + placement != SymbolPlacementType::Point; SymbolQuads quads; @@ -237,8 +238,9 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, isSDF = image->second->sdf; } - const Point glyphOffset = - alongLine ? Point{positionedGlyph.x + halfAdvance, positionedGlyph.y} : Point{0.0f, 0.0f}; + const Point glyphOffset = alongLine + ? Point{positionedGlyph.x + halfAdvance, positionedGlyph.y} + : Point{0.0f, 0.0f}; Point builtInOffset = alongLine ? Point{0.0f, 0.0f} : Point{positionedGlyph.x + halfAdvance + textOffset[0], @@ -246,15 +248,16 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, Point verticalizedLabelOffset = {0.0f, 0.0f}; if (rotateVerticalGlyph) { - // Vertical POI labels, that are rotated 90deg CW and whose glyphs must preserve upright orientation - // need to be rotated 90deg CCW. After quad is rotated, it is translated to the original built-in - // offset. + // Vertical POI labels, that are rotated 90deg CW and whose + // glyphs must preserve upright orientation need to be rotated + // 90deg CCW. After quad is rotated, it is translated to the + // original built-in offset. verticalizedLabelOffset = builtInOffset; builtInOffset = {0.0f, 0.0f}; } - const float x1 = - (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset.x; + const float x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + + builtInOffset.x; const float y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset.y; const float x2 = x1 + rect.w * positionedGlyph.scale / pixelRatio; const float y2 = y1 + rect.h * positionedGlyph.scale / pixelRatio; @@ -265,21 +268,24 @@ SymbolQuads getGlyphQuads(const Shaping& shapedText, Point br{x2, y2}; if (rotateVerticalGlyph) { - // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) - // In horizontal orientation, the y values for glyphs are below the midline - // and we use a "yOffset" of -17 to pull them up to the middle. - // By rotating counter-clockwise around the point at the center of the left - // edge of a 24x24 layout box centered below the midline, we align the center - // of the glyphs with the horizontal midline, so the yOffset is no longer - // necessary, but we also pull the glyph to the left along the x axis. - // The y coordinate includes baseline yOffset, therefore, needs to be accounted - // for when glyph is rotated and translated. + // Vertical-supporting glyphs are laid out in 24x24 point boxes + // (1 square em) In horizontal orientation, the y values for + // glyphs are below the midline and we use a "yOffset" of -17 to + // pull them up to the middle. By rotating counter-clockwise + // around the point at the center of the left edge of a 24x24 + // layout box centered below the midline, we align the center of + // the glyphs with the horizontal midline, so the yOffset is no + // longer necessary, but we also pull the glyph to the left + // along the x axis. The y coordinate includes baseline yOffset, + // therefore, needs to be accounted for when glyph is rotated + // and translated. const Point center{-halfAdvance, halfAdvance - Shaping::yOffset}; const float verticalRotation = static_cast(-M_PI_2); - // xHalfWidhtOffsetcorrection is a difference between full-width and half-width - // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. + // xHalfWidhtOffsetcorrection is a difference between full-width + // and half-width advance, should be 0 for full-width glyphs and + // will pull up half-width glyphs. const float xHalfWidhtOffsetcorrection = util::ONE_EM / 2.f - halfAdvance; const float yImageOffsetCorrection = positionedGlyph.imageID ? xHalfWidhtOffsetcorrection : 0.0f; const Point xOffsetCorrection{5.0f - Shaping::yOffset - xHalfWidhtOffsetcorrection, diff --git a/src/mbgl/text/shaping.cpp b/src/mbgl/text/shaping.cpp index 9f83cea7d23..991792fed79 100644 --- a/src/mbgl/text/shaping.cpp +++ b/src/mbgl/text/shaping.cpp @@ -10,8 +10,8 @@ #include namespace { - // Zero width space that is used to suggest break points for Japanese labels. - char16_t ZWSP = u'\u200b'; +// Zero width space that is used to suggest break points for Japanese labels. +char16_t ZWSP = u'\u200b'; } // namespace namespace mbgl { @@ -21,33 +21,33 @@ AnchorAlignment AnchorAlignment::getAnchorAlignment(style::SymbolAnchorType anch AnchorAlignment result(0.5f, 0.5f); switch (anchor) { - case style::SymbolAnchorType::Right: - case style::SymbolAnchorType::TopRight: - case style::SymbolAnchorType::BottomRight: - result.horizontalAlign = 1.0f; - break; - case style::SymbolAnchorType::Left: - case style::SymbolAnchorType::TopLeft: - case style::SymbolAnchorType::BottomLeft: - result.horizontalAlign = 0.0f; - break; - default: - break; + case style::SymbolAnchorType::Right: + case style::SymbolAnchorType::TopRight: + case style::SymbolAnchorType::BottomRight: + result.horizontalAlign = 1.0f; + break; + case style::SymbolAnchorType::Left: + case style::SymbolAnchorType::TopLeft: + case style::SymbolAnchorType::BottomLeft: + result.horizontalAlign = 0.0f; + break; + default: + break; } switch (anchor) { - case style::SymbolAnchorType::Bottom: - case style::SymbolAnchorType::BottomLeft: - case style::SymbolAnchorType::BottomRight: - result.verticalAlign = 1.0f; - break; - case style::SymbolAnchorType::Top: - case style::SymbolAnchorType::TopLeft: - case style::SymbolAnchorType::TopRight: - result.verticalAlign = 0.0f; - break; - default: - break; + case style::SymbolAnchorType::Bottom: + case style::SymbolAnchorType::BottomLeft: + case style::SymbolAnchorType::BottomRight: + result.verticalAlign = 1.0f; + break; + case style::SymbolAnchorType::Top: + case style::SymbolAnchorType::TopLeft: + case style::SymbolAnchorType::TopRight: + result.verticalAlign = 0.0f; + break; + default: + break; } return result; @@ -55,16 +55,16 @@ AnchorAlignment AnchorAlignment::getAnchorAlignment(style::SymbolAnchorType anch style::TextJustifyType getAnchorJustification(style::SymbolAnchorType anchor) { switch (anchor) { - case style::SymbolAnchorType::Right: - case style::SymbolAnchorType::TopRight: - case style::SymbolAnchorType::BottomRight: - return style::TextJustifyType::Right; - case style::SymbolAnchorType::Left: - case style::SymbolAnchorType::TopLeft: - case style::SymbolAnchorType::BottomLeft: - return style::TextJustifyType::Left; - default: - return style::TextJustifyType::Center; + case style::SymbolAnchorType::Right: + case style::SymbolAnchorType::TopRight: + case style::SymbolAnchorType::BottomRight: + return style::TextJustifyType::Right; + case style::SymbolAnchorType::Left: + case style::SymbolAnchorType::TopLeft: + case style::SymbolAnchorType::BottomLeft: + return style::TextJustifyType::Left; + default: + return style::TextJustifyType::Center; } } @@ -192,7 +192,8 @@ float getGlyphAdvance(char16_t codePoint, if (image == imagePositions.end()) { return 0.0f; } - return image->second.displaySize()[0] * static_cast(section.scale) * util::ONE_EM / layoutTextSize + spacing; + return image->second.displaySize()[0] * static_cast(section.scale) * util::ONE_EM / layoutTextSize + + spacing; } } @@ -203,13 +204,13 @@ float determineAverageLineWidth(const TaggedString& logicalInput, const ImagePositions& imagePositions, float layoutTextSize) { float totalWidth = 0; - + for (std::size_t i = 0; i < logicalInput.length(); i++) { const SectionOptions& section = logicalInput.getSection(i); char16_t codePoint = logicalInput.getCharCodeAt(i); totalWidth += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, layoutTextSize, spacing); } - + auto targetLineCount = static_cast(::fmax(1, std::ceil(totalWidth / maxWidth))); return totalWidth / targetLineCount; } @@ -241,7 +242,7 @@ float calculatePenalty(char16_t codePoint, char16_t nextCodePoint, bool penaliza if (codePoint == 0x28 || codePoint == 0xff08) { penalty += 50; } - + // Penalize close parenthesis at beginning of line if (nextCodePoint == 0x29 || nextCodePoint == 0xff09) { penalty += 50; @@ -257,29 +258,37 @@ float calculatePenalty(char16_t codePoint, char16_t nextCodePoint, bool penaliza } struct PotentialBreak { - PotentialBreak(const std::size_t p_index, const float p_x, const PotentialBreak* p_priorBreak, const float p_badness) - : index(p_index), x(p_x), priorBreak(p_priorBreak), badness(p_badness) - {} - + PotentialBreak(const std::size_t p_index, + const float p_x, + const PotentialBreak* p_priorBreak, + const float p_badness) + : index(p_index), + x(p_x), + priorBreak(p_priorBreak), + badness(p_badness) {} + const std::size_t index; const float x; const PotentialBreak* priorBreak; const float badness; }; - -PotentialBreak evaluateBreak(const std::size_t breakIndex, const float breakX, const float targetWidth, const std::list& potentialBreaks, const float penalty, const bool isLastBreak) { +PotentialBreak evaluateBreak(const std::size_t breakIndex, + const float breakX, + const float targetWidth, + const std::list& potentialBreaks, + const float penalty, + const bool isLastBreak) { // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth // ...but in fact we allow lines longer than maxWidth (if there's no break points) // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give // more lopsided results. - + const PotentialBreak* bestPriorBreak = nullptr; float bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); for (const auto& potentialBreak : potentialBreaks) { const float lineWidth = breakX - potentialBreak.x; - float breakBadness = - calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + float breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; if (breakBadness <= bestBreakBadness) { bestPriorBreak = &potentialBreak; bestBreakBadness = breakBadness; @@ -290,7 +299,7 @@ PotentialBreak evaluateBreak(const std::size_t breakIndex, const float breakX, c } std::set leastBadBreaks(const PotentialBreak& lastLineBreak) { - std::set leastBadBreaks = { lastLineBreak.index }; + std::set leastBadBreaks = {lastLineBreak.index}; const PotentialBreak* priorBreak = lastLineBreak.priorBreak; while (priorBreak) { leastBadBreaks.insert(priorBreak->index); @@ -299,7 +308,6 @@ std::set leastBadBreaks(const PotentialBreak& lastLineBreak) { return leastBadBreaks; } - // We determine line breaks based on shaped text in logical order. Working in visual order would be // more intuitive, but we can't do that because the visual order may be changed by line breaks! std::set determineLineBreaks(const TaggedString& logicalInput, @@ -311,18 +319,18 @@ std::set determineLineBreaks(const TaggedString& logicalInput, if (!maxWidth) { return {}; } - + if (logicalInput.empty()) { return {}; } - const float targetWidth = - determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + const float targetWidth = determineAverageLineWidth( + logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); std::list potentialBreaks; float currentX = 0; // Find first occurance of zero width space (ZWSP) character. - const bool hasServerSuggestedBreaks = logicalInput.rawText().find_first_of(ZWSP) != std::string::npos; + const bool hasServerSuggestedBreaks = logicalInput.rawText().find_first_of(ZWSP) != std::string::npos; for (std::size_t i = 0; i < logicalInput.length(); i++) { const SectionOptions& section = logicalInput.getSection(i); @@ -331,20 +339,24 @@ std::set determineLineBreaks(const TaggedString& logicalInput, currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, layoutTextSize, spacing); } - // Ideographic characters, spaces, and word-breaking punctuation that often appear without - // surrounding spaces. + // Ideographic characters, spaces, and word-breaking punctuation that + // often appear without surrounding spaces. if (i < logicalInput.length() - 1) { const bool allowsIdeographicBreak = util::i18n::allowsIdeographicBreaking(codePoint); if (section.imageID || allowsIdeographicBreak || util::i18n::allowsWordBreaking(codePoint)) { const bool penalizableIdeographicBreak = allowsIdeographicBreak && hasServerSuggestedBreaks; const std::size_t nextIndex = i + 1; - potentialBreaks.push_back(evaluateBreak(nextIndex, currentX, targetWidth, potentialBreaks, - calculatePenalty(codePoint, logicalInput.getCharCodeAt(nextIndex), penalizableIdeographicBreak), - false)); + potentialBreaks.push_back(evaluateBreak( + nextIndex, + currentX, + targetWidth, + potentialBreaks, + calculatePenalty(codePoint, logicalInput.getCharCodeAt(nextIndex), penalizableIdeographicBreak), + false)); } } } - + return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialBreaks, 0, true)); } @@ -366,13 +378,14 @@ void shapeLines(Shaping& shaping, float maxLineLength = 0.0f; float maxLineHeight = 0.0f; - const float justify = - textJustify == style::TextJustifyType::Right ? 1.0f : textJustify == style::TextJustifyType::Left ? 0.0f : 0.5f; + const float justify = textJustify == style::TextJustifyType::Right ? 1.0f + : textJustify == style::TextJustifyType::Left ? 0.0f + : 0.5f; for (TaggedString& line : lines) { // Collapse whitespace so it doesn't throw off justification line.trim(); - + const double lineMaxScale = line.getMaxScale(); const double maxLineOffset = (lineMaxScale - 1.0) * util::ONE_EM; double lineOffset = 0.0; @@ -384,7 +397,7 @@ void shapeLines(Shaping& shaping, y += lineHeight; // Still need a line feed after empty line continue; } - + for (std::size_t i = 0; i < line.length(); i++) { const std::size_t sectionIndex = line.getSectionIndex(i); const SectionOptions& section = line.sectionAt(sectionIndex); @@ -397,14 +410,15 @@ void shapeLines(Shaping& shaping, double sectionScale = section.scale; assert(sectionScale); - const bool vertical = - !(writingMode == WritingModeType::Horizontal || - // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled. - (!allowVerticalPlacement && !util::i18n::hasUprightVerticalOrientation(codePoint)) || - // If vertical placement is ebabled, don't verticalize glyphs that - // are from complex text layout script, or whitespaces. - (allowVerticalPlacement && - (util::i18n::isWhitespace(codePoint) || util::i18n::isCharInComplexShapingScript(codePoint)))); + const bool vertical = !( + writingMode == WritingModeType::Horizontal || + // Don't verticalize glyphs that have no upright orientation + // if vertical placement is disabled. + (!allowVerticalPlacement && !util::i18n::hasUprightVerticalOrientation(codePoint)) || + // If vertical placement is ebabled, don't verticalize glyphs + // that are from complex text layout script, or whitespaces. + (allowVerticalPlacement && + (util::i18n::isWhitespace(codePoint) || util::i18n::isCharInComplexShapingScript(codePoint)))); if (!section.imageID) { auto glyphPositionMap = glyphPositions.find(section.fontStackHash); @@ -460,8 +474,8 @@ void shapeLines(Shaping& shaping, // Difference between height of an image and one EM at max line scale. // Pushes current line down if an image size is over 1 EM at max line scale. - double offset = - (vertical ? displaySize[0] : displaySize[1]) * sectionScale - util::ONE_EM * lineMaxScale; + double offset = (vertical ? displaySize[0] : displaySize[1]) * sectionScale - + util::ONE_EM * lineMaxScale; if (offset > 0.0 && offset > lineOffset) { lineOffset = offset; } diff --git a/src/mbgl/text/shaping.hpp b/src/mbgl/text/shaping.hpp index 1043aad6bfe..8be0322f516 100644 --- a/src/mbgl/text/shaping.hpp +++ b/src/mbgl/text/shaping.hpp @@ -13,8 +13,8 @@ namespace mbgl { struct AnchorAlignment { AnchorAlignment(float horizontal, float vertical) - : horizontalAlign(horizontal), verticalAlign(vertical) { - } + : horizontalAlign(horizontal), + verticalAlign(vertical) {} static AnchorAlignment getAnchorAlignment(style::SymbolAnchorType anchor); diff --git a/src/mbgl/text/tagged_string.cpp b/src/mbgl/text/tagged_string.cpp index 4fc5139775f..e6872923640 100644 --- a/src/mbgl/text/tagged_string.cpp +++ b/src/mbgl/text/tagged_string.cpp @@ -55,7 +55,8 @@ void TaggedString::trim() { std::size_t trailingWhitespace = styledText.first.find_last_not_of(u" \t\n\v\f\r") + 1; styledText.first = styledText.first.substr(beginningWhitespace, trailingWhitespace - beginningWhitespace); - styledText.second = std::vector(styledText.second.begin() + beginningWhitespace, styledText.second.begin() + trailingWhitespace); + styledText.second = std::vector(styledText.second.begin() + beginningWhitespace, + styledText.second.begin() + trailingWhitespace); } } @@ -66,7 +67,7 @@ double TaggedString::getMaxScale() const { } return maxScale; } - + void TaggedString::verticalizePunctuation() { // Relies on verticalization changing characters in place so that style indices don't need updating styledText.first = util::i18n::verticalizePunctuation(styledText.first); diff --git a/src/mbgl/text/tagged_string.hpp b/src/mbgl/text/tagged_string.hpp index 0ff92307ecb..a402ae577d0 100644 --- a/src/mbgl/text/tagged_string.hpp +++ b/src/mbgl/text/tagged_string.hpp @@ -13,10 +13,11 @@ struct SectionOptions { : scale(scale_), fontStackHash(FontStackHasher()(fontStack_)), fontStack(std::move(fontStack_)), - textColor(std::move(textColor_)) - {} + textColor(std::move(textColor_)) {} - explicit SectionOptions(std::string imageID_) : scale(1.0), imageID(std::move(imageID_)) {} + explicit SectionOptions(std::string imageID_) + : scale(1.0), + imageID(std::move(imageID_)) {} double scale; FontStackHash fontStackHash; @@ -44,43 +45,27 @@ struct TaggedString { TaggedString() = default; TaggedString(std::u16string text_, SectionOptions options) - : styledText(std::move(text_), - std::vector(text_.size(), 0)) { + : styledText(std::move(text_), std::vector(text_.size(), 0)) { sections.push_back(std::move(options)); } - + TaggedString(StyledText styledText_, std::vector sections_) - : styledText(std::move(styledText_)) - , sections(std::move(sections_)) { - } + : styledText(std::move(styledText_)), + sections(std::move(sections_)) {} - std::size_t length() const { - return styledText.first.length(); - } - - std::size_t sectionCount() const { - return sections.size(); - } - - bool empty() const { - return styledText.first.empty(); - } - - const SectionOptions& getSection(std::size_t index) const { - return sections.at(styledText.second.at(index)); - } - - char16_t getCharCodeAt(std::size_t index) const { - return styledText.first[index]; - } - - const std::u16string& rawText() const { - return styledText.first; - } - - const StyledText& getStyledText() const { - return styledText; - } + std::size_t length() const { return styledText.first.length(); } + + std::size_t sectionCount() const { return sections.size(); } + + bool empty() const { return styledText.first.empty(); } + + const SectionOptions& getSection(std::size_t index) const { return sections.at(styledText.second.at(index)); } + + char16_t getCharCodeAt(std::size_t index) const { return styledText.first[index]; } + + const std::u16string& rawText() const { return styledText.first; } + + const StyledText& getStyledText() const { return styledText; } void addTextSection(const std::u16string& text, double scale, @@ -89,21 +74,15 @@ struct TaggedString { void addImageSection(const std::string& imageID); - const SectionOptions& sectionAt(std::size_t index) const { - return sections.at(index); - } - - const std::vector& getSections() const { - return sections; - } - - uint8_t getSectionIndex(std::size_t characterIndex) const { - return styledText.second.at(characterIndex); - } - + const SectionOptions& sectionAt(std::size_t index) const { return sections.at(index); } + + const std::vector& getSections() const { return sections; } + + uint8_t getSectionIndex(std::size_t characterIndex) const { return styledText.second.at(characterIndex); } + double getMaxScale() const; void trim(); - + void verticalizePunctuation(); bool allowsVerticalWritingMode(); diff --git a/src/mbgl/tile/custom_geometry_tile.cpp b/src/mbgl/tile/custom_geometry_tile.cpp index e24d2d8dd51..9aa1cdf2a41 100644 --- a/src/mbgl/tile/custom_geometry_tile.cpp +++ b/src/mbgl/tile/custom_geometry_tile.cpp @@ -31,7 +31,6 @@ CustomGeometryTile::~CustomGeometryTile() { } void CustomGeometryTile::setTileData(const GeoJSON& geoJSON) { - auto featureData = mapbox::feature::feature_collection(); if (geoJSON.is() && !geoJSON.get().empty()) { auto scale = util::EXTENT / options->tileSize; @@ -54,11 +53,11 @@ void CustomGeometryTile::invalidateTileData() { observer->onTileChanged(*this); } -//Fetching tile data for custom sources is assumed to be an expensive operation. -// Only required tiles make fetchTile requests. Attempt to cancel a tile -// that is no longer required. +// Fetching tile data for custom sources is assumed to be an expensive operation. +// Only required tiles make fetchTile requests. Attempt to cancel a tile +// that is no longer required. void CustomGeometryTile::setNecessity(TileNecessity newNecessity) { - if (newNecessity != necessity || stale ) { + if (newNecessity != necessity || stale) { necessity = newNecessity; if (necessity == TileNecessity::Required) { loader.invoke(&style::CustomTileLoader::fetchTile, id, actorRef); @@ -69,10 +68,7 @@ void CustomGeometryTile::setNecessity(TileNecessity newNecessity) { } } -void CustomGeometryTile::querySourceFeatures( - std::vector& result, - const SourceQueryOptions& queryOptions) { - +void CustomGeometryTile::querySourceFeatures(std::vector& result, const SourceQueryOptions& queryOptions) { // Ignore the sourceLayer, there is only one auto layer = getData()->getLayer({}); @@ -82,7 +78,8 @@ void CustomGeometryTile::querySourceFeatures( auto feature = layer->getFeature(i); // Apply filter, if any - if (queryOptions.filter && !(*queryOptions.filter)(style::expression::EvaluationContext { static_cast(id.overscaledZ), feature.get() })) { + if (queryOptions.filter && !(*queryOptions.filter)(style::expression::EvaluationContext{ + static_cast(id.overscaledZ), feature.get()})) { continue; } diff --git a/src/mbgl/tile/custom_geometry_tile.hpp b/src/mbgl/tile/custom_geometry_tile.hpp index 06952871271..f88d62196bf 100644 --- a/src/mbgl/tile/custom_geometry_tile.hpp +++ b/src/mbgl/tile/custom_geometry_tile.hpp @@ -14,7 +14,7 @@ namespace style { class CustomTileLoader; } // namespace style -class CustomGeometryTile: public GeometryTile { +class CustomGeometryTile : public GeometryTile { public: CustomGeometryTile(const OverscaledTileID&, std::string sourceID, @@ -28,9 +28,7 @@ class CustomGeometryTile: public GeometryTile { void setNecessity(TileNecessity) final; - void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&) override; + void querySourceFeatures(std::vector& result, const SourceQueryOptions&) override; private: bool stale = true; diff --git a/src/mbgl/tile/geojson_tile.cpp b/src/mbgl/tile/geojson_tile.cpp index 0b37510978c..7af90adc560 100644 --- a/src/mbgl/tile/geojson_tile.cpp +++ b/src/mbgl/tile/geojson_tile.cpp @@ -28,10 +28,7 @@ void GeoJSONTile::updateData(std::shared_ptr data_, bool nee }); } -void GeoJSONTile::querySourceFeatures( - std::vector& result, - const SourceQueryOptions& options) { - +void GeoJSONTile::querySourceFeatures(std::vector& result, const SourceQueryOptions& options) { // Ignore the sourceLayer, there is only one if (auto tileData = getData()) { if (auto layer = tileData->getLayer({})) { @@ -40,7 +37,8 @@ void GeoJSONTile::querySourceFeatures( auto feature = layer->getFeature(i); // Apply filter, if any - if (options.filter && !(*options.filter)(style::expression::EvaluationContext { static_cast(this->id.overscaledZ), feature.get() })) { + if (options.filter && !(*options.filter)(style::expression::EvaluationContext{ + static_cast(this->id.overscaledZ), feature.get()})) { continue; } diff --git a/src/mbgl/tile/geojson_tile.hpp b/src/mbgl/tile/geojson_tile.hpp index 240b23e9bce..1d5dda1dffa 100644 --- a/src/mbgl/tile/geojson_tile.hpp +++ b/src/mbgl/tile/geojson_tile.hpp @@ -19,9 +19,7 @@ class GeoJSONTile : public GeometryTile { void updateData(std::shared_ptr data, bool needsRelayout = false); - void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&) override; + void querySourceFeatures(std::vector& result, const SourceQueryOptions&) override; private: std::shared_ptr data; diff --git a/src/mbgl/tile/geojson_tile_data.hpp b/src/mbgl/tile/geojson_tile_data.hpp index 6353b7151dc..0e9bae23304 100644 --- a/src/mbgl/tile/geojson_tile_data.hpp +++ b/src/mbgl/tile/geojson_tile_data.hpp @@ -3,28 +3,22 @@ namespace mbgl { -// Implements a simple in-memory Tile type that holds GeoJSON values. A GeoJSON tile can only have -// one layer, and it is always returned regardless of which layer is requested. +// Implements a simple in-memory Tile type that holds GeoJSON values. A GeoJSON +// tile can only have one layer, and it is always returned regardless of which +// layer is requested. class GeoJSONTileFeature : public GeometryTileFeature { public: const mapbox::feature::feature& feature; GeoJSONTileFeature(const mapbox::feature::feature& feature_) - : feature(feature_) { - } + : feature(feature_) {} - FeatureType getType() const override { - return apply_visitor(ToFeatureType(), feature.geometry); - } + FeatureType getType() const override { return apply_visitor(ToFeatureType(), feature.geometry); } - const PropertyMap& getProperties() const override { - return feature.properties; - } + const PropertyMap& getProperties() const override { return feature.properties; } - FeatureIdentifier getID() const override { - return feature.id; - } + FeatureIdentifier getID() const override { return feature.id; } const GeometryCollection& getGeometries() const override { if (!geometry) { @@ -53,20 +47,15 @@ class GeoJSONTileFeature : public GeometryTileFeature { class GeoJSONTileLayer : public GeometryTileLayer { public: GeoJSONTileLayer(std::shared_ptr> features_) - : features(std::move(features_)) { - } + : features(std::move(features_)) {} - std::size_t featureCount() const override { - return features->size(); - } + std::size_t featureCount() const override { return features->size(); } std::unique_ptr getFeature(std::size_t i) const override { return std::make_unique((*features)[i]); } - std::string getName() const override { - return ""; - } + std::string getName() const override { return ""; } private: std::shared_ptr> features; @@ -75,23 +64,17 @@ class GeoJSONTileLayer : public GeometryTileLayer { class GeoJSONTileData : public GeometryTileData { public: GeoJSONTileData(mapbox::feature::feature_collection features_) - : features(std::make_shared>( - std::move(features_))) { - } + : features(std::make_shared>(std::move(features_))) {} GeoJSONTileData(std::shared_ptr> features_) - : features(std::move(features_)) { - } + : features(std::move(features_)) {} - std::unique_ptr clone() const override { - return std::make_unique(features); - } + std::unique_ptr clone() const override { return std::make_unique(features); } std::unique_ptr getLayer(const std::string&) const override { return std::make_unique(features); } - private: std::shared_ptr> features; }; diff --git a/src/mbgl/tile/geometry_tile.cpp b/src/mbgl/tile/geometry_tile.cpp index d3f72582e22..4e50367b0a5 100644 --- a/src/mbgl/tile/geometry_tile.cpp +++ b/src/mbgl/tile/geometry_tile.cpp @@ -36,17 +36,15 @@ LayerRenderData* GeometryTile::LayoutResult::getLayerRenderData(const style::Lay // Layer data might be outdated, see issue #12432. return nullptr; } - return &result; + return &result; } class GeometryTileRenderData final : public TileRenderData { public: - GeometryTileRenderData( - std::shared_ptr layoutResult_, - std::shared_ptr atlasTextures_) - : TileRenderData(std::move(atlasTextures_)) - , layoutResult(std::move(layoutResult_)) { - } + GeometryTileRenderData(std::shared_ptr layoutResult_, + std::shared_ptr atlasTextures_) + : TileRenderData(std::move(atlasTextures_)), + layoutResult(std::move(layoutResult_)) {} private: // TileRenderData overrides. @@ -76,7 +74,7 @@ std::optional GeometryTileRenderData::getPattern(const std::strin void GeometryTileRenderData::upload(gfx::UploadPass& uploadPass) { if (!layoutResult) return; - auto uploadFn = [&] (Bucket& bucket) { + auto uploadFn = [&](Bucket& bucket) { if (bucket.needsUpload()) { bucket.upload(uploadPass); } @@ -116,23 +114,22 @@ void GeometryTileRenderData::prepare(const SourcePrepareParameters& parameters) Bucket* GeometryTileRenderData::getBucket(const Layer::Impl& layer) const { const LayerRenderData* data = getLayerRenderData(layer); - return data ? data->bucket.get() : nullptr; + return data ? data->bucket.get() : nullptr; } const LayerRenderData* GeometryTileRenderData::getLayerRenderData(const style::Layer::Impl& layerImpl) const { return layoutResult ? layoutResult->getLayerRenderData(layerImpl) : nullptr; } - /* Correlation between GeometryTile and GeometryTileWorker is safeguarded by two correlation schemes: GeometryTile's 'correlationID' is used for ensuring the tile will be flagged as non-pending only when the placement coming from the last operation (as in - 'setData', 'setLayers', 'setShowCollisionBoxes') occurs. This is important for - still mode rendering as we want to render only when all layout and placement - operations are completed. + 'setData', 'setLayers', 'setShowCollisionBoxes') occurs. This is important + for still mode rendering as we want to render only when all layout and + placement operations are completed. GeometryTileWorker's 'imageCorrelationID' is used for checking whether an image request reply coming from `GeometryTile` is valid. Previous image @@ -140,9 +137,7 @@ const LayerRenderData* GeometryTileRenderData::getLayerRenderData(const style::L that could flag the tile as non-pending too early. */ -GeometryTile::GeometryTile(const OverscaledTileID& id_, - std::string sourceID_, - const TileParameters& parameters) +GeometryTile::GeometryTile(const OverscaledTileID& id_, std::string sourceID_, const TileParameters& parameters) : Tile(Kind::Geometry, id_), ImageRequestor(parameters.imageManager), sourceID(std::move(sourceID_)), @@ -159,8 +154,7 @@ GeometryTile::GeometryTile(const OverscaledTileID& id_, glyphManager(parameters.glyphManager), imageManager(parameters.imageManager), mode(parameters.mode), - showCollisionBoxes(parameters.debugOptions & MapDebugOptions::Collision) { -} + showCollisionBoxes(parameters.debugOptions & MapDebugOptions::Collision) {} GeometryTile::~GeometryTile() { glyphManager.removeRequestor(*this); @@ -181,8 +175,8 @@ void GeometryTile::setError(std::exception_ptr err) { } void GeometryTile::setData(std::unique_ptr data_) { - // Mark the tile as pending again if it was complete before to prevent signaling a complete - // state despite pending parse operations. + // Mark the tile as pending again if it was complete before to prevent + // signaling a complete state despite pending parse operations. pending = true; ++correlationID; @@ -191,8 +185,8 @@ void GeometryTile::setData(std::unique_ptr data_) { } void GeometryTile::reset() { - // Mark the tile as pending again if it was complete before to prevent signaling a complete - // state despite pending parse operations. + // Mark the tile as pending again if it was complete before to prevent + // signaling a complete state despite pending parse operations. pending = true; ++correlationID; @@ -204,8 +198,8 @@ std::unique_ptr GeometryTile::createRenderData() { } void GeometryTile::setLayers(const std::vector>& layers) { - // Mark the tile as pending again if it was complete before to prevent signaling a complete - // state despite pending parse operations. + // Mark the tile as pending again if it was complete before to prevent + // signaling a complete state despite pending parse operations. pending = true; std::vector> impls; @@ -217,8 +211,7 @@ void GeometryTile::setLayers(const std::vector>& laye assert(layerImpl.getTypeInfo()->source != LayerTypeInfo::Source::NotRequired); assert(layerImpl.source == sourceID); assert(layerImpl.visibility != VisibilityType::None); - if (id.overscaledZ < std::floor(layerImpl.minZoom) || - id.overscaledZ >= std::ceil(layerImpl.maxZoom)) { + if (id.overscaledZ < std::floor(layerImpl.minZoom) || id.overscaledZ >= std::ceil(layerImpl.maxZoom)) { continue; } @@ -247,9 +240,9 @@ void GeometryTile::onLayout(std::shared_ptr result, const uint64_t layoutResult = std::move(result); if (!atlasTextures) { - atlasTextures = std::make_shared(); + atlasTextures = std::make_shared(); } - + observer->onTileChanged(*this); } @@ -260,7 +253,7 @@ void GeometryTile::onError(std::exception_ptr err, const uint64_t resultCorrelat } observer->onTileError(*this, std::move(err)); } - + void GeometryTile::onGlyphsAvailable(GlyphMap glyphs) { worker.self().invoke(&GeometryTileWorker::onGlyphsAvailable, std::move(glyphs)); } @@ -271,8 +264,15 @@ void GeometryTile::getGlyphs(GlyphDependencies glyphDependencies) { } } -void GeometryTile::onImagesAvailable(ImageMap images, ImageMap patterns, ImageVersionMap versionMap, uint64_t imageCorrelationID) { - worker.self().invoke(&GeometryTileWorker::onImagesAvailable, std::move(images), std::move(patterns), std::move(versionMap), imageCorrelationID); +void GeometryTile::onImagesAvailable(ImageMap images, + ImageMap patterns, + ImageVersionMap versionMap, + uint64_t imageCorrelationID) { + worker.self().invoke(&GeometryTileWorker::onImagesAvailable, + std::move(images), + std::move(patterns), + std::move(versionMap), + imageCorrelationID); } void GeometryTile::getImages(ImageRequestPair pair) { @@ -299,7 +299,7 @@ bool GeometryTile::layerPropertiesUpdated(const ImmutablefeatureIndex) { - return nullptr; + return nullptr; } return layoutResult->featureIndex->getData(); } @@ -320,9 +320,11 @@ float GeometryTile::getQueryPadding(const std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState& transformState, + const GeometryCoordinates& queryGeometry, + const TransformState& transformState, const std::unordered_map& layers, - const RenderedQueryOptions& options, const mat4& projMatrix, + const RenderedQueryOptions& options, + const mat4& projMatrix, const SourceFeatureState& featureState) { if (!getData()) return; @@ -332,21 +334,25 @@ void GeometryTile::queryRenderedFeatures(std::unordered_mapfeatureIndex->query(result, queryGeometry, transformState, posMatrix, + layoutResult->featureIndex->query(result, + queryGeometry, + transformState, + posMatrix, util::tileSize_D * id.overscaleFactor(), - std::pow(2, transformState.getZoom() - id.overscaledZ), options, id.toUnwrapped(), - layers, queryPadding * transformState.maxPitchScaleFactor(), featureState); + std::pow(2, transformState.getZoom() - id.overscaledZ), + options, + id.toUnwrapped(), + layers, + queryPadding * transformState.maxPitchScaleFactor(), + featureState); } -void GeometryTile::querySourceFeatures( - std::vector& result, - const SourceQueryOptions& options) { - +void GeometryTile::querySourceFeatures(std::vector& result, const SourceQueryOptions& options) { // Data not yet available, or tile is empty if (!getData()) { return; } - + // No source layers, specified, nothing to do if (!options.sourceLayers) { Log::Warning(Event::General, "At least one sourceLayer required"); @@ -357,14 +363,15 @@ void GeometryTile::querySourceFeatures( // Go throught all sourceLayers, if any // to gather all the features auto layer = getData()->getLayer(sourceLayer); - + if (layer) { auto featureCount = layer->featureCount(); for (std::size_t i = 0; i < featureCount; i++) { auto feature = layer->getFeature(i); // Apply filter, if any - if (options.filter && !(*options.filter)(style::expression::EvaluationContext { static_cast(this->id.overscaledZ), feature.get() })) { + if (options.filter && !(*options.filter)(style::expression::EvaluationContext{ + static_cast(this->id.overscaledZ), feature.get()})) { continue; } diff --git a/src/mbgl/tile/geometry_tile.hpp b/src/mbgl/tile/geometry_tile.hpp index 769bce3f5c8..058a33dae64 100644 --- a/src/mbgl/tile/geometry_tile.hpp +++ b/src/mbgl/tile/geometry_tile.hpp @@ -27,16 +27,14 @@ class TileAtlasTextures; class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { public: - GeometryTile(const OverscaledTileID&, - std::string sourceID, - const TileParameters&); + GeometryTile(const OverscaledTileID&, std::string sourceID, const TileParameters&); ~GeometryTile() override; void setError(std::exception_ptr); void setData(std::unique_ptr); - // Resets the tile's data and layers and leaves the tile in pending state, waiting for the new - // data and layers to come. + // Resets the tile's data and layers and leaves the tile in pending state, + // waiting for the new data and layers to come. void reset(); std::unique_ptr createRenderData() override; @@ -45,21 +43,21 @@ class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { void onGlyphsAvailable(GlyphMap) override; void onImagesAvailable(ImageMap, ImageMap, ImageVersionMap versionMap, uint64_t imageCorrelationID) override; - + void getGlyphs(GlyphDependencies); void getImages(ImageRequestPair); bool layerPropertiesUpdated(const Immutable&) override; void queryRenderedFeatures(std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState&, + const GeometryCoordinates& queryGeometry, + const TransformState&, const std::unordered_map& layers, - const RenderedQueryOptions& options, const mat4& projMatrix, + const RenderedQueryOptions& options, + const mat4& projMatrix, const SourceFeatureState& featureState) override; - void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&) override; + void querySourceFeatures(std::vector& result, const SourceQueryOptions&) override; float getQueryPadding(const std::unordered_map&) override; @@ -105,7 +103,7 @@ class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { void markObsolete(); // Used to signal the worker that it should abandon parsing this tile as soon as possible. - std::atomic obsolete { false }; + std::atomic obsolete{false}; std::shared_ptr mailbox; Actor worker; @@ -120,9 +118,9 @@ class GeometryTile : public Tile, public GlyphRequestor, public ImageRequestor { std::shared_ptr atlasTextures; const MapMode mode; - + bool showCollisionBoxes; - + enum class FadeState { Loaded, NeedsFirstPlacement, diff --git a/src/mbgl/tile/geometry_tile_data.cpp b/src/mbgl/tile/geometry_tile_data.cpp index 9062ebad4c3..d3df362156c 100644 --- a/src/mbgl/tile/geometry_tile_data.cpp +++ b/src/mbgl/tile/geometry_tile_data.cpp @@ -99,12 +99,10 @@ std::vector classifyRings(const GeometryCollection& rings) { void limitHoles(GeometryCollection& polygon, uint32_t maxHoles) { if (polygon.size() > 1 + maxHoles) { - std::nth_element(polygon.begin() + 1, - polygon.begin() + 1 + maxHoles, - polygon.end(), - [] (const auto& a, const auto& b) { - return std::fabs(signedArea(a)) > std::fabs(signedArea(b)); - }); + std::nth_element( + polygon.begin() + 1, polygon.begin() + 1 + maxHoles, polygon.end(), [](const auto& a, const auto& b) { + return std::fabs(signedArea(a)) > std::fabs(signedArea(b)); + }); polygon.resize(1 + maxHoles); } } @@ -114,12 +112,9 @@ Feature::geometry_type convertGeometry(const GeometryTileFeature& geometryTileFe const double x0 = util::EXTENT * static_cast(tileID.x); const double y0 = util::EXTENT * static_cast(tileID.y); - auto tileCoordinatesToLatLng = [&] (const Point& p) { + auto tileCoordinatesToLatLng = [&](const Point& p) { double y2 = 180 - (p.y + y0) * 360 / size; - return Point( - (p.x + x0) * 360 / size - 180, - std::atan(std::exp(y2 * M_PI / 180)) * 360.0 / M_PI - 90.0 - ); + return Point((p.x + x0) * 360 / size - 180, std::atan(std::exp(y2 * M_PI / 180)) * 360.0 / M_PI - 90.0); }; const GeometryCollection& geometries = geometryTileFeature.getGeometries(); @@ -192,12 +187,12 @@ GeometryCollection convertGeometry(const Feature::geometry_type& geometryTileFea Point p; auto x = (c.x + 180.0) * size / 360.0 - x0; - p.x = - int16_t(util::clamp(static_cast(x), std::numeric_limits::min(), std::numeric_limits::max())); + p.x = int16_t(util::clamp( + static_cast(x), std::numeric_limits::min(), std::numeric_limits::max())); auto y = (180 - (std::log(std::tan((c.y + 90) * M_PI / 360.0)) * 180 / M_PI)) * size / 360 - y0; - p.y = - int16_t(util::clamp(static_cast(y), std::numeric_limits::min(), std::numeric_limits::max())); + p.y = int16_t(util::clamp( + static_cast(y), std::numeric_limits::min(), std::numeric_limits::max())); return p; }; @@ -265,7 +260,7 @@ GeometryCollection convertGeometry(const Feature::geometry_type& geometryTileFea } Feature convertFeature(const GeometryTileFeature& geometryTileFeature, const CanonicalTileID& tileID) { - Feature feature { convertGeometry(geometryTileFeature, tileID) }; + Feature feature{convertGeometry(geometryTileFeature, tileID)}; feature.properties = geometryTileFeature.getProperties(); feature.id = geometryTileFeature.getID(); return feature; diff --git a/src/mbgl/tile/geometry_tile_data.hpp b/src/mbgl/tile/geometry_tile_data.hpp index 1b8cc3fdc2f..993c709fb8f 100644 --- a/src/mbgl/tile/geometry_tile_data.hpp +++ b/src/mbgl/tile/geometry_tile_data.hpp @@ -23,8 +23,10 @@ class GeometryCoordinates : public std::vector { using coordinate_type = int16_t; template - GeometryCoordinates(Args&&... args) : std::vector(std::forward(args)...) {} - GeometryCoordinates(std::initializer_list args) : std::vector(args) {} + GeometryCoordinates(Args&&... args) + : std::vector(std::forward(args)...) {} + GeometryCoordinates(std::initializer_list args) + : std::vector(args) {} GeometryCoordinates() = default; }; @@ -32,8 +34,10 @@ class GeometryCollection : public std::vector { public: using coordinate_type = int16_t; template - GeometryCollection(Args&&... args) : std::vector(std::forward(args)...) {} - GeometryCollection(std::initializer_list args) : std::vector(args) {} + GeometryCollection(Args&&... args) + : std::vector(std::forward(args)...) {} + GeometryCollection(std::initializer_list args) + : std::vector(args) {} GeometryCollection(GeometryCollection&&) = default; GeometryCollection& operator=(GeometryCollection&&) = default; GeometryCollection() = default; @@ -50,7 +54,7 @@ class GeometryTileFeature { virtual FeatureType getType() const = 0; virtual std::optional getValue(const std::string& key) const = 0; virtual const PropertyMap& getProperties() const; - virtual FeatureIdentifier getID() const { return NullValue {}; } + virtual FeatureIdentifier getID() const { return NullValue{}; } virtual const GeometryCollection& getGeometries() const; }; @@ -59,8 +63,8 @@ class GeometryTileLayer { virtual ~GeometryTileLayer() = default; virtual std::size_t featureCount() const = 0; - // Returns the feature object at the given position within the layer. The returned feature - // object may *not* outlive the layer object. + // Returns the feature object at the given position within the layer. The + // returned feature object may *not* outlive the layer object. virtual std::unique_ptr getFeature(std::size_t) const = 0; virtual std::string getName() const = 0; @@ -71,8 +75,8 @@ class GeometryTileData { virtual ~GeometryTileData() = default; virtual std::unique_ptr clone() const = 0; - // Returns the layer with the given name. The returned layer object *may* outlive the data - // object. + // Returns the layer with the given name. The returned layer object *may* + // outlive the data object. virtual std::unique_ptr getLayer(const std::string&) const = 0; }; @@ -94,18 +98,10 @@ Feature convertFeature(const GeometryTileFeature&, const CanonicalTileID&); GeometryCollection fixupPolygons(const GeometryCollection&); struct ToGeometryCollection { - GeometryCollection operator()(const mapbox::geometry::empty&) const { - return GeometryCollection(); - } - GeometryCollection operator()(const mapbox::geometry::point& geom) const { - return { { geom } }; - } - GeometryCollection operator()(const mapbox::geometry::multi_point& geom) const { - return { geom }; - } - GeometryCollection operator()(const mapbox::geometry::line_string& geom) const { - return { geom }; - } + GeometryCollection operator()(const mapbox::geometry::empty&) const { return GeometryCollection(); } + GeometryCollection operator()(const mapbox::geometry::point& geom) const { return {{geom}}; } + GeometryCollection operator()(const mapbox::geometry::multi_point& geom) const { return {geom}; } + GeometryCollection operator()(const mapbox::geometry::line_string& geom) const { return {geom}; } GeometryCollection operator()(const mapbox::geometry::multi_line_string& geom) const { GeometryCollection collection; collection.reserve(geom.size()); diff --git a/src/mbgl/tile/geometry_tile_worker.cpp b/src/mbgl/tile/geometry_tile_worker.cpp index 7025392b10d..8ab89f6a20e 100644 --- a/src/mbgl/tile/geometry_tile_worker.cpp +++ b/src/mbgl/tile/geometry_tile_worker.cpp @@ -73,17 +73,17 @@ GeometryTileWorker::~GeometryTileWorker() = default; v v (do parse or symbol layout; self-send "coalesced"; goto [coalescing]) - The idea is that in the [idle] state, parsing happens immediately in response to - a "set" message, and symbol layout happens once all symbol dependencies are met. - During this processing, multiple "set" messages might get queued in the mailbox. - At the end of processing, we self-send "coalesced", read all the queued messages - until we get to "coalesced", and then re-parse if there were one or more "set"s or - return to the [idle] state if not. - - One important goal of the design is to prevent starvation. Under heavy load new - requests for tiles should not prevent in progress request from completing. - It is nevertheless possible to restart an in-progress request: - + The idea is that in the [idle] state, parsing happens immediately in response + to a "set" message, and symbol layout happens once all symbol dependencies + are met. During this processing, multiple "set" messages might get queued in + the mailbox. At the end of processing, we self-send "coalesced", read all the + queued messages until we get to "coalesced", and then re-parse if there were + one or more "set"s or return to the [idle] state if not. + + One important goal of the design is to prevent starvation. Under heavy load + new requests for tiles should not prevent in progress request from + completing. It is nevertheless possible to restart an in-progress request: + - [Idle] setData -> parse() sends getGlyphs, hasPendingDependencies() is true enters [Coalescing], sends coalesced @@ -96,24 +96,25 @@ GeometryTileWorker::~GeometryTileWorker() = default; - [NeedsSymbolLayout] coalesced -> finalizeLayout() Generates result depending on whether dependencies are met -> [Idle] - - In this situation, we are counting on the idea that even with rapid changes to - the tile's data, the set of glyphs/images it requires will not keep growing without - limit. - - Although parsing (which populates all non-symbol buckets and requests dependencies - for symbol buckets) is internally separate from symbol layout, we only return - results to the foreground when we have completed both steps. Because we _move_ - the result buckets to the foreground, it is necessary to re-generate all buckets from - scratch for `setShowCollisionBoxes`, even though it only affects symbol layers. - + + In this situation, we are counting on the idea that even with rapid changes + to the tile's data, the set of glyphs/images it requires will not keep + growing without limit. + + Although parsing (which populates all non-symbol buckets and requests + dependencies for symbol buckets) is internally separate from symbol layout, + we only return results to the foreground when we have completed both steps. + Because we _move_ the result buckets to the foreground, it is necessary to + re-generate all buckets from scratch for `setShowCollisionBoxes`, even though + it only affects symbol layers. + The GL JS equivalent (in worker_tile.js and vector_tile_worker_source.js) - is somewhat simpler because it relies on getGlyphs/getImages calls that transfer - an entire set of glyphs/images on every tile load, while the native logic - maintains a local state that can be incrementally updated. Because each tile load - call becomes self-contained, the equivalent of the coalescing logic is handled by - 'reloadTile' queueing a single extra 'reloadTile' callback to run after the next - completed parse. + is somewhat simpler because it relies on getGlyphs/getImages calls that + transfer an entire set of glyphs/images on every tile load, while the native + logic maintains a local state that can be incrementally updated. Because each + tile load call becomes self-contained, the equivalent of the coalescing logic + is handled by 'reloadTile' queueing a single extra 'reloadTile' callback to + run after the next completed parse. */ void GeometryTileWorker::setData(std::unique_ptr data_, @@ -125,16 +126,16 @@ void GeometryTileWorker::setData(std::unique_ptr data_, availableImages = std::move(availableImages_); switch (state) { - case Idle: - parse(); - coalesce(); - break; + case Idle: + parse(); + coalesce(); + break; - case Coalescing: - case NeedsParse: - case NeedsSymbolLayout: - state = NeedsParse; - break; + case Coalescing: + case NeedsParse: + case NeedsSymbolLayout: + state = NeedsParse; + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -150,18 +151,18 @@ void GeometryTileWorker::setLayers(std::vector> layer availableImages = std::move(availableImages_); switch (state) { - case Idle: - parse(); - coalesce(); - break; + case Idle: + parse(); + coalesce(); + break; - case Coalescing: - case NeedsSymbolLayout: - state = NeedsParse; - break; + case Coalescing: + case NeedsSymbolLayout: + state = NeedsParse; + break; - case NeedsParse: - break; + case NeedsParse: + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -190,22 +191,22 @@ void GeometryTileWorker::setShowCollisionBoxes(bool showCollisionBoxes_, uint64_ correlationID = correlationID_; switch (state) { - case Idle: - if (!hasPendingParseResult()) { - // Trigger parse if nothing is in flight, otherwise symbol layout will automatically - // pick up the change - parse(); - coalesce(); - } - break; + case Idle: + if (!hasPendingParseResult()) { + // Trigger parse if nothing is in flight, otherwise symbol + // layout will automatically pick up the change + parse(); + coalesce(); + } + break; - case Coalescing: - state = NeedsSymbolLayout; - break; + case Coalescing: + state = NeedsSymbolLayout; + break; - case NeedsSymbolLayout: - case NeedsParse: - break; + case NeedsSymbolLayout: + case NeedsParse: + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -215,25 +216,25 @@ void GeometryTileWorker::setShowCollisionBoxes(bool showCollisionBoxes_, uint64_ void GeometryTileWorker::symbolDependenciesChanged() { try { switch (state) { - case Idle: - if (!layouts.empty()) { - // Layouts are created only by parsing and the parse result can only be - // cleared by performLayout, which also clears the layouts. - assert(hasPendingParseResult()); - finalizeLayout(); - coalesce(); - } - break; + case Idle: + if (!layouts.empty()) { + // Layouts are created only by parsing and the parse result can only be + // cleared by performLayout, which also clears the layouts. + assert(hasPendingParseResult()); + finalizeLayout(); + coalesce(); + } + break; - case Coalescing: - if (!layouts.empty()) { - state = NeedsSymbolLayout; - } - break; + case Coalescing: + if (!layouts.empty()) { + state = NeedsSymbolLayout; + } + break; - case NeedsSymbolLayout: - case NeedsParse: - break; + case NeedsSymbolLayout: + case NeedsParse: + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -243,26 +244,26 @@ void GeometryTileWorker::symbolDependenciesChanged() { void GeometryTileWorker::coalesced() { try { switch (state) { - case Idle: - assert(false); - break; + case Idle: + assert(false); + break; - case Coalescing: - state = Idle; - break; + case Coalescing: + state = Idle; + break; - case NeedsParse: - parse(); - coalesce(); - break; + case NeedsParse: + parse(); + coalesce(); + break; - case NeedsSymbolLayout: - // We may have entered NeedsSymbolLayout while coalescing - // after a performLayout. In that case, we need to - // start over with parsing in order to do another layout. - hasPendingParseResult() ? finalizeLayout() : parse(); - coalesce(); - break; + case NeedsSymbolLayout: + // We may have entered NeedsSymbolLayout while coalescing + // after a performLayout. In that case, we need to + // start over with parsing in order to do another layout. + hasPendingParseResult() ? finalizeLayout() : parse(); + coalesce(); + break; } } catch (...) { parent.invoke(&GeometryTile::onError, std::current_exception(), correlationID); @@ -300,7 +301,10 @@ void GeometryTileWorker::onGlyphsAvailable(GlyphMap newGlyphMap) { symbolDependenciesChanged(); } -void GeometryTileWorker::onImagesAvailable(ImageMap newIconMap, ImageMap newPatternMap, ImageVersionMap newVersionMap, uint64_t imageCorrelationID_) { +void GeometryTileWorker::onImagesAvailable(ImageMap newIconMap, + ImageMap newPatternMap, + ImageVersionMap newVersionMap, + uint64_t imageCorrelationID_) { if (imageCorrelationID != imageCorrelationID_) { return; // Ignore outdated image request replies. } @@ -367,7 +371,7 @@ void GeometryTileWorker::parse() { } const style::Layer::Impl& leaderImpl = *(group.at(0)->baseImpl); - BucketParameters parameters { id, mode, pixelRatio, leaderImpl.getTypeInfo() }; + BucketParameters parameters{id, mode, pixelRatio, leaderImpl.getTypeInfo()}; auto geometryLayer = (*data)->getLayer(leaderImpl.sourceLayer); if (!geometryLayer) { @@ -381,10 +385,12 @@ void GeometryTileWorker::parse() { featureIndex->setBucketLayerIDs(leaderImpl.id, layerIDs); - // Symbol layers and layers that support pattern properties have an extra step at layout time to figure out what images/glyphs - // are needed to render the layer. They use the intermediate Layout data structure to accomplish this, - // and either immediately create a bucket if no images/glyphs are used, or the Layout is stored until - // the images/glyphs are available to add the features to the buckets. + // Symbol layers and layers that support pattern properties have an + // extra step at layout time to figure out what images/glyphs are needed + // to render the layer. They use the intermediate Layout data structure + // to accomplish this, and either immediately create a bucket if no + // images/glyphs are used, or the Layout is stored until the + // images/glyphs are available to add the features to the buckets. if (leaderImpl.getTypeInfo()->layout == LayerTypeInfo::Layout::Required) { std::unique_ptr layout = LayerManager::get()->createLayout( {parameters, glyphDependencies, imageDependencies, availableImages}, std::move(geometryLayer), group); @@ -424,10 +430,10 @@ void GeometryTileWorker::parse() { requestNewImages(imageDependencies); MBGL_TIMING_FINISH(watch, - " Action: " << "Parsing," << - " SourceID: " << sourceID.c_str() << - " Canonical: " << static_cast(id.canonical.z) << "/" << id.canonical.x << "/" << id.canonical.y << - " Time"); + " Action: " + << "Parsing," + << " SourceID: " << sourceID.c_str() << " Canonical: " << static_cast(id.canonical.z) + << "/" << id.canonical.x << "/" << id.canonical.y << " Time"); finalizeLayout(); } @@ -439,7 +445,7 @@ bool GeometryTileWorker::hasPendingDependencies() const { } return !pendingImageDependencies.empty(); } - + bool GeometryTileWorker::hasPendingParseResult() const { return bool(featureIndex); } @@ -448,7 +454,7 @@ void GeometryTileWorker::finalizeLayout() { if (!data || !layers || !hasPendingParseResult() || hasPendingDependencies()) { return; } - + MBGL_TIMING_START(watch) std::optional glyphAtlasImage; ImageAtlas iconAtlas = makeImageAtlas(imageMap, patternMap, versionMap); @@ -476,19 +482,17 @@ void GeometryTileWorker::finalizeLayout() { layouts.clear(); firstLoad = false; - + MBGL_TIMING_FINISH(watch, - " Action: " << "SymbolLayout," << - " SourceID: " << sourceID.c_str() << - " Canonical: " << static_cast(id.canonical.z) << "/" << id.canonical.x << "/" << id.canonical.y << - " Time"); - - parent.invoke(&GeometryTile::onLayout, std::make_shared( - std::move(renderData), - std::move(featureIndex), - std::move(glyphAtlasImage), - std::move(iconAtlas) - ), correlationID); + " Action: " + << "SymbolLayout," + << " SourceID: " << sourceID.c_str() << " Canonical: " << static_cast(id.canonical.z) + << "/" << id.canonical.x << "/" << id.canonical.y << " Time"); + + parent.invoke(&GeometryTile::onLayout, + std::make_shared( + std::move(renderData), std::move(featureIndex), std::move(glyphAtlasImage), std::move(iconAtlas)), + correlationID); } } // namespace mbgl diff --git a/src/mbgl/tile/geometry_tile_worker.hpp b/src/mbgl/tile/geometry_tile_worker.hpp index 9dacf2ea968..6e5a660a07b 100644 --- a/src/mbgl/tile/geometry_tile_worker.hpp +++ b/src/mbgl/tile/geometry_tile_worker.hpp @@ -56,12 +56,12 @@ class GeometryTileWorker { void coalesced(); void parse(); void finalizeLayout(); - + void coalesce(); void requestNewGlyphs(const GlyphDependencies&); void requestNewImages(const ImageDependencies&); - + void symbolDependenciesChanged(); bool hasPendingDependencies() const; bool hasPendingParseResult() const; @@ -76,7 +76,7 @@ class GeometryTileWorker { const std::atomic& obsolete; const MapMode mode; const float pixelRatio; - + std::unique_ptr featureIndex; std::unordered_map renderData; diff --git a/src/mbgl/tile/raster_dem_tile.cpp b/src/mbgl/tile/raster_dem_tile.cpp index 19160c10ef4..c116fedafad 100644 --- a/src/mbgl/tile/raster_dem_tile.cpp +++ b/src/mbgl/tile/raster_dem_tile.cpp @@ -14,22 +14,18 @@ namespace mbgl { -RasterDEMTile::RasterDEMTile(const OverscaledTileID& id_, - const TileParameters& parameters, - const Tileset& tileset) +RasterDEMTile::RasterDEMTile(const OverscaledTileID& id_, const TileParameters& parameters, const Tileset& tileset) : Tile(Kind::RasterDEM, id_), loader(*this, id_, parameters, tileset), mailbox(std::make_shared(*Scheduler::GetCurrent())), - worker(Scheduler::GetBackground(), - ActorRef(*this, mailbox)) { - + worker(Scheduler::GetBackground(), ActorRef(*this, mailbox)) { encoding = tileset.encoding; - if ( id.canonical.y == 0 ){ + if (id.canonical.y == 0) { // this tile doesn't have upper neighboring tiles so marked those as backfilled neighboringTiles = neighboringTiles | DEMTileNeighbors::NoUpper; } - if (id.canonical.y + 1 == std::pow(2, id.canonical.z)){ + if (id.canonical.y + 1 == std::pow(2, id.canonical.z)) { // this tile doesn't have lower neighboring tiles so marked those as backfilled neighboringTiles = neighboringTiles | DEMTileNeighbors::NoLower; } @@ -85,8 +81,8 @@ HillshadeBucket* RasterDEMTile::getBucket() const { void RasterDEMTile::backfillBorder(const RasterDEMTile& borderTile, const DEMTileNeighbors mask) { int32_t dx = static_cast(borderTile.id.canonical.x) - static_cast(id.canonical.x); - const auto dy = - static_cast(static_cast(borderTile.id.canonical.y) - static_cast(id.canonical.y)); + const auto dy = static_cast(static_cast(borderTile.id.canonical.y) - + static_cast(id.canonical.y)); const auto dim = static_cast(pow(2, id.canonical.z)); if (dx == 0 && dy == 0) return; if (std::abs(dy) > 1) return; @@ -106,8 +102,8 @@ void RasterDEMTile::backfillBorder(const RasterDEMTile& borderTile, const DEMTil tileDEM.backfillBorder(borderDEM, dx, dy); // update the bitmask to indicate that this tiles have been backfilled by flipping the relevant bit this->neighboringTiles = this->neighboringTiles | mask; - // mark HillshadeBucket.prepared as false so it runs through the prepare render pass - // with the new texture data we just backfilled + // mark HillshadeBucket.prepared as false so it runs through the prepare + // render pass with the new texture data we just backfilled bucket->setPrepared(false); } } diff --git a/src/mbgl/tile/raster_dem_tile.hpp b/src/mbgl/tile/raster_dem_tile.hpp index 21f189556ed..337dd370101 100644 --- a/src/mbgl/tile/raster_dem_tile.hpp +++ b/src/mbgl/tile/raster_dem_tile.hpp @@ -12,35 +12,35 @@ class TileParameters; class HillshadeBucket; enum class DEMTileNeighbors : uint8_t { - // 0b00000000 - Empty = 0 << 1, - - // 0b00000001 - Left = 1 << 0, - // 0b00000010 - Right = 1 << 1, - // 0b00000100 - TopLeft = 1 << 2, - // 0b00001000 - TopCenter = 1 << 3, - // 0b00010000 - TopRight = 1 << 4, - // 0b00100000 - BottomLeft = 1 << 5, - // 0b01000000 - BottomCenter = 1 << 6, - // 0b10000000 - BottomRight = 1 << 7, - - // helper enums for tiles with no upper/lower neighbors - // and completely backfilled tiles - - // 0b00011100 - NoUpper = 0b00011100, - // 0b11100000 - NoLower = 0b11100000, - // 0b11111111 - Complete = 0b11111111 + // 0b00000000 + Empty = 0 << 1, + + // 0b00000001 + Left = 1 << 0, + // 0b00000010 + Right = 1 << 1, + // 0b00000100 + TopLeft = 1 << 2, + // 0b00001000 + TopCenter = 1 << 3, + // 0b00010000 + TopRight = 1 << 4, + // 0b00100000 + BottomLeft = 1 << 5, + // 0b01000000 + BottomCenter = 1 << 6, + // 0b10000000 + BottomRight = 1 << 7, + + // helper enums for tiles with no upper/lower neighbors + // and completely backfilled tiles + + // 0b00011100 + NoUpper = 0b00011100, + // 0b11100000 + NoLower = 0b11100000, + // 0b11111111 + Complete = 0b11111111 }; inline DEMTileNeighbors operator|(DEMTileNeighbors a, DEMTileNeighbors b) { @@ -61,9 +61,7 @@ class Layer; class RasterDEMTile final : public Tile { public: - RasterDEMTile(const OverscaledTileID&, - const TileParameters&, - const Tileset&); + RasterDEMTile(const OverscaledTileID&, const TileParameters&, const Tileset&); ~RasterDEMTile() override; std::unique_ptr createRenderData() override; @@ -82,7 +80,7 @@ class RasterDEMTile final : public Tile { // neighboringTiles is a bitmask for which neighboring tiles have been backfilled // there are max 8 possible neighboring tiles, so each bit represents one neighbor DEMTileNeighbors neighboringTiles = DEMTileNeighbors::Empty; - + void setMask(TileMask&&) override; void onParsed(std::unique_ptr result, uint64_t correlationID); @@ -93,14 +91,13 @@ class RasterDEMTile final : public Tile { std::shared_ptr mailbox; Actor worker; - + uint64_t correlationID = 0; Tileset::DEMEncoding encoding; // Contains the Bucket object for the tile. Buckets are render // objects and they get added by tile parsing operations. std::shared_ptr bucket; - }; } // namespace mbgl diff --git a/src/mbgl/tile/raster_dem_tile_worker.cpp b/src/mbgl/tile/raster_dem_tile_worker.cpp index 92fe3d919a2..3b24e3538b4 100644 --- a/src/mbgl/tile/raster_dem_tile_worker.cpp +++ b/src/mbgl/tile/raster_dem_tile_worker.cpp @@ -13,7 +13,8 @@ void RasterDEMTileWorker::parse(const std::shared_ptr& data, uint64_t correlationID, Tileset::DEMEncoding encoding) { if (!data) { - parent.invoke(&RasterDEMTile::onParsed, nullptr, correlationID); // No data; empty tile. + parent.invoke(&RasterDEMTile::onParsed, nullptr, + correlationID); // No data; empty tile. return; } diff --git a/src/mbgl/tile/raster_tile.cpp b/src/mbgl/tile/raster_tile.cpp index 371eb3b48b7..58192e5e047 100644 --- a/src/mbgl/tile/raster_tile.cpp +++ b/src/mbgl/tile/raster_tile.cpp @@ -14,15 +14,11 @@ namespace mbgl { -RasterTile::RasterTile(const OverscaledTileID& id_, - const TileParameters& parameters, - const Tileset& tileset) +RasterTile::RasterTile(const OverscaledTileID& id_, const TileParameters& parameters, const Tileset& tileset) : Tile(Kind::Raster, id_), loader(*this, id_, parameters, tileset), mailbox(std::make_shared(*Scheduler::GetCurrent())), - worker(Scheduler::GetBackground(), - ActorRef(*this, mailbox)) { -} + worker(Scheduler::GetBackground(), ActorRef(*this, mailbox)) {} RasterTile::~RasterTile() = default; diff --git a/src/mbgl/tile/raster_tile.hpp b/src/mbgl/tile/raster_tile.hpp index bf5ea7152ac..b0cc46e253e 100644 --- a/src/mbgl/tile/raster_tile.hpp +++ b/src/mbgl/tile/raster_tile.hpp @@ -17,9 +17,7 @@ class Layer; class RasterTile final : public Tile { public: - RasterTile(const OverscaledTileID&, - const TileParameters&, - const Tileset&); + RasterTile(const OverscaledTileID&, const TileParameters&, const Tileset&); ~RasterTile() override; std::unique_ptr createRenderData() override; diff --git a/src/mbgl/tile/raster_tile_worker.cpp b/src/mbgl/tile/raster_tile_worker.cpp index 2a4cfeaf312..134a0943382 100644 --- a/src/mbgl/tile/raster_tile_worker.cpp +++ b/src/mbgl/tile/raster_tile_worker.cpp @@ -11,7 +11,8 @@ RasterTileWorker::RasterTileWorker(const ActorRef&, ActorRef& data, uint64_t correlationID) { if (!data) { - parent.invoke(&RasterTile::onParsed, nullptr, correlationID); // No data; empty tile. + parent.invoke(&RasterTile::onParsed, nullptr, + correlationID); // No data; empty tile. return; } diff --git a/src/mbgl/tile/tile.cpp b/src/mbgl/tile/tile.cpp index eda0367f04f..7b174d44b3b 100644 --- a/src/mbgl/tile/tile.cpp +++ b/src/mbgl/tile/tile.cpp @@ -8,7 +8,10 @@ namespace mbgl { static TileObserver nullObserver; -Tile::Tile(Kind kind_, OverscaledTileID id_) : kind(kind_), id(id_), observer(&nullObserver) {} +Tile::Tile(Kind kind_, OverscaledTileID id_) + : kind(kind_), + id(id_), + observer(&nullObserver) {} Tile::~Tile() = default; @@ -16,8 +19,7 @@ void Tile::setObserver(TileObserver* observer_) { observer = observer_; } -void Tile::cancel() { -} +void Tile::cancel() {} void Tile::setTriedCache() { triedOptional = true; @@ -27,10 +29,18 @@ void Tile::setTriedCache() { void Tile::dumpDebugLogs() const { std::string kindString; switch (kind) { - case Kind::Geometry: kindString = "Geometry"; break; - case Kind::Raster: kindString = "Raster"; break; - case Kind::RasterDEM: kindString = "RasterDEM"; break; - default: kindString = "Unknown"; break; + case Kind::Geometry: + kindString = "Geometry"; + break; + case Kind::Raster: + kindString = "Raster"; + break; + case Kind::RasterDEM: + kindString = "RasterDEM"; + break; + default: + kindString = "Unknown"; + break; } Log::Info(Event::General, "Tile::Kind: " + kindString); Log::Info(Event::General, "Tile::id: " + util::toString(id)); @@ -39,16 +49,18 @@ void Tile::dumpDebugLogs() const { Log::Info(Event::General, "Tile::loaded: " + std::string(isLoaded() ? "yes" : "no")); } -void Tile::queryRenderedFeatures(std::unordered_map>&, const GeometryCoordinates&, - const TransformState&, const std::unordered_map&, - const RenderedQueryOptions&, const mat4&, const SourceFeatureState&) {} +void Tile::queryRenderedFeatures(std::unordered_map>&, + const GeometryCoordinates&, + const TransformState&, + const std::unordered_map&, + const RenderedQueryOptions&, + const mat4&, + const SourceFeatureState&) {} float Tile::getQueryPadding(const std::unordered_map&) { return 0; } -void Tile::querySourceFeatures( - std::vector&, - const SourceQueryOptions&) {} +void Tile::querySourceFeatures(std::vector&, const SourceQueryOptions&) {} } // namespace mbgl diff --git a/src/mbgl/tile/tile.hpp b/src/mbgl/tile/tile.hpp index 3ab008fc8ce..77652e6e18b 100644 --- a/src/mbgl/tile/tile.hpp +++ b/src/mbgl/tile/tile.hpp @@ -74,69 +74,61 @@ class Tile { // // Tile implementation should update the contained layer // render data with the given properties. - // - // Returns `true` if the corresponding render layer data is present in this tile (and i.e. it - // was succesfully updated); returns `false` otherwise. + // + // Returns `true` if the corresponding render layer data is present in this + // tile (and i.e. it was succesfully updated); returns `false` otherwise. virtual bool layerPropertiesUpdated(const Immutable& layerProperties) = 0; virtual void setShowCollisionBoxes(const bool) {} virtual void setLayers(const std::vector>&) {} virtual void setMask(TileMask&&) {} virtual void queryRenderedFeatures(std::unordered_map>& result, - const GeometryCoordinates& queryGeometry, const TransformState&, + const GeometryCoordinates& queryGeometry, + const TransformState&, const std::unordered_map&, - const RenderedQueryOptions& options, const mat4& projMatrix, + const RenderedQueryOptions& options, + const mat4& projMatrix, const SourceFeatureState& featureState); - virtual void querySourceFeatures( - std::vector& result, - const SourceQueryOptions&); + virtual void querySourceFeatures(std::vector& result, const SourceQueryOptions&); virtual float getQueryPadding(const std::unordered_map&); void setTriedCache(); - // Returns true when the tile source has received a first response, regardless of whether a load - // error occurred or actual data was loaded. - bool hasTriedCache() const { - return triedOptional; - } + // Returns true when the tile source has received a first response, + // regardless of whether a load error occurred or actual data was loaded. + bool hasTriedCache() const { return triedOptional; } // Tile data considered "Renderable" can be used for rendering. Data in // partial state is still waiting for network resources but can also // be rendered, although layers will be missing. - bool isRenderable() const { - return renderable; - } - - // A tile is "Loaded" when we have received a response from a FileSource, and have attempted to - // parse the tile (if applicable). Tile implementations should set this to true when a load - // error occurred, or after the tile was parsed successfully. - bool isLoaded() const { - return loaded; - } - - // "Completion" of a tile means that we have attempted to load it, and parsed it completely, - // i.e. no parsing or placement operations are pending for that tile. - // Completeness doesn't mean that the tile can be rendered, but merely that we have exhausted - // all options to get this tile to a renderable state. Some tiles may not be renderable, but - // complete, e.g. when a raster tile couldn't be loaded, or parsing failed. - bool isComplete() const { - return loaded && !pending; - } - - // "holdForFade" is used to keep tiles in the render tree after they're no longer - // ideal tiles in order to allow symbols to fade out - virtual bool holdForFade() const { - return false; - } + bool isRenderable() const { return renderable; } + + // A tile is "Loaded" when we have received a response from a FileSource, + // and have attempted to parse the tile (if applicable). Tile + // implementations should set this to true when a load error occurred, or + // after the tile was parsed successfully. + bool isLoaded() const { return loaded; } + + // "Completion" of a tile means that we have attempted to load it, and + // parsed it completely, i.e. no parsing or placement operations are pending + // for that tile. Completeness doesn't mean that the tile can be rendered, + // but merely that we have exhausted all options to get this tile to a + // renderable state. Some tiles may not be renderable, but complete, e.g. + // when a raster tile couldn't be loaded, or parsing failed. + bool isComplete() const { return loaded && !pending; } + + // "holdForFade" is used to keep tiles in the render tree after they're no + // longer ideal tiles in order to allow symbols to fade out + virtual bool holdForFade() const { return false; } // Set whenever this tile is used as an ideal tile virtual void markRenderedIdeal() {} // Set when the tile is removed from the ideal render set but may still be held for fading virtual void markRenderedPreviously() {} // Placement operation performed while this tile is fading - // We hold onto a tile for two placements: fading starts with the first placement - // and will have time to finish by the second placement. + // We hold onto a tile for two placements: fading starts with the first + // placement and will have time to finish by the second placement. virtual void performedFadePlacement() {} virtual void setFeatureState(const LayerFeatureStates&) {} @@ -147,8 +139,8 @@ class Tile { OverscaledTileID id; std::optional modified; std::optional expires; - // Indicates whether this tile is used for the currently visible layers on the map. - // Re-initialized at every source update. + // Indicates whether this tile is used for the currently visible layers on + // the map. Re-initialized at every source update. bool usedByRenderedLayers = false; protected: @@ -157,7 +149,6 @@ class Tile { bool pending = false; bool loaded = false; - TileObserver* observer = nullptr; }; diff --git a/src/mbgl/tile/tile_cache.cpp b/src/mbgl/tile/tile_cache.cpp index 272ecdfee58..09bfb928a8c 100644 --- a/src/mbgl/tile/tile_cache.cpp +++ b/src/mbgl/tile/tile_cache.cpp @@ -47,7 +47,6 @@ Tile* TileCache::get(const OverscaledTileID& key) { } std::unique_ptr TileCache::pop(const OverscaledTileID& key) { - std::unique_ptr tile; auto it = tiles.find(key); diff --git a/src/mbgl/tile/tile_cache.hpp b/src/mbgl/tile/tile_cache.hpp index f893124aa4e..d5b295cd9ed 100644 --- a/src/mbgl/tile/tile_cache.hpp +++ b/src/mbgl/tile/tile_cache.hpp @@ -3,7 +3,6 @@ #include #include - #include #include #include @@ -12,7 +11,8 @@ namespace mbgl { class TileCache { public: - TileCache(size_t size_ = 0) : size(size_) {} + TileCache(size_t size_ = 0) + : size(size_) {} void setSize(size_t); size_t getSize() const { return size; }; diff --git a/src/mbgl/tile/tile_loader.hpp b/src/mbgl/tile/tile_loader.hpp index 99d9047f8d4..9709cf77278 100644 --- a/src/mbgl/tile/tile_loader.hpp +++ b/src/mbgl/tile/tile_loader.hpp @@ -16,18 +16,16 @@ class TileLoader { public: TileLoader(const TileLoader&) = delete; TileLoader& operator=(const TileLoader&) = delete; - TileLoader(T&, - const OverscaledTileID&, - const TileParameters&, - const Tileset&); + TileLoader(T&, const OverscaledTileID&, const TileParameters&, const Tileset&); ~TileLoader(); void setNecessity(TileNecessity newNecessity); void setUpdateParameters(const TileUpdateParameters&); private: - // called when the tile is one of the ideal tiles that we want to show definitely. the tile source - // should try to make every effort (e.g. fetch from internet, or revalidate existing resources). + // called when the tile is one of the ideal tiles that we want to show + // definitely. the tile source should try to make every effort (e.g. fetch + // from internet, or revalidate existing resources). void makeRequired(); // called when the zoom level no longer corresponds to the displayed one, but diff --git a/src/mbgl/tile/tile_loader_impl.hpp b/src/mbgl/tile/tile_loader_impl.hpp index 3a8094e6306..cc1e50de1ce 100644 --- a/src/mbgl/tile/tile_loader_impl.hpp +++ b/src/mbgl/tile/tile_loader_impl.hpp @@ -21,14 +21,13 @@ TileLoader::TileLoader(T& tile_, const Tileset& tileset) : tile(tile_), necessity(TileNecessity::Optional), - resource(Resource::tile( - tileset.tiles.at(0), - parameters.pixelRatio, - id.canonical.x, - id.canonical.y, - id.canonical.z, - tileset.scheme, - Resource::LoadingMethod::CacheOnly)), + resource(Resource::tile(tileset.tiles.at(0), + parameters.pixelRatio, + id.canonical.x, + id.canonical.y, + id.canonical.z, + tileset.scheme, + Resource::LoadingMethod::CacheOnly)), fileSource(parameters.fileSource) { assert(!request); if (!fileSource) { @@ -37,19 +36,21 @@ TileLoader::TileLoader(T& tile_, } if (fileSource->supportsCacheOnlyRequests()) { - // When supported, the first request is always std::optional, even if the TileLoader - // is marked as required. That way, we can let the first std::optional request continue - // to load when the TileLoader is later changed from required to std::optional. If we - // started out with a required request, we'd have to cancel everything, including the + // When supported, the first request is always std::optional, even if + // the TileLoader is marked as required. That way, we can let the first + // std::optional request continue to load when the TileLoader is later + // changed from required to std::optional. If we started out with a + // required request, we'd have to cancel everything, including the // initial std::optional part of the request. loadFromCache(); } else if (necessity == TileNecessity::Required) { - // When the file source doesn't support cache-only requests, and we definiitely need this - // data, we can start out with a network request immediately. + // When the file source doesn't support cache-only requests, and we + // definiitely need this data, we can start out with a network request + // immediately. loadFromNetwork(); } else { - // When the FileSource doesn't support cache-only requests, we do nothing until the - // data is definitely required. + // When the FileSource doesn't support cache-only requests, we do + // nothing until the data is definitely required. } } @@ -95,11 +96,12 @@ void TileLoader::loadFromCache() { tile.setTriedCache(); if (res.error && res.error->reason == Response::Error::Reason::NotFound) { - // When the cache-only request could not be satisfied, don't treat it as an error. - // A cache lookup could still return data, _and_ an error, in particular when we were - // able to find the data, but it is expired and the Cache-Control headers indicated that - // we aren't allowed to use expired responses. In this case, we still get the data which - // we can use in our conditional network request. + // When the cache-only request could not be satisfied, don't treat + // it as an error. A cache lookup could still return data, _and_ an + // error, in particular when we were able to find the data, but it + // is expired and the Cache-Control headers indicated that we aren't + // allowed to use expired responses. In this case, we still get the + // data which we can use in our conditional network request. resource.priorModified = res.modified; resource.priorExpires = res.expires; resource.priorEtag = res.etag; @@ -124,8 +126,8 @@ void TileLoader::makeRequired() { template void TileLoader::makeOptional() { if (hasPendingNetworkRequest()) { - // Abort the current request, but only when we know that we're specifically querying for a - // network resource only. + // Abort the current request, but only when we know that we're + // specifically querying for a network resource only. request.reset(); } } @@ -136,8 +138,8 @@ void TileLoader::loadedData(const Response& res) { tile.setError(std::make_exception_ptr(std::runtime_error(res.error->message))); } else if (res.notModified) { resource.priorExpires = res.expires; - // Do not notify the tile; when we get this message, it already has the current - // version of the data. + // Do not notify the tile; when we get this message, it already has the + // current version of the data. tile.setMetadata(res.modified, res.expires); } else { resource.priorModified = res.modified; @@ -156,12 +158,12 @@ void TileLoader::loadFromNetwork() { return; } - // Instead of using Resource::LoadingMethod::All, we're first doing a CacheOnly, and then a - // NetworkOnly request. + // Instead of using Resource::LoadingMethod::All, we're first doing a + // CacheOnly, and then a NetworkOnly request. resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.minimumUpdateInterval = updateParameters.minimumUpdateInterval; - resource.storagePolicy = - updateParameters.isVolatile ? Resource::StoragePolicy::Volatile : Resource::StoragePolicy::Permanent; + resource.storagePolicy = updateParameters.isVolatile ? Resource::StoragePolicy::Volatile + : Resource::StoragePolicy::Permanent; request = fileSource->request(resource, [this](const Response& res) { loadedData(res); }); } diff --git a/src/mbgl/tile/vector_tile.cpp b/src/mbgl/tile/vector_tile.cpp index cff6e473132..736c6ff9e12 100644 --- a/src/mbgl/tile/vector_tile.cpp +++ b/src/mbgl/tile/vector_tile.cpp @@ -10,7 +10,8 @@ VectorTile::VectorTile(const OverscaledTileID& id_, std::string sourceID_, const TileParameters& parameters, const Tileset& tileset) - : GeometryTile(id_, std::move(sourceID_), parameters), loader(*this, id_, parameters, tileset) {} + : GeometryTile(id_, std::move(sourceID_), parameters), + loader(*this, id_, parameters, tileset) {} void VectorTile::setNecessity(TileNecessity necessity) { loader.setNecessity(necessity); diff --git a/src/mbgl/tile/vector_tile.hpp b/src/mbgl/tile/vector_tile.hpp index 817c0c25d86..d703a3b7067 100644 --- a/src/mbgl/tile/vector_tile.hpp +++ b/src/mbgl/tile/vector_tile.hpp @@ -10,10 +10,7 @@ class TileParameters; class VectorTile : public GeometryTile { public: - VectorTile(const OverscaledTileID&, - std::string sourceID, - const TileParameters&, - const Tileset&); + VectorTile(const OverscaledTileID&, std::string sourceID, const TileParameters&, const Tileset&); void setNecessity(TileNecessity) final; void setUpdateParameters(const TileUpdateParameters&) final; diff --git a/src/mbgl/tile/vector_tile_data.cpp b/src/mbgl/tile/vector_tile_data.cpp index a6139b412e8..8df24eec764 100644 --- a/src/mbgl/tile/vector_tile_data.cpp +++ b/src/mbgl/tile/vector_tile_data.cpp @@ -4,21 +4,19 @@ namespace mbgl { -VectorTileFeature::VectorTileFeature(const mapbox::vector_tile::layer& layer, - const protozero::data_view& view) - : feature(view, layer) { -} +VectorTileFeature::VectorTileFeature(const mapbox::vector_tile::layer& layer, const protozero::data_view& view) + : feature(view, layer) {} FeatureType VectorTileFeature::getType() const { switch (feature.getType()) { - case mapbox::vector_tile::GeomType::POINT: - return FeatureType::Point; - case mapbox::vector_tile::GeomType::LINESTRING: - return FeatureType::LineString; - case mapbox::vector_tile::GeomType::POLYGON: - return FeatureType::Polygon; - default: - return FeatureType::Unknown; + case mapbox::vector_tile::GeomType::POINT: + return FeatureType::Point; + case mapbox::vector_tile::GeomType::LINESTRING: + return FeatureType::LineString; + case mapbox::vector_tile::GeomType::POLYGON: + return FeatureType::Polygon; + default: + return FeatureType::Unknown; } } @@ -44,8 +42,7 @@ const GeometryCollection& VectorTileFeature::getGeometries() const { try { lines = feature.getGeometries(scale); - } - catch(const std::runtime_error& ex) { + } catch (const std::runtime_error& ex) { Log::Error(Event::ParseTile, "Could not get geometries: " + std::string(ex.what())); lines = GeometryCollection(); } @@ -57,10 +54,9 @@ const GeometryCollection& VectorTileFeature::getGeometries() const { return *lines; } -VectorTileLayer::VectorTileLayer(std::shared_ptr data_, - const protozero::data_view& view) - : data(std::move(data_)), layer(view) { -} +VectorTileLayer::VectorTileLayer(std::shared_ptr data_, const protozero::data_view& view) + : data(std::move(data_)), + layer(view) {} std::size_t VectorTileLayer::featureCount() const { return layer.featureCount(); @@ -74,8 +70,8 @@ std::string VectorTileLayer::getName() const { return layer.getName(); } -VectorTileData::VectorTileData(std::shared_ptr data_) : data(std::move(data_)) { -} +VectorTileData::VectorTileData(std::shared_ptr data_) + : data(std::move(data_)) {} std::unique_ptr VectorTileData::clone() const { return std::make_unique(data); @@ -83,8 +79,9 @@ std::unique_ptr VectorTileData::clone() const { std::unique_ptr VectorTileData::getLayer(const std::string& name) const { if (!parsed) { - // We're parsing this lazily so that we can construct VectorTileData objects on the main - // thread without incurring the overhead of parsing immediately. + // We're parsing this lazily so that we can construct VectorTileData + // objects on the main thread without incurring the overhead of parsing + // immediately. layers = mapbox::vector_tile::buffer(*data).getLayers(); parsed = true; } diff --git a/src/mbgl/util/bounding_volumes.cpp b/src/mbgl/util/bounding_volumes.cpp index b8e1d2d8d84..742a33134d6 100644 --- a/src/mbgl/util/bounding_volumes.cpp +++ b/src/mbgl/util/bounding_volumes.cpp @@ -33,9 +33,13 @@ Point ProjectPointsToAxis(const std::array& points, const vec3& namespace util { -AABB::AABB() : min({{0, 0, 0}}), max({{0, 0, 0}}) {} +AABB::AABB() + : min({{0, 0, 0}}), + max({{0, 0, 0}}) {} -AABB::AABB(const vec3& min_, const vec3& max_) : min(min_), max(max_) {} +AABB::AABB(const vec3& min_, const vec3& max_) + : min(min_), + max(max_) {} vec3 AABB::closestPoint(const vec3& point) const { return {{std::max(std::min(max[0], point[0]), min[0]), @@ -60,8 +64,9 @@ AABB AABB::quadrant(int idx) const { const double xCenter = 0.5 * (max[0] + min[0]); const double yCenter = 0.5 * (max[1] + min[1]); - // This aabb is split into 4 quadrants. For each axis define in which side of the split "idx" is - // The result for indices 0, 1, 2, 3 is: { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } + // This aabb is split into 4 quadrants. For each axis define in which side + // of the split "idx" is The result for indices 0, 1, 2, 3 is: { 0, 0 }, { + // 1, 0 }, { 0, 1 }, { 1, 1 } const std::array xSplit = {{0, 1, 0, 1}}; const std::array ySplit = {{0, 0, 1, 1}}; @@ -102,15 +107,17 @@ enum { }; Frustum::Frustum(const std::array& points_, const std::array& planes_) - : points(points_), planes(planes_) { + : points(points_), + planes(planes_) { const Point xBounds = ProjectPointsToAxis(points, {{0, 0, 0}}, {{1, 0, 0}}); const Point yBounds = ProjectPointsToAxis(points, {{0, 0, 0}}, {{0, 1, 0}}); const Point zBounds = ProjectPointsToAxis(points, {{0, 0, 0}}, {{0, 0, 1}}); bounds = AABB({{xBounds.x, yBounds.x, zBounds.x}}, {{xBounds.y, yBounds.y, zBounds.y}}); - // Precompute a set of separating axis candidates for precise intersection tests. - // Remaining axes not covered in basic intersection tests are: axis[] = (edges of aabb) x (edges of frustum) + // Precompute a set of separating axis candidates for precise intersection + // tests. Remaining axes not covered in basic intersection tests are: axis[] + // = (edges of aabb) x (edges of frustum) std::array frustumEdges = {{vec3Sub(points[near_br], points[near_bl]), vec3Sub(points[near_tl], points[near_bl]), vec3Sub(points[far_tl], points[near_tl]), @@ -252,4 +259,4 @@ IntersectionResult Frustum::intersectsPrecise(const AABB& aabb, bool edgeCasesOn } } // namespace util -} // namespace mbgl \ No newline at end of file +} // namespace mbgl diff --git a/src/mbgl/util/camera.cpp b/src/mbgl/util/camera.cpp index e6a85dcfc0d..bc009e6385e 100644 --- a/src/mbgl/util/camera.cpp +++ b/src/mbgl/util/camera.cpp @@ -89,7 +89,8 @@ static void updateTransform(mat4& transform, const vec3& position) { getColumn(transform, 3)[2] = position[2]; } -Camera::Camera() : orientation(Quaternion::identity) { +Camera::Camera() + : orientation(Quaternion::identity) { matrix::identity(transform); } diff --git a/src/mbgl/util/camera.hpp b/src/mbgl/util/camera.hpp index 231c1b6a911..a930c4fc0d4 100644 --- a/src/mbgl/util/camera.hpp +++ b/src/mbgl/util/camera.hpp @@ -30,8 +30,9 @@ class Camera { void setOrientation(const Quaternion& orientation_); void setPosition(const vec3& position); - // Computes orientation using forward and up vectors of the provided coordinate frame. - // Only bearing and pitch components will be used. Does not return a value if input is invalid + // Computes orientation using forward and up vectors of the provided + // coordinate frame. Only bearing and pitch components will be used. Does + // not return a value if input is invalid static std::optional orientationFromFrame(const vec3& forward, const vec3& up); private: diff --git a/src/mbgl/util/chrono.cpp b/src/mbgl/util/chrono.cpp index 03e97eedf58..d815771e77d 100644 --- a/src/mbgl/util/chrono.cpp +++ b/src/mbgl/util/chrono.cpp @@ -15,21 +15,28 @@ namespace mbgl { namespace util { static const char *week[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; -static const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; +static const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; std::string rfc1123(Timestamp timestamp) { std::time_t time = std::chrono::system_clock::to_time_t(timestamp); std::tm info; _gmtime(&time, &info); - // Buffer size 30 is OK assuming the year has 4 digits. However, In theory, it might have - // more digits. Under gcc 8.3.0 with -Os optimization flag, there is compiler warning - // complaining about the buffer size might be too small. Inceasing the buffer to 32 fixes - // the warning. + // Buffer size 30 is OK assuming the year has 4 digits. However, In theory, + // it might have more digits. Under gcc 8.3.0 with -Os optimization flag, + // there is compiler warning complaining about the buffer size might be too + // small. Inceasing the buffer to 32 fixes the warning. char buffer[32]; - snprintf(buffer, 32, "%s, %02d %s %4d %02d:%02d:%02d GMT", week[info.tm_wday], info.tm_mday, - months[info.tm_mon], 1900 + info.tm_year, info.tm_hour, info.tm_min, info.tm_sec); + snprintf(buffer, + 32, + "%s, %02d %s %4d %02d:%02d:%02d GMT", + week[info.tm_wday], + info.tm_mday, + months[info.tm_mon], + 1900 + info.tm_year, + info.tm_hour, + info.tm_min, + info.tm_sec); return buffer; } @@ -42,7 +49,7 @@ std::string iso8601(Timestamp timestamp) { return buffer; } -Timestamp parseTimestamp(const char* timestamp) { +Timestamp parseTimestamp(const char *timestamp) { return std::chrono::time_point_cast(std::chrono::system_clock::from_time_t(parse_date(timestamp))); } diff --git a/src/mbgl/util/client_options.cpp b/src/mbgl/util/client_options.cpp index c5651278d65..0ce667d595e 100644 --- a/src/mbgl/util/client_options.cpp +++ b/src/mbgl/util/client_options.cpp @@ -9,12 +9,20 @@ class ClientOptions::Impl { }; // These requires the complete type of Impl. -ClientOptions::ClientOptions() : impl_(std::make_unique()) {} +ClientOptions::ClientOptions() + : impl_(std::make_unique()) {} ClientOptions::~ClientOptions() = default; ClientOptions::ClientOptions(ClientOptions&&) noexcept = default; -ClientOptions::ClientOptions(const ClientOptions& other) : impl_(std::make_unique(*other.impl_)) {} -ClientOptions& ClientOptions::operator=(const ClientOptions& other) {impl_ = std::make_unique(*other.impl_); return *this; } -ClientOptions& ClientOptions::operator=(ClientOptions&& options) {swap(impl_, options.impl_); return *this; } +ClientOptions::ClientOptions(const ClientOptions& other) + : impl_(std::make_unique(*other.impl_)) {} +ClientOptions& ClientOptions::operator=(const ClientOptions& other) { + impl_ = std::make_unique(*other.impl_); + return *this; +} +ClientOptions& ClientOptions::operator=(ClientOptions&& options) { + swap(impl_, options.impl_); + return *this; +} ClientOptions ClientOptions::clone() const { return ClientOptions(*this); @@ -38,4 +46,4 @@ const std::string& ClientOptions::version() const { return impl_->version; } -} // namespace mbgl +} // namespace mbgl diff --git a/src/mbgl/util/color.cpp b/src/mbgl/util/color.cpp index a94d4800b38..44fb65f732a 100644 --- a/src/mbgl/util/color.cpp +++ b/src/mbgl/util/color.cpp @@ -11,12 +11,7 @@ std::optional Color::parse(const std::string& s) { // Premultiply the color. if (css_color) { const float factor = css_color->a / 255; - return {{ - css_color->r * factor, - css_color->g * factor, - css_color->b * factor, - css_color->a - }}; + return {{css_color->r * factor, css_color->g * factor, css_color->b * factor, css_color->a}}; } else { return {}; } @@ -24,16 +19,13 @@ std::optional Color::parse(const std::string& s) { std::string Color::stringify() const { std::array array = toArray(); - return "rgba(" + - util::toString(array[0]) + "," + - util::toString(array[1]) + "," + - util::toString(array[2]) + "," + - util::toString(array[3]) + ")"; + return "rgba(" + util::toString(array[0]) + "," + util::toString(array[1]) + "," + util::toString(array[2]) + "," + + util::toString(array[3]) + ")"; } std::array Color::toArray() const { if (a == 0) { - return {{ 0, 0, 0, 0 }}; + return {{0, 0, 0, 0}}; } else { return {{ r * 255 / a, @@ -45,7 +37,10 @@ std::array Color::toArray() const { } mbgl::Value Color::toObject() const { - return mapbox::base::ValueObject{{"r", static_cast(r)}, {"g", static_cast(g)}, {"b", static_cast(b)}, {"a", static_cast(a)}}; + return mapbox::base::ValueObject{{"r", static_cast(r)}, + {"g", static_cast(g)}, + {"b", static_cast(b)}, + {"a", static_cast(a)}}; } mbgl::Value Color::serialize() const { diff --git a/src/mbgl/util/default_style.cpp b/src/mbgl/util/default_style.cpp index b1f2d2f4326..2eb455aee4c 100644 --- a/src/mbgl/util/default_style.cpp +++ b/src/mbgl/util/default_style.cpp @@ -3,9 +3,10 @@ namespace mbgl { namespace util { -DefaultStyle::DefaultStyle(std::string url_, std::string name_, int version_): - url(url_), name(name_), currentVersion(version_) - {} +DefaultStyle::DefaultStyle(std::string url_, std::string name_, int version_) + : url(url_), + name(name_), + currentVersion(version_) {} const std::string& DefaultStyle::getUrl() const { return url; diff --git a/src/mbgl/util/event.cpp b/src/mbgl/util/event.cpp index 0c08d72a8cf..0cc08a383a4 100644 --- a/src/mbgl/util/event.cpp +++ b/src/mbgl/util/event.cpp @@ -3,33 +3,35 @@ namespace mbgl { -MBGL_DEFINE_ENUM(EventSeverity, { - { EventSeverity::Debug, "DEBUG" }, - { EventSeverity::Info, "INFO" }, - { EventSeverity::Warning, "WARNING" }, - { EventSeverity::Error, "ERROR" }, - { EventSeverity(-1), "UNKNOWN" }, -}); +MBGL_DEFINE_ENUM(EventSeverity, + { + {EventSeverity::Debug, "DEBUG"}, + {EventSeverity::Info, "INFO"}, + {EventSeverity::Warning, "WARNING"}, + {EventSeverity::Error, "ERROR"}, + {EventSeverity(-1), "UNKNOWN"}, + }); -MBGL_DEFINE_ENUM(Event, { - { Event::General, "General" }, - { Event::Setup, "Setup" }, - { Event::Shader, "Shader" }, - { Event::ParseStyle, "ParseStyle" }, - { Event::ParseTile, "ParseTile" }, - { Event::Render, "Render" }, - { Event::Style, "Style" }, - { Event::Database, "Database" }, - { Event::HttpRequest, "HttpRequest" }, - { Event::Sprite, "Sprite" }, - { Event::Image, "Image" }, - { Event::OpenGL, "OpenGL" }, - { Event::JNI, "JNI" }, - { Event::Android, "Android" }, - { Event::Crash, "Crash" }, - { Event::Glyph, "Glyph" }, - { Event::Timing, "Timing" }, - { Event(-1), "Unknown" }, -}); +MBGL_DEFINE_ENUM(Event, + { + {Event::General, "General"}, + {Event::Setup, "Setup"}, + {Event::Shader, "Shader"}, + {Event::ParseStyle, "ParseStyle"}, + {Event::ParseTile, "ParseTile"}, + {Event::Render, "Render"}, + {Event::Style, "Style"}, + {Event::Database, "Database"}, + {Event::HttpRequest, "HttpRequest"}, + {Event::Sprite, "Sprite"}, + {Event::Image, "Image"}, + {Event::OpenGL, "OpenGL"}, + {Event::JNI, "JNI"}, + {Event::Android, "Android"}, + {Event::Crash, "Crash"}, + {Event::Glyph, "Glyph"}, + {Event::Timing, "Timing"}, + {Event(-1), "Unknown"}, + }); } // namespace mbgl diff --git a/src/mbgl/util/geo.cpp b/src/mbgl/util/geo.cpp index 649bd8f7d38..0f5d10c5027 100644 --- a/src/mbgl/util/geo.cpp +++ b/src/mbgl/util/geo.cpp @@ -22,18 +22,17 @@ double lon_(const uint8_t z, const int64_t x) { } // end namespace -LatLng::LatLng(const CanonicalTileID& id) : lat(lat_(id.z, id.y)), lon(lon_(id.z, id.x)) { -} +LatLng::LatLng(const CanonicalTileID& id) + : lat(lat_(id.z, id.y)), + lon(lon_(id.z, id.x)) {} LatLng::LatLng(const UnwrappedTileID& id) : lat(lat_(id.canonical.z, id.canonical.y)), - lon(lon_(id.canonical.z, id.canonical.x) + id.wrap * util::DEGREES_MAX) { -} + lon(lon_(id.canonical.z, id.canonical.x) + id.wrap * util::DEGREES_MAX) {} LatLngBounds::LatLngBounds(const CanonicalTileID& id) - : sw({ lat_(id.z, id.y + 1), lon_(id.z, id.x) }), - ne({ lat_(id.z, id.y), lon_(id.z, id.x + 1) }) { -} + : sw({lat_(id.z, id.y + 1), lon_(id.z, id.x)}), + ne({lat_(id.z, id.y), lon_(id.z, id.x + 1)}) {} bool LatLngBounds::contains(const CanonicalTileID& tileID) const { return util::TileRange::fromLatLngBounds(*this, tileID.z).contains(tileID); @@ -50,7 +49,7 @@ bool LatLngBounds::contains(const LatLngBounds& area, LatLng::WrapMode wrap /*= } bool containsUnwrapped = area.east() <= east() && area.west() >= west(); - if(containsUnwrapped) { + if (containsUnwrapped) { return true; } else if (wrap == LatLng::Wrapped) { LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); @@ -78,15 +77,11 @@ bool LatLngBounds::intersects(const LatLngBounds area, LatLng::WrapMode wrap /*= LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); LatLngBounds other(area.sw.wrapped(), area.ne.wrapped()); if (crossesAntimeridian()) { - return area.crossesAntimeridian() || - other.east() > wrapped.west() || - other.west() < wrapped.east(); - } else if (other.crossesAntimeridian()){ - return other.east() > wrapped.west() || - other.west() < wrapped.east(); + return area.crossesAntimeridian() || other.east() > wrapped.west() || other.west() < wrapped.east(); + } else if (other.crossesAntimeridian()) { + return other.east() > wrapped.west() || other.west() < wrapped.east(); } else { - return other.east() > wrapped.west() && - other.west() < wrapped.east(); + return other.east() > wrapped.west() && other.west() < wrapped.east(); } } return false; @@ -108,7 +103,7 @@ LatLng LatLngBounds::constrain(const LatLng& p) const { lng = util::clamp(lng, west(), east()); } - return LatLng { lat, lng }; + return LatLng{lat, lng}; } bool LatLngBounds::containsLatitude(double latitude) const { diff --git a/src/mbgl/util/geometry_util.cpp b/src/mbgl/util/geometry_util.cpp index f354359f7f5..86079cf15bc 100644 --- a/src/mbgl/util/geometry_util.cpp +++ b/src/mbgl/util/geometry_util.cpp @@ -43,7 +43,9 @@ bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2) template bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, const Point& d) { // a, b are end points for line segment1, c and d are end points for line segment2 - const auto perp = [](const Point& v1, const Point& v2) { return (v1.x * v2.y - v1.y * v2.x); }; + const auto perp = [](const Point& v1, const Point& v2) { + return (v1.x * v2.y - v1.y * v2.x); + }; // check if two segments are parallel or not // precondition is end point a, b is inside polygon, if line a->b is @@ -147,9 +149,7 @@ template bool segmentIntersectSegment(const Point& a, template bool rayIntersect(const Point& p, const Point& p1, const Point& p2); template bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2); template bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon& polygon); -template bool pointWithinPolygon(const Point& point, - const Polygon& polygon, - bool trueOnBoundary); +template bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary); template bool pointWithinPolygons(const Point& point, const MultiPolygon& polygons, bool trueOnBoundary); @@ -162,8 +162,6 @@ template bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, const Point& d); -template bool pointWithinPolygon(const Point& point, - const Polygon& polygon, - bool trueOnBoundary); +template bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary); } // namespace mbgl diff --git a/src/mbgl/util/grid_index.cpp b/src/mbgl/util/grid_index.cpp index cb197ef320a..fa24e33f31f 100644 --- a/src/mbgl/util/grid_index.cpp +++ b/src/mbgl/util/grid_index.cpp @@ -7,21 +7,19 @@ namespace mbgl { - template -GridIndex::GridIndex(const float width_, const float height_, const uint32_t cellSize_) : - width(width_), - height(height_), - xCellCount(static_cast(std::ceil(width / cellSize_))), - yCellCount(static_cast(std::ceil(height / cellSize_))), - xScale(xCellCount / width), - yScale(yCellCount / height) - { - assert(width > 0.0f); - assert(height > 0.0f); - boxCells.resize(xCellCount * yCellCount); - circleCells.resize(xCellCount * yCellCount); - } +GridIndex::GridIndex(const float width_, const float height_, const uint32_t cellSize_) + : width(width_), + height(height_), + xCellCount(static_cast(std::ceil(width / cellSize_))), + yCellCount(static_cast(std::ceil(height / cellSize_))), + xScale(xCellCount / width), + yScale(yCellCount / height) { + assert(width > 0.0f); + assert(height > 0.0f); + boxCells.resize(xCellCount * yCellCount); + circleCells.resize(xCellCount * yCellCount); +} template void GridIndex::insert(T&& t, const BBox& bbox) { @@ -132,10 +130,10 @@ typename GridIndex::BBox GridIndex::convertToBox(const BCircle& circle) co } template -void GridIndex::query(const BBox& queryBBox, std::function resultFn) const { +void GridIndex::query(const BBox& queryBBox, std::function resultFn) const { std::unordered_set seenBoxes; std::unordered_set seenCircles; - + if (noIntersection(queryBBox)) { return; } else if (completeIntersection(queryBBox)) { @@ -177,7 +175,7 @@ void GridIndex::query(const BBox& queryBBox, std::function::query(const BBox& queryBBox, std::function -void GridIndex::query(const BCircle& queryBCircle, std::function resultFn) const { +void GridIndex::query(const BCircle& queryBCircle, std::function resultFn) const { std::unordered_set seenBoxes; std::unordered_set seenCircles; @@ -242,7 +240,7 @@ void GridIndex::query(const BCircle& queryBCircle, std::function::convertToYCellCoord(const float y) const { template bool GridIndex::boxesCollide(const BBox& first, const BBox& second) const { - return first.min.x <= second.max.x && - first.min.y <= second.max.y && - first.max.x >= second.min.x && + return first.min.x <= second.max.x && first.min.y <= second.max.y && first.max.x >= second.min.x && first.max.y >= second.min.y; } @@ -315,7 +311,6 @@ bool GridIndex::empty() const { return boxElements.empty() && circleElements.empty(); } - template class GridIndex; } // namespace mbgl diff --git a/src/mbgl/util/grid_index.hpp b/src/mbgl/util/grid_index.hpp index daad43cb4ef..455ca19685f 100644 --- a/src/mbgl/util/grid_index.hpp +++ b/src/mbgl/util/grid_index.hpp @@ -14,33 +14,29 @@ namespace mbgl { namespace geometry { template -struct circle -{ +struct circle { using point_type = mapbox::geometry::point; constexpr circle(point_type const& center_, T const& radius_) - : center(center_), radius(radius_) - {} + : center(center_), + radius(radius_) {} point_type center; T radius; }; template -constexpr bool operator==(circle const& lhs, circle const& rhs) -{ +constexpr bool operator==(circle const& lhs, circle const& rhs) { return lhs.center == rhs.center && lhs.radius == rhs.radius; } template -constexpr bool operator!=(circle const& lhs, circle const& rhs) -{ +constexpr bool operator!=(circle const& lhs, circle const& rhs) { return lhs.center != rhs.center || lhs.radius != rhs.radius; } } // namespace geometry - /* GridIndex is a data structure for testing the intersection of circles and rectangles in a 2d plane. @@ -63,13 +59,13 @@ class GridIndex { void insert(T&& t, const BBox&); void insert(T&& t, const BCircle&); - + std::vector query(const BBox&) const; - std::vector> queryWithBoxes(const BBox&) const; - + std::vector> queryWithBoxes(const BBox&) const; + bool hitTest(const BBox&, std::optional> predicate = std::nullopt) const; bool hitTest(const BCircle&, std::optional> predicate = std::nullopt) const; - + bool empty() const; private: @@ -77,8 +73,8 @@ class GridIndex { bool completeIntersection(const BBox& queryBBox) const; BBox convertToBox(const BCircle& circle) const; - void query(const BBox&, std::function) const; - void query(const BCircle&, std::function) const; + void query(const BBox&, std::function) const; + void query(const BCircle&, std::function) const; std::size_t convertToXCellCoord(float x) const; std::size_t convertToYCellCoord(float y) const; @@ -89,7 +85,7 @@ class GridIndex { const float width; const float height; - + const std::size_t xCellCount; const std::size_t yCellCount; const double xScale; @@ -97,10 +93,9 @@ class GridIndex { std::vector> boxElements; std::vector> circleElements; - + std::vector> boxCells; std::vector> circleCells; - }; } // namespace mbgl diff --git a/src/mbgl/util/hash.hpp b/src/mbgl/util/hash.hpp index 89aba00f72f..cb92fe9bed6 100644 --- a/src/mbgl/util/hash.hpp +++ b/src/mbgl/util/hash.hpp @@ -15,7 +15,7 @@ void hash_combine(std::size_t& seed, const T& v) { template std::size_t hash(Args&&... args) { std::size_t seed = 0; - ignore({ (hash_combine(seed, args), 0)... }); + ignore({(hash_combine(seed, args), 0)...}); return seed; } diff --git a/src/mbgl/util/http_header.cpp b/src/mbgl/util/http_header.cpp index 89a3c016021..dbff7a275a0 100644 --- a/src/mbgl/util/http_header.cpp +++ b/src/mbgl/util/http_header.cpp @@ -5,7 +5,7 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable: 4828) +#pragma warning(disable : 4828) #endif #include @@ -24,11 +24,13 @@ CacheControl CacheControl::parse(const std::string& value) { namespace phoenix = boost::phoenix; CacheControl result; - qi::phrase_parse(value.begin(), value.end(), ( - (qi::lit("must-revalidate") [ phoenix::ref(result.mustRevalidate) = true ]) | - (qi::lit("max-age") >> '=' >> qi::ulong_long [ phoenix::ref(result.maxAge) = qi::_1 ]) | - (*(('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"') | (qi::char_ - '"' - ','))) - ) % ',', qi::ascii::space); + qi::phrase_parse(value.begin(), + value.end(), + ((qi::lit("must-revalidate")[phoenix::ref(result.mustRevalidate) = true]) | + (qi::lit("max-age") >> '=' >> qi::ulong_long[phoenix::ref(result.maxAge) = qi::_1]) | + (*(('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"') | (qi::char_ - '"' - ',')))) % + ',', + qi::ascii::space); return result; } diff --git a/src/mbgl/util/http_timeout.cpp b/src/mbgl/util/http_timeout.cpp index 07d9b79f3fc..647c65a4d37 100644 --- a/src/mbgl/util/http_timeout.cpp +++ b/src/mbgl/util/http_timeout.cpp @@ -7,8 +7,9 @@ namespace mbgl { namespace http { -Duration errorRetryTimeout(Response::Error::Reason failedRequestReason, uint32_t failedRequests, std::optional retryAfter) { - +Duration errorRetryTimeout(Response::Error::Reason failedRequestReason, + uint32_t failedRequests, + std::optional retryAfter) { if (failedRequestReason == Response::Error::Reason::Server) { // Retry after one second three times, then start exponential backoff. return Seconds(failedRequests <= 3 ? 1 : 1u << std::min(failedRequests - 3, 31u)); diff --git a/src/mbgl/util/http_timeout.hpp b/src/mbgl/util/http_timeout.hpp index 23db9300fa4..09f7e060273 100644 --- a/src/mbgl/util/http_timeout.hpp +++ b/src/mbgl/util/http_timeout.hpp @@ -8,7 +8,9 @@ namespace mbgl { namespace http { -Duration errorRetryTimeout(Response::Error::Reason failedRequestReason, uint32_t failedRequests, std::optional retryAfter = std::nullopt); +Duration errorRetryTimeout(Response::Error::Reason failedRequestReason, + uint32_t failedRequests, + std::optional retryAfter = std::nullopt); Duration expirationTimeout(std::optional expires, uint32_t expiredRequests); diff --git a/src/mbgl/util/i18n.cpp b/src/mbgl/util/i18n.cpp index 246f918f01f..95e06462ad9 100644 --- a/src/mbgl/util/i18n.cpp +++ b/src/mbgl/util/i18n.cpp @@ -12,8 +12,10 @@ namespace { @param first The first codepoint in the block, inclusive. @param last The last codepoint in the block, inclusive. */ -#define DEFINE_IS_IN_UNICODE_BLOCK(name, first, last) \ - inline bool isIn##name(char16_t codepoint) { return codepoint >= (first) && codepoint <= (last); } +#define DEFINE_IS_IN_UNICODE_BLOCK(name, first, last) \ + inline bool isIn##name(char16_t codepoint) { \ + return codepoint >= (first) && codepoint <= (last); \ + } // The following table comes from . // Keep it synchronized with . @@ -86,8 +88,8 @@ DEFINE_IS_IN_UNICODE_BLOCK(UnifiedCanadianAboriginalSyllabicsExtended, 0x18B0, 0 // DEFINE_IS_IN_UNICODE_BLOCK(VedicExtensions, 0x1CD0, 0x1CFF) // DEFINE_IS_IN_UNICODE_BLOCK(PhoneticExtensions, 0x1D00, 0x1D7F) // DEFINE_IS_IN_UNICODE_BLOCK(PhoneticExtensionsSupplement, 0x1D80, 0x1DBF) -// DEFINE_IS_IN_UNICODE_BLOCK(CombiningDiacriticalMarksSupplement, 0x1DC0, 0x1DFF) -// DEFINE_IS_IN_UNICODE_BLOCK(LatinExtendedAdditional, 0x1E00, 0x1EFF) +// DEFINE_IS_IN_UNICODE_BLOCK(CombiningDiacriticalMarksSupplement, 0x1DC0, +// 0x1DFF) DEFINE_IS_IN_UNICODE_BLOCK(LatinExtendedAdditional, 0x1E00, 0x1EFF) // DEFINE_IS_IN_UNICODE_BLOCK(GreekExtended, 0x1F00, 0x1FFF) DEFINE_IS_IN_UNICODE_BLOCK(GeneralPunctuation, 0x2000, 0x206F) // DEFINE_IS_IN_UNICODE_BLOCK(SuperscriptsandSubscripts, 0x2070, 0x209F) @@ -260,16 +262,16 @@ DEFINE_IS_IN_UNICODE_BLOCK(HalfwidthandFullwidthForms, 0xFF00, 0xFFEF) // DEFINE_IS_IN_UNICODE_BLOCK(CuneiformNumbersandPunctuation, 0x12400, 0x1247F) // DEFINE_IS_IN_UNICODE_BLOCK(EarlyDynasticCuneiform, 0x12480, 0x1254F) // DEFINE_IS_IN_UNICODE_BLOCK(EgyptianHieroglyphs, 0x13000, 0x1342F) -// DEFINE_IS_IN_UNICODE_BLOCK(EgyptianHieroglyphFormatControls, 0x13430, 0x1343F) -// DEFINE_IS_IN_UNICODE_BLOCK(AnatolianHieroglyphs, 0x14400, 0x1467F) +// DEFINE_IS_IN_UNICODE_BLOCK(EgyptianHieroglyphFormatControls, 0x13430, +// 0x1343F) DEFINE_IS_IN_UNICODE_BLOCK(AnatolianHieroglyphs, 0x14400, 0x1467F) // DEFINE_IS_IN_UNICODE_BLOCK(BamumSupplement, 0x16800, 0x16A3F) // DEFINE_IS_IN_UNICODE_BLOCK(Mro, 0x16A40, 0x16A6F) // DEFINE_IS_IN_UNICODE_BLOCK(BassaVah, 0x16AD0, 0x16AFF) // DEFINE_IS_IN_UNICODE_BLOCK(PahawhHmong, 0x16B00, 0x16B8F) // DEFINE_IS_IN_UNICODE_BLOCK(Medefaidrin, 0x16E40, 0x16E9F) // DEFINE_IS_IN_UNICODE_BLOCK(Miao, 0x16F00, 0x16F9F) -// DEFINE_IS_IN_UNICODE_BLOCK(IdeographicSymbolsandPunctuation, 0x16FE0, 0x16FFF) -// DEFINE_IS_IN_UNICODE_BLOCK(Tangut, 0x17000, 0x187FF) +// DEFINE_IS_IN_UNICODE_BLOCK(IdeographicSymbolsandPunctuation, 0x16FE0, +// 0x16FFF) DEFINE_IS_IN_UNICODE_BLOCK(Tangut, 0x17000, 0x187FF) // DEFINE_IS_IN_UNICODE_BLOCK(TangutComponents, 0x18800, 0x18AFF) // DEFINE_IS_IN_UNICODE_BLOCK(KanaSupplement, 0x1B000, 0x1B0FF) // DEFINE_IS_IN_UNICODE_BLOCK(KanaExtendedA, 0x1B100, 0x1B12F) @@ -292,51 +294,46 @@ DEFINE_IS_IN_UNICODE_BLOCK(HalfwidthandFullwidthForms, 0xFF00, 0xFFEF) // DEFINE_IS_IN_UNICODE_BLOCK(Adlam, 0x1E900, 0x1E95F) // DEFINE_IS_IN_UNICODE_BLOCK(IndicSiyaqNumbers, 0x1EC70, 0x1ECBF) // DEFINE_IS_IN_UNICODE_BLOCK(OttomanSiyaqNumbers, 0x1ED00, 0x1ED4F) -// DEFINE_IS_IN_UNICODE_BLOCK(ArabicMathematicalAlphabeticSymbols, 0x1EE00, 0x1EEFF) -// DEFINE_IS_IN_UNICODE_BLOCK(MahjongTiles, 0x1F000, 0x1F02F) +// DEFINE_IS_IN_UNICODE_BLOCK(ArabicMathematicalAlphabeticSymbols, 0x1EE00, +// 0x1EEFF) DEFINE_IS_IN_UNICODE_BLOCK(MahjongTiles, 0x1F000, 0x1F02F) // DEFINE_IS_IN_UNICODE_BLOCK(DominoTiles, 0x1F030, 0x1F09F) // DEFINE_IS_IN_UNICODE_BLOCK(PlayingCards, 0x1F0A0, 0x1F0FF) // DEFINE_IS_IN_UNICODE_BLOCK(EnclosedAlphanumericSupplement, 0x1F100, 0x1F1FF) // DEFINE_IS_IN_UNICODE_BLOCK(EnclosedIdeographicSupplement, 0x1F200, 0x1F2FF) -// DEFINE_IS_IN_UNICODE_BLOCK(MiscellaneousSymbolsandPictographs, 0x1F300, 0x1F5FF) -// DEFINE_IS_IN_UNICODE_BLOCK(Emoticons, 0x1F600, 0x1F64F) +// DEFINE_IS_IN_UNICODE_BLOCK(MiscellaneousSymbolsandPictographs, 0x1F300, +// 0x1F5FF) DEFINE_IS_IN_UNICODE_BLOCK(Emoticons, 0x1F600, 0x1F64F) // DEFINE_IS_IN_UNICODE_BLOCK(OrnamentalDingbats, 0x1F650, 0x1F67F) // DEFINE_IS_IN_UNICODE_BLOCK(TransportandMapSymbols, 0x1F680, 0x1F6FF) // DEFINE_IS_IN_UNICODE_BLOCK(AlchemicalSymbols, 0x1F700, 0x1F77F) // DEFINE_IS_IN_UNICODE_BLOCK(GeometricShapesExtended, 0x1F780, 0x1F7FF) // DEFINE_IS_IN_UNICODE_BLOCK(SupplementalArrowsC, 0x1F800, 0x1F8FF) -// DEFINE_IS_IN_UNICODE_BLOCK(SupplementalSymbolsandPictographs, 0x1F900, 0x1F9FF) -// DEFINE_IS_IN_UNICODE_BLOCK(ChessSymbols, 0x1FA00, 0x1FA6F) +// DEFINE_IS_IN_UNICODE_BLOCK(SupplementalSymbolsandPictographs, 0x1F900, +// 0x1F9FF) DEFINE_IS_IN_UNICODE_BLOCK(ChessSymbols, 0x1FA00, 0x1FA6F) // DEFINE_IS_IN_UNICODE_BLOCK(SymbolsandPictographsExtendedA, 0x1FA70, 0x1FAFF) // DEFINE_IS_IN_UNICODE_BLOCK(CJKUnifiedIdeographsExtensionB, 0x20000, 0x2A6DF) // DEFINE_IS_IN_UNICODE_BLOCK(CJKUnifiedIdeographsExtensionC, 0x2A700, 0x2B73F) // DEFINE_IS_IN_UNICODE_BLOCK(CJKUnifiedIdeographsExtensionD, 0x2B740, 0x2B81F) // DEFINE_IS_IN_UNICODE_BLOCK(CJKUnifiedIdeographsExtensionE, 0x2B820, 0x2CEAF) // DEFINE_IS_IN_UNICODE_BLOCK(CJKUnifiedIdeographsExtensionF, 0x2CEB0, 0x2EBEF) -// DEFINE_IS_IN_UNICODE_BLOCK(CJKCompatibilityIdeographsSupplement, 0x2F800, 0x2FA1F) -// DEFINE_IS_IN_UNICODE_BLOCK(Tags, 0xE0000, 0xE007F) +// DEFINE_IS_IN_UNICODE_BLOCK(CJKCompatibilityIdeographsSupplement, 0x2F800, +// 0x2FA1F) DEFINE_IS_IN_UNICODE_BLOCK(Tags, 0xE0000, 0xE007F) // DEFINE_IS_IN_UNICODE_BLOCK(VariationSelectorsSupplement, 0xE0100, 0xE01EF) // DEFINE_IS_IN_UNICODE_BLOCK(SupplementaryPrivateUseAreaA, 0xF0000, 0xFFFFF) // DEFINE_IS_IN_UNICODE_BLOCK(SupplementaryPrivateUseAreaB, 0x100000, 0x10FFFF) MAPBOX_ETERNAL_CONSTEXPR const auto verticalPunctuation = mapbox::eternal::map({ - { u'!', u'︕' }, { u'#', u'#' }, { u'$', u'$' }, { u'%', u'%' }, { u'&', u'&' }, - { u'(', u'︵' }, { u')', u'︶' }, { u'*', u'*' }, { u'+', u'+' }, { u',', u'︐' }, - { u'-', u'︲' }, { u'.', u'・' }, { u'/', u'/' }, { u':', u'︓' }, { u';', u'︔' }, - { u'<', u'︿' }, { u'=', u'=' }, { u'>', u'﹀' }, { u'?', u'︖' }, { u'@', u'@' }, - { u'[', u'﹇' }, { u'\\', u'\' }, { u']', u'﹈' }, { u'^', u'^' }, { u'_', u'︳' }, - { u'`', u'`' }, { u'{', u'︷' }, { u'|', u'―' }, { u'}', u'︸' }, { u'~', u'~' }, - { u'¢', u'¢' }, { u'£', u'£' }, { u'¥', u'¥' }, { u'¦', u'¦' }, { u'¬', u'¬' }, - { u'¯', u' ̄' }, { u'–', u'︲' }, { u'—', u'︱' }, { u'‘', u'﹃' }, { u'’', u'﹄' }, - { u'“', u'﹁' }, { u'”', u'﹂' }, { u'…', u'︙' }, { u'‧', u'・' }, { u'₩', u'₩' }, - { u'、', u'︑' }, { u'。', u'︒' }, { u'〈', u'︿' }, { u'〉', u'﹀' }, { u'《', u'︽' }, - { u'》', u'︾' }, { u'「', u'﹁' }, { u'」', u'﹂' }, { u'『', u'﹃' }, { u'』', u'﹄' }, - { u'【', u'︻' }, { u'】', u'︼' }, { u'〔', u'︹' }, { u'〕', u'︺' }, { u'〖', u'︗' }, - { u'〗', u'︘' }, { u'!', u'︕' }, { u'(', u'︵' }, { u')', u'︶' }, { u',', u'︐' }, - { u'-', u'︲' }, { u'.', u'・' }, { u':', u'︓' }, { u';', u'︔' }, { u'<', u'︿' }, - { u'>', u'﹀' }, { u'?', u'︖' }, { u'[', u'﹇' }, { u']', u'﹈' }, { u'_', u'︳' }, - { u'{', u'︷' }, { u'|', u'―' }, { u'}', u'︸' }, { u'⦅', u'︵' }, { u'⦆', u'︶' }, - { u'。', u'︒' }, { u'「', u'﹁' }, { u'」', u'﹂' }, + {u'!', u'︕'}, {u'#', u'#'}, {u'$', u'$'}, {u'%', u'%'}, {u'&', u'&'}, {u'(', u'︵'}, {u')', u'︶'}, + {u'*', u'*'}, {u'+', u'+'}, {u',', u'︐'}, {u'-', u'︲'}, {u'.', u'・'}, {u'/', u'/'}, {u':', u'︓'}, + {u';', u'︔'}, {u'<', u'︿'}, {u'=', u'='}, {u'>', u'﹀'}, {u'?', u'︖'}, {u'@', u'@'}, {u'[', u'﹇'}, + {u'\\', u'\'}, {u']', u'﹈'}, {u'^', u'^'}, {u'_', u'︳'}, {u'`', u'`'}, {u'{', u'︷'}, {u'|', u'―'}, + {u'}', u'︸'}, {u'~', u'~'}, {u'¢', u'¢'}, {u'£', u'£'}, {u'¥', u'¥'}, {u'¦', u'¦'}, {u'¬', u'¬'}, + {u'¯', u' ̄'}, {u'–', u'︲'}, {u'—', u'︱'}, {u'‘', u'﹃'}, {u'’', u'﹄'}, {u'“', u'﹁'}, {u'”', u'﹂'}, + {u'…', u'︙'}, {u'‧', u'・'}, {u'₩', u'₩'}, {u'、', u'︑'}, {u'。', u'︒'}, {u'〈', u'︿'}, {u'〉', u'﹀'}, + {u'《', u'︽'}, {u'》', u'︾'}, {u'「', u'﹁'}, {u'」', u'﹂'}, {u'『', u'﹃'}, {u'』', u'﹄'}, {u'【', u'︻'}, + {u'】', u'︼'}, {u'〔', u'︹'}, {u'〕', u'︺'}, {u'〖', u'︗'}, {u'〗', u'︘'}, {u'!', u'︕'}, {u'(', u'︵'}, + {u')', u'︶'}, {u',', u'︐'}, {u'-', u'︲'}, {u'.', u'・'}, {u':', u'︓'}, {u';', u'︔'}, {u'<', u'︿'}, + {u'>', u'﹀'}, {u'?', u'︖'}, {u'[', u'﹇'}, {u']', u'﹈'}, {u'_', u'︳'}, {u'{', u'︷'}, {u'|', u'―'}, + {u'}', u'︸'}, {u'⦅', u'︵'}, {u'⦆', u'︶'}, {u'。', u'︒'}, {u'「', u'﹁'}, {u'」', u'﹂'}, }); } // namespace @@ -358,11 +355,13 @@ bool allowsWordBreaking(char16_t chr) { || chr == 0xb7 /* middle dot */ || chr == 0x200b /* zero-width space */ || chr == 0x2010 /* hyphen */ - || chr == 0x2013 /* en dash */); + || chr == 0x2013 /* en dash */ + ); } bool charAllowsLetterSpacing(char16_t chr) { - return !(isInArabic(chr) || isInArabicSupplement(chr) || isInArabicExtendedA(chr) || isInArabicPresentationFormsA(chr) || isInArabicPresentationFormsB(chr)); + return !(isInArabic(chr) || isInArabicSupplement(chr) || isInArabicExtendedA(chr) || + isInArabicPresentationFormsA(chr) || isInArabicPresentationFormsB(chr)); } bool allowsLetterSpacing(const std::u16string& string) { @@ -380,22 +379,18 @@ bool allowsIdeographicBreaking(const std::u16string& string) { bool allowsIdeographicBreaking(char16_t chr) { // Allow U+2027 "Interpunct" for hyphenation of Chinese words - if (chr == 0x2027) - return true; + if (chr == 0x2027) return true; // Return early for characters outside all ideographic ranges. - if (chr < 0x2E80) - return false; + if (chr < 0x2E80) return false; return (isInBopomofo(chr) || isInBopomofoExtended(chr) || isInCJKCompatibility(chr) || - isInCJKCompatibilityForms(chr) || isInCJKCompatibilityIdeographs(chr) || - isInCJKRadicalsSupplement(chr) || isInCJKStrokes(chr) || - isInCJKSymbolsandPunctuation(chr) || isInCJKUnifiedIdeographs(chr) || + isInCJKCompatibilityForms(chr) || isInCJKCompatibilityIdeographs(chr) || isInCJKRadicalsSupplement(chr) || + isInCJKStrokes(chr) || isInCJKSymbolsandPunctuation(chr) || isInCJKUnifiedIdeographs(chr) || isInCJKUnifiedIdeographsExtensionA(chr) || isInEnclosedCJKLettersandMonths(chr) || - isInHalfwidthandFullwidthForms(chr) || isInHiragana(chr) || - isInIdeographicDescriptionCharacters(chr) || isInKangxiRadicals(chr) || - isInKatakana(chr) || isInKatakanaPhoneticExtensions(chr) || isInVerticalForms(chr) || - isInYiRadicals(chr) || isInYiSyllables(chr)); + isInHalfwidthandFullwidthForms(chr) || isInHiragana(chr) || isInIdeographicDescriptionCharacters(chr) || + isInKangxiRadicals(chr) || isInKatakana(chr) || isInKatakanaPhoneticExtensions(chr) || + isInVerticalForms(chr) || isInYiRadicals(chr) || isInYiSyllables(chr)); // The following blocks also allow ideographic breaking; however, for other // reasons, Mapbox GL lacks support for codepoints beyond U+FFFF. @@ -415,8 +410,7 @@ bool allowsIdeographicBreaking(char16_t chr) { bool allowsFixedWidthGlyphGeneration(char16_t chr) { // Mirrors conservative set of characters used in glyph_manager.js/_tinySDF - return isInCJKUnifiedIdeographs(chr) || isInHangulSyllables(chr) - || isInKatakana(chr) || isInHiragana(chr); + return isInCJKUnifiedIdeographs(chr) || isInHangulSyllables(chr) || isInKatakana(chr) || isInHiragana(chr); } bool allowsVerticalWritingMode(const std::u16string& string) { @@ -437,52 +431,42 @@ bool allowsVerticalWritingMode(const std::u16string& string) { // “neutral” characters. bool hasUprightVerticalOrientation(char16_t chr) { - if (chr == u'˪' || chr == u'˫') - return true; + if (chr == u'˪' || chr == u'˫') return true; // Return early for characters outside all ranges whose characters remain // upright in vertical writing mode. - if (chr < 0x1100) - return false; + if (chr < 0x1100) return false; - if (isInBopomofo(chr) || isInBopomofoExtended(chr)) - return true; + if (isInBopomofo(chr) || isInBopomofoExtended(chr)) return true; if (isInCJKCompatibilityForms(chr)) { - if (!(chr >= u'﹉' && chr <= u'﹏')) - return true; + if (!(chr >= u'﹉' && chr <= u'﹏')) return true; } - if (isInCJKCompatibility(chr) || isInCJKCompatibilityIdeographs(chr) || - isInCJKRadicalsSupplement(chr) || isInCJKStrokes(chr)) + if (isInCJKCompatibility(chr) || isInCJKCompatibilityIdeographs(chr) || isInCJKRadicalsSupplement(chr) || + isInCJKStrokes(chr)) return true; if (isInCJKSymbolsandPunctuation(chr)) { - if (!(chr >= u'〈' && chr <= u'】') && !(chr >= u'〔' && chr <= u'〟') && chr != u'〰') - return true; + if (!(chr >= u'〈' && chr <= u'】') && !(chr >= u'〔' && chr <= u'〟') && chr != u'〰') return true; } if (isInCJKUnifiedIdeographs(chr) || isInCJKUnifiedIdeographsExtensionA(chr) || - isInEnclosedCJKLettersandMonths(chr) || isInHangulCompatibilityJamo(chr) || - isInHangulJamo(chr) || isInHangulJamoExtendedA(chr) || isInHangulJamoExtendedB(chr) || - isInHangulSyllables(chr) || isInHiragana(chr) || + isInEnclosedCJKLettersandMonths(chr) || isInHangulCompatibilityJamo(chr) || isInHangulJamo(chr) || + isInHangulJamoExtendedA(chr) || isInHangulJamoExtendedB(chr) || isInHangulSyllables(chr) || isInHiragana(chr) || isInIdeographicDescriptionCharacters(chr) || isInKanbun(chr) || isInKangxiRadicals(chr)) return true; if (isInKatakana(chr)) { - if (chr != u'ー') - return true; + if (chr != u'ー') return true; } - if (isInKatakanaPhoneticExtensions(chr)) - return true; + if (isInKatakanaPhoneticExtensions(chr)) return true; if (isInHalfwidthandFullwidthForms(chr)) { - if (chr != u'(' && chr != u')' && chr != u'-' && !(chr >= u':' && chr <= u'>') && - chr != u'[' && chr != u']' && chr != u'_' && !(chr >= u'{' && chr <= 0xFFDF) && - chr != u' ̄' && !(chr >= u'│' && chr <= 0xFFEF)) + if (chr != u'(' && chr != u')' && chr != u'-' && !(chr >= u':' && chr <= u'>') && chr != u'[' && + chr != u']' && chr != u'_' && !(chr >= u'{' && chr <= 0xFFDF) && chr != u' ̄' && + !(chr >= u'│' && chr <= 0xFFEF)) return true; } if (isInSmallFormVariants(chr)) { - if (!(chr >= u'﹘' && chr <= u'﹞') && !(chr >= u'﹣' && chr <= u'﹦')) - return true; + if (!(chr >= u'﹘' && chr <= u'﹞') && !(chr >= u'﹣' && chr <= u'﹦')) return true; } - if (isInUnifiedCanadianAboriginalSyllabics(chr) || - isInUnifiedCanadianAboriginalSyllabicsExtended(chr) || isInVerticalForms(chr) || - isInYijingHexagramSymbols(chr) || isInYiSyllables(chr) || isInYiRadicals(chr)) + if (isInUnifiedCanadianAboriginalSyllabics(chr) || isInUnifiedCanadianAboriginalSyllabicsExtended(chr) || + isInVerticalForms(chr) || isInYijingHexagramSymbols(chr) || isInYiSyllables(chr) || isInYiRadicals(chr)) return true; // https://github.com/mapbox/mapbox-gl/issues/29 @@ -526,15 +510,14 @@ bool hasUprightVerticalOrientation(char16_t chr) { bool hasNeutralVerticalOrientation(char16_t chr) { if (isInLatin1Supplement(chr)) { - if (chr == u'§' || chr == u'©' || chr == u'®' || chr == u'±' || chr == u'¼' || - chr == u'½' || chr == u'¾' || chr == u'×' || chr == u'÷') { + if (chr == u'§' || chr == u'©' || chr == u'®' || chr == u'±' || chr == u'¼' || chr == u'½' || chr == u'¾' || + chr == u'×' || chr == u'÷') { return true; } } if (isInGeneralPunctuation(chr)) { - if (chr == u'‖' || chr == u'†' || chr == u'‡' || chr == u'‰' || chr == u'‱' || - chr == u'※' || chr == u'‼' || chr == u'⁂' || chr == u'⁇' || chr == u'⁈' || - chr == u'⁉' || chr == u'⁑') { + if (chr == u'‖' || chr == u'†' || chr == u'‡' || chr == u'‰' || chr == u'‱' || chr == u'※' || chr == u'‼' || + chr == u'⁂' || chr == u'⁇' || chr == u'⁈' || chr == u'⁉' || chr == u'⁑') { return true; } } @@ -542,32 +525,27 @@ bool hasNeutralVerticalOrientation(char16_t chr) { return true; } if (isInMiscellaneousTechnical(chr)) { - if ((chr >= u'⌀' && chr <= u'⌇') || (chr >= u'⌌' && chr <= u'⌟') || - (chr >= u'⌤' && chr <= u'⌨') || chr == u'⌫' || (chr >= u'⍽' && chr <= u'⎚') || - (chr >= u'⎾' && chr <= u'⏍') || chr == u'⏏' || (chr >= u'⏑' && chr <= u'⏛') || - (chr >= u'⏢' && chr <= 0x23FF)) { + if ((chr >= u'⌀' && chr <= u'⌇') || (chr >= u'⌌' && chr <= u'⌟') || (chr >= u'⌤' && chr <= u'⌨') || + chr == u'⌫' || (chr >= u'⍽' && chr <= u'⎚') || (chr >= u'⎾' && chr <= u'⏍') || chr == u'⏏' || + (chr >= u'⏑' && chr <= u'⏛') || (chr >= u'⏢' && chr <= 0x23FF)) { return true; } } - if (isInControlPictures(chr) || isInOpticalCharacterRecognition(chr) || - isInEnclosedAlphanumerics(chr) || isInGeometricShapes(chr)) { + if (isInControlPictures(chr) || isInOpticalCharacterRecognition(chr) || isInEnclosedAlphanumerics(chr) || + isInGeometricShapes(chr)) { return true; } if (isInMiscellaneousSymbols(chr)) { - if ((chr >= u'⬒' && chr <= u'⬯') || - (chr >= u'⭐' && chr <= 0x2B59 /* heavy circled saltire */) || - (chr >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && - chr <= 0x2BEB)) { + if ((chr >= u'⬒' && chr <= u'⬯') || (chr >= u'⭐' && chr <= 0x2B59 /* heavy circled saltire */) || + (chr >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && chr <= 0x2BEB)) { return true; } } if (isInCJKSymbolsandPunctuation(chr) || isInKatakana(chr) || isInPrivateUseArea(chr) || - isInCJKCompatibilityForms(chr) || isInSmallFormVariants(chr) || - isInHalfwidthandFullwidthForms(chr)) { + isInCJKCompatibilityForms(chr) || isInSmallFormVariants(chr) || isInHalfwidthandFullwidthForms(chr)) { return true; } - if (chr == u'∞' || chr == u'∴' || chr == u'∵' || - (chr >= 0x2700 /* black safety scissors */ && chr <= u'❧') || + if (chr == u'∞' || chr == u'∴' || chr == u'∵' || (chr >= 0x2700 /* black safety scissors */ && chr <= u'❧') || (chr >= u'❶' && chr <= u'➓') || chr == 0xFFFC /* object replacement character */ || chr == 0xFFFD /* replacement character */) { return true; @@ -589,11 +567,10 @@ std::u16string verticalizePunctuation(const std::u16string& input) { char16_t nextCharCode = i < input.size() - 1 ? input[i + 1] : 0; char16_t prevCharCode = i ? input[i - 1] : 0; - bool canReplacePunctuation = - ((!nextCharCode || !hasRotatedVerticalOrientation(nextCharCode) || - verticalPunctuation.count(input[i + 1])) && - (!prevCharCode || !hasRotatedVerticalOrientation(prevCharCode) || - verticalPunctuation.count(input[i - 1]))); + bool canReplacePunctuation = ((!nextCharCode || !hasRotatedVerticalOrientation(nextCharCode) || + verticalPunctuation.count(input[i + 1])) && + (!prevCharCode || !hasRotatedVerticalOrientation(prevCharCode) || + verticalPunctuation.count(input[i - 1]))); if (char16_t repl = canReplacePunctuation ? verticalizePunctuation(input[i]) : 0) { output += repl; @@ -608,7 +585,7 @@ std::u16string verticalizePunctuation(const std::u16string& input) { char16_t verticalizePunctuation(char16_t chr) { return verticalPunctuation.count(chr) ? verticalPunctuation.at(chr) : 0; } - + bool charInSupportedScript(char16_t chr) { // This is a rough heuristic: whether we "can render" a script // actually depends on the properties of the font being used @@ -628,7 +605,7 @@ bool charInSupportedScript(char16_t chr) { // Main blocks for Tibetan and Myanmar isInKhmer(chr)); } - + bool isStringInSupportedScript(const std::string& input) { auto u16string = util::convertUTF8ToUTF16(input); for (char16_t chr : u16string) { @@ -640,11 +617,8 @@ bool isStringInSupportedScript(const std::string& input) { } bool isCharInComplexShapingScript(char16_t chr) { - return isInArabic(chr) || - isInArabicSupplement(chr) || - isInArabicExtendedA(chr) || - isInArabicPresentationFormsA(chr) || - isInArabicPresentationFormsB(chr); + return isInArabic(chr) || isInArabicSupplement(chr) || isInArabicExtendedA(chr) || + isInArabicPresentationFormsA(chr) || isInArabicPresentationFormsB(chr); } bool isWhitespace(char16_t chr) { diff --git a/src/mbgl/util/i18n.hpp b/src/mbgl/util/i18n.hpp index 7e75aa06f76..9a33ad02852 100644 --- a/src/mbgl/util/i18n.hpp +++ b/src/mbgl/util/i18n.hpp @@ -72,7 +72,7 @@ std::u16string verticalizePunctuation(const std::u16string& input); @return The character’s specialized vertical form; 0 if not applicable. */ char16_t verticalizePunctuation(char16_t chr); - + bool isStringInSupportedScript(const std::string& input); bool isCharInComplexShapingScript(char16_t chr); diff --git a/src/mbgl/util/interpolate.cpp b/src/mbgl/util/interpolate.cpp index e44a541a312..1ac96038bea 100644 --- a/src/mbgl/util/interpolate.cpp +++ b/src/mbgl/util/interpolate.cpp @@ -13,10 +13,8 @@ float interpolationFactor(float base, Range range, float z) { } else if (base == 1.0f) { return zoomProgress / zoomDiff; } else { - return static_cast( - (std::pow(static_cast(base), zoomProgress) - 1) / - (std::pow(static_cast(base), zoomDiff) - 1) - ); + return static_cast((std::pow(static_cast(base), zoomProgress) - 1) / + (std::pow(static_cast(base), zoomDiff) - 1)); } } diff --git a/src/mbgl/util/intersection_tests.cpp b/src/mbgl/util/intersection_tests.cpp index eb2f38c64ba..bd762437369 100644 --- a/src/mbgl/util/intersection_tests.cpp +++ b/src/mbgl/util/intersection_tests.cpp @@ -9,7 +9,9 @@ bool polygonContainsPoint(const GeometryCoordinates& ring, const GeometryCoordin for (auto i = ring.begin(), j = ring.end() - 1; i != ring.end(); j = i++) { auto& p1 = *i; auto& p2 = *j; - if (((p1.y > p.y) != (p2.y > p.y)) && (p.x < static_cast(p2.x - p1.x) * static_cast(p.y - p1.y) / static_cast(p2.y - p1.y) + p1.x)) { + if (((p1.y > p.y) != (p2.y > p.y)) && + (p.x < static_cast(p2.x - p1.x) * static_cast(p.y - p1.y) / static_cast(p2.y - p1.y) + + p1.x)) { c = !c; } } @@ -47,9 +49,12 @@ bool isCounterClockwise(const GeometryCoordinate& a, const GeometryCoordinate& b return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); } -bool lineSegmentIntersectsLineSegment(const GeometryCoordinate& a0, const GeometryCoordinate& a1, const GeometryCoordinate& b0, const GeometryCoordinate& b1) { +bool lineSegmentIntersectsLineSegment(const GeometryCoordinate& a0, + const GeometryCoordinate& a1, + const GeometryCoordinate& b0, + const GeometryCoordinate& b1) { return isCounterClockwise(a0, b0, b1) != isCounterClockwise(a1, b0, b1) && - isCounterClockwise(a0, a1, b0) != isCounterClockwise(a0, a1, b1); + isCounterClockwise(a0, a1, b0) != isCounterClockwise(a0, a1, b1); } bool lineIntersectsLine(const GeometryCoordinates& lineA, const GeometryCoordinates& lineB) { if (lineA.empty() || lineB.empty()) return false; @@ -88,7 +93,9 @@ bool polygonIntersectsBufferedPoint(const GeometryCoordinates& polygon, const Ge return false; } -bool polygonIntersectsBufferedMultiPoint(const GeometryCoordinates& polygon, const GeometryCollection& rings, float radius) { +bool polygonIntersectsBufferedMultiPoint(const GeometryCoordinates& polygon, + const GeometryCollection& rings, + float radius) { for (auto& ring : rings) { for (auto& point : ring) { if (polygonIntersectsBufferedPoint(polygon, point, radius)) return true; @@ -97,7 +104,9 @@ bool polygonIntersectsBufferedMultiPoint(const GeometryCoordinates& polygon, con return false; } -bool polygonIntersectsBufferedMultiLine(const GeometryCoordinates& polygon, const GeometryCollection& multiLine, float radius) { +bool polygonIntersectsBufferedMultiLine(const GeometryCoordinates& polygon, + const GeometryCollection& multiLine, + float radius) { for (auto& line : multiLine) { if (polygon.size() >= 3) { for (auto& p : line) { diff --git a/src/mbgl/util/io.cpp b/src/mbgl/util/io.cpp index 7c6fefe7629..68b7dfa64b0 100644 --- a/src/mbgl/util/io.cpp +++ b/src/mbgl/util/io.cpp @@ -16,9 +16,9 @@ namespace mbgl { namespace util { -IOException::IOException(int err, const std::string& msg) - : std::runtime_error(msg + ": " + std::strerror(errno)), code(err) { -} +IOException::IOException(int err, const std::string &msg) + : std::runtime_error(msg + ": " + std::strerror(errno)), + code(err) {} void write_file(const std::string &filename, const std::string &data) { FILE *fd = fopen(filename.c_str(), MBGL_FOPEN_MODE_WBE); @@ -51,14 +51,14 @@ std::optional readFile(const std::string &filename) { return {}; } -void deleteFile(const std::string& filename) { +void deleteFile(const std::string &filename) { const int ret = std::remove(filename.c_str()); if (ret != 0 && errno != ENOENT) { throw IOException(errno, "Could not delete file " + filename); } } -void copyFile(const std::string& destination, const std::string& source) { +void copyFile(const std::string &destination, const std::string &source) { std::ifstream src(source, std::ios::binary); if (!src.good()) { throw IOException(errno, "Cannot read file " + source); diff --git a/src/mbgl/util/io.hpp b/src/mbgl/util/io.hpp index f4f7ddeb6b1..7e57b312798 100644 --- a/src/mbgl/util/io.hpp +++ b/src/mbgl/util/io.hpp @@ -12,10 +12,10 @@ struct IOException : std::runtime_error { const int code = 0; }; -void write_file(const std::string &filename, const std::string &data); -std::string read_file(const std::string &filename); +void write_file(const std::string& filename, const std::string& data); +std::string read_file(const std::string& filename); -std::optional readFile(const std::string &filename); +std::optional readFile(const std::string& filename); void deleteFile(const std::string& filename); void copyFile(const std::string& destination, const std::string& source); diff --git a/src/mbgl/util/literal.hpp b/src/mbgl/util/literal.hpp index d4fec49b35f..aa7c622c077 100644 --- a/src/mbgl/util/literal.hpp +++ b/src/mbgl/util/literal.hpp @@ -9,11 +9,9 @@ namespace mbgl { template struct string_literal { - static constexpr const char chars[] = { Cs..., 0 }; + static constexpr const char chars[] = {Cs..., 0}; - static constexpr const char* value() { - return chars; - } + static constexpr const char* value() { return chars; } }; template @@ -35,23 +33,17 @@ struct concat_literals; template <> struct concat_literals<> { - static constexpr auto value() { - return ""; - } + static constexpr auto value() { return ""; } }; template struct concat_literals, string_literal, Rest...> { - static constexpr auto value() { - return concat_literals, Rest...>::value(); - } + static constexpr auto value() { return concat_literals, Rest...>::value(); } }; template struct concat_literals> { - static constexpr auto value() { - return string_literal::value(); - } + static constexpr auto value() { return string_literal::value(); } }; } // namespace detail diff --git a/src/mbgl/util/logging.cpp b/src/mbgl/util/logging.cpp index 92884bc7f11..89a5e08e359 100644 --- a/src/mbgl/util/logging.cpp +++ b/src/mbgl/util/logging.cpp @@ -20,7 +20,8 @@ std::mutex mutex; class Log::Impl { public: - Impl() : scheduler(Scheduler::GetSequenced()) {} + Impl() + : scheduler(Scheduler::GetSequenced()) {} void record(EventSeverity severity, Event event, int64_t code, const std::string& msg) { if (useThread) { @@ -35,7 +36,8 @@ class Log::Impl { const std::shared_ptr scheduler; }; -Log::Log() : impl(std::make_unique()) {} +Log::Log() + : impl(std::make_unique()) {} Log::~Log() = default; @@ -60,11 +62,11 @@ std::unique_ptr Log::removeObserver() { return observer; } -void Log::record(EventSeverity severity, Event event, const std::string &msg) { +void Log::record(EventSeverity severity, Event event, const std::string& msg) { get()->impl->record(severity, event, -1, msg); } -void Log::record(EventSeverity severity, Event event, int64_t code, const std::string &msg) { +void Log::record(EventSeverity severity, Event event, int64_t code, const std::string& msg) { get()->impl->record(severity, event, code, msg); } @@ -74,8 +76,7 @@ void Log::record(EventSeverity severity, const std::string& msg, const std::optional& threadName) { std::lock_guard lock(mutex); - if (currentObserver && severity != EventSeverity::Debug && - currentObserver->onRecord(severity, event, code, msg)) { + if (currentObserver && severity != EventSeverity::Debug && currentObserver->onRecord(severity, event, code, msg)) { return; } diff --git a/src/mbgl/util/longest_common_subsequence.hpp b/src/mbgl/util/longest_common_subsequence.hpp index 522b5a86b1c..d9072695783 100644 --- a/src/mbgl/util/longest_common_subsequence.hpp +++ b/src/mbgl/util/longest_common_subsequence.hpp @@ -8,26 +8,23 @@ namespace mbgl { /* - Computes the longest common subsequence (LCS) of sequences A and B, represented - by pairs of random access iterators. The result is output to the provided output - iterator. Equality of elements is determined by the provided comparator, defaulting - to ==. + Computes the longest common subsequence (LCS) of sequences A and B, + represented by pairs of random access iterators. The result is output to the + provided output iterator. Equality of elements is determined by the provided + comparator, defaulting to ==. The algorithm used is the O(ND) time and space algorithm from: - Myers, Eugene W. An O(ND) Difference Algorithm and Its Variations. Algorithmica - (1986) 1: 251. http://xmailserver.org/diff2.pdf + Myers, Eugene W. An O(ND) Difference Algorithm and Its Variations. + Algorithmica (1986) 1: 251. http://xmailserver.org/diff2.pdf - For understanding this algorithm, http://simplygenius.net/Article/DiffTutorial1 is - also helpful. + For understanding this algorithm, + http://simplygenius.net/Article/DiffTutorial1 is also helpful. TODO: implement the O(N) space refinement presented in the paper. */ template -OutIt longest_common_subsequence(InIt a, InIt endA, - InIt b, InIt endB, - OutIt outIt, - Equal eq) { +OutIt longest_common_subsequence(InIt a, InIt endA, InIt b, InIt endB, OutIt outIt, Equal eq) { const std::ptrdiff_t N = endA - a; const std::ptrdiff_t M = endB - b; const std::ptrdiff_t D = N + M; @@ -39,19 +36,19 @@ OutIt longest_common_subsequence(InIt a, InIt endA, std::vector> vs; // Self-executing lambda to allow `return` to break from inner loop, and avoid shadowing `v`. - [&] () { + [&]() { std::vector v; v.resize(2 * D + 1); v[1] = 0; - // Core of the algorithm: greedily find farthest-reaching D-paths for increasing - // values of D. Store the farthest-reaching endpoints found in each iteration for - // later reconstructing the LCS. + // Core of the algorithm: greedily find farthest-reaching D-paths for + // increasing values of D. Store the farthest-reaching endpoints found + // in each iteration for later reconstructing the LCS. for (std::ptrdiff_t d = 0; d <= D; ++d) { for (std::ptrdiff_t k = -d; k <= d; k += 2) { std::ptrdiff_t x = (k == -d || (k != d && v.at(k - 1 + D) < v.at(k + 1 + D))) - ? v.at(k + 1 + D) // moving down - : v.at(k - 1 + D) + 1; // moving right + ? v.at(k + 1 + D) // moving down + : v.at(k - 1 + D) + 1; // moving right std::ptrdiff_t y = x - k; @@ -96,10 +93,8 @@ OutIt longest_common_subsequence(InIt a, InIt endA, return std::copy(lcsReverse.rbegin(), lcsReverse.rend(), outIt); } -template < typename InIt, typename OutIt > -OutIt longest_common_subsequence(InIt a, InIt endA, - InIt b, InIt endB, - OutIt outIt) { +template +OutIt longest_common_subsequence(InIt a, InIt endA, InIt b, InIt endB, OutIt outIt) { return longest_common_subsequence(a, endA, b, endB, outIt, std::equal_to<>()); } diff --git a/src/mbgl/util/mapbox.cpp b/src/mbgl/util/mapbox.cpp index 17d5534254d..7793f1b196d 100644 --- a/src/mbgl/util/mapbox.cpp +++ b/src/mbgl/util/mapbox.cpp @@ -24,98 +24,95 @@ inline int nthOccurrenceFromEnd(const std::string& str, const std::string& searc size_t pos = str.length(); int cnt = 0; - while (cnt != nth){ - pos-=1; + while (cnt != nth) { + pos -= 1; pos = str.rfind(search, pos); - if ( pos == std::string::npos ) - return -1; + if (pos == std::string::npos) return -1; cnt++; } return static_cast(pos); } inline void replace(std::string& str, const std::string& search, const std::string& replacement) { - std::string::size_type pos = 0u; - while((pos = str.find(search, pos)) != std::string::npos){ - str.replace(pos, search.length(), replacement); - pos += replacement.length(); - } + std::string::size_type pos = 0u; + while ((pos = str.find(search, pos)) != std::string::npos) { + str.replace(pos, search.length(), replacement); + pos += replacement.length(); + } } bool isCanonicalURL(const TileServerOptions& tileServerOptions, const std::string& url) { if (tileServerOptions.uriSchemeAlias().empty() || tileServerOptions.baseURL().empty()) { return false; } - + const auto& protocol = tileServerOptions.uriSchemeAlias() + "://"; return url.compare(0, protocol.length(), protocol) == 0; } std::map createTokenMap(const std::string& urlTemplate, const std::string& url) { const URL parsedUrl(url); - + // e.g. tiles/satellite/tiles.json auto path = url.substr(parsedUrl.path.first, parsedUrl.path.second); - + // --- find tokens in the urlTemplate (such as {path}, ...) std::regex r(R"(\{(domain|path|directory|filename|extension)\})"); std::vector> tokenList; - for(std::sregex_iterator i = std::sregex_iterator(urlTemplate.begin(), urlTemplate.end(), r); - i != std::sregex_iterator(); - ++i) - { + for (std::sregex_iterator i = std::sregex_iterator(urlTemplate.begin(), urlTemplate.end(), r); + i != std::sregex_iterator(); + ++i) { const std::smatch& m = *i; if (m.size() > 0) { auto captureGroupValue = m[1].str(); - if (!captureGroupValue.empty()){ + if (!captureGroupValue.empty()) { std::pair tokenInfo; tokenInfo.first = captureGroupValue; tokenList.push_back(tokenInfo); } } } - + // --- extract token values // /tiles{path}/tiles.json in tiles/satellite/tiles.json // e.g. path = /satelite - std::regex tokenPattern (R"(\{domain\}|\{path\}|\{directory\}|\{filename\}|\{extension\})"); - std::string templatePattern = std::regex_replace (urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any); + std::regex tokenPattern(R"(\{domain\}|\{path\}|\{directory\}|\{filename\}|\{extension\})"); + std::string templatePattern = std::regex_replace( + urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any); std::regex r2(templatePattern); int idx = 0; - for(std::sregex_iterator i = std::sregex_iterator(path.begin(), path.end(), r2); - i != std::sregex_iterator(); - ++i) - { + for (std::sregex_iterator i = std::sregex_iterator(path.begin(), path.end(), r2); i != std::sregex_iterator(); + ++i) { const std::smatch& m = *i; if (m.size() > 0) { auto captureGroupValue = m[1].str(); - if (!captureGroupValue.empty()){ + if (!captureGroupValue.empty()) { tokenList[idx].second = captureGroupValue; idx++; } } } - + std::map tokenMap; - std::copy(tokenList.begin(), tokenList.end(), - std::inserter(tokenMap, tokenMap.begin())); - + std::copy(tokenList.begin(), tokenList.end(), std::inserter(tokenMap, tokenMap.begin())); + return tokenMap; } bool isNormalizedSourceURL(const std::string& baseURL, const std::string& urlTemplate, const std::string& url) { - if (baseURL.empty() || urlTemplate.empty()){ + if (baseURL.empty() || urlTemplate.empty()) { return false; } - - std::regex tokenPattern (R"(\{.+\})"); - std::string urlPattern = std::regex_replace (urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any)+"(.*)"; - std::string pattern (baseURL + urlPattern); - - if (std::regex_match (url, std::regex(pattern))){ + + std::regex tokenPattern(R"(\{.+\})"); + std::string urlPattern = std::regex_replace(urlTemplate, tokenPattern, "(.+)", std::regex_constants::match_any) + + "(.*)"; + std::string pattern(baseURL + urlPattern); + + if (std::regex_match(url, std::regex(pattern))) { return true; } - + return false; } @@ -125,35 +122,36 @@ bool isNormalizedURL(const TileServerOptions& tileServerOptions, const std::stri // Make sure that we are dealing with a valid tile URL. // Has to be with the tile template prefix, with a valid filename + extension - + if (tileServerOptions.uriSchemeAlias() == "mapbox") { const URL baseURL(tileServerOptions.baseURL()); auto domain = str.substr(url.domain.first, url.domain.second); - + replace(domain, ".cn", ".com"); // hack for mapbox china - + auto refDomain = tileServerOptions.baseURL().substr(baseURL.domain.first, baseURL.domain.second); const auto refDomainIdx = nthOccurrenceFromEnd(refDomain, ".", 2); refDomain = refDomain.substr(refDomainIdx + 1, refDomain.length() - refDomainIdx - 1); - + if (!endsWith(domain, refDomain) || path.filename.second == 0 || path.extension.second <= 1) { // Not a proper tile URL. return false; } - } - else { + } else { if (path.filename.second == 0 || path.extension.second <= 1) { // Not a proper tile URL. return false; } } - + return true; } std::string makeQueryString(const TileServerOptions& tileServerOptions, const std::string& apiKey) { - std::string queryString = (!tileServerOptions.requiresApiKey() || tileServerOptions.apiKeyParameterName().empty() || apiKey.empty()) ? - "" : "?" + tileServerOptions.apiKeyParameterName() + "=" + apiKey; + std::string queryString = (!tileServerOptions.requiresApiKey() || tileServerOptions.apiKeyParameterName().empty() || + apiKey.empty()) + ? "" + : "?" + tileServerOptions.apiKeyParameterName() + "=" + apiKey; return queryString; } @@ -168,8 +166,7 @@ std::string normalizeSourceURL(const TileServerOptions& tileServerOptions, return str; } if (tileServerOptions.requiresApiKey() && apiKey.empty()) { - throw std::runtime_error( - "You must provide API key for tile sources"); + throw std::runtime_error("You must provide API key for tile sources"); } std::string suffix = ""; @@ -182,8 +179,9 @@ std::string normalizeSourceURL(const TileServerOptions& tileServerOptions, Log::Error(Event::ParseStyle, "Invalid source URL"); return str; } - - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.sourceVersionPrefix().value_or("") + tileServerOptions.sourceTemplate() + makeQueryString(tileServerOptions, apiKey) + suffix; + + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.sourceVersionPrefix().value_or("") + + tileServerOptions.sourceTemplate() + makeQueryString(tileServerOptions, apiKey) + suffix; return transformURL(tpl, str, url); } @@ -200,10 +198,10 @@ std::string normalizeStyleURL(const TileServerOptions& tileServerOptions, Log::Error(Event::ParseStyle, "Invalid style URL"); return str; } - - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.styleVersionPrefix().value_or("") + tileServerOptions.styleTemplate() + makeQueryString(tileServerOptions, apiKey); - + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.styleVersionPrefix().value_or("") + + tileServerOptions.styleTemplate() + makeQueryString(tileServerOptions, apiKey); + return transformURL(tpl, str, url); } @@ -221,7 +219,8 @@ std::string normalizeSpriteURL(const TileServerOptions& tileServerOptions, return str; } - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.spritesVersionPrefix().value_or("") + tileServerOptions.spritesTemplate() + makeQueryString(tileServerOptions, apiKey); + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.spritesVersionPrefix().value_or("") + + tileServerOptions.spritesTemplate() + makeQueryString(tileServerOptions, apiKey); return transformURL(tpl, str, url); } @@ -239,7 +238,8 @@ std::string normalizeGlyphsURL(const TileServerOptions& tileServerOptions, return str; } - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.glyphsVersionPrefix().value_or("") + tileServerOptions.glyphsTemplate() + makeQueryString(tileServerOptions, apiKey); + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.glyphsVersionPrefix().value_or("") + + tileServerOptions.glyphsTemplate() + makeQueryString(tileServerOptions, apiKey); return transformURL(tpl, str, url); } @@ -249,7 +249,7 @@ std::string normalizeTileURL(const TileServerOptions& tileServerOptions, if (!isCanonicalURL(tileServerOptions, str)) { return str; } - + const URL url(str); auto domainName = tileServerOptions.tileDomainName(); if (!equals(str, url.domain, domainName)) { @@ -257,28 +257,30 @@ std::string normalizeTileURL(const TileServerOptions& tileServerOptions, return str; } - const auto tpl = tileServerOptions.baseURL() + tileServerOptions.tileVersionPrefix().value_or("") + tileServerOptions.tileTemplate() + makeQueryString(tileServerOptions, apiKey); + const auto tpl = tileServerOptions.baseURL() + tileServerOptions.tileVersionPrefix().value_or("") + + tileServerOptions.tileTemplate() + makeQueryString(tileServerOptions, apiKey); return transformURL(tpl, str, url); } -std::string -canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::string& str, const style::SourceType type, const uint16_t tileSize) { - - if (!isNormalizedURL(tileServerOptions, str)){ +std::string canonicalizeTileURL(const TileServerOptions& tileServerOptions, + const std::string& str, + const style::SourceType type, + const uint16_t tileSize) { + if (!isNormalizedURL(tileServerOptions, str)) { return str; } std::string result = tileServerOptions.uriSchemeAlias() + "://" + tileServerOptions.tileDomainName(); - + const URL url(str); const Path path(str, url.path.first, url.path.second); - + int versionPrefixLen = 0; const auto& versionPrefix = tileServerOptions.tileVersionPrefix(); - if (versionPrefix.has_value()){ + if (versionPrefix.has_value()) { versionPrefixLen = static_cast(versionPrefix.value().length()); } - + result.append(str, path.directory.first + versionPrefixLen, path.directory.second - versionPrefixLen); result.append(str, path.filename.first, path.filename.second); if (type == style::SourceType::Raster || type == style::SourceType::RasterDEM) { @@ -296,8 +298,7 @@ canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::strin const auto& apiKey = tileServerOptions.apiKeyParameterName() + "="; if (str.compare(idx, apiKey.length(), apiKey) != 0) { result.append(1, hasQuery ? '&' : '?'); - result.append(str, idx, ampersandIdx != std::string::npos ? ampersandIdx - idx - : std::string::npos); + result.append(str, idx, ampersandIdx != std::string::npos ? ampersandIdx - idx : std::string::npos); hasQuery = true; } idx = ampersandIdx; @@ -307,8 +308,11 @@ canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::strin return result; } -void canonicalizeTileset(const TileServerOptions& tileServerOptions, Tileset& tileset, - const std::string& sourceURL, style::SourceType type, uint16_t tileSize) { +void canonicalizeTileset(const TileServerOptions& tileServerOptions, + Tileset& tileset, + const std::string& sourceURL, + style::SourceType type, + uint16_t tileSize) { if (isCanonicalURL(tileServerOptions, sourceURL) || isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.sourceTemplate(), sourceURL)) { for (auto& url : tileset.tiles) { @@ -317,21 +321,21 @@ void canonicalizeTileset(const TileServerOptions& tileServerOptions, Tileset& ti } } -std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& url){ - if (url.empty()) - return url; - +std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& url) { + if (url.empty()) return url; + if (isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.sourceTemplate(), url)) { auto tokenMap = createTokenMap(tileServerOptions.sourceTemplate(), url); - + auto retVal = tileServerOptions.uriSchemeAlias() + "://"; if (tokenMap.find("domain") != tokenMap.end()) { retVal += tokenMap.at("domain"); } else { if (!tileServerOptions.sourceDomainName().empty()) retVal += tileServerOptions.sourceDomainName(); } - - if (tileServerOptions.sourceVersionPrefix().has_value()) retVal += tileServerOptions.sourceVersionPrefix().value(); + + if (tileServerOptions.sourceVersionPrefix().has_value()) + retVal += tileServerOptions.sourceVersionPrefix().value(); if (tokenMap.find("path") != tokenMap.end()) { retVal += tokenMap.at("path"); @@ -340,28 +344,28 @@ std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, co if (tokenMap.find("filename") != tokenMap.end()) retVal += tokenMap.at("filename"); if (tokenMap.find("extension") != tokenMap.end()) retVal += tokenMap.at("extension"); } - + return retVal; } return url; } -std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& url){ - if (url.empty()) - return url; - +std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& url) { + if (url.empty()) return url; + if (isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.spritesTemplate(), url)) { auto tokenMap = createTokenMap(tileServerOptions.spritesTemplate(), url); - + auto retVal = tileServerOptions.uriSchemeAlias() + "://"; if (tokenMap.find("domain") != tokenMap.end()) { retVal += tokenMap.at("domain"); } else { if (!tileServerOptions.spritesDomainName().empty()) retVal += tileServerOptions.spritesDomainName(); } - - if (tileServerOptions.spritesVersionPrefix().has_value()) retVal += tileServerOptions.spritesVersionPrefix().value(); - + + if (tileServerOptions.spritesVersionPrefix().has_value()) + retVal += tileServerOptions.spritesVersionPrefix().value(); + if (tokenMap.find("path") != tokenMap.end()) { retVal += tokenMap.at("path"); } else { @@ -369,30 +373,30 @@ std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, co if (tokenMap.find("filename") != tokenMap.end()) retVal += tokenMap.at("filename"); if (tokenMap.find("extension") != tokenMap.end()) retVal += tokenMap.at("extension"); } - + return retVal; } - + return url; } -std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, const std::string& url){ - if (url.empty()) - return url; - +std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, const std::string& url) { + if (url.empty()) return url; + // "https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=uwvyvzaF2P7UWbyOEvjU" if (isNormalizedSourceURL(tileServerOptions.baseURL(), tileServerOptions.glyphsTemplate(), url)) { auto tokenMap = createTokenMap(tileServerOptions.glyphsTemplate(), url); - + auto retVal = tileServerOptions.uriSchemeAlias() + "://"; if (tokenMap.find("domain") != tokenMap.end()) { retVal += tokenMap.at("domain"); } else { if (!tileServerOptions.glyphsDomainName().empty()) retVal += tileServerOptions.glyphsDomainName(); } - - if (tileServerOptions.glyphsVersionPrefix().has_value()) retVal += tileServerOptions.glyphsVersionPrefix().value(); - + + if (tileServerOptions.glyphsVersionPrefix().has_value()) + retVal += tileServerOptions.glyphsVersionPrefix().value(); + if (tokenMap.find("path") != tokenMap.end()) { retVal += tokenMap.at("path"); } else { @@ -400,11 +404,10 @@ std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, con if (tokenMap.find("filename") != tokenMap.end()) retVal += tokenMap.at("filename"); if (tokenMap.find("extension") != tokenMap.end()) retVal += tokenMap.at("extension"); } - + return retVal; } - - + return url; } diff --git a/src/mbgl/util/mapbox.hpp b/src/mbgl/util/mapbox.hpp index 57d46810cc2..5030357b355 100644 --- a/src/mbgl/util/mapbox.hpp +++ b/src/mbgl/util/mapbox.hpp @@ -11,22 +11,36 @@ class Tileset; namespace util { namespace mapbox { -bool isCanonicalURL(const TileServerOptions& tileServerOptions,const std::string& url); - -std::string normalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeStyleURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeGlyphsURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); -std::string normalizeTileURL(const TileServerOptions& tileServerOptions, const std::string& str, const std::string& apiKey); +bool isCanonicalURL(const TileServerOptions& tileServerOptions, const std::string& url); + +std::string normalizeSourceURL(const TileServerOptions& tileServerOptions, + const std::string& str, + const std::string& apiKey); +std::string normalizeStyleURL(const TileServerOptions& tileServerOptions, + const std::string& str, + const std::string& apiKey); +std::string normalizeSpriteURL(const TileServerOptions& tileServerOptions, + const std::string& str, + const std::string& apiKey); +std::string normalizeGlyphsURL(const TileServerOptions& tileServerOptions, + const std::string& str, + const std::string& apiKey); +std::string normalizeTileURL(const TileServerOptions& tileServerOptions, + const std::string& str, + const std::string& apiKey); // Return a "mapbox://tiles/..." URL (suitable for normalizeTileURL) for the given Mapbox tile URL. -std::string canonicalizeTileURL(const TileServerOptions& tileServerOptions, const std::string& str, style::SourceType, uint16_t tileSize); +std::string canonicalizeTileURL(const TileServerOptions& tileServerOptions, + const std::string& str, + style::SourceType, + uint16_t tileSize); std::string canonicalizeSourceURL(const TileServerOptions& tileServerOptions, const std::string& url); std::string canonicalizeSpriteURL(const TileServerOptions& tileServerOptions, const std::string& url); std::string canonicalizeGlyphURL(const TileServerOptions& tileServerOptions, const std::string& url); // Replace URL templates with "mapbox://tiles/..." URLs (suitable for normalizeTileURL). -void canonicalizeTileset(const TileServerOptions& tileServerOptions, Tileset&, const std::string& url, style::SourceType, uint16_t tileSize); +void canonicalizeTileset( + const TileServerOptions& tileServerOptions, Tileset&, const std::string& url, style::SourceType, uint16_t tileSize); extern const uint64_t DEFAULT_OFFLINE_TILE_COUNT_LIMIT; diff --git a/src/mbgl/util/mat2.cpp b/src/mbgl/util/mat2.cpp index 89617d8449e..1d0f1585de1 100644 --- a/src/mbgl/util/mat2.cpp +++ b/src/mbgl/util/mat2.cpp @@ -40,8 +40,8 @@ void matrix::rotate(mat2& out, const mat2& a, double rad) { double a3 = a[3]; double s = std::sin(rad); double c = std::cos(rad); - out[0] = a0 * c + a2 * s; - out[1] = a1 * c + a3 * s; + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; out[2] = a0 * -s + a2 * c; out[3] = a1 * -s + a3 * c; } diff --git a/src/mbgl/util/mat4.cpp b/src/mbgl/util/mat4.cpp index 9909b7e3eee..b69eb3262d1 100644 --- a/src/mbgl/util/mat4.cpp +++ b/src/mbgl/util/mat4.cpp @@ -186,13 +186,31 @@ void translate(mat4& out, const mat4& a, double x, double y, double z) { double a22; double a23; - a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; - a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; - a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; - - out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; - out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; - out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; out[12] = a00 * x + a10 * y + a20 * z + a[12]; out[13] = a01 * x + a11 * y + a21 * z + a[13]; @@ -214,10 +232,10 @@ void rotate_x(mat4& out, const mat4& a, double rad) { double a23 = a[11]; if (&a != &out) { // If the source and destination differ, copy the unchanged rows - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; @@ -248,10 +266,10 @@ void rotate_y(mat4& out, const mat4& a, double rad) { double a23 = a[11]; if (&a != &out) { // If the source and destination differ, copy the unchanged rows - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; @@ -282,8 +300,8 @@ void rotate_z(mat4& out, const mat4& a, double rad) { double a13 = a[7]; if (&a != &out) { // If the source and destination differ, copy the unchanged last row - out[8] = a[8]; - out[9] = a[9]; + out[8] = a[8]; + out[9] = a[9]; out[10] = a[10]; out[11] = a[11]; out[12] = a[12]; @@ -350,19 +368,28 @@ void multiply(mat4& out, const mat4& a, const mat4& b) { out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; diff --git a/src/mbgl/util/math.hpp b/src/mbgl/util/math.hpp index d7350337429..40f3015e7fb 100644 --- a/src/mbgl/util/math.hpp +++ b/src/mbgl/util/math.hpp @@ -26,10 +26,7 @@ T angle_to(const Point& a, const Point& b) { // Reflect an angle around 0 degrees template std::array flip(const std::array& c) { - return {{ - static_cast(2 * M_PI - c[0]), - static_cast(2 * M_PI - c[1]) - }}; + return {{static_cast(2 * M_PI - c[0]), static_cast(2 * M_PI - c[1])}}; } template @@ -37,7 +34,7 @@ Point normal(const S1& a, const S2& b) { T dx = b.x - a.x; T dy = b.y - a.y; T c = std::sqrt(dx * dx + dy * dy); - return { dx / c, dy / c }; + return {dx / c, dy / c}; } template diff --git a/src/mbgl/util/premultiply.cpp b/src/mbgl/util/premultiply.cpp index 02c045fbb40..130d3ba4936 100644 --- a/src/mbgl/util/premultiply.cpp +++ b/src/mbgl/util/premultiply.cpp @@ -9,7 +9,7 @@ PremultipliedImage premultiply(UnassociatedImage&& src) { PremultipliedImage dst; dst.size = src.size; - src.size = { 0, 0 }; + src.size = {0, 0}; dst.data = std::move(src.data); uint8_t* data = dst.data.get(); @@ -30,7 +30,7 @@ UnassociatedImage unpremultiply(PremultipliedImage&& src) { UnassociatedImage dst; dst.size = src.size; - src.size = { 0, 0 }; + src.size = {0, 0}; dst.data = std::move(src.data); uint8_t* data = dst.data.get(); diff --git a/src/mbgl/util/quaternion.hpp b/src/mbgl/util/quaternion.hpp index b2ae40eaf76..0a62217ed09 100644 --- a/src/mbgl/util/quaternion.hpp +++ b/src/mbgl/util/quaternion.hpp @@ -13,9 +13,15 @@ struct Quaternion { }; }; - Quaternion() : Quaternion(0.0, 0.0, 0.0, 0.0) {} - Quaternion(double x_, double y_, double z_, double w_) : x(x_), y(y_), z(z_), w(w_) {} - Quaternion(const vec4& vec) : m(vec) {} + Quaternion() + : Quaternion(0.0, 0.0, 0.0, 0.0) {} + Quaternion(double x_, double y_, double z_, double w_) + : x(x_), + y(y_), + z(z_), + w(w_) {} + Quaternion(const vec4& vec) + : m(vec) {} Quaternion conjugate() const; Quaternion normalized() const; diff --git a/src/mbgl/util/rapidjson.cpp b/src/mbgl/util/rapidjson.cpp index 32a3c0b929e..d63afd58712 100644 --- a/src/mbgl/util/rapidjson.cpp +++ b/src/mbgl/util/rapidjson.cpp @@ -4,10 +4,8 @@ namespace mbgl { std::string formatJSONParseError(const JSDocument& doc) { - return std::string{ rapidjson::GetParseError_En(doc.GetParseError()) } + " at offset " + + return std::string{rapidjson::GetParseError_En(doc.GetParseError())} + " at offset " + util::toString(doc.GetErrorOffset()); } } // namespace mbgl - - diff --git a/src/mbgl/util/rect.hpp b/src/mbgl/util/rect.hpp index f5937f5c94e..7e76a9f7ad8 100644 --- a/src/mbgl/util/rect.hpp +++ b/src/mbgl/util/rect.hpp @@ -5,12 +5,16 @@ namespace mbgl { template struct Rect { Rect() = default; - Rect(T x_, T y_, T w_, T h_) : x(x_), y(y_), w(w_), h(h_) {} + Rect(T x_, T y_, T w_, T h_) + : x(x_), + y(y_), + w(w_), + h(h_) {} T x = 0, y = 0; T w = 0, h = 0; template - Rect operator *(Number value) const { + Rect operator*(Number value) const { return Rect(x * value, y * value, w * value, h * value); } diff --git a/src/mbgl/util/stopwatch.cpp b/src/mbgl/util/stopwatch.cpp index 68534039939..611c0f60f56 100644 --- a/src/mbgl/util/stopwatch.cpp +++ b/src/mbgl/util/stopwatch.cpp @@ -10,21 +10,31 @@ namespace mbgl { namespace util { stopwatch::stopwatch(Event event_) - : event(event_), start(Clock::now()) {} + : event(event_), + start(Clock::now()) {} stopwatch::stopwatch(EventSeverity severity_, Event event_) - : severity(severity_), event(event_), start(Clock::now()) {} + : severity(severity_), + event(event_), + start(Clock::now()) {} stopwatch::stopwatch(std::string name_, Event event_) - : name(std::move(name_)), event(event_), start(Clock::now()) {} + : name(std::move(name_)), + event(event_), + start(Clock::now()) {} stopwatch::stopwatch(std::string name_, EventSeverity severity_, Event event_) - : name(std::move(name_)), severity(severity_), event(event_), start(Clock::now()) {} + : name(std::move(name_)), + severity(severity_), + event(event_), + start(Clock::now()) {} void stopwatch::report(const std::string &name_) { Duration duration = Clock::now() - start; - const auto logMsg = name_ + ": " + std::to_string(std::chrono::duration(duration).count()); + const auto logMsg = name_ + ": " + + std::to_string( + std::chrono::duration(duration).count()); Log::Record(severity, event, logMsg); start += duration; diff --git a/src/mbgl/util/stopwatch.hpp b/src/mbgl/util/stopwatch.hpp index daa313f7024..3e29122c0ab 100644 --- a/src/mbgl/util/stopwatch.hpp +++ b/src/mbgl/util/stopwatch.hpp @@ -11,14 +11,15 @@ namespace mbgl { namespace util { - + #ifdef MBGL_TIMING -// Declare 'watch' as a shared_ptr so it can be captured by value in a lambda function -#define MBGL_TIMING_START(watch) std::shared_ptr watch = std::make_unique(Event::Timing); -#define MBGL_TIMING_FINISH(watch, message) \ - do { \ - std::stringstream messageStream; \ - messageStream << message; \ +// Declare 'watch' as a shared_ptr so it can be captured by value in a lambda function +#define MBGL_TIMING_START(watch) \ + std::shared_ptr watch = std::make_unique(Event::Timing); +#define MBGL_TIMING_FINISH(watch, message) \ + do { \ + std::stringstream messageStream; \ + messageStream << message; \ watch->report(messageStream.str()); \ } while (0); #else diff --git a/src/mbgl/util/thread_local.hpp b/src/mbgl/util/thread_local.hpp index cf5579a2ba9..8b96dd3080c 100644 --- a/src/mbgl/util/thread_local.hpp +++ b/src/mbgl/util/thread_local.hpp @@ -25,17 +25,11 @@ class ThreadLocal : public impl::ThreadLocalBase { public: ThreadLocal() = default; - ThreadLocal(T* val) { - set(val); - } + ThreadLocal(T* val) { set(val); } - T* get() { - return reinterpret_cast(impl::ThreadLocalBase::get()); - } + T* get() { return reinterpret_cast(impl::ThreadLocalBase::get()); } - void set(T* ptr) { - impl::ThreadLocalBase::set(ptr); - } + void set(T* ptr) { impl::ThreadLocalBase::set(ptr); } }; } // namespace util diff --git a/src/mbgl/util/tile_coordinate.hpp b/src/mbgl/util/tile_coordinate.hpp index f0acc2c33a3..d3ac2298548 100644 --- a/src/mbgl/util/tile_coordinate.hpp +++ b/src/mbgl/util/tile_coordinate.hpp @@ -21,29 +21,30 @@ class TileCoordinate { static TileCoordinate fromLatLng(double zoom, const LatLng& latLng) { const double scale = std::pow(2.0, zoom); - return { Projection::project(latLng, scale) / util::tileSize_D, zoom }; + return {Projection::project(latLng, scale) / util::tileSize_D, zoom}; } - static TileCoordinate fromScreenCoordinate(const TransformState& state, uint8_t zoom, const ScreenCoordinate& screenCoordinate) { + static TileCoordinate fromScreenCoordinate(const TransformState& state, + uint8_t zoom, + const ScreenCoordinate& screenCoordinate) { return state.screenCoordinateToTileCoordinate(screenCoordinate, zoom); } TileCoordinate zoomTo(double zoom) const { const double scaleDiff = std::pow(2.0, zoom - z); - return { p * scaleDiff, zoom }; + return {p * scaleDiff, zoom}; } static GeometryCoordinate toGeometryCoordinate(const UnwrappedTileID& tileID, const TileCoordinatePoint& point) { const double scale = std::pow(2.0, tileID.canonical.z); - auto zoomed = TileCoordinate { point, 0 }.zoomTo(tileID.canonical.z); - return { - int16_t(util::clamp(static_cast((zoomed.p.x - tileID.canonical.x - tileID.wrap * scale) * util::EXTENT), - std::numeric_limits::min(), - std::numeric_limits::max())), - int16_t(util::clamp(static_cast((zoomed.p.y - tileID.canonical.y) * util::EXTENT), - std::numeric_limits::min(), - std::numeric_limits::max())) - }; + auto zoomed = TileCoordinate{point, 0}.zoomTo(tileID.canonical.z); + return {int16_t(util::clamp( + static_cast((zoomed.p.x - tileID.canonical.x - tileID.wrap * scale) * util::EXTENT), + std::numeric_limits::min(), + std::numeric_limits::max())), + int16_t(util::clamp(static_cast((zoomed.p.y - tileID.canonical.y) * util::EXTENT), + std::numeric_limits::min(), + std::numeric_limits::max()))}; } }; diff --git a/src/mbgl/util/tile_cover.cpp b/src/mbgl/util/tile_cover.cpp index afd5974542b..9186dcd47ad 100644 --- a/src/mbgl/util/tile_cover.cpp +++ b/src/mbgl/util/tile_cover.cpp @@ -40,9 +40,8 @@ void scanSpans(edge e0, edge e1, int32_t ymin, int32_t ymax, ScanLine& scanLine) double y1 = ::fmin(ymax, std::ceil(e1.y1)); // sort edges by x-coordinate - if ((e0.x0 == e1.x0 && e0.y0 == e1.y0) ? - (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) : - (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0)) { + if ((e0.x0 == e1.x0 && e0.y0 == e1.y0) ? (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) + : (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0)) { std::swap(e0, e1); } @@ -70,9 +69,15 @@ void scanTriangle(const Point& a, edge ca = edge(c, a); // sort edges by y-length - if (ab.dy > bc.dy) { std::swap(ab, bc); } - if (ab.dy > ca.dy) { std::swap(ab, ca); } - if (bc.dy > ca.dy) { std::swap(bc, ca); } + if (ab.dy > bc.dy) { + std::swap(ab, bc); + } + if (ab.dy > ca.dy) { + std::swap(ab, ca); + } + if (bc.dy > ca.dy) { + std::swap(bc, ca); + } // scan span! scan span! if (ab.dy) scanSpans(ca, ab, ymin, ymax, scanLine); @@ -106,7 +111,7 @@ std::vector tileCover(const Point& tl, for (x = x0; x < x1; ++x) { const auto dx = x + 0.5 - c.x; const auto dy = y + 0.5 - c.y; - t.emplace_back(ID{ x, y, dx * dx + dy * dy }); + t.emplace_back(ID{x, y, dx * dx + dy * dy}); } } }; @@ -124,9 +129,8 @@ std::vector tileCover(const Point& tl, }); // Erase duplicate tile IDs (they typically occur at the common side of both triangles). - t.erase(std::unique(t.begin(), t.end(), [](const ID& a, const ID& b) { - return a.x == b.x && a.y == b.y; - }), t.end()); + t.erase(std::unique(t.begin(), t.end(), [](const ID& a, const ID& b) { return a.x == b.x && a.y == b.y; }), + t.end()); std::vector result; result.reserve(t.size()); @@ -147,7 +151,9 @@ int32_t coveringZoomLevel(double zoom, style::SourceType type, uint16_t size) { } } -std::vector tileCover(const TransformState& state, uint8_t z, const std::optional& overscaledZ) { +std::vector tileCover(const TransformState& state, + uint8_t z, + const std::optional& overscaledZ) { struct Node { AABB aabb; uint8_t zoom; @@ -175,7 +181,8 @@ std::vector tileCover(const TransformState& state, uint8_t z, const Frustum frustum = Frustum::fromInvProjMatrix(state.getInvProjectionMatrix(), worldSize, z, flippedY); - // There should always be a certain number of maximum zoom level tiles surrounding the center location + // There should always be a certain number of maximum zoom level tiles + // surrounding the center location const double radiusOfMaxLvlLodInTiles = 3; const auto newRootTile = [&](int16_t wrap) -> Node { @@ -217,17 +224,19 @@ std::vector tileCover(const TransformState& state, uint8_t z, const double* longestDim = std::max_element(distanceXyz.data(), distanceXyz.data() + distanceXyz.size()); assert(longestDim); - // We're using distance based heuristics to determine if a tile should be split into quadrants or not. - // radiusOfMaxLvlLodInTiles defines that there's always a certain number of maxLevel tiles next to the map - // center. Using the fact that a parent node in quadtree is twice the size of its children (per dimension) we - // can define distance thresholds for each relative level: f(k) = offset + 2 + 4 + 8 + 16 + ... + 2^k. This is - // the same as "offset+2^(k+1)-2" + // We're using distance based heuristics to determine if a tile should + // be split into quadrants or not. radiusOfMaxLvlLodInTiles defines that + // there's always a certain number of maxLevel tiles next to the map + // center. Using the fact that a parent node in quadtree is twice the + // size of its children (per dimension) we can define distance + // thresholds for each relative level: f(k) = offset + 2 + 4 + 8 + 16 + + // ... + 2^k. This is the same as "offset+2^(k+1)-2" const double distToSplit = radiusOfMaxLvlLodInTiles + (1 << (maxZoom - node.zoom)) - 2; // Have we reached the target depth or is the tile too far away to be any split further? if (node.zoom == maxZoom || (*longestDim > distToSplit && node.zoom >= minZoom)) { - // Perform precise intersection test between the frustum and aabb. This will cull < 1% false positives - // missed by the original test + // Perform precise intersection test between the frustum and aabb. + // This will cull < 1% false positives missed by the original test if (node.fullyVisible || frustum.intersectsPrecise(node.aabb, true) != IntersectionResult::Separate) { const OverscaledTileID id = { node.zoom == maxZoom ? overscaledZoom : node.zoom, node.wrap, node.zoom, node.x, node.y}; @@ -270,23 +279,19 @@ std::vector tileCover(const TransformState& state, uint8_t z, } std::vector tileCover(const LatLngBounds& bounds_, uint8_t z) { - if (bounds_.isEmpty() || - bounds_.south() > util::LATITUDE_MAX || - bounds_.north() < -util::LATITUDE_MAX) { + if (bounds_.isEmpty() || bounds_.south() > util::LATITUDE_MAX || bounds_.north() < -util::LATITUDE_MAX) { return {}; } - LatLngBounds bounds = LatLngBounds::hull( - { std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west() }, - { std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east() }); - - return tileCover( - Projection::project(bounds.northwest(), z), - Projection::project(bounds.northeast(), z), - Projection::project(bounds.southeast(), z), - Projection::project(bounds.southwest(), z), - Projection::project(bounds.center(), z), - z); + LatLngBounds bounds = LatLngBounds::hull({std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west()}, + {std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east()}); + + return tileCover(Projection::project(bounds.northwest(), z), + Projection::project(bounds.northeast(), z), + Projection::project(bounds.southeast(), z), + Projection::project(bounds.southwest(), z), + Projection::project(bounds.center(), z), + z); } std::vector tileCover(const Geometry& geometry, uint8_t z) { @@ -302,7 +307,7 @@ std::vector tileCover(const Geometry& geometry, uint8_t // Taken from https://github.com/mapbox/sphericalmercator#xyzbbox-zoom-tms_style-srs // Computes the projected tiles for the lower left and upper right points of the bounds // and uses that to compute the tile cover count -uint64_t tileCount(const LatLngBounds& bounds, uint8_t zoom){ +uint64_t tileCount(const LatLngBounds& bounds, uint8_t zoom) { if (zoom == 0) { return 1; } @@ -329,14 +334,11 @@ uint64_t tileCount(const Geometry& geometry, uint8_t z) { return tileCount; } -TileCover::TileCover(const LatLngBounds&bounds_, uint8_t z) { - LatLngBounds bounds = LatLngBounds::hull( - { std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west() }, - { std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east() }); +TileCover::TileCover(const LatLngBounds& bounds_, uint8_t z) { + LatLngBounds bounds = LatLngBounds::hull({std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west()}, + {std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east()}); - if (bounds.isEmpty() || - bounds.south() > util::LATITUDE_MAX || - bounds.north() < -util::LATITUDE_MAX) { + if (bounds.isEmpty() || bounds.south() > util::LATITUDE_MAX || bounds.north() < -util::LATITUDE_MAX) { bounds = LatLngBounds::world(); } @@ -345,13 +347,12 @@ TileCover::TileCover(const LatLngBounds&bounds_, uint8_t z) { auto se = Projection::project(bounds.southeast(), z); auto nw = Projection::project(bounds.northwest(), z); - Polygon p({ {sw, nw, ne, se, sw} }); + Polygon p({{sw, nw, ne, se, sw}}); impl = std::make_unique(z, p, false); } -TileCover::TileCover(const Geometry& geom, uint8_t z, bool project/* = true*/) - : impl( std::make_unique(z, geom, project)) { -} +TileCover::TileCover(const Geometry& geom, uint8_t z, bool project /* = true*/) + : impl(std::make_unique(z, geom, project)) {} TileCover::~TileCover() = default; diff --git a/src/mbgl/util/tile_cover_impl.cpp b/src/mbgl/util/tile_cover_impl.cpp index 9cf2d109c87..9054be01b8f 100644 --- a/src/mbgl/util/tile_cover_impl.cpp +++ b/src/mbgl/util/tile_cover_impl.cpp @@ -24,18 +24,18 @@ void start_list_on_local_minimum(PointList& points) { auto pt = points.begin(); auto next_pt = std::next(pt); while (pt != points.end()) { - if ((pt->y <= prev_pt->y) && - (pt->y < next_pt->y)) { + if ((pt->y <= prev_pt->y) && (pt->y < next_pt->y)) { break; } prev_pt = pt; pt++; next_pt++; - if (next_pt == points.end()) { next_pt = std::next(points.begin()); } + if (next_pt == points.end()) { + next_pt = std::next(points.begin()); + } } - if (pt == points.end()) - return; - //Re-close linear rings with first_pt = last_pt + if (pt == points.end()) return; + // Re-close linear rings with first_pt = last_pt if (points.back() == points.front()) { points.pop_back(); } @@ -43,18 +43,23 @@ void start_list_on_local_minimum(PointList& points) { points.push_back(*points.begin()); } -//Create a bound towards a local maximum point, starting from pt. -// Traverse from current pt until the next pt changes y-direction, and copy -// all points from start to end (inclusive) into a Bound. +// Create a bound towards a local maximum point, starting from pt. +// Traverse from current pt until the next pt changes y-direction, and copy +// all points from start to end (inclusive) into a Bound. Bound create_bound_towards_maximum(PointList& points, PointList::iterator& pt) { - if (std::distance(pt, points.end()) < 2) { return {}; } + if (std::distance(pt, points.end()) < 2) { + return {}; + } const auto begin = pt; auto next_pt = std::next(begin); while (pt->y <= next_pt->y) { pt++; next_pt++; - if (next_pt == points.end()) { pt++; break; } + if (next_pt == points.end()) { + pt++; + break; + } } const auto pt_distance = std::distance(begin, next_pt); @@ -69,18 +74,23 @@ Bound create_bound_towards_maximum(PointList& points, PointList::iterator& pt) { return bnd; } -//Create a bound towards a local minimum point, starting from pt. -// Traverse from current pt until the next pt changes y-direction, and copy -// all points from start to end (inclusive) into a Bound. +// Create a bound towards a local minimum point, starting from pt. +// Traverse from current pt until the next pt changes y-direction, and copy +// all points from start to end (inclusive) into a Bound. Bound create_bound_towards_minimum(PointList& points, PointList::iterator& pt) { - if (std::distance(pt, points.end()) < 2) { return {}; } + if (std::distance(pt, points.end()) < 2) { + return {}; + } auto begin = pt; auto next_pt = std::next(begin); while (pt->y > next_pt->y) { pt++; next_pt++; - if (next_pt == points.end()) { pt++; break; } + if (next_pt == points.end()) { + pt++; + break; + } } const auto pt_distance = std::distance(begin, next_pt); @@ -89,20 +99,20 @@ Bound create_bound_towards_minimum(PointList& points, PointList::iterator& pt) { } Bound bnd; bnd.points.reserve(static_cast(std::distance(begin, next_pt))); - //For bounds that start at a max, reverse copy so that all bounds start at a min + // For bounds that start at a max, reverse copy so that all bounds start at a min std::reverse_copy(begin, next_pt, std::back_inserter(bnd.points)); bnd.winding = false; return bnd; } // Given a set of points (ring or list) representing a shape, compute a set of -// Bounds, where each Bound represents edges going from a local minima to a local -// maxima point. The BoundsMap is an edge table indexed on the starting Y-tile -// of each Bound. +// Bounds, where each Bound represents edges going from a local minima to a +// local maxima point. The BoundsMap is an edge table indexed on the starting +// Y-tile of each Bound. void build_bounds_map(PointList& points, uint32_t maxTile, BoundsMap& et, bool closed = false) { if (points.size() < 2) return; - //While traversing closed rings, start the bounds at a local minimum. - // (For linestrings the starting point is always a local maxima/minima) + // While traversing closed rings, start the bounds at a local minimum. + // (For linestrings the starting point is always a local maxima/minima) if (closed) { start_list_on_local_minimum(points); } @@ -114,13 +124,13 @@ void build_bounds_map(PointList& points, uint32_t maxTile, BoundsMap& et, bool c if (to_max.points.size() >= 2) { // Projections may result in values beyond the bounds, clamp to max tile coordinates - const auto y = - static_cast(std::floor(clamp(to_max.points.front().y, 0.0, static_cast(maxTile)))); + const auto y = static_cast( + std::floor(clamp(to_max.points.front().y, 0.0, static_cast(maxTile)))); et[y].push_back(to_max); } if (to_min.points.size() >= 2) { - const auto y = - static_cast(std::floor(clamp(to_min.points.front().y, 0.0, static_cast(maxTile)))); + const auto y = static_cast( + std::floor(clamp(to_min.points.front().y, 0.0, static_cast(maxTile)))); et[y].push_back(to_min); } } @@ -141,19 +151,19 @@ std::vector scan_row(uint32_t y, Bounds& activeBounds) { std::vector tile_range; tile_range.reserve(activeBounds.size()); - for(Bound& b: activeBounds) { - TileSpan xp = { INT_MAX, 0, b.winding }; + for (Bound& b : activeBounds) { + TileSpan xp = {INT_MAX, 0, b.winding}; double x; const auto numEdges = b.points.size() - 1; while (b.currentPoint < numEdges) { x = b.interpolate(y); update_span(xp, x); - // If this edge ends beyond the current row, find the x-intercept where - // it exits the row + // If this edge ends beyond the current row, find the x-intercept + // where it exits the row auto& p1 = b.points[b.currentPoint + 1]; - if (p1.y > y+1) { - x = b.interpolate(y+1); + if (p1.y > y + 1) { + x = b.interpolate(y + 1); update_span(xp, x); break; } else if (b.currentPoint == numEdges - 1) { @@ -169,15 +179,14 @@ std::vector scan_row(uint32_t y, Bounds& activeBounds) { // or there are no more edges auto bound = activeBounds.begin(); while (bound != activeBounds.end()) { - if ( bound->currentPoint == bound->points.size() - 1 && - bound->points[bound->currentPoint].y <= y+1) { + if (bound->currentPoint == bound->points.size() - 1 && bound->points[bound->currentPoint].y <= y + 1) { bound = activeBounds.erase(bound); } else { bound++; } } // Sort the X-extents of each crossing bound by x_min, x_max - std::sort(tile_range.begin(), tile_range.end(), [] (TileSpan& a, TileSpan& b) { + std::sort(tile_range.begin(), tile_range.end(), [](TileSpan& a, TileSpan& b) { return std::tie(a.xmin, a.xmax) < std::tie(b.xmin, b.xmax); }); @@ -187,15 +196,16 @@ std::vector scan_row(uint32_t y, Bounds& activeBounds) { struct BuildBoundsMap { int32_t zoom; bool project = false; - BuildBoundsMap(int32_t z, bool p): zoom(z), project(p) {} + BuildBoundsMap(int32_t z, bool p) + : zoom(z), + project(p) {} void buildTable(const std::vector>& points, BoundsMap& et, bool closed = false) const { PointList projectedPoints; if (project) { projectedPoints.reserve(points.size()); - for(const auto&p : points) { - projectedPoints.push_back( - Projection::project(LatLng{ p.y, p.x }, zoom)); + for (const auto& p : points) { + projectedPoints.push_back(Projection::project(LatLng{p.y, p.x}, zoom)); } } else { projectedPoints.insert(projectedPoints.end(), points.begin(), points.end()); @@ -204,15 +214,13 @@ struct BuildBoundsMap { } void buildPolygonTable(const Polygon& polygon, BoundsMap& et) const { - for(const auto&ring : polygon) { + for (const auto& ring : polygon) { buildTable(ring, et, true); } } - BoundsMap operator()(const EmptyGeometry&) const { - return {}; - } + BoundsMap operator()(const EmptyGeometry&) const { return {}; } - BoundsMap operator()(const Point&p) const { + BoundsMap operator()(const Point& p) const { Bound bnd; auto point = p; if (project) { @@ -228,7 +236,7 @@ struct BuildBoundsMap { BoundsMap operator()(const MultiPoint& points) const { BoundsMap et; - for (const Point& p: points) { + for (const Point& p : points) { Bound bnd; auto point = p; if (project) { @@ -250,7 +258,7 @@ struct BuildBoundsMap { BoundsMap operator()(const MultiLineString& lines) const { BoundsMap et; - for(const auto&line : lines) { + for (const auto& line : lines) { buildTable(line, et); } return et; @@ -264,19 +272,17 @@ struct BuildBoundsMap { BoundsMap operator()(const MultiPolygon& polygons) const { BoundsMap et; - for(const auto& polygon: polygons) { + for (const auto& polygon : polygons) { buildPolygonTable(polygon, et); } return et; } - BoundsMap operator()(const mapbox::geometry::geometry_collection&) const { - return {}; - } + BoundsMap operator()(const mapbox::geometry::geometry_collection&) const { return {}; } }; TileCover::Impl::Impl(int32_t z, const Geometry& geom, bool project) - : zoom(z) { + : zoom(z) { ToFeatureType toFeatureType; isClosed = apply_visitor(toFeatureType, geom) == FeatureType::Polygon; @@ -284,7 +290,7 @@ TileCover::Impl::Impl(int32_t z, const Geometry& geom, bool project) boundsMap = apply_visitor(toBoundsMap, geom); if (boundsMap.empty()) return; - //Iniitalize the active edge table, and current row span + // Iniitalize the active edge table, and current row span currentBounds = boundsMap.begin(); tileY = 0; nextRow(); @@ -302,16 +308,15 @@ void TileCover::Impl::nextRow() { // Update activeBounds for next row if (currentBounds != boundsMap.end()) { if (activeBounds.empty() && currentBounds->first > tileY) { - //For multi-geoms: use the next row with an edge table starting point + // For multi-geoms: use the next row with an edge table starting point tileY = currentBounds->first; } if (tileY == currentBounds->first) { - std::move(currentBounds->second.begin(), currentBounds->second.end(), - std::back_inserter(activeBounds)); + std::move(currentBounds->second.begin(), currentBounds->second.end(), std::back_inserter(activeBounds)); currentBounds++; } } - //Scan the active bounds and update currentRange with x_min, x_max pairs + // Scan the active bounds and update currentRange with x_min, x_max pairs auto xps = util::scan_row(tileY, activeBounds); if (xps.empty()) { return; @@ -335,9 +340,7 @@ void TileCover::Impl::nextRow() { } bool TileCover::Impl::hasNext() const { - return (!tileXSpans.empty() - && tileX < tileXSpans.front().second - && tileY < (1u << zoom)); + return (!tileXSpans.empty() && tileX < tileXSpans.front().second && tileY < (1u << zoom)); } std::optional TileCover::Impl::next() { diff --git a/src/mbgl/util/tile_cover_impl.hpp b/src/mbgl/util/tile_cover_impl.hpp index fdb7ce16b1e..af48923bc79 100644 --- a/src/mbgl/util/tile_cover_impl.hpp +++ b/src/mbgl/util/tile_cover_impl.hpp @@ -49,7 +49,7 @@ struct Bound { auto x = p0.x; if (dx == 0) { return x; - } else if (dy == 0){ + } else if (dy == 0) { return y <= p0.y ? p0.x : p1.x; } if (y < p0.y) return x; @@ -59,20 +59,19 @@ struct Bound { } }; -// Implements a modified scan-line algorithm to provide a streaming interface for -// tile cover on arbitrary shapes. -// A `BoundsMap` is genereted from the input geometry where each tuple indicates -// the set of Bounds that start at a y tile coordinate. Each bound represents -// a chain of edges from a local y-minima to a local y-maxima. -// For each row, the activeBounds list aggregates all bounds that enter into or -// begin in that row. This running list of bounds is scanned, capturing the -// x-coordinates spanned by edges in a bound until the bound exits the row (or -// ends). The result is a set of (possibly overlapping) min,max pairs of x coordinates -// (spans). In the simplest case a span represents the x-coordinates at which a -// single edge intersects the top and bottom of a tile row. Interior tiles of a -// polygon are captured by merging spans using the non-zero rule. -// The result of a scan using `nextRow()` is a list of spans (tileXSpans) of x-coordinates -// that includes edges and interiors of polygons. +// Implements a modified scan-line algorithm to provide a streaming interface +// for tile cover on arbitrary shapes. A `BoundsMap` is genereted from the input +// geometry where each tuple indicates the set of Bounds that start at a y tile +// coordinate. Each bound represents a chain of edges from a local y-minima to a +// local y-maxima. For each row, the activeBounds list aggregates all bounds +// that enter into or begin in that row. This running list of bounds is scanned, +// capturing the x-coordinates spanned by edges in a bound until the bound exits +// the row (or ends). The result is a set of (possibly overlapping) min,max +// pairs of x coordinates (spans). In the simplest case a span represents the +// x-coordinates at which a single edge intersects the top and bottom of a tile +// row. Interior tiles of a polygon are captured by merging spans using the +// non-zero rule. The result of a scan using `nextRow()` is a list of spans +// (tileXSpans) of x-coordinates that includes edges and interiors of polygons. // next() returns a tileID for each x-coordinate from (first, second] in each // span in tileXSpans. class TileCover::Impl { diff --git a/src/mbgl/util/tile_range.hpp b/src/mbgl/util/tile_range.hpp index bfd62f706b1..9f8da359631 100644 --- a/src/mbgl/util/tile_range.hpp +++ b/src/mbgl/util/tile_range.hpp @@ -21,21 +21,19 @@ class TileRange { auto swProj = Projection::project(bounds.southwest().wrapped(), maxZoom); auto ne = bounds.northeast(); - auto neProj = Projection::project(ne.longitude() > util::LONGITUDE_MAX ? ne.wrapped() : ne , maxZoom); + auto neProj = Projection::project(ne.longitude() > util::LONGITUDE_MAX ? ne.wrapped() : ne, maxZoom); const auto maxTile = std::pow(2.0, maxZoom); const auto minX = static_cast(std::floor(swProj.x)); const auto maxX = static_cast(std::floor(neProj.x)); - const auto minY = static_cast(util::clamp(std::floor(neProj.y), 0.0 , maxTile)); + const auto minY = static_cast(util::clamp(std::floor(neProj.y), 0.0, maxTile)); const auto maxY = static_cast(util::clamp(std::floor(swProj.y), 0.0, maxTile)); return {{{minX, minY}, {maxX, maxY}}, {minZoom, maxZoom}}; } // Compute the range of tiles covered by the bounds. - static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t z) { - return fromLatLngBounds(bounds, z, z); - } + static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t z) { return fromLatLngBounds(bounds, z, z); } bool contains(const CanonicalTileID& tileID) { if (tileID.z <= zoomRange.max && tileID.z >= zoomRange.min) { @@ -47,20 +45,18 @@ class TileRange { auto x1 = range.max.x >> dz; auto y0 = range.min.y >> dz; auto y1 = range.max.y >> dz; - return (range.min.x > range.max.x ? //For wrapped bounds - tileID.x >= x0 || tileID.x <= x1 : - tileID.x <= x1 && tileID.x >= x0) && - tileID.y <= y1 && - tileID.y >= y0; + return (range.min.x > range.max.x ? // For wrapped bounds + tileID.x >= x0 || tileID.x <= x1 + : tileID.x <= x1 && tileID.x >= x0) && + tileID.y <= y1 && tileID.y >= y0; } return false; } private: TileRange(Range> range_, Range z_) - : range(range_), - zoomRange(z_) { - } + : range(range_), + zoomRange(z_) {} }; } // namespace util diff --git a/src/mbgl/util/tile_server_options.cpp b/src/mbgl/util/tile_server_options.cpp index 5e5918a246f..61a050152e9 100644 --- a/src/mbgl/util/tile_server_options.cpp +++ b/src/mbgl/util/tile_server_options.cpp @@ -2,282 +2,287 @@ namespace mbgl { - class TileServerOptions::Impl { - public: - std::string baseURL; - std::optional versionPrefix; - std::string uriSchemeAlias; - - std::string sourceTemplate; - std::string sourceDomainName; - std::optional sourceVersionPrefix; - - std::string styleTemplate; - std::string styleDomainName; - std::optional styleVersionPrefix; - - std::string spritesTemplate; - std::string spritesDomainName; - std::optional spritesVersionPrefix; - - std::string glyphsTemplate; - std::string glyphsDomainName; - std::optional glyphsVersionPrefix; - - std::string tileTemplate; - std::string tileDomainName; - std::optional tileVersionPrefix; - - std::string apiKeyParameterName; - bool apiKeyRequired; - - std::vector defaultStyles; - std::string defaultStyle; - }; - - - TileServerOptions::TileServerOptions() : impl_(std::make_unique()) {} - TileServerOptions::~TileServerOptions() = default; - - // movable - TileServerOptions::TileServerOptions(TileServerOptions &&) noexcept = default; - TileServerOptions& TileServerOptions::operator=(TileServerOptions &&) noexcept = default; - - // copyable - TileServerOptions::TileServerOptions(const TileServerOptions& options) - : impl_(std::make_unique(*options.impl_)) {} - - TileServerOptions TileServerOptions::clone() const { - return TileServerOptions(*this); - } - - TileServerOptions& TileServerOptions::withBaseURL(std::string url) { - impl_->baseURL = std::move(url); - return *this; - } - - const std::string& TileServerOptions::baseURL() const { - return impl_->baseURL; - } - - TileServerOptions& TileServerOptions::withUriSchemeAlias(std::string alias) { - impl_->uriSchemeAlias = std::move(alias); - return *this; - } - - const std::string& TileServerOptions::uriSchemeAlias() const { - return impl_->uriSchemeAlias; - } - - TileServerOptions& TileServerOptions::withSourceTemplate(std::string sourceTemplate, std::string domainName, std::optional versionPrefix) { - impl_->sourceTemplate = std::move(sourceTemplate); - impl_->sourceVersionPrefix = std::move(versionPrefix); - impl_->sourceDomainName = std::move(domainName); - return *this; - } - - const std::string& TileServerOptions::sourceTemplate() const { - return impl_->sourceTemplate; - } - - const std::string& TileServerOptions::sourceDomainName() const { - return impl_->sourceDomainName; - } - - const std::optional& TileServerOptions::sourceVersionPrefix() const { - return impl_->sourceVersionPrefix; - } - - TileServerOptions& TileServerOptions::withStyleTemplate(std::string styleTemplate, std::string domainName, std::optional versionPrefix) { - impl_->styleTemplate = std::move(styleTemplate); - impl_->styleDomainName = std::move(domainName); - impl_->styleVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::styleTemplate() const { - return impl_->styleTemplate; - } - - const std::string& TileServerOptions::styleDomainName() const { - return impl_->styleDomainName; - } - - const std::optional& TileServerOptions::styleVersionPrefix() const { - return impl_->styleVersionPrefix; - } - - TileServerOptions& TileServerOptions::withSpritesTemplate(std::string spritesTemplate, std::string domainName, std::optional versionPrefix) { - impl_->spritesTemplate = std::move(spritesTemplate); - impl_->spritesDomainName = std::move(domainName); - impl_->spritesVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::spritesTemplate() const { - return impl_->spritesTemplate; - } - - const std::string& TileServerOptions::spritesDomainName() const { - return impl_->spritesDomainName; - } - - const std::optional& TileServerOptions::spritesVersionPrefix() const { - return impl_->spritesVersionPrefix; - } - - TileServerOptions& TileServerOptions::withGlyphsTemplate(std::string glyphsTemplate, std::string domainName, std::optional versionPrefix) { - impl_->glyphsTemplate = std::move(glyphsTemplate); - impl_->glyphsDomainName = std::move(domainName); - impl_->glyphsVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::glyphsTemplate() const { - return impl_->glyphsTemplate; - } - - const std::string& TileServerOptions::glyphsDomainName() const { - return impl_->glyphsDomainName; - } - - const std::optional& TileServerOptions::glyphsVersionPrefix() const { - return impl_->glyphsVersionPrefix; - } - - TileServerOptions& TileServerOptions::withTileTemplate(std::string tileTemplate, std::string domainName, std::optional versionPrefix) { - impl_->tileTemplate = std::move(tileTemplate); - impl_->tileDomainName = std::move(domainName); - impl_->tileVersionPrefix = std::move(versionPrefix); - return *this; - } - - const std::string& TileServerOptions::tileTemplate() const { - return impl_->tileTemplate; - } - - const std::string& TileServerOptions::tileDomainName() const { - return impl_->tileDomainName; - } - - const std::optional& TileServerOptions::tileVersionPrefix() const { - return impl_->tileVersionPrefix; - } - - TileServerOptions& TileServerOptions::withApiKeyParameterName(std::string apiKeyParameterName) { - impl_->apiKeyParameterName = std::move(apiKeyParameterName); - return *this; - } - - const std::string& TileServerOptions::apiKeyParameterName() const { - return impl_->apiKeyParameterName; - } - - TileServerOptions& TileServerOptions::setRequiresApiKey(bool apiKeyRequired) { - impl_->apiKeyRequired = apiKeyRequired; - return *this; - } - - bool TileServerOptions::requiresApiKey() const { - return impl_->apiKeyRequired; - } - - const std::vector TileServerOptions::defaultStyles() const { - return impl_->defaultStyles; - } - - TileServerOptions& TileServerOptions::withDefaultStyles(std::vector styles) { - impl_->defaultStyles = std::move(styles); - return *this; - } - - TileServerOptions& TileServerOptions::withDefaultStyle(std::string defaultStyle) { - impl_->defaultStyle = std::move(defaultStyle); - return *this; - } - - const std::string& TileServerOptions::defaultStyle() const { - return impl_->defaultStyle; - } - - TileServerOptions TileServerOptions::DefaultConfiguration() { - return MapLibreConfiguration(); - } - - TileServerOptions TileServerOptions::MapLibreConfiguration() { - std::vector styles { - // https://demotiles.maplibre.org/style.json - mbgl::util::DefaultStyle("maplibre://maps/style", "Basic", 1) - }; - - TileServerOptions options = TileServerOptions() - .withBaseURL("https://demotiles.maplibre.org") - .withUriSchemeAlias("maplibre") - .withApiKeyParameterName("") - .withSourceTemplate("/tiles/{domain}.json", "", {}) - .withStyleTemplate("{path}.json", "maps", {}) - .withSpritesTemplate("/{path}/sprite{scale}.{format}", "", {}) - .withGlyphsTemplate("/font/{fontstack}/{start}-{end}.pbf", "fonts", {}) - .withTileTemplate("/{path}", "tiles", {}) - .withDefaultStyles(styles) - .withDefaultStyle("Basic") - .setRequiresApiKey(false); - return options; - } - - // - - TileServerOptions TileServerOptions::MapboxConfiguration() { - std::vector styles { - mbgl::util::DefaultStyle("mapbox://styles/mapbox/streets-v11", "Streets", 11), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/outdoors-v11", "Outdoors", 11), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/light-v10", "Light", 10), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/dark-v10", "Dark", 10), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-v9", "Satellite", 9), - mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-streets-v11", - "Satellite Streets", 11) - }; - - TileServerOptions options = TileServerOptions() - .withBaseURL("https://api.mapbox.com") - .withUriSchemeAlias("mapbox") - .withApiKeyParameterName("access_token") - .withSourceTemplate("/{domain}.json", "", {"/v4"}) - .withStyleTemplate("/styles/v1{path}", "styles", {}) - .withSpritesTemplate("/styles/v1{directory}{filename}/sprite{extension}", "sprites", {}) - .withGlyphsTemplate("/fonts/v1{path}", "fonts", {}) - .withTileTemplate("{path}", "tiles", {"/v4"}) - .withDefaultStyles(styles) - .withDefaultStyle("Streets") - .setRequiresApiKey(true); - return options; - } - - TileServerOptions TileServerOptions::MapTilerConfiguration() { - - std::vector styles{ - mbgl::util::DefaultStyle("maptiler://maps/streets", "Streets", 1), - mbgl::util::DefaultStyle("maptiler://maps/outdoor", "Outdoor", 1), - mbgl::util::DefaultStyle("maptiler://maps/basic", "Basic", 1), - mbgl::util::DefaultStyle("maptiler://maps/bright", "Bright", 1), - mbgl::util::DefaultStyle("maptiler://maps/pastel", "Pastel", 1), - mbgl::util::DefaultStyle("maptiler://maps/hybrid", "Satellite Hybrid", 1), - mbgl::util::DefaultStyle("maptiler://maps/topo", "Satellite Topo", 1) - }; - - TileServerOptions options = TileServerOptions() - .withBaseURL("https://api.maptiler.com") - .withUriSchemeAlias("maptiler") - .withApiKeyParameterName("key") - .withSourceTemplate("/tiles{path}/tiles.json", "sources", {}) - .withStyleTemplate("/maps{path}/style.json", "maps", {}) - .withSpritesTemplate("/maps{path}", "sprites", {}) - .withGlyphsTemplate("/fonts{path}", "fonts", {}) - .withTileTemplate("{path}", "tiles", {}) - .withDefaultStyles(styles) - .withDefaultStyle("Streets") - .setRequiresApiKey(true); - return options; - } - -} // namespace mbgl +class TileServerOptions::Impl { +public: + std::string baseURL; + std::optional versionPrefix; + std::string uriSchemeAlias; + + std::string sourceTemplate; + std::string sourceDomainName; + std::optional sourceVersionPrefix; + + std::string styleTemplate; + std::string styleDomainName; + std::optional styleVersionPrefix; + + std::string spritesTemplate; + std::string spritesDomainName; + std::optional spritesVersionPrefix; + + std::string glyphsTemplate; + std::string glyphsDomainName; + std::optional glyphsVersionPrefix; + + std::string tileTemplate; + std::string tileDomainName; + std::optional tileVersionPrefix; + + std::string apiKeyParameterName; + bool apiKeyRequired; + + std::vector defaultStyles; + std::string defaultStyle; +}; + +TileServerOptions::TileServerOptions() + : impl_(std::make_unique()) {} +TileServerOptions::~TileServerOptions() = default; + +// movable +TileServerOptions::TileServerOptions(TileServerOptions&&) noexcept = default; +TileServerOptions& TileServerOptions::operator=(TileServerOptions&&) noexcept = default; + +// copyable +TileServerOptions::TileServerOptions(const TileServerOptions& options) + : impl_(std::make_unique(*options.impl_)) {} + +TileServerOptions TileServerOptions::clone() const { + return TileServerOptions(*this); +} + +TileServerOptions& TileServerOptions::withBaseURL(std::string url) { + impl_->baseURL = std::move(url); + return *this; +} + +const std::string& TileServerOptions::baseURL() const { + return impl_->baseURL; +} + +TileServerOptions& TileServerOptions::withUriSchemeAlias(std::string alias) { + impl_->uriSchemeAlias = std::move(alias); + return *this; +} + +const std::string& TileServerOptions::uriSchemeAlias() const { + return impl_->uriSchemeAlias; +} + +TileServerOptions& TileServerOptions::withSourceTemplate(std::string sourceTemplate, + std::string domainName, + std::optional versionPrefix) { + impl_->sourceTemplate = std::move(sourceTemplate); + impl_->sourceVersionPrefix = std::move(versionPrefix); + impl_->sourceDomainName = std::move(domainName); + return *this; +} + +const std::string& TileServerOptions::sourceTemplate() const { + return impl_->sourceTemplate; +} + +const std::string& TileServerOptions::sourceDomainName() const { + return impl_->sourceDomainName; +} + +const std::optional& TileServerOptions::sourceVersionPrefix() const { + return impl_->sourceVersionPrefix; +} + +TileServerOptions& TileServerOptions::withStyleTemplate(std::string styleTemplate, + std::string domainName, + std::optional versionPrefix) { + impl_->styleTemplate = std::move(styleTemplate); + impl_->styleDomainName = std::move(domainName); + impl_->styleVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::styleTemplate() const { + return impl_->styleTemplate; +} + +const std::string& TileServerOptions::styleDomainName() const { + return impl_->styleDomainName; +} + +const std::optional& TileServerOptions::styleVersionPrefix() const { + return impl_->styleVersionPrefix; +} + +TileServerOptions& TileServerOptions::withSpritesTemplate(std::string spritesTemplate, + std::string domainName, + std::optional versionPrefix) { + impl_->spritesTemplate = std::move(spritesTemplate); + impl_->spritesDomainName = std::move(domainName); + impl_->spritesVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::spritesTemplate() const { + return impl_->spritesTemplate; +} + +const std::string& TileServerOptions::spritesDomainName() const { + return impl_->spritesDomainName; +} + +const std::optional& TileServerOptions::spritesVersionPrefix() const { + return impl_->spritesVersionPrefix; +} + +TileServerOptions& TileServerOptions::withGlyphsTemplate(std::string glyphsTemplate, + std::string domainName, + std::optional versionPrefix) { + impl_->glyphsTemplate = std::move(glyphsTemplate); + impl_->glyphsDomainName = std::move(domainName); + impl_->glyphsVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::glyphsTemplate() const { + return impl_->glyphsTemplate; +} + +const std::string& TileServerOptions::glyphsDomainName() const { + return impl_->glyphsDomainName; +} + +const std::optional& TileServerOptions::glyphsVersionPrefix() const { + return impl_->glyphsVersionPrefix; +} + +TileServerOptions& TileServerOptions::withTileTemplate(std::string tileTemplate, + std::string domainName, + std::optional versionPrefix) { + impl_->tileTemplate = std::move(tileTemplate); + impl_->tileDomainName = std::move(domainName); + impl_->tileVersionPrefix = std::move(versionPrefix); + return *this; +} + +const std::string& TileServerOptions::tileTemplate() const { + return impl_->tileTemplate; +} + +const std::string& TileServerOptions::tileDomainName() const { + return impl_->tileDomainName; +} + +const std::optional& TileServerOptions::tileVersionPrefix() const { + return impl_->tileVersionPrefix; +} + +TileServerOptions& TileServerOptions::withApiKeyParameterName(std::string apiKeyParameterName) { + impl_->apiKeyParameterName = std::move(apiKeyParameterName); + return *this; +} + +const std::string& TileServerOptions::apiKeyParameterName() const { + return impl_->apiKeyParameterName; +} + +TileServerOptions& TileServerOptions::setRequiresApiKey(bool apiKeyRequired) { + impl_->apiKeyRequired = apiKeyRequired; + return *this; +} + +bool TileServerOptions::requiresApiKey() const { + return impl_->apiKeyRequired; +} + +const std::vector TileServerOptions::defaultStyles() const { + return impl_->defaultStyles; +} + +TileServerOptions& TileServerOptions::withDefaultStyles(std::vector styles) { + impl_->defaultStyles = std::move(styles); + return *this; +} + +TileServerOptions& TileServerOptions::withDefaultStyle(std::string defaultStyle) { + impl_->defaultStyle = std::move(defaultStyle); + return *this; +} + +const std::string& TileServerOptions::defaultStyle() const { + return impl_->defaultStyle; +} + +TileServerOptions TileServerOptions::DefaultConfiguration() { + return MapLibreConfiguration(); +} + +TileServerOptions TileServerOptions::MapLibreConfiguration() { + std::vector styles{// https://demotiles.maplibre.org/style.json + mbgl::util::DefaultStyle("maplibre://maps/style", "Basic", 1)}; + + TileServerOptions options = TileServerOptions() + .withBaseURL("https://demotiles.maplibre.org") + .withUriSchemeAlias("maplibre") + .withApiKeyParameterName("") + .withSourceTemplate("/tiles/{domain}.json", "", {}) + .withStyleTemplate("{path}.json", "maps", {}) + .withSpritesTemplate("/{path}/sprite{scale}.{format}", "", {}) + .withGlyphsTemplate("/font/{fontstack}/{start}-{end}.pbf", "fonts", {}) + .withTileTemplate("/{path}", "tiles", {}) + .withDefaultStyles(styles) + .withDefaultStyle("Basic") + .setRequiresApiKey(false); + return options; +} + +// + +TileServerOptions TileServerOptions::MapboxConfiguration() { + std::vector styles{ + mbgl::util::DefaultStyle("mapbox://styles/mapbox/streets-v11", "Streets", 11), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/outdoors-v11", "Outdoors", 11), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/light-v10", "Light", 10), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/dark-v10", "Dark", 10), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-v9", "Satellite", 9), + mbgl::util::DefaultStyle("mapbox://styles/mapbox/satellite-streets-v11", "Satellite Streets", 11)}; + + TileServerOptions options = TileServerOptions() + .withBaseURL("https://api.mapbox.com") + .withUriSchemeAlias("mapbox") + .withApiKeyParameterName("access_token") + .withSourceTemplate("/{domain}.json", "", {"/v4"}) + .withStyleTemplate("/styles/v1{path}", "styles", {}) + .withSpritesTemplate( + "/styles/v1{directory}{filename}/sprite{extension}", "sprites", {}) + .withGlyphsTemplate("/fonts/v1{path}", "fonts", {}) + .withTileTemplate("{path}", "tiles", {"/v4"}) + .withDefaultStyles(styles) + .withDefaultStyle("Streets") + .setRequiresApiKey(true); + return options; +} + +TileServerOptions TileServerOptions::MapTilerConfiguration() { + std::vector styles{ + mbgl::util::DefaultStyle("maptiler://maps/streets", "Streets", 1), + mbgl::util::DefaultStyle("maptiler://maps/outdoor", "Outdoor", 1), + mbgl::util::DefaultStyle("maptiler://maps/basic", "Basic", 1), + mbgl::util::DefaultStyle("maptiler://maps/bright", "Bright", 1), + mbgl::util::DefaultStyle("maptiler://maps/pastel", "Pastel", 1), + mbgl::util::DefaultStyle("maptiler://maps/hybrid", "Satellite Hybrid", 1), + mbgl::util::DefaultStyle("maptiler://maps/topo", "Satellite Topo", 1)}; + + TileServerOptions options = TileServerOptions() + .withBaseURL("https://api.maptiler.com") + .withUriSchemeAlias("maptiler") + .withApiKeyParameterName("key") + .withSourceTemplate("/tiles{path}/tiles.json", "sources", {}) + .withStyleTemplate("/maps{path}/style.json", "maps", {}) + .withSpritesTemplate("/maps{path}", "sprites", {}) + .withGlyphsTemplate("/fonts{path}", "fonts", {}) + .withTileTemplate("{path}", "tiles", {}) + .withDefaultStyles(styles) + .withDefaultStyle("Streets") + .setRequiresApiKey(true); + return options; +} + +} // namespace mbgl diff --git a/src/mbgl/util/tiny_sdf.cpp b/src/mbgl/util/tiny_sdf.cpp index 3a7ef999861..bcd9f1d51f8 100644 --- a/src/mbgl/util/tiny_sdf.cpp +++ b/src/mbgl/util/tiny_sdf.cpp @@ -12,11 +12,8 @@ namespace tinysdf { static const double INF = 1e20; // 1D squared distance transform -void edt1d(std::vector& f, - std::vector& d, - std::vector& v, - std::vector& z, - uint32_t n) { +void edt1d( + std::vector& f, std::vector& d, std::vector& v, std::vector& z, uint32_t n) { v[0] = 0; z[0] = -INF; z[1] = +INF; @@ -39,7 +36,6 @@ void edt1d(std::vector& f, } } - // 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/ void edt(std::vector& data, uint32_t width, @@ -73,9 +69,9 @@ void edt(std::vector& data, AlphaImage transformRasterToSDF(const AlphaImage& rasterInput, double radius, double cutoff) { uint32_t size = rasterInput.size.width * rasterInput.size.height; uint32_t maxDimension = std::max(rasterInput.size.width, rasterInput.size.height); - + AlphaImage sdf(rasterInput.size); - + // temporary arrays for the distance transform std::vector gridOuter(size); std::vector gridInner(size); @@ -83,7 +79,7 @@ AlphaImage transformRasterToSDF(const AlphaImage& rasterInput, double radius, do std::vector d(maxDimension); std::vector z(maxDimension + 1); std::vector v(maxDimension); - + for (uint32_t i = 0; i < size; i++) { double a = static_cast(rasterInput.data[i]) / 255; // alpha value gridOuter[i] = a == 1.0 ? 0.0 : a == 0.0 ? tinysdf::INF : std::pow(std::max(0.0, 0.5 - a), 2.0); @@ -95,7 +91,8 @@ AlphaImage transformRasterToSDF(const AlphaImage& rasterInput, double radius, do for (uint32_t i = 0; i < size; i++) { double distance = gridOuter[i] - gridInner[i]; - sdf.data[i] = static_cast(std::max(0l, std::min(255l, ::lround(255.0 - 255.0 * (distance / radius + cutoff))))); + sdf.data[i] = static_cast( + std::max(0l, std::min(255l, ::lround(255.0 - 255.0 * (distance / radius + cutoff))))); } return sdf; diff --git a/src/mbgl/util/tiny_sdf.hpp b/src/mbgl/util/tiny_sdf.hpp index 33c9280cbdf..1395f5ad6b6 100644 --- a/src/mbgl/util/tiny_sdf.hpp +++ b/src/mbgl/util/tiny_sdf.hpp @@ -6,11 +6,12 @@ namespace mbgl { namespace util { /* - C++ port of https://github.com/mapbox/tiny-sdf, which is in turn based on the - Felzenszwalb/Huttenlocher distance transform paper (https://cs.brown.edu/~pff/papers/dt-final.pdf). - Note there exists an alternative C++ implementation from the paper’s authors at - https://cs.brown.edu/~pff/dt/, which this implementation is not based on. - + C++ port of https://github.com/mapbox/tiny-sdf, which is in turn based on + the Felzenszwalb/Huttenlocher distance transform paper + (https://cs.brown.edu/~pff/papers/dt-final.pdf). Note there exists an + alternative C++ implementation from the paper’s authors at + https://cs.brown.edu/~pff/dt/, which this implementation is not based on. + Takes an alpha channel raster input and transforms it into an alpha channel Signed Distance Field (SDF) output of the same dimensions. */ diff --git a/src/mbgl/util/token.hpp b/src/mbgl/util/token.hpp index f2fc334cc48..05e295ad077 100644 --- a/src/mbgl/util/token.hpp +++ b/src/mbgl/util/token.hpp @@ -24,9 +24,10 @@ std::string replaceTokens(const std::string &source, const Lookup &lookup) { result.append(pos, brace); pos = brace; if (pos != end) { - for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++); + for (brace++; brace != end && tokenReservedChars.find(*brace) == std::string::npos; brace++) + ; if (brace != end && *brace == '}') { - std::string key { pos + 1, brace }; + std::string key{pos + 1, brace}; if (std::optional replacement = lookup(key)) { result.append(*replacement); } else { diff --git a/src/mbgl/util/url.cpp b/src/mbgl/util/url.cpp index 9dbefaebcb8..8d29374cddd 100644 --- a/src/mbgl/util/url.cpp +++ b/src/mbgl/util/url.cpp @@ -73,15 +73,15 @@ URL::URL(const std::string& str) const auto hashPos = str.find('#'); const auto queryPos = str.find('?'); if (queryPos == std::string::npos || hashPos < queryPos) { - return { hashPos != std::string::npos ? hashPos : str.size(), 0 }; + return {hashPos != std::string::npos ? hashPos : str.size(), 0}; } - return { queryPos, (hashPos != std::string::npos ? hashPos : str.size()) - queryPos }; + return {queryPos, (hashPos != std::string::npos ? hashPos : str.size()) - queryPos}; }()), scheme([&]() -> Segment { - if (str.empty() || !isAlphaCharacter(str.front())) return { 0, 0 }; + if (str.empty() || !isAlphaCharacter(str.front())) return {0, 0}; size_t schemeEnd = 0; while (schemeEnd < query.first && isSchemeCharacter(str[schemeEnd])) ++schemeEnd; - return { 0, str[schemeEnd] == ':' ? schemeEnd : 0 }; + return {0, str[schemeEnd] == ':' ? schemeEnd : 0}; }()), domain([&]() -> Segment { auto domainPos = scheme.first + scheme.second; @@ -90,7 +90,7 @@ URL::URL(const std::string& str) } const bool isData = str.compare(scheme.first, scheme.second, "data") == 0; const auto endPos = str.find(isData ? ',' : '/', domainPos); - return { domainPos, std::min(query.first, endPos) - domainPos }; + return {domainPos, std::min(query.first, endPos) - domainPos}; }()), path([&]() -> Segment { auto pathPos = domain.first + domain.second; @@ -99,16 +99,15 @@ URL::URL(const std::string& str) // Skip comma pathPos++; } - return { pathPos, query.first - pathPos }; - }()) { -} + return {pathPos, query.first - pathPos}; + }()) {} Path::Path(const std::string& str, const size_t pos, const size_t count) : directory([&]() -> Segment { // Finds the string between pos and the first /, if it exists const auto endPos = count == std::string::npos ? str.size() : pos + count; const auto slashPos = str.rfind('/', endPos); - return { pos, slashPos == std::string::npos || slashPos < pos ? 0 : slashPos + 1 - pos }; + return {pos, slashPos == std::string::npos || slashPos < pos ? 0 : slashPos + 1 - pos}; }()), extension([&]() -> Segment { auto dotPos = str.rfind('.', pos + count); @@ -116,20 +115,18 @@ Path::Path(const std::string& str, const size_t pos, const size_t count) // Count a preceding @2x to the file extension as well. const char* factor = "@2x"; const size_t factorLen = strlen(factor); - if (dotPos >= factorLen && dotPos < endPos && - str.compare(dotPos - factorLen, factorLen, factor) == 0) { + if (dotPos >= factorLen && dotPos < endPos && str.compare(dotPos - factorLen, factorLen, factor) == 0) { dotPos -= factorLen; } if (dotPos == std::string::npos || dotPos < directory.first + directory.second) { - return { endPos, 0 }; + return {endPos, 0}; } - return { dotPos, endPos - dotPos }; + return {dotPos, endPos - dotPos}; }()), filename([&]() -> Segment { const auto filePos = directory.first + directory.second; - return { filePos, extension.first - filePos }; - }()) { -} + return {filePos, extension.first - filePos}; + }()) {} std::string transformURL(const std::string& tpl, const std::string& str, const URL& url) { auto result = util::replaceTokens(tpl, [&](const std::string& token) -> std::optional { diff --git a/src/mbgl/util/url.hpp b/src/mbgl/util/url.hpp index 33522b416ce..04ef4676256 100644 --- a/src/mbgl/util/url.hpp +++ b/src/mbgl/util/url.hpp @@ -22,9 +22,10 @@ class URL { URL(const std::string&); }; -// Class that holds position + lenth pairs for directory, extension, and filename of a path. -// The extension will contain the preceding ., and optionally a preceding @2x specifier. -// The filename will not contain the file extension. +// Class that holds position + lenth pairs for directory, extension, and +// filename of a path. The extension will contain the preceding ., and +// optionally a preceding @2x specifier. The filename will not contain the file +// extension. class Path { public: using Segment = std::pair; // position, length @@ -36,8 +37,8 @@ class Path { Path(const std::string&, size_t pos = 0, size_t count = std::string::npos); }; -// Parses the given URL and replaces the tokens in template with parts of the URL. -// When parsing "http://example.com/foo/bar/baz.png", valid tokens are: +// Parses the given URL and replaces the tokens in template with parts of the +// URL. When parsing "http://example.com/foo/bar/baz.png", valid tokens are: // * {scheme} == "http" // * {domain} == "example.com" // * {path} == "foo/bar/baz.png" diff --git a/src/mbgl/util/work_request.cpp b/src/mbgl/util/work_request.cpp index eb84df7bf2c..635e480fbf8 100644 --- a/src/mbgl/util/work_request.cpp +++ b/src/mbgl/util/work_request.cpp @@ -6,7 +6,8 @@ namespace mbgl { -WorkRequest::WorkRequest(Task task_) : task(std::move(task_)) { +WorkRequest::WorkRequest(Task task_) + : task(std::move(task_)) { assert(task); } diff --git a/test/actor/actor.test.cpp b/test/actor/actor.test.cpp index 5b395074ed0..033a29e86e2 100644 --- a/test/actor/actor.test.cpp +++ b/test/actor/actor.test.cpp @@ -26,7 +26,8 @@ TEST(Actor, Construction) { TEST(Actor, Destruction) { struct TestActor { - TestActor(ActorRef, bool& destructed_) : destructed(destructed_){}; + TestActor(ActorRef, bool& destructed_) + : destructed(destructed_){}; ~TestActor() { destructed = true; } bool& destructed; @@ -47,7 +48,9 @@ TEST(Actor, DestructionBlocksOnReceive) { std::atomic waited; TestActor(ActorRef, std::promise promise_, std::future future_) - : promise(std::move(promise_)), future(std::move(future_)), waited(false) {} + : promise(std::move(promise_)), + future(std::move(future_)), + waited(false) {} ~TestActor() { EXPECT_TRUE(waited.load()); } @@ -84,12 +87,9 @@ TEST(Actor, DestructionBlocksOnSend) { TestScheduler(std::promise promise_, std::future future_) : promise(std::move(promise_)), future(std::move(future_)), - waited(false) { - } + waited(false) {} - ~TestScheduler() override { - EXPECT_TRUE(waited.load()); - } + ~TestScheduler() override { EXPECT_TRUE(waited.load()); } void schedule(std::function) final { promise.set_value(); @@ -133,9 +133,7 @@ TEST(Actor, DestructionAllowedInReceiveOnSameThread) { struct TestActor { TestActor(ActorRef){}; - void callMeBack(std::function callback) { - callback(); - } + void callMeBack(std::function callback) { callback(); } }; std::promise callbackFiredPromise; @@ -161,9 +159,7 @@ TEST(Actor, SelfDestructionDoesntCrashWaitingReceivingThreads) { struct TestActor { TestActor(ActorRef){}; - void callMeBack(std::function callback) { - callback(); - } + void callMeBack(std::function callback) { callback(); } }; std::promise actorClosedPromise; @@ -171,7 +167,7 @@ TEST(Actor, SelfDestructionDoesntCrashWaitingReceivingThreads) { auto closingActor = std::make_unique>(Scheduler::GetBackground()); auto waitingActor = std::make_unique>(Scheduler::GetBackground()); - std::atomic waitingMessageProcessed {false}; + std::atomic waitingMessageProcessed{false}; // Callback (triggered while mutex is locked in Mailbox::receive()) closingActor->self().invoke(&TestActor::callMeBack, [&]() { @@ -187,10 +183,7 @@ TEST(Actor, SelfDestructionDoesntCrashWaitingReceivingThreads) { }); // Wait for the message to be queued - ASSERT_EQ( - messageQueuedPromise.get_future().wait_for(std::chrono::seconds(1)), - std::future_status::ready - ); + ASSERT_EQ(messageQueuedPromise.get_future().wait_for(std::chrono::seconds(1)), std::future_status::ready); // Destroy the Actor/Mailbox in the same thread closingActor.reset(); @@ -209,16 +202,15 @@ TEST(Actor, OrderedMailbox) { int last = 0; std::promise promise; - TestActor(ActorRef, std::promise promise_) : promise(std::move(promise_)) {} + TestActor(ActorRef, std::promise promise_) + : promise(std::move(promise_)) {} void receive(int i) { EXPECT_EQ(i, last + 1); last = i; } - void end() { - promise.set_value(); - } + void end() { promise.set_value(); } }; std::promise endedPromise; @@ -240,7 +232,8 @@ TEST(Actor, NonConcurrentMailbox) { int last = 0; std::promise promise; - TestActor(ActorRef, std::promise promise_) : promise(std::move(promise_)) {} + TestActor(ActorRef, std::promise promise_) + : promise(std::move(promise_)) {} void receive(int i) { EXPECT_EQ(i, last + 1); @@ -248,9 +241,7 @@ TEST(Actor, NonConcurrentMailbox) { std::this_thread::sleep_for(1ms); } - void end() { - promise.set_value(); - } + void end() { promise.set_value(); } }; std::promise endedPromise; @@ -271,9 +262,7 @@ TEST(Actor, Ask) { struct TestActor { TestActor(ActorRef) {} - int doubleIt(int i) { - return i * 2; - } + int doubleIt(int i) { return i * 2; } }; Actor test(Scheduler::GetBackground()); @@ -293,11 +282,10 @@ TEST(Actor, AskVoid) { struct TestActor { bool& executed; - TestActor(bool& executed_) : executed(executed_) {} + TestActor(bool& executed_) + : executed(executed_) {} - void doIt() { - executed = true; - } + void doIt() { executed = true; } }; bool executed = false; @@ -315,18 +303,14 @@ TEST(Actor, NoSelfActorRef) { Actor trivial(Scheduler::GetBackground()); - // With arguments struct WithArguments { std::promise promise; WithArguments(std::promise promise_) - : promise(std::move(promise_)) { - } + : promise(std::move(promise_)) {} - void receive() { - promise.set_value(); - } + void receive() { promise.set_value(); } }; std::promise promise; @@ -338,22 +322,20 @@ TEST(Actor, NoSelfActorRef) { } TEST(Actor, TwoPhaseConstruction) { - // This test mimics, in simplified form, the approach used by the Thread to construct - // its actor in two parts so that the Thread instance can be created without waiting - // for the target thread to be up and running. + // This test mimics, in simplified form, the approach used by the + // Thread to construct its actor in two parts so that the + // Thread instance can be created without waiting for the target + // thread to be up and running. struct TestActor { - TestActor(ActorRef, std::shared_ptr destroyed_) : destroyed(std::move(destroyed_)){}; + TestActor(ActorRef, std::shared_ptr destroyed_) + : destroyed(std::move(destroyed_)){}; ~TestActor() { *destroyed = true; } - void callMe(std::promise p) { - p.set_value(); - } + void callMe(std::promise p) { p.set_value(); } - void stop() { - util::RunLoop::Get()->stop(); - } + void stop() { util::RunLoop::Get()->stop(); } std::shared_ptr destroyed; }; @@ -368,10 +350,7 @@ TEST(Actor, TwoPhaseConstruction) { parent.self().invoke(&TestActor::callMe, std::move(queueExecuted)); parent.self().invoke(&TestActor::stop); - auto thread = std::thread([ - capturedArgs = std::make_tuple(destroyed), - &parent - ] () mutable { + auto thread = std::thread([capturedArgs = std::make_tuple(destroyed), &parent]() mutable { util::RunLoop loop(util::RunLoop::Type::New); EstablishedActor test(loop, parent, capturedArgs); loop.run(); @@ -383,5 +362,3 @@ TEST(Actor, TwoPhaseConstruction) { EXPECT_TRUE(*destroyed); } - - diff --git a/test/actor/actor_ref.test.cpp b/test/actor/actor_ref.test.cpp index 59917060317..5ef2adaf457 100644 --- a/test/actor/actor_ref.test.cpp +++ b/test/actor/actor_ref.test.cpp @@ -14,13 +14,12 @@ TEST(ActorRef, CanOutliveActor) { struct TestActorRef { bool& died; - TestActorRef(ActorRef, bool& died_) : died(died_) {} + TestActorRef(ActorRef, bool& died_) + : died(died_) {} ~TestActorRef() { died = true; } - void receive() { - FAIL(); - } + void receive() { FAIL(); } }; bool died = false; @@ -39,13 +38,9 @@ TEST(ActorRef, Ask) { struct TestActorRef { TestActorRef(ActorRef) {} - int gimme() { - return 20; - } + int gimme() { return 20; } - int echo(int i) { - return i; - } + int echo(int i) { return i; } }; Actor actor(Scheduler::GetBackground()); @@ -61,11 +56,10 @@ TEST(ActorRef, AskVoid) { struct TestActorRef { bool& executed; - TestActorRef(bool& executed_) : executed(executed_) {} + TestActorRef(bool& executed_) + : executed(executed_) {} - void doIt() { - executed = true; - } + void doIt() { executed = true; } }; bool executed = false; @@ -83,13 +77,12 @@ TEST(ActorRef, AskOnDestroyedActor) { struct TestActorRef { bool& died; - TestActorRef(ActorRef, bool& died_) : died(died_) {} + TestActorRef(ActorRef, bool& died_) + : died(died_) {} ~TestActorRef() { died = true; } - int receive() { - return 1; - } + int receive() { return 1; } }; bool died = false; diff --git a/test/algorithm/update_renderables.test.cpp b/test/algorithm/update_renderables.test.cpp index bca04ab6614..ff0705b3da6 100644 --- a/test/algorithm/update_renderables.test.cpp +++ b/test/algorithm/update_renderables.test.cpp @@ -17,29 +17,24 @@ struct GetTileDataAction { const OverscaledTileID tileID; const LookupResult found; - bool operator==(const GetTileDataAction& rhs) const { - return tileID == rhs.tileID && found == rhs.found; - } + bool operator==(const GetTileDataAction& rhs) const { return tileID == rhs.tileID && found == rhs.found; } }; std::ostream& operator<<(std::ostream& os, const GetTileDataAction& action) { return os << "GetTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) << ", { " << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " - << action.tileID.canonical.y << " } }, " - << (action.found == Found ? "Found" : "NotFound") << " }\n"; + << action.tileID.canonical.y << " } }, " << (action.found == Found ? "Found" : "NotFound") << " }\n"; } struct CreateTileDataAction { const OverscaledTileID tileID; - bool operator==(const CreateTileDataAction& rhs) const { - return tileID == rhs.tileID; - } + bool operator==(const CreateTileDataAction& rhs) const { return tileID == rhs.tileID; } }; std::ostream& operator<<(std::ostream& os, const CreateTileDataAction& action) { - return os << "CreateTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) << ", { " - << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " + return os << "CreateTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) + << ", { " << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " << action.tileID.canonical.y << " } } }\n"; } @@ -53,8 +48,8 @@ struct RetainTileDataAction { }; std::ostream& operator<<(std::ostream& os, const RetainTileDataAction& action) { - return os << "RetainTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) << ", { " - << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " + return os << "RetainTileDataAction{ { " << int(action.tileID.overscaledZ) << ", " << int(action.tileID.wrap) + << ", { " << int(action.tileID.canonical.z) << ", " << action.tileID.canonical.x << ", " << action.tileID.canonical.y << " } }, " << (action.necessity == TileNecessity::Required ? "Required" : "Optional") << " }\n"; } @@ -63,31 +58,25 @@ struct RenderTileAction { const UnwrappedTileID tileID; const MockTileData& tileData; - bool operator==(const RenderTileAction& rhs) const { - return tileID == rhs.tileID && &tileData == &rhs.tileData; - } + bool operator==(const RenderTileAction& rhs) const { return tileID == rhs.tileID && &tileData == &rhs.tileData; } }; std::ostream& operator<<(std::ostream& os, const RenderTileAction& action) { - const int64_t x = - (1ul << action.tileID.canonical.z) * action.tileID.wrap + action.tileID.canonical.x; + const int64_t x = (1ul << action.tileID.canonical.z) * action.tileID.wrap + action.tileID.canonical.x; return os << "RenderTileAction{ { " << int(action.tileID.canonical.z) << ", " << x << ", " - << action.tileID.canonical.y << " }, *tile_" - << int(action.tileData.tileID.overscaledZ) << "_" - << int(action.tileData.tileID.canonical.z) << "_" - << action.tileData.tileID.canonical.x << "_" << action.tileData.tileID.canonical.y - << " }\n"; + << action.tileID.canonical.y << " }, *tile_" << int(action.tileData.tileID.overscaledZ) << "_" + << int(action.tileData.tileID.canonical.z) << "_" << action.tileData.tileID.canonical.x << "_" + << action.tileData.tileID.canonical.y << " }\n"; } -using ActionLogEntry = - variant; +using ActionLogEntry = variant; using ActionLog = std::vector; template auto getTileDataFn(ActionLog& log, const T& dataTiles) { return [&](const auto& id) { auto it = dataTiles.find(id); - log.emplace_back(GetTileDataAction{ id, it != dataTiles.end() ? Found : NotFound }); + log.emplace_back(GetTileDataAction{id, it != dataTiles.end() ? Found : NotFound}); return (it != dataTiles.end()) ? it->second.get() : nullptr; }; } @@ -95,7 +84,7 @@ auto getTileDataFn(ActionLog& log, const T& dataTiles) { template auto createTileDataFn(ActionLog& log, T& dataTiles) { return [&](const auto& id) { - log.emplace_back(CreateTileDataAction{ id }); + log.emplace_back(CreateTileDataAction{id}); return (dataTiles[id] = std::make_unique(id)).get(); }; } @@ -103,14 +92,14 @@ auto createTileDataFn(ActionLog& log, T& dataTiles) { template auto retainTileDataFn(ActionLog& log) { return [&](auto& tileData, TileNecessity necessity) { - log.emplace_back(RetainTileDataAction{ tileData.tileID, necessity }); + log.emplace_back(RetainTileDataAction{tileData.tileID, necessity}); }; } template auto renderTileFn(ActionLog& log) { return [&](const auto& id, auto& tileData) { - log.emplace_back(RenderTileAction{ id, tileData }); + log.emplace_back(RenderTileAction{id, tileData}); }; } @@ -125,15 +114,15 @@ TEST(UpdateRenderables, SingleTile) { source.idealTiles.emplace(OverscaledTileID{1, 1, 1}); // Make sure that we're getting the tile back. - auto tile_1_1_1_1 = source.createTileData(OverscaledTileID{ 1, 1, 1 }); + auto tile_1_1_1_1 = source.createTileData(OverscaledTileID{1, 1, 1}); tile_1_1_1_1->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render ideal tile + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render ideal tile }), log); @@ -142,9 +131,9 @@ TEST(UpdateRenderables, SingleTile) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render ideal tile + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render ideal tile }), log); @@ -154,86 +143,86 @@ TEST(UpdateRenderables, SingleTile) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 1, 0, { 1, 0, 1 } } }, // create ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // four child tiles - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile - - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render found tile + GetTileDataAction{{1, 0, {1, 0, 1}}, NotFound}, // missing ideal tile + CreateTileDataAction{{1, 0, {1, 0, 1}}}, // create ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // four child tiles + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile + + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render found tile }), log); // Mark the created tile as having the optional request tried. log.clear(); - source.dataTiles[{ 1, 0, { 1, 0, 1 } }]->triedOptional = true; + source.dataTiles[{1, 0, {1, 0, 1}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // missing ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // four child tiles - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile - CreateTileDataAction{ { 0, 0, { 0, 0, 0 } } }, // load parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // found ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render found tile + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // missing ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // four child tiles + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile + CreateTileDataAction{{0, 0, {0, 0, 0}}}, // load parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // found ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render found tile }), log); // Now insert the missing tile and check that we're rendering it. log.clear(); - auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{ 1, 0, 1 }); + auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{1, 0, 1}); tile_1_1_0_1->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // newly added tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // render ideal tile + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // newly added tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // render ideal tile - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render found tile + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render found tile }), log); - // Insert another tile, and another bucket that has a different name and check that we're not - // using it. + // Insert another tile, and another bucket that has a different name and + // check that we're not using it. log.clear(); source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, 0 }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, 0}); algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // found tile, not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // four child tiles - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // found tile, not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // four child tiles + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // // optional parent tile was already created before, but is not renderable - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // render ideal tile + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // render ideal tile - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // render ideal tile + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // render ideal tile }), log); @@ -243,17 +232,17 @@ TEST(UpdateRenderables, SingleTile) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // found tile, now ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // found tile, now ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, Found }, // ideal tile - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 1, 1 }, *tile_1_1_1_1 }, // + GetTileDataAction{{1, 0, {1, 1, 1}}, Found}, // ideal tile + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 1, 1}, *tile_1_1_1_1}, // }), log); } @@ -271,35 +260,35 @@ TEST(UpdateRenderables, UseParentTile) { source.idealTiles.emplace(OverscaledTileID{1, 1, 1}); // Make sure that we're getting the tile back. - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 1, 0, { 1, 0, 1 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent found! - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // render parent - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 1, 0, { 1, 1, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 2, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 2, 1 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, NotFound }, // missing tile - CreateTileDataAction{ { 1, 0, { 1, 1, 1 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 1, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 2, 2 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 2, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 3, 3 } }, NotFound }, // ... + GetTileDataAction{{1, 0, {1, 0, 1}}, NotFound}, // missing ideal tile + CreateTileDataAction{{1, 0, {1, 0, 1}}}, // + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent found! + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // render parent + GetTileDataAction{{1, 0, {1, 1, 0}}, NotFound}, // missing ideal tile + CreateTileDataAction{{1, 0, {1, 1, 0}}}, // + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 2, 0}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 2, 1}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 1, 1}}, NotFound}, // missing tile + CreateTileDataAction{{1, 0, {1, 1, 1}}}, // + RetainTileDataAction{{1, 0, {1, 1, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 2, 2}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 2, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 3, 3}}, NotFound}, // ... }), log); } @@ -314,39 +303,39 @@ TEST(UpdateRenderables, DontUseWrongParentTile) { source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); - auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{ 1, 1, 0 }); + auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{1, 1, 0}); tile_1_1_1_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // parent tile, missing - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile, missing + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // missing ideal tile + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // parent tile, missing + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile, missing }), log); // Now mark the created tile as having the optional request tried. log.clear(); - source.dataTiles[{ 2, 0, { 2, 0, 0 } }]->triedOptional = true; + source.dataTiles[{2, 0, {2, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // non-ready ideal tile - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // parent tile, missing - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // find optional parent - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // parent tile, missing + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // non-ready ideal tile + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // parent tile, missing + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // find optional parent + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // parent tile, missing }), log); @@ -356,27 +345,27 @@ TEST(UpdateRenderables, DontUseWrongParentTile) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // non-ready ideal tile - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // non-ready ideal tile + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // // this tile was added by the previous invocation of updateRenderables - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // parent tile not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // missing parent tile - - GetTileDataAction{ { 2, 0, { 2, 2, 0 } }, NotFound }, // missing ideal tile - CreateTileDataAction{ { 2, 0, { 2, 2, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 2, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 4, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 3, 0, { 3, 4, 1 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 5, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 5, 1 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, Found }, // found parent tile - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 1, 0 }, *tile_1_1_1_0 }, // render parent tile + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // parent tile not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // missing parent tile + + GetTileDataAction{{2, 0, {2, 2, 0}}, NotFound}, // missing ideal tile + CreateTileDataAction{{2, 0, {2, 2, 0}}}, // + RetainTileDataAction{{2, 0, {2, 2, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 4, 0}}, NotFound}, // child tile + GetTileDataAction{{3, 0, {3, 4, 1}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 5, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 5, 1}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 1, 0}}, Found}, // found parent tile + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 1, 0}, *tile_1_1_1_0}, // render parent tile }), log); } @@ -391,25 +380,25 @@ TEST(UpdateRenderables, UseParentTileWhenChildNotReady) { source.idealTiles.emplace(OverscaledTileID{1, 0, 1}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{ 1, 0, 1 }); + auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{1, 0, 1}); // Don't create bucket. // Make sure that it renders the parent tile. algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // found, but not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 2 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 0, 3 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 2 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 3 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, ready - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // render parent tile + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // found, but not ready + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 2}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 0, 3}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 2}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 3}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, ready + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // render parent tile }), log); @@ -419,9 +408,9 @@ TEST(UpdateRenderables, UseParentTileWhenChildNotReady) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // found and ready - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // render ideal tile + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // found and ready + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // render ideal tile }), log); } @@ -437,29 +426,29 @@ TEST(UpdateRenderables, UseOverlappingParentTile) { source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); source.idealTiles.emplace(OverscaledTileID{1, 0, 1}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{ 1, 0, 1 }); + auto tile_1_1_0_1 = source.createTileData(OverscaledTileID{1, 0, 1}); tile_1_1_0_1->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile not found - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, Found }, // ideal tile found - RetainTileDataAction{ { 1, 0, { 1, 0, 1 } }, TileNecessity::Required }, // - RenderTileAction{ { 1, 0, 1 }, *tile_1_1_0_1 }, // + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile not found + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + + GetTileDataAction{{1, 0, {1, 0, 1}}, Found}, // ideal tile found + RetainTileDataAction{{1, 0, {1, 0, 1}}, TileNecessity::Required}, // + RenderTileAction{{1, 0, 1}, *tile_1_1_0_1}, // }), log); } @@ -474,26 +463,26 @@ TEST(UpdateRenderables, UseChildTiles) { source.idealTiles.emplace(OverscaledTileID{0, 0, 0}); - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, 0 }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, 0}); tile_1_1_0_0->renderable = true; - auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{ 1, 1, 0 }); + auto tile_1_1_1_0 = source.createTileData(OverscaledTileID{1, 1, 0}); tile_1_1_1_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 0, 0, { 0, 0, 0 } } }, // - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // child tile found - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // render child tile - GetTileDataAction{ { 1, 0, { 1, 0, 1 } }, NotFound }, // child tile not found - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, Found }, // child tile found - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 1, 0 }, *tile_1_1_1_0 }, // render child tile - GetTileDataAction{ { 1, 0, { 1, 1, 1 } }, NotFound }, // child tile not found - // no parent tile of 0 to consider + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{0, 0, {0, 0, 0}}}, // + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // child tile found + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // render child tile + GetTileDataAction{{1, 0, {1, 0, 1}}, NotFound}, // child tile not found + GetTileDataAction{{1, 0, {1, 1, 0}}, Found}, // child tile found + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 1, 0}, *tile_1_1_1_0}, // render child tile + GetTileDataAction{{1, 0, {1, 1, 1}}, NotFound}, // child tile not found + // no parent tile of 0 to consider }), log); } @@ -508,101 +497,101 @@ TEST(UpdateRenderables, PreferChildTiles) { source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, 0 }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, 0}); tile_2_2_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile, not found - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // child tile, not found - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile, not found + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // child tile, not found + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // }), log); - // Now add more children to cover the ideal tile fully, until it is covered fully, and verify - // that the parent doesn't get rendered. + // Now add more children to cover the ideal tile fully, until it is covered + // fully, and verify that the parent doesn't get rendered. log.clear(); - auto tile_2_2_0_1 = source.createTileData(OverscaledTileID{ 2, 0, 1 }); + auto tile_2_2_0_1 = source.createTileData(OverscaledTileID{2, 0, 1}); tile_2_2_0_1->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready // ideal tile was added in previous invocation, but is not yet ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 0, 1 } }, TileNecessity::Optional }, // ... - RenderTileAction{ { 2, 0, 1 }, *tile_2_2_0_1 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // child tile, not found - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 0, 1}}, TileNecessity::Optional}, // ... + RenderTileAction{{2, 0, 1}, *tile_2_2_0_1}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // child tile, not found + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // }), log); log.clear(); - auto tile_2_2_1_0 = source.createTileData(OverscaledTileID{ 2, 1, 0 }); + auto tile_2_2_1_0 = source.createTileData(OverscaledTileID{2, 1, 0}); tile_2_2_1_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready // ideal tile was added in first invocation, but is not yet ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 0, 1 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 1 }, *tile_2_2_0_1 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 1, 0 }, *tile_2_2_1_0 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // child tile, not found - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile, found - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 0, 1}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 1}, *tile_2_2_0_1}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 1, 0}, *tile_2_2_1_0}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // child tile, not found + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile, found + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // }), log); // Adding the last child tile covers 1/0/0 fully, so we don't need 0/0/0 anymore. log.clear(); - auto tile_2_2_1_1 = source.createTileData(OverscaledTileID{ 2, 1, 1 }); + auto tile_2_2_1_1 = source.createTileData(OverscaledTileID{2, 1, 1}); tile_2_2_1_1->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready // ideal tile was added in first invocation, but is not yet ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile, found - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 0, 1 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 1 }, *tile_2_2_0_1 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 1, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 1, 0 }, *tile_2_2_1_0 }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, Found }, // ... - RetainTileDataAction{ { 2, 0, { 2, 1, 1 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 1, 1 }, *tile_2_2_1_1 }, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile, found + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 0, 1}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 1}, *tile_2_2_0_1}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 1, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 1, 0}, *tile_2_2_1_0}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, Found}, // ... + RetainTileDataAction{{2, 0, {2, 1, 1}}, TileNecessity::Optional}, // + RenderTileAction{{2, 1, 1}, *tile_2_2_1_1}, // }), log); } @@ -617,45 +606,45 @@ TEST(UpdateRenderables, UseParentAndChildTiles) { source.idealTiles.emplace(OverscaledTileID{1, 0, 0}); - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, 0 }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, 0}); tile_0_0_0_0->renderable = true; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, 0 }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, 0}); tile_2_2_0_0->renderable = true; // Check that it uses the child tile and the parent tile to cover the rest. algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // child tile - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // child tile + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // }), log); // Then, remove the child tile and check that it now only the parent tile. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 2, 0, 0 }); + source.dataTiles.erase(OverscaledTileID{2, 0, 0}); algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // parent tile - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // parent tile + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // }), log); } @@ -671,20 +660,20 @@ TEST(UpdateRenderables, DontUseTilesLowerThanMinzoom) { source.zoomRange.min = 2; source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, 0 }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, 0}); tile_1_1_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // - // no requests for zoom 1 tiles + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // + // no requests for zoom 1 tiles }), log); } @@ -701,67 +690,65 @@ TEST(UpdateRenderables, UseOverzoomedTileAfterMaxzoom) { source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); // Add a child tile (that should never occur in practice) and make sure it's not selected. - auto tile_3_3_0_0 = source.createTileData(OverscaledTileID{ 3, 0, 0 }); + auto tile_3_3_0_0 = source.createTileData(OverscaledTileID{3, 0, 0}); tile_3_3_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ( - ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // overzoomed tile, not children! - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // - }), - log); + EXPECT_EQ(ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // overzoomed tile, not children! + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // + }), + log); // Mark the created tile as having tried the optional request. log.clear(); - source.dataTiles[{ 2, 0, { 2, 0, 0 } }]->triedOptional = true; + source.dataTiles[{2, 0, {2, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ( - ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // ideal tile, missing - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // overzoomed tile, not children! - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // - }), - log); + EXPECT_EQ(ActionLog({ + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // ideal tile, missing + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // overzoomed tile, not children! + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // + }), + log); // Switch to overzoomed tile and only add a non-overzoomed ("parent") tile at first. log.clear(); source.idealTiles.clear(); source.idealTiles.emplace(OverscaledTileID{3, 0, {2, 0, 0}}); - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // ideal tile, missing - CreateTileDataAction{ { 3, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // ideal tile, missing + CreateTileDataAction{{3, 0, {2, 0, 0}}}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // }), log); // Then add the overzoomed tile matching the zoom level we're rendering. log.clear(); - auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 2, 0, 0 }, *tile_3_2_0_0 }, // + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{2, 0, 0}, *tile_3_2_0_0}, // }), log); @@ -772,27 +759,27 @@ TEST(UpdateRenderables, UseOverzoomedTileAfterMaxzoom) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // }), log); // Now remove the best match. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + source.dataTiles.erase(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0 = nullptr; // Use the overzoomed tile even though it doesn't match the zoom level. algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // use overzoomed tile! - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_3_2_0_0 }, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // use overzoomed tile! + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_3_2_0_0}, // }), log); } @@ -809,70 +796,70 @@ TEST(UpdateRenderables, AscendToNonOverzoomedTiles) { source.idealTiles.emplace(OverscaledTileID{3, 0, {2, 0, 0}}); // Add a matching overzoomed tile and make sure it gets selected. - auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - RenderTileAction{ { 2, 0, 0 }, *tile_3_2_0_0 }, // + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + RenderTileAction{{2, 0, 0}, *tile_3_2_0_0}, // }), log); // Then, swap it with a non-overzoomed tile. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + source.dataTiles.erase(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0 = nullptr; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 3, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // prefer using a child first - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 2, 0, 0 }, *tile_2_2_0_0 }, // + GetTileDataAction{{3, 0, {2, 0, 0}}, NotFound}, // + CreateTileDataAction{{3, 0, {2, 0, 0}}}, // + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // prefer using a child first + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{2, 0, 0}, *tile_2_2_0_0}, // }), log); // Then, swap it with a parent tile. log.clear(); - source.dataTiles.erase(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + source.dataTiles.erase(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0 = nullptr; - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, { 1, 0, 0 } }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, {1, 0, 0}}); tile_1_1_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // }), log); // Now, mark the created tile as found. log.clear(); - source.dataTiles[{ 3, 0, { 2, 0, 0 } }]->triedOptional = true; + source.dataTiles[{3, 0, {2, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, // + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{4, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, // }), log); } @@ -891,61 +878,61 @@ TEST(UpdateRenderables, DoNotAscendMultipleTimesIfNotFound) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 8, 0, { 8, 0, 0 } }, NotFound }, // ideal tile - CreateTileDataAction{ { 8, 0, { 8, 0, 0 } } }, // - RetainTileDataAction{ { 8, 0, { 8, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... - - GetTileDataAction{ { 8, 0, { 8, 1, 0 } }, NotFound }, // ideal tile - CreateTileDataAction{ { 8, 0, { 8, 1, 0 } } }, // - RetainTileDataAction{ { 8, 0, { 8, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 2, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 2, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 1 } }, NotFound }, // ... - // no second ascent to 0 + GetTileDataAction{{8, 0, {8, 0, 0}}, NotFound}, // ideal tile + CreateTileDataAction{{8, 0, {8, 0, 0}}}, // + RetainTileDataAction{{8, 0, {8, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 0, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{6, 0, {6, 0, 0}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ... + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... + + GetTileDataAction{{8, 0, {8, 1, 0}}, NotFound}, // ideal tile + CreateTileDataAction{{8, 0, {8, 1, 0}}}, // + RetainTileDataAction{{8, 0, {8, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 2, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 2, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 1}}, NotFound}, // ... + // no second ascent to 0 }), log); // Now add a mid-level tile that stops the ascent log.clear(); - auto tile_4_0_0_0 = source.createTileData(OverscaledTileID{ 4, 0, { 4, 0, 0 } }); + auto tile_4_0_0_0 = source.createTileData(OverscaledTileID{4, 0, {4, 0, 0}}); tile_4_0_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 8, 0, { 8, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 8, 0, { 8, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 0, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // stops ascent - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 4, 0, 0 }, *tile_4_0_0_0 }, // - - GetTileDataAction{ { 8, 0, { 8, 1, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 8, 0, { 8, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 9, 0, { 9, 2, 0 } }, NotFound }, // child tile - GetTileDataAction{ { 9, 0, { 9, 2, 1 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 0 } }, NotFound }, // ... - GetTileDataAction{ { 9, 0, { 9, 3, 1 } }, NotFound }, // ... - // no second ascent to 0 + GetTileDataAction{{8, 0, {8, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{8, 0, {8, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 0, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 0, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 1, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{6, 0, {6, 0, 0}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ... + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // stops ascent + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{4, 0, 0}, *tile_4_0_0_0}, // + + GetTileDataAction{{8, 0, {8, 1, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{8, 0, {8, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{9, 0, {9, 2, 0}}, NotFound}, // child tile + GetTileDataAction{{9, 0, {9, 2, 1}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 0}}, NotFound}, // ... + GetTileDataAction{{9, 0, {9, 3, 1}}, NotFound}, // ... + // no second ascent to 0 }), log); } @@ -960,21 +947,21 @@ TEST(UpdateRenderables, DontRetainUnusedNonIdealTiles) { source.idealTiles.emplace(OverscaledTileID{2, 0, 0}); - source.createTileData(OverscaledTileID{ 1, 0, 0 }); - source.createTileData(OverscaledTileID{ 2, 0, 0 }); + source.createTileData(OverscaledTileID{1, 0, 0}); + source.createTileData(OverscaledTileID{2, 0, 0}); algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 3, 0, { 3, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, // parent tile, not ready - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 0, 1}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 0}}, NotFound}, // + GetTileDataAction{{3, 0, {3, 1, 1}}, NotFound}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, // parent tile, not ready + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // }), log); } @@ -998,51 +985,52 @@ TEST(UpdateRenderables, WrappedTiles) { source.idealTiles.emplace(OverscaledTileID{1, id.wrap, id.canonical}); } - auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{ 0, 0, { 0, 0, 0 } }); + auto tile_0_0_0_0 = source.createTileData(OverscaledTileID{0, 0, {0, 0, 0}}); tile_0_0_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); - EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 1, -1, { 1, 1, 0 } }, NotFound }, // ideal tile 1/-1/0 (wrapped to -1) - CreateTileDataAction{ { 1, -1, { 1, 1, 0 } } }, // - RetainTileDataAction{ { 1, -1, { 1, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, -1, { 2, 2, 0 } }, NotFound }, // - GetTileDataAction{ { 2, -1, { 2, 2, 1 } }, NotFound }, // - GetTileDataAction{ { 2, -1, { 2, 3, 0 } }, NotFound }, // - GetTileDataAction{ { 2, -1, { 2, 3, 1 } }, NotFound }, // - GetTileDataAction{ { 0, -1, { 0, 0, 0 } }, NotFound }, // { 0, 0, 0 } exists, but not the version wrapped to -1 - - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ideal tile 1/0/0 - CreateTileDataAction{ { 1, 0, { 1, 0, 0 } } }, // - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, Found }, // - RetainTileDataAction{ { 0, 0, { 0, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 0, 0, 0 }, *tile_0_0_0_0 }, // - - GetTileDataAction{ { 1, 0, { 1, 1, 0 } }, NotFound }, // ideal tile 1/1/0, doesn't match 1/-/1/0 - CreateTileDataAction{ { 1, 0, { 1, 1, 0 } } }, - RetainTileDataAction{ { 1, 0, { 1, 1, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 0, { 2, 2, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 2, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 3, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 0, { 2, 3, 1 } }, NotFound }, // - // do not ascent; 0/0/0 has been rendered already for 1/0/0 - - GetTileDataAction{ { 1, 1, { 1, 0, 0 } }, NotFound }, // ideal tile 1/2/0 (wrapped to 1) - CreateTileDataAction{ { 1, 1, { 1, 0, 0 } } }, - RetainTileDataAction{ { 1, 1, { 1, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 2, 1, { 2, 0, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 1, { 2, 0, 1 } }, NotFound }, // - GetTileDataAction{ { 2, 1, { 2, 1, 0 } }, NotFound }, // - GetTileDataAction{ { 2, 1, { 2, 1, 1 } }, NotFound }, // - GetTileDataAction{ { 0, 1, { 0, 0, 0 } }, NotFound }, // { 0, 0, 0 } exists, but not the version wrapped to -1 - }), - log); + EXPECT_EQ( + ActionLog({ + GetTileDataAction{{1, -1, {1, 1, 0}}, NotFound}, // ideal tile 1/-1/0 (wrapped to -1) + CreateTileDataAction{{1, -1, {1, 1, 0}}}, // + RetainTileDataAction{{1, -1, {1, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, -1, {2, 2, 0}}, NotFound}, // + GetTileDataAction{{2, -1, {2, 2, 1}}, NotFound}, // + GetTileDataAction{{2, -1, {2, 3, 0}}, NotFound}, // + GetTileDataAction{{2, -1, {2, 3, 1}}, NotFound}, // + GetTileDataAction{{0, -1, {0, 0, 0}}, NotFound}, // { 0, 0, 0 } exists, but not the version wrapped to -1 + + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ideal tile 1/0/0 + CreateTileDataAction{{1, 0, {1, 0, 0}}}, // + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 0, {0, 0, 0}}, Found}, // + RetainTileDataAction{{0, 0, {0, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{0, 0, 0}, *tile_0_0_0_0}, // + + GetTileDataAction{{1, 0, {1, 1, 0}}, NotFound}, // ideal tile 1/1/0, doesn't match 1/-/1/0 + CreateTileDataAction{{1, 0, {1, 1, 0}}}, + RetainTileDataAction{{1, 0, {1, 1, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 0, {2, 2, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 2, 1}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 3, 0}}, NotFound}, // + GetTileDataAction{{2, 0, {2, 3, 1}}, NotFound}, // + // do not ascent; 0/0/0 has been rendered already for 1/0/0 + + GetTileDataAction{{1, 1, {1, 0, 0}}, NotFound}, // ideal tile 1/2/0 (wrapped to 1) + CreateTileDataAction{{1, 1, {1, 0, 0}}}, + RetainTileDataAction{{1, 1, {1, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{2, 1, {2, 0, 0}}, NotFound}, // + GetTileDataAction{{2, 1, {2, 0, 1}}, NotFound}, // + GetTileDataAction{{2, 1, {2, 1, 0}}, NotFound}, // + GetTileDataAction{{2, 1, {2, 1, 1}}, NotFound}, // + GetTileDataAction{{0, 1, {0, 0, 0}}, NotFound}, // { 0, 0, 0 } exists, but not the version wrapped to -1 + }), + log); } TEST(UpdateRenderables, RepeatedRenderWithMissingOptionals) { @@ -1058,19 +1046,19 @@ TEST(UpdateRenderables, RepeatedRenderWithMissingOptionals) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, NotFound }, // ideal tile, not found - CreateTileDataAction{ { 6, 0, { 6, 0, 0 } } }, // - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, NotFound}, // ideal tile, not found + CreateTileDataAction{{6, 0, {6, 0, 0}}}, // + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); @@ -1079,41 +1067,41 @@ TEST(UpdateRenderables, RepeatedRenderWithMissingOptionals) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 6, 0, { 6, 0, 0 } }]->triedOptional = true; + source.dataTiles[{6, 0, {6, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - CreateTileDataAction{ { 5, 0, { 5, 0, 0 } } }, // - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + CreateTileDataAction{{5, 0, {5, 0, 0}}}, // + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); @@ -1122,117 +1110,117 @@ TEST(UpdateRenderables, RepeatedRenderWithMissingOptionals) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 5, 0, { 5, 0, 0 } }]->triedOptional = true; + source.dataTiles[{5, 0, {5, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - CreateTileDataAction{ { 4, 0, { 4, 0, 0 } } }, // - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + CreateTileDataAction{{4, 0, {4, 0, 0}}}, // + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 4, 0, { 4, 0, 0 } }]->triedOptional = true; + source.dataTiles[{4, 0, {4, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - CreateTileDataAction{ { 3, 0, { 3, 0, 0 } } }, // - RetainTileDataAction{ { 3, 0, { 3, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ... + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + CreateTileDataAction{{3, 0, {3, 0, 0}}}, // + RetainTileDataAction{{3, 0, {3, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); // Mark next level has having tried optional. log.clear(); - source.dataTiles[{ 3, 0, { 3, 0, 0 } }]->triedOptional = true; + source.dataTiles[{3, 0, {3, 0, 0}}]->triedOptional = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 3, 0, { 3, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - CreateTileDataAction{ { 2, 0, { 2, 0, 0 } } }, // - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ... + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, Found}, // ... + RetainTileDataAction{{3, 0, {3, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + CreateTileDataAction{{2, 0, {2, 0, 0}}}, // + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); // Mark as found log.clear(); - auto tile_3_3_0_0 = source.dataTiles[{ 3, 0, { 3, 0, 0 } }].get(); + auto tile_3_3_0_0 = source.dataTiles[{3, 0, {3, 0, 0}}].get(); tile_3_3_0_0->renderable = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not ready - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 7, 0, 0 } }, NotFound }, // children - GetTileDataAction{ { 7, 0, { 7, 0, 1 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 0 } }, NotFound }, // ... - GetTileDataAction{ { 7, 0, { 7, 1, 1 } }, NotFound }, // ... - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, Found }, // ascent - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 4, 0, { 4, 0, 0 } }, TileNecessity::Optional }, // - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, Found }, // ... - RetainTileDataAction{ { 3, 0, { 3, 0, 0 } }, TileNecessity::Optional }, // - RenderTileAction{ { 3, 0, 0 }, *tile_3_3_0_0 }, // + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not ready + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {7, 0, 0}}, NotFound}, // children + GetTileDataAction{{7, 0, {7, 0, 1}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 0}}, NotFound}, // ... + GetTileDataAction{{7, 0, {7, 1, 1}}, NotFound}, // ... + GetTileDataAction{{5, 0, {5, 0, 0}}, Found}, // ascent + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{4, 0, {4, 0, 0}}, Found}, // ... + RetainTileDataAction{{4, 0, {4, 0, 0}}, TileNecessity::Optional}, // + GetTileDataAction{{3, 0, {3, 0, 0}}, Found}, // ... + RetainTileDataAction{{3, 0, {3, 0, 0}}, TileNecessity::Optional}, // + RenderTileAction{{3, 0, 0}, *tile_3_3_0_0}, // }), log); } @@ -1248,24 +1236,24 @@ TEST(UpdateRenderables, LoadRequiredIfIdealTileCantBeFound) { source.zoomRange.max = 6; source.idealTiles.emplace(OverscaledTileID{6, 0, 0}); - auto tile_6_6_0_0 = source.createTileData(OverscaledTileID{ 6, 0, { 6, 0, 0 } }); + auto tile_6_6_0_0 = source.createTileData(OverscaledTileID{6, 0, {6, 0, 0}}); tile_6_6_0_0->triedOptional = true; tile_6_6_0_0->loaded = true; algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 6, 0, { 6, 0, 0 } }, Found }, // ideal tile, not found - RetainTileDataAction{ { 6, 0, { 6, 0, 0 } }, TileNecessity::Required }, // - GetTileDataAction{ { 7, 0, { 6, 0, 0 } }, NotFound }, // overzoomed child - GetTileDataAction{ { 5, 0, { 5, 0, 0 } }, NotFound }, // ascent - CreateTileDataAction{ { 5, 0, { 5, 0, 0 } } }, - RetainTileDataAction{ { 5, 0, { 5, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 4, 0, { 4, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 3, 0, { 3, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, NotFound }, // ... - GetTileDataAction{ { 0, 0, { 0, 0, 0 } }, NotFound }, // ... + GetTileDataAction{{6, 0, {6, 0, 0}}, Found}, // ideal tile, not found + RetainTileDataAction{{6, 0, {6, 0, 0}}, TileNecessity::Required}, // + GetTileDataAction{{7, 0, {6, 0, 0}}, NotFound}, // overzoomed child + GetTileDataAction{{5, 0, {5, 0, 0}}, NotFound}, // ascent + CreateTileDataAction{{5, 0, {5, 0, 0}}}, + RetainTileDataAction{{5, 0, {5, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{4, 0, {4, 0, 0}}, NotFound}, // ... + GetTileDataAction{{3, 0, {3, 0, 0}}, NotFound}, // ... + GetTileDataAction{{2, 0, {2, 0, 0}}, NotFound}, // ... + GetTileDataAction{{1, 0, {1, 0, 0}}, NotFound}, // ... + GetTileDataAction{{0, 0, {0, 0, 0}}, NotFound}, // ... }), log); } @@ -1282,23 +1270,23 @@ TEST(UpdateRenderables, LoadOverscaledMaxZoomTile) { source.zoomRange.max = 2; source.idealTiles.emplace(OverscaledTileID{4, 0, {2, 0, 0}}); - auto tile_4_2_0_0 = source.createTileData(OverscaledTileID{ 4, 0, { 2, 0, 0 } }); + auto tile_4_2_0_0 = source.createTileData(OverscaledTileID{4, 0, {2, 0, 0}}); tile_4_2_0_0->renderable = false; tile_4_2_0_0->triedOptional = true; tile_4_2_0_0->loaded = true; - auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{ 3, 0, { 2, 0, 0 } }); + auto tile_3_2_0_0 = source.createTileData(OverscaledTileID{3, 0, {2, 0, 0}}); tile_3_2_0_0->renderable = false; tile_3_2_0_0->triedOptional = true; tile_3_2_0_0->loaded = true; - auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{ 2, 0, { 2, 0, 0 } }); + auto tile_2_2_0_0 = source.createTileData(OverscaledTileID{2, 0, {2, 0, 0}}); tile_2_2_0_0->renderable = false; tile_2_2_0_0->triedOptional = true; tile_2_2_0_0->loaded = true; // Tile level 1 won't be overscaled. - auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{ 1, 0, { 1, 0, 0 } }); + auto tile_1_1_0_0 = source.createTileData(OverscaledTileID{1, 0, {1, 0, 0}}); tile_1_1_0_0->renderable = true; tile_1_1_0_0->triedOptional = true; tile_1_1_0_0->loaded = true; @@ -1306,16 +1294,16 @@ TEST(UpdateRenderables, LoadOverscaledMaxZoomTile) { algorithm::updateRenderables( getTileData, createTileData, retainTileData, renderTile, source.idealTiles, source.zoomRange); EXPECT_EQ(ActionLog({ - GetTileDataAction{ { 4, 0, { 2, 0, 0 } }, Found }, - RetainTileDataAction{ { 4, 0, { 2, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 5, 0, { 2, 0, 0 } }, NotFound }, - GetTileDataAction{ { 3, 0, { 2, 0, 0 } }, Found }, - RetainTileDataAction{ { 3, 0, { 2, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 2, 0, { 2, 0, 0 } }, Found }, - RetainTileDataAction{ { 2, 0, { 2, 0, 0 } }, TileNecessity::Required }, - GetTileDataAction{ { 1, 0, { 1, 0, 0 } }, Found }, - RetainTileDataAction{ { 1, 0, { 1, 0, 0 } }, TileNecessity::Required }, - RenderTileAction{ { 1, 0, 0 }, *tile_1_1_0_0 }, + GetTileDataAction{{4, 0, {2, 0, 0}}, Found}, + RetainTileDataAction{{4, 0, {2, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{5, 0, {2, 0, 0}}, NotFound}, + GetTileDataAction{{3, 0, {2, 0, 0}}, Found}, + RetainTileDataAction{{3, 0, {2, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{2, 0, {2, 0, 0}}, Found}, + RetainTileDataAction{{2, 0, {2, 0, 0}}, TileNecessity::Required}, + GetTileDataAction{{1, 0, {1, 0, 0}}, Found}, + RetainTileDataAction{{1, 0, {1, 0, 0}}, TileNecessity::Required}, + RenderTileAction{{1, 0, 0}, *tile_1_1_0_0}, }), log); } diff --git a/test/algorithm/update_tile_masks.test.cpp b/test/algorithm/update_tile_masks.test.cpp index 5c14ec650b9..faf150652d2 100644 --- a/test/algorithm/update_tile_masks.test.cpp +++ b/test/algorithm/update_tile_masks.test.cpp @@ -8,11 +8,8 @@ namespace { class FakeTile { public: FakeTile(TileMask mask_) - : mask(std::move(mask_)) { - } - void setMask(TileMask mask_) { - mask = std::move(mask_); - } + : mask(std::move(mask_)) {} + void setMask(TileMask mask_) { mask = std::move(mask_); } const bool usedByRenderedLayers = true; TileMask mask; @@ -26,91 +23,93 @@ bool operator==(const FakeTile& lhs, const FakeTile& rhs) { void validate(std::map expected) { auto actual = expected; - std::for_each(actual.begin(), actual.end(), - [](auto& renderable) { renderable.second.mask.clear(); }); + std::for_each(actual.begin(), actual.end(), [](auto& renderable) { renderable.second.mask.clear(); }); algorithm::updateTileMasks(actual); EXPECT_EQ(expected, actual); } TEST(UpdateTileMasks, NoChildren) { - validate({ - { UnwrappedTileID{ 0, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } } - }); + validate({{UnwrappedTileID{0, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}}); validate({ - { UnwrappedTileID{ 4, 3, 8 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{4, 3, 8}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 1, 1 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 1, 1}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 2, 2, 3 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{2, 2, 3}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } TEST(UpdateTileMasks, ParentAndFourChildren) { validate({ // Mask is empty (== not rendered!) because we have four covering children. - { UnwrappedTileID{ 0, 0, 0 }, TileMask{} }, + {UnwrappedTileID{0, 0, 0}, TileMask{}}, // All four covering children - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 0, 1 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 1, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 1, 1, 1 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 0, 1}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 1, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{1, 1, 1}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } TEST(UpdateTileMasks, OneChild) { validate({ - { UnwrappedTileID{ 0, 0, 0 }, - // Only render the three children that aren't covering the other tile. - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 } } }, - { UnwrappedTileID{ 1, 0, 0 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{0, 0, 0}, + // Only render the three children that aren't covering the other tile. + TileMask{CanonicalTileID{1, 0, 1}, CanonicalTileID{1, 1, 0}, CanonicalTileID{1, 1, 1}}}, + {UnwrappedTileID{1, 0, 0}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } TEST(UpdateTileMasks, Complex) { validate({ - { UnwrappedTileID{ 0, 0, 0 }, - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 2, 2, 3 }, CanonicalTileID{ 2, 3, 2 }, - CanonicalTileID{ 3, 6, 7 }, CanonicalTileID{ 3, 7, 6 } } }, - { UnwrappedTileID{ 0, { 1, 0, 0 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 0, { 2, 2, 2 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 0, { 3, 7, 7 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 0, { 3, 6, 6 } }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{0, 0, 0}, + TileMask{CanonicalTileID{1, 0, 1}, + CanonicalTileID{1, 1, 0}, + CanonicalTileID{2, 2, 3}, + CanonicalTileID{2, 3, 2}, + CanonicalTileID{3, 6, 7}, + CanonicalTileID{3, 7, 6}}}, + {UnwrappedTileID{0, {1, 0, 0}}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{0, {2, 2, 2}}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{0, {3, 7, 7}}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{0, {3, 6, 6}}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 0, 0, 0 }, - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 }, CanonicalTileID{ 2, 0, 0 }, - CanonicalTileID{ 2, 0, 1 }, CanonicalTileID{ 2, 1, 0 }, - CanonicalTileID{ 3, 2, 3 }, CanonicalTileID{ 3, 3, 2 }, - CanonicalTileID{ 3, 3, 3 }, CanonicalTileID{ 4, 4, 5 }, - CanonicalTileID{ 4, 5, 4 }, CanonicalTileID{ 4, 5, 5 } } }, - { UnwrappedTileID{ 4, 4, 4 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{0, 0, 0}, + TileMask{CanonicalTileID{1, 0, 1}, + CanonicalTileID{1, 1, 0}, + CanonicalTileID{1, 1, 1}, + CanonicalTileID{2, 0, 0}, + CanonicalTileID{2, 0, 1}, + CanonicalTileID{2, 1, 0}, + CanonicalTileID{3, 2, 3}, + CanonicalTileID{3, 3, 2}, + CanonicalTileID{3, 3, 3}, + CanonicalTileID{4, 4, 5}, + CanonicalTileID{4, 5, 4}, + CanonicalTileID{4, 5, 5}}}, + {UnwrappedTileID{4, 4, 4}, TileMask{CanonicalTileID{0, 0, 0}}}, }); validate({ - { UnwrappedTileID{ 12, 1028, 1456 }, - TileMask{ CanonicalTileID{ 1, 1, 1 }, CanonicalTileID{ 2, 3, 0 }, - CanonicalTileID{ 2, 3, 1 } } }, - { UnwrappedTileID{ 13, 2056, 2912 }, - TileMask{ CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 } } }, - { UnwrappedTileID{ 13, 2056, 2913 }, - TileMask{ CanonicalTileID{ 1, 0, 0 }, CanonicalTileID{ 1, 1, 0 }, - CanonicalTileID{ 1, 1, 1 } } }, - { UnwrappedTileID{ 14, 4112, 5824 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 14, 4112, 5827 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 14, 4114, 5824 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, - { UnwrappedTileID{ 14, 4114, 5825 }, TileMask{ CanonicalTileID{ 0, 0, 0 } } }, + {UnwrappedTileID{12, 1028, 1456}, + TileMask{CanonicalTileID{1, 1, 1}, CanonicalTileID{2, 3, 0}, CanonicalTileID{2, 3, 1}}}, + {UnwrappedTileID{13, 2056, 2912}, + TileMask{CanonicalTileID{1, 0, 1}, CanonicalTileID{1, 1, 0}, CanonicalTileID{1, 1, 1}}}, + {UnwrappedTileID{13, 2056, 2913}, + TileMask{CanonicalTileID{1, 0, 0}, CanonicalTileID{1, 1, 0}, CanonicalTileID{1, 1, 1}}}, + {UnwrappedTileID{14, 4112, 5824}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{14, 4112, 5827}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{14, 4114, 5824}, TileMask{CanonicalTileID{0, 0, 0}}}, + {UnwrappedTileID{14, 4114, 5825}, TileMask{CanonicalTileID{0, 0, 0}}}, }); } diff --git a/test/api/annotations.test.cpp b/test/api/annotations.test.cpp index ca4c0ecfe6f..19e0985c6a0 100644 --- a/test/api/annotations.test.cpp +++ b/test/api/annotations.test.cpp @@ -27,12 +27,14 @@ std::unique_ptr namedMarker(const std::string& name) { class AnnotationTest { public: util::RunLoop loop; - HeadlessFrontend frontend { 1 }; + HeadlessFrontend frontend{1}; - MapAdapter map { frontend, MapObserver::nullObserver(), std::make_shared(), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; + MapAdapter map{frontend, + MapObserver::nullObserver(), + std::make_shared(), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; - void checkRendering(const char * name) { + void checkRendering(const char* name) { test::checkImage(std::string("test/fixtures/annotations/") + name, frontend.render(map).image, 0.0002, 0.1); } }; @@ -44,26 +46,28 @@ TEST(Annotations, SymbolAnnotation) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point(0, 0), "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point(0, 0), "default_marker"}); test.checkRendering("point_annotation"); -// auto size = test.frontend.getSize(); -// auto screenBox = ScreenBox { {}, { double(size.width), double(size.height) } }; -// for (uint8_t zoom = test.map.getMinZoom(); zoom <= test.map.getMaxZoom(); ++zoom) { -// test.map.jumpTo(CameraOptions().withZoom(zoom)); -// test.checkRendering("point_annotation"); -// EXPECT_EQ(test.map.queryPointAnnotations(screenBox).size(), 1u); -// } + // auto size = test.frontend.getSize(); + // auto screenBox = ScreenBox { {}, { double(size.width), + // double(size.height) } }; for (uint8_t zoom = test.map.getMinZoom(); + // zoom <= test.map.getMaxZoom(); ++zoom) { + // test.map.jumpTo(CameraOptions().withZoom(zoom)); + // test.checkRendering("point_annotation"); + // EXPECT_EQ(test.map.queryPointAnnotations(screenBox).size(), 1u); + // } } TEST(Annotations, SymbolAnnotationTileBoundary) { - // Almost exactly the same as SymbolAnnotation test above, but offset my fractions of a degree - // tests precision issue from https://github.com/mapbox/mapbox-gl-native/issues/12472 + // Almost exactly the same as SymbolAnnotation test above, but offset my + // fractions of a degree tests precision issue from + // https://github.com/mapbox/mapbox-gl-native/issues/12472 AnnotationTest test; - + test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point(0.000000000000001, 0.00000000000001), "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point(0.000000000000001, 0.00000000000001), "default_marker"}); test.map.jumpTo(CameraOptions().withZoom(10)); test.checkRendering("point_annotation"); } @@ -71,10 +75,10 @@ TEST(Annotations, SymbolAnnotationTileBoundary) { TEST(Annotations, LineAnnotation) { AnnotationTest test; - LineString line = {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }}; - LineAnnotation annotation { line }; + LineString line = {{{0, 0}, {45, 45}, {30, 0}}}; + LineAnnotation annotation{line}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotation(annotation); @@ -87,8 +91,8 @@ TEST(Annotations, LineAnnotation) { TEST(Annotations, FillAnnotation) { AnnotationTest test; - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation annotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation annotation{polygon}; annotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -103,17 +107,17 @@ TEST(Annotations, AntimeridianAnnotationSmall) { AnnotationTest test; double antimeridian = 180; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 0, antimeridian }).withZoom(0.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{0, antimeridian}).withZoom(0.0)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - LineString line = {{ { antimeridian, 20 }, { antimeridian, -20 } }}; - LineAnnotation lineAnnotation { line }; + LineString line = {{{antimeridian, 20}, {antimeridian, -20}}}; + LineAnnotation lineAnnotation{line}; lineAnnotation.color = Color::red(); - lineAnnotation.width = { 2 }; + lineAnnotation.width = {2}; test.map.addAnnotation(lineAnnotation); - Polygon polygon = { {{ { antimeridian+10, 0 }, { antimeridian - 10, 10 }, { antimeridian-10, -10 } }} }; - FillAnnotation polygonAnnotation { polygon }; + Polygon polygon = {{{{antimeridian + 10, 0}, {antimeridian - 10, 10}, {antimeridian - 10, -10}}}}; + FillAnnotation polygonAnnotation{polygon}; polygonAnnotation.color = Color::blue(); test.map.addAnnotation(polygonAnnotation); @@ -127,14 +131,14 @@ TEST(Annotations, AntimeridianAnnotationLarge) { test.map.jumpTo(CameraOptions().withCenter(mbgl::LatLng(0.0, antimeridian)).withZoom(0.0)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - LineString line = {{ { antimeridian, 20 }, { antimeridian, -20 } }}; - LineAnnotation lineAnnotation { line }; + LineString line = {{{antimeridian, 20}, {antimeridian, -20}}}; + LineAnnotation lineAnnotation{line}; lineAnnotation.color = Color::red(); - lineAnnotation.width = { 2 }; + lineAnnotation.width = {2}; test.map.addAnnotation(lineAnnotation); - Polygon polygon = { {{ { antimeridian-10, 0 }, { -antimeridian+10, 10 }, { -antimeridian+10, -10 } }} }; - FillAnnotation polygonAnnotation { polygon }; + Polygon polygon = {{{{antimeridian - 10, 0}, {-antimeridian + 10, 10}, {-antimeridian + 10, -10}}}}; + FillAnnotation polygonAnnotation{polygon}; polygonAnnotation.color = Color::blue(); test.map.addAnnotation(polygonAnnotation); @@ -144,10 +148,10 @@ TEST(Annotations, AntimeridianAnnotationLarge) { TEST(Annotations, OverlappingFillAnnotation) { AnnotationTest test; - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation underlaidAnnotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation underlaidAnnotation{polygon}; underlaidAnnotation.color = Color::green(); - FillAnnotation overlaidAnnotation { polygon }; + FillAnnotation overlaidAnnotation{polygon}; overlaidAnnotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -161,11 +165,11 @@ TEST(Annotations, AddMultiple) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { -10, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{-10, 0}, "default_marker"}); test.frontend.render(test.map); - test.map.addAnnotation(SymbolAnnotation { Point { 10, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{10, 0}, "default_marker"}); test.checkRendering("add_multiple"); } @@ -175,8 +179,8 @@ TEST(Annotations, NonImmediateAdd) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.frontend.render(test.map); - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation annotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation annotation{polygon}; annotation.color = Color::red(); test.map.addAnnotation(annotation); @@ -189,11 +193,11 @@ TEST(Annotations, UpdateSymbolAnnotationGeometry) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); test.map.addAnnotationImage(namedMarker("flipped_marker")); - AnnotationID point = test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + AnnotationID point = test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); - test.map.updateAnnotation(point, SymbolAnnotation { Point { -10, 0 }, "default_marker" }); + test.map.updateAnnotation(point, SymbolAnnotation{Point{-10, 0}, "default_marker"}); test.checkRendering("update_point"); } @@ -203,27 +207,27 @@ TEST(Annotations, UpdateSymbolAnnotationIcon) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); test.map.addAnnotationImage(namedMarker("flipped_marker")); - AnnotationID point = test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + AnnotationID point = test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); - test.map.updateAnnotation(point, SymbolAnnotation { Point { 0, 0 }, "flipped_marker" }); + test.map.updateAnnotation(point, SymbolAnnotation{Point{0, 0}, "flipped_marker"}); test.checkRendering("update_icon"); } TEST(Annotations, UpdateLineAnnotationGeometry) { AnnotationTest test; - LineAnnotation annotation { LineString {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }} }; + LineAnnotation annotation{LineString{{{0, 0}, {45, 45}, {30, 0}}}}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); AnnotationID line = test.map.addAnnotation(annotation); test.frontend.render(test.map); - annotation.geometry = LineString {{ { 0, 0 }, { -45, -45 } }}; + annotation.geometry = LineString{{{0, 0}, {-45, -45}}}; test.map.updateAnnotation(line, annotation); test.checkRendering("update_line_geometry"); } @@ -231,9 +235,9 @@ TEST(Annotations, UpdateLineAnnotationGeometry) { TEST(Annotations, UpdateLineAnnotationStyle) { AnnotationTest test; - LineAnnotation annotation { LineString {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }} }; + LineAnnotation annotation{LineString{{{0, 0}, {45, 45}, {30, 0}}}}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); AnnotationID line = test.map.addAnnotation(annotation); @@ -241,7 +245,7 @@ TEST(Annotations, UpdateLineAnnotationStyle) { test.frontend.render(test.map); annotation.color = Color::green(); - annotation.width = { 2 }; + annotation.width = {2}; test.map.updateAnnotation(line, annotation); test.checkRendering("update_line_style"); } @@ -249,7 +253,7 @@ TEST(Annotations, UpdateLineAnnotationStyle) { TEST(Annotations, UpdateFillAnnotationGeometry) { AnnotationTest test; - FillAnnotation annotation { Polygon { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} } }; + FillAnnotation annotation{Polygon{{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}}; annotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -257,7 +261,7 @@ TEST(Annotations, UpdateFillAnnotationGeometry) { test.frontend.render(test.map); - annotation.geometry = Polygon { {{ { 0, 0 }, { 0, 45 }, { 45, 0 } }} }; + annotation.geometry = Polygon{{{{0, 0}, {0, 45}, {45, 0}}}}; test.map.updateAnnotation(fill, annotation); test.checkRendering("update_fill_geometry"); } @@ -265,8 +269,8 @@ TEST(Annotations, UpdateFillAnnotationGeometry) { TEST(Annotations, UpdateFillAnnotationStyle) { AnnotationTest test; - Polygon polygon = { {{ { 0, 0 }, { 0, 45 }, { 45, 45 }, { 45, 0 } }} }; - FillAnnotation annotation { polygon }; + Polygon polygon = {{{{0, 0}, {0, 45}, {45, 45}, {45, 0}}}}; + FillAnnotation annotation{polygon}; annotation.color = Color::red(); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -284,7 +288,7 @@ TEST(Annotations, RemovePoint) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - AnnotationID point = test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + AnnotationID point = test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); @@ -295,10 +299,10 @@ TEST(Annotations, RemovePoint) { TEST(Annotations, RemoveShape) { AnnotationTest test; - LineString line = {{ { 0, 0 }, { 45, 45 } }}; - LineAnnotation annotation { line }; + LineString line = {{{0, 0}, {45, 45}}}; + LineAnnotation annotation{line}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); AnnotationID shape = test.map.addAnnotation(annotation); @@ -312,7 +316,7 @@ TEST(Annotations, RemoveShape) { TEST(Annotations, ImmediateRemoveShape) { AnnotationTest test; - test.map.removeAnnotation(test.map.addAnnotation(LineAnnotation { LineString() })); + test.map.removeAnnotation(test.map.addAnnotation(LineAnnotation{LineString()})); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.frontend.render(test.map); @@ -323,7 +327,7 @@ TEST(Annotations, SwitchStyle) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); @@ -336,7 +340,7 @@ TEST(Annotations, ReaddImage) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); test.frontend.render(test.map); @@ -349,8 +353,8 @@ TEST(Annotations, QueryRenderedFeatures) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 0 }, "default_marker" }); - test.map.addAnnotation(SymbolAnnotation { Point { 0, 50 }, "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point{0, 0}, "default_marker"}); + test.map.addAnnotation(SymbolAnnotation{Point{0, 50}, "default_marker"}); test.frontend.render(test.map); @@ -381,7 +385,7 @@ TEST(Annotations, QueryFractionalZoomLevels) { AnnotationTest test; auto viewSize = test.frontend.getSize(); - auto box = ScreenBox { {}, { double(viewSize.width), double(viewSize.height) } }; + auto box = ScreenBox{{}, {double(viewSize.width), double(viewSize.height)}}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); @@ -389,7 +393,8 @@ TEST(Annotations, QueryFractionalZoomLevels) { std::vector ids; for (int longitude = 0; longitude < 10; longitude += 2) { for (int latitude = 0; latitude < 10; latitude += 2) { - ids.push_back(test.map.addAnnotation(SymbolAnnotation { { double(latitude), double(longitude) }, "default_marker" })); + ids.push_back( + test.map.addAnnotation(SymbolAnnotation{{double(latitude), double(longitude)}, "default_marker"})); } } @@ -401,8 +406,12 @@ TEST(Annotations, QueryFractionalZoomLevels) { // Filter out repeated features. // See 'edge-cases/null-island' query-test for reference. - auto sortID = [](const Feature& lhs, const Feature& rhs) { return lhs.id < rhs.id; }; - auto sameID = [](const Feature& lhs, const Feature& rhs) { return lhs.id == rhs.id; }; + auto sortID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id < rhs.id; + }; + auto sameID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id == rhs.id; + }; std::sort(features.begin(), features.end(), sortID); features.erase(std::unique(features.begin(), features.end(), sameID), features.end()); EXPECT_EQ(features.size(), ids.size()); @@ -413,7 +422,7 @@ TEST(Annotations, VisibleFeatures) { AnnotationTest test; auto viewSize = test.frontend.getSize(); - auto box = ScreenBox { {}, { double(viewSize.width), double(viewSize.height) } }; + auto box = ScreenBox{{}, {double(viewSize.width), double(viewSize.height)}}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); @@ -422,7 +431,8 @@ TEST(Annotations, VisibleFeatures) { std::vector ids; for (int longitude = 0; longitude < 10; longitude += 2) { for (int latitude = 0; latitude <= 10; latitude += 2) { - ids.push_back(test.map.addAnnotation(SymbolAnnotation { { double(latitude), double(longitude) }, "default_marker" })); + ids.push_back( + test.map.addAnnotation(SymbolAnnotation{{double(latitude), double(longitude)}, "default_marker"})); } } @@ -431,8 +441,12 @@ TEST(Annotations, VisibleFeatures) { test.frontend.render(test.map); auto features = test.frontend.getRenderer()->queryRenderedFeatures(box, {}); - auto sortID = [](const Feature& lhs, const Feature& rhs) { return lhs.id < rhs.id; }; - auto sameID = [](const Feature& lhs, const Feature& rhs) { return lhs.id == rhs.id; }; + auto sortID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id < rhs.id; + }; + auto sameID = [](const Feature& lhs, const Feature& rhs) { + return lhs.id == rhs.id; + }; std::sort(features.begin(), features.end(), sortID); features.erase(std::unique(features.begin(), features.end(), sameID), features.end()); EXPECT_EQ(features.size(), ids.size()); @@ -450,26 +464,26 @@ TEST(Annotations, ViewFrustumCulling) { // rectangle are not rendered for different camera setup, especially when // using edge insets - viewport center is then offsetted. - // Important premise of this test is "static const float viewportPadding = 100;" - // as defined in collision_index.cpp: tests using edge insets are writen so that - // padding is 128 (half of viewSize width). If increasing viewportPadding, - // increase the padding in test cases below. + // Important premise of this test is "static const float viewportPadding = + // 100;" as defined in collision_index.cpp: tests using edge insets are + // writen so that padding is 128 (half of viewSize width). If increasing + // viewportPadding, increase the padding in test cases below. AnnotationTest test; auto viewSize = test.frontend.getSize(); - auto box = ScreenBox { {}, { double(viewSize.width), double(viewSize.height) } }; + auto box = ScreenBox{{}, {double(viewSize.width), double(viewSize.height)}}; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.addAnnotationImage(namedMarker("default_marker")); - const LatLng center = { 5.0, 5.0 }; + const LatLng center = {5.0, 5.0}; test.map.jumpTo(CameraOptions().withCenter(center).withZoom(3.0)); // Batch conversion of pixels to latLngs - const std::vector batchLatLngs = - test.map.latLngsForPixels({ScreenCoordinate(0, 0), - ScreenCoordinate(viewSize.width, viewSize.height), - ScreenCoordinate(viewSize.width, 0), - ScreenCoordinate(0, viewSize.height)}); + const std::vector batchLatLngs = test.map.latLngsForPixels( + {ScreenCoordinate(0, 0), + ScreenCoordinate(viewSize.width, viewSize.height), + ScreenCoordinate(viewSize.width, 0), + ScreenCoordinate(0, viewSize.height)}); ASSERT_EQ(4, batchLatLngs.size()); // Single conversion of pixel to latLng @@ -499,22 +513,23 @@ TEST(Annotations, ViewFrustumCulling) { std::vector>> expectedVisibleForCamera = { // Start with all markers visible. - { CameraOptions(), { 0, 1, 2, 3, 4 } }, + {CameraOptions(), {0, 1, 2, 3, 4}}, // Move center to topLeft: only former center and top left (now center) are visible. - { CameraOptions().withCenter(tl), { 0, 4 } }, + {CameraOptions().withCenter(tl), {0, 4}}, // Reset center. With pitch: only top row markers and center are visible. - { CameraOptions().withCenter(center).withPitch(45), { 0, 1, 4 } }, + {CameraOptions().withCenter(center).withPitch(45), {0, 1, 4}}, // Reset pitch, and use padding to move viewport center: only topleft and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { viewSize.height * 0.5, viewSize.width * 0.5, 0, 0 }), { 0, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{viewSize.height * 0.5, viewSize.width * 0.5, 0, 0}), + {0, 4}}, // Use opposite padding to move viewport center: only bottom right and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { 0, 0, viewSize.height * 0.5, viewSize.width * 0.5 }), { 3, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{0, 0, viewSize.height * 0.5, viewSize.width * 0.5}), + {3, 4}}, // Use top padding to move viewport center: top row and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { viewSize.height * 0.5, 0, 0, 0 }), { 0, 1, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{viewSize.height * 0.5, 0, 0, 0}), {0, 1, 4}}, // Use bottom padding: only bottom right and center are visible. - { CameraOptions().withPitch(0).withPadding(EdgeInsets { 0, 0, viewSize.height * 0.5, 0 }), { 2, 3, 4 } }, + {CameraOptions().withPitch(0).withPadding(EdgeInsets{0, 0, viewSize.height * 0.5, 0}), {2, 3, 4}}, // Left padding and pitch: top left, bottom left and center are visible. - { CameraOptions().withPitch(45).withPadding(EdgeInsets { 0, viewSize.width * 0.5, 0, 0 }), { 0, 2, 4 } } - }; + {CameraOptions().withPitch(45).withPadding(EdgeInsets{0, viewSize.width * 0.5, 0, 0}), {0, 2, 4}}}; for (unsigned i = 0; i < expectedVisibleForCamera.size(); i++) { auto testCase = expectedVisibleForCamera[i]; @@ -522,9 +537,11 @@ TEST(Annotations, ViewFrustumCulling) { test.frontend.render(test.map); auto features = test.frontend.getRenderer()->queryRenderedFeatures(box, {}); for (uint64_t id : testCase.second) { // testCase.second is vector of ids expected. - EXPECT_NE(std::find_if(features.begin(), features.end(), [&id](auto feature) { - return id == feature.id.template get(); - }), features.end()) << "Point with id " << id << " is missing in test case " << i; + EXPECT_NE(std::find_if(features.begin(), + features.end(), + [&id](auto feature) { return id == feature.id.template get(); }), + features.end()) + << "Point with id " << id << " is missing in test case " << i; EXPECT_EQ(features.size(), testCase.second.size()) << " in test case " << i; } } @@ -538,9 +555,9 @@ TEST(Annotations, TopOffsetPixels) { } TEST(Annotations, DebugEmpty) { - // This test should render nothing, not even the tile borders. Tile borders are only rendered - // when there is an actual tile we're trying to render, but since there is no annotation, we - // should not render them. + // This test should render nothing, not even the tile borders. Tile borders + // are only rendered when there is an actual tile we're trying to render, + // but since there is no annotation, we should not render them. AnnotationTest test; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); @@ -550,21 +567,20 @@ TEST(Annotations, DebugEmpty) { test.checkRendering("debug_empty"); } - TEST(Annotations, DebugSparse) { if (gfx::Backend::GetType() != gfx::Backend::Type::OpenGL) { return; } - // This test should only render the top right tile with the associated tile border, but no other - // tiles because they're all empty. + // This test should only render the top right tile with the associated tile + // border, but no other tiles because they're all empty. AnnotationTest test; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); test.map.setDebug(MapDebugOptions::TileBorders); test.map.jumpTo(CameraOptions().withZoom(1.0)); test.map.addAnnotationImage(namedMarker("default_marker")); - test.map.addAnnotation(SymbolAnnotation { Point(10, 10), "default_marker" }); + test.map.addAnnotation(SymbolAnnotation{Point(10, 10), "default_marker"}); test.checkRendering("debug_sparse"); } @@ -572,10 +588,10 @@ TEST(Annotations, DebugSparse) { TEST(Annotations, ChangeMaxZoom) { AnnotationTest test; - LineString line = {{ { 0, 0 }, { 45, 45 }, { 30, 0 } }}; - LineAnnotation annotation { line }; + LineString line = {{{0, 0}, {45, 45}, {30, 0}}}; + LineAnnotation annotation{line}; annotation.color = Color::red(); - annotation.width = { 5 }; + annotation.width = {5}; test.map.setBounds(BoundOptions().withMaxZoom(6)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); diff --git a/test/api/api_misuse.test.cpp b/test/api/api_misuse.test.cpp index 549f26c8d42..14b13497a9d 100644 --- a/test/api/api_misuse.test.cpp +++ b/test/api/api_misuse.test.cpp @@ -13,15 +13,15 @@ using namespace mbgl; - TEST(API, RenderWithoutCallback) { FixtureLog log; util::RunLoop loop; - HeadlessFrontend frontend { 1 }; + HeadlessFrontend frontend{1}; - auto map = std::make_unique(frontend, MapObserver::nullObserver(), + auto map = std::make_unique(frontend, + MapObserver::nullObserver(), std::make_shared(), MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())); map->renderStill(nullptr); @@ -29,7 +29,7 @@ TEST(API, RenderWithoutCallback) { // Force Map thread to join. map.reset(); - const FixtureLogObserver::LogMessage logMessage { + const FixtureLogObserver::LogMessage logMessage{ EventSeverity::Error, Event::General, int64_t(-1), diff --git a/test/api/custom_geometry_source.test.cpp b/test/api/custom_geometry_source.test.cpp index 93cf6ba56e1..006fed5e0ed 100644 --- a/test/api/custom_geometry_source.test.cpp +++ b/test/api/custom_geometry_source.test.cpp @@ -19,20 +19,22 @@ using namespace mbgl::style; TEST(CustomGeometrySource, Grid) { util::RunLoop loop; - HeadlessFrontend frontend { 1 }; - Map map(frontend, MapObserver::nullObserver(), + HeadlessFrontend frontend{1}; + Map map(frontend, + MapObserver::nullObserver(), MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 37.8, -122.5 }).withZoom(10.0)); + map.jumpTo(CameraOptions().withCenter(LatLng{37.8, -122.5}).withZoom(10.0)); CustomGeometrySource::Options options; options.fetchTileFunction = [&map](const mbgl::CanonicalTileID& tileID) { double gridSpacing = 0.1; FeatureCollection features; const LatLngBounds bounds(tileID); - for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; y >= floor(bounds.south() / gridSpacing) * gridSpacing; y -= gridSpacing) { - + for (double y = ceil(bounds.north() / gridSpacing) * gridSpacing; + y >= floor(bounds.south() / gridSpacing) * gridSpacing; + y -= gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(bounds.west(), y); gridLine.emplace_back(bounds.east(), y); @@ -40,14 +42,16 @@ TEST(CustomGeometrySource, Grid) { features.emplace_back(gridLine); } - for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; x <= ceil(bounds.east() / gridSpacing) * gridSpacing; x += gridSpacing) { + for (double x = floor(bounds.west() / gridSpacing) * gridSpacing; + x <= ceil(bounds.east() / gridSpacing) * gridSpacing; + x += gridSpacing) { mapbox::geojson::line_string gridLine; gridLine.emplace_back(x, bounds.south()); gridLine.emplace_back(x, bounds.north()); - + features.emplace_back(gridLine); } - auto source = static_cast(map.getStyle().getSource("custom")); + auto source = static_cast(map.getStyle().getSource("custom")); if (source) { source->setTileData(tileID, features); } @@ -57,11 +61,11 @@ TEST(CustomGeometrySource, Grid) { auto fillLayer = std::make_unique("landcover", "mapbox"); fillLayer->setSourceLayer("landcover"); - fillLayer->setFillColor(Color{ 1.0, 1.0, 0.0, 1.0 }); + fillLayer->setFillColor(Color{1.0, 1.0, 0.0, 1.0}); map.getStyle().addLayer(std::move(fillLayer)); auto layer = std::make_unique("grid", "custom"); - layer->setLineColor(Color{ 1.0, 1.0, 1.0, 1.0 }); + layer->setLineColor(Color{1.0, 1.0, 1.0, 1.0}); map.getStyle().addLayer(std::move(layer)); test::checkImage("test/fixtures/custom_geometry_source/grid", frontend.render(map).image, 0.0006, 0.1); diff --git a/test/api/custom_layer.test.cpp b/test/api/custom_layer.test.cpp index 2cfa7bf4004..63ac1954f16 100644 --- a/test/api/custom_layer.test.cpp +++ b/test/api/custom_layer.test.cpp @@ -17,8 +17,8 @@ using namespace mbgl; using namespace mbgl::style; using namespace mbgl::platform; -// Note that custom layers need to draw geometry with a z value of 1 to take advantage of -// depth-based fragment culling. +// Note that custom layers need to draw geometry with a z value of 1 to take +// advantage of depth-based fragment culling. static const GLchar* vertexShaderSource = R"MBGL_SHADER( attribute vec2 a_pos; void main() { @@ -32,9 +32,9 @@ void main() { } )MBGL_SHADER"; -// Not using any mbgl-specific stuff (other than a basic error-checking macro) in the -// layer implementation because it is intended to reflect how someone using custom layers -// might actually write their own implementation. +// Not using any mbgl-specific stuff (other than a basic error-checking macro) +// in the layer implementation because it is intended to reflect how someone +// using custom layers might actually write their own implementation. class TestLayer : public mbgl::style::CustomLayerHost { public: @@ -52,7 +52,7 @@ class TestLayer : public mbgl::style::CustomLayerHost { MBGL_CHECK_ERROR(glLinkProgram(program)); a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); - GLfloat triangle[] = { 0, 0.5, 0.5, -0.5, -0.5, -0.5 }; + GLfloat triangle[] = {0, 0.5, 0.5, -0.5, -0.5, -0.5}; MBGL_CHECK_ERROR(glGenBuffers(1, &buffer)); MBGL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, buffer)); MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(GLfloat), triangle, GL_STATIC_DRAW)); @@ -69,14 +69,14 @@ class TestLayer : public mbgl::style::CustomLayerHost { void contextLost() override {} void deinitialize() override { - if (program) { - MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); - MBGL_CHECK_ERROR(glDetachShader(program, vertexShader)); - MBGL_CHECK_ERROR(glDetachShader(program, fragmentShader)); - MBGL_CHECK_ERROR(glDeleteShader(vertexShader)); - MBGL_CHECK_ERROR(glDeleteShader(fragmentShader)); - MBGL_CHECK_ERROR(glDeleteProgram(program)); - } + if (program) { + MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); + MBGL_CHECK_ERROR(glDetachShader(program, vertexShader)); + MBGL_CHECK_ERROR(glDetachShader(program, fragmentShader)); + MBGL_CHECK_ERROR(glDeleteShader(vertexShader)); + MBGL_CHECK_ERROR(glDeleteShader(fragmentShader)); + MBGL_CHECK_ERROR(glDeleteProgram(program)); + } } GLuint program = 0; @@ -93,19 +93,18 @@ TEST(CustomLayer, Basic) { util::RunLoop loop; - HeadlessFrontend frontend { 1 }; - Map map(frontend, MapObserver::nullObserver(), + HeadlessFrontend frontend{1}; + Map map(frontend, + MapObserver::nullObserver(), MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 37.8, -122.5 }).withZoom(10.0)); - map.getStyle().addLayer(std::make_unique( - "custom", - std::make_unique())); + map.jumpTo(CameraOptions().withCenter(LatLng{37.8, -122.5}).withZoom(10.0)); + map.getStyle().addLayer(std::make_unique("custom", std::make_unique())); auto layer = std::make_unique("landcover", "mapbox"); layer->setSourceLayer("landcover"); - layer->setFillColor(Color{ 1.0, 1.0, 0.0, 1.0 }); + layer->setFillColor(Color{1.0, 1.0, 0.0, 1.0}); map.getStyle().addLayer(std::move(layer)); test::checkImage("test/fixtures/custom_layer/basic", frontend.render(map).image, 0.0006, 0.1); diff --git a/test/api/query.test.cpp b/test/api/query.test.cpp index 44724d7fdaa..87d34feaebe 100644 --- a/test/api/query.test.cpp +++ b/test/api/query.test.cpp @@ -26,21 +26,23 @@ class QueryTest { public: QueryTest() { map.getStyle().loadJSON(util::read_file("test/fixtures/api/query_style.json")); - map.getStyle().addImage(std::make_unique("test-icon", - decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f)); + map.getStyle().addImage(std::make_unique( + "test-icon", decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f)); frontend.render(map); } util::RunLoop loop; std::shared_ptr fileSource = std::make_shared(); - HeadlessFrontend frontend { 1 }; - MapAdapter map { frontend, MapObserver::nullObserver(), fileSource, - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; + HeadlessFrontend frontend{1}; + MapAdapter map{frontend, + MapObserver::nullObserver(), + fileSource, + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())}; }; std::vector getTopClusterFeature(QueryTest& test) { - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://url"s, resource.url); Response response; response.data = std::make_unique(util::read_file("test/fixtures/supercluster/places.json"s)); @@ -65,9 +67,8 @@ std::vector getTopClusterFeature(QueryTest& test) { test.frontend.render(test.map); auto screenCoordinate = test.map.pixelForLatLng(coordinate); - const RenderedQueryOptions queryOptions({{{ "cluster_layer"s}}, {}}); - return test.frontend.getRenderer()->queryRenderedFeatures(screenCoordinate, - queryOptions); + const RenderedQueryOptions queryOptions({{{"cluster_layer"s}}, {}}); + return test.frontend.getRenderer()->queryRenderedFeatures(screenCoordinate, queryOptions); } } // end namespace @@ -97,18 +98,18 @@ TEST(Query, QueryRenderedFeatures) { TEST(Query, QueryRenderedFeaturesFilterLayer) { QueryTest test; - auto zz = test.map.pixelForLatLng({ 0, 0 }); + auto zz = test.map.pixelForLatLng({0, 0}); - auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "layer1"}}, {}}); + auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"layer1"}}, {}}); EXPECT_EQ(features1.size(), 1u); - auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "layer1", "layer2" }}, {}}); + auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"layer1", "layer2"}}, {}}); EXPECT_EQ(features2.size(), 2u); - auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "foobar" }}, {}}); + auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"foobar"}}, {}}); EXPECT_EQ(features3.size(), 0u); - auto features4 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "foobar", "layer3" }}, {}}); + auto features4 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"foobar", "layer3"}}, {}}); EXPECT_EQ(features4.size(), 1u); } @@ -116,18 +117,18 @@ TEST(Query, QueryRenderedFeaturesFilter) { using namespace mbgl::style::expression::dsl; QueryTest test; - auto zz = test.map.pixelForLatLng({ 0, 0 }); + auto zz = test.map.pixelForLatLng({0, 0}); const Filter eqFilter(eq(get("key1"), literal("value1"))); - auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{}, { eqFilter }}); + auto features1 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{}, {eqFilter}}); EXPECT_EQ(features1.size(), 1u); const Filter idNotEqFilter(ne(id(), literal("feature1"))); - auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{ "layer4" }}, { idNotEqFilter }}); + auto features2 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{{"layer4"}}, {idNotEqFilter}}); EXPECT_EQ(features2.size(), 0u); const Filter gtFilter(gt(number(get("key2")), literal(1.0))); - auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{ }, { gtFilter }}); + auto features3 = test.frontend.getRenderer()->queryRenderedFeatures(zz, {{}, {gtFilter}}); EXPECT_EQ(features3.size(), 1u); } @@ -164,7 +165,7 @@ TEST(Query, QuerySourceFeaturesOptionValidation) { // VectorSource, requires a layer id features = test.frontend.getRenderer()->querySourceFeatures("source5"); ASSERT_EQ(features.size(), 0u); - + // RasterSource, not supported features = test.frontend.getRenderer()->querySourceFeatures("source6"); ASSERT_EQ(features.size(), 0u); @@ -176,25 +177,22 @@ TEST(Query, QuerySourceFeaturesFilter) { QueryTest test; const Filter eqFilter(eq(get("key1"), literal("value1"))); - auto features1 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, { eqFilter }}); + auto features1 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, {eqFilter}}); EXPECT_EQ(features1.size(), 1u); const Filter idNotEqFilter(ne(id(), literal("feature1"))); - auto features2 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, { idNotEqFilter }}); + auto features2 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, {idNotEqFilter}}); EXPECT_EQ(features2.size(), 0u); const Filter gtFilter(gt(number(get("key2")), literal(1.0))); - auto features3 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, { gtFilter }}); + auto features3 = test.frontend.getRenderer()->querySourceFeatures("source4", {{}, {gtFilter}}); EXPECT_EQ(features3.size(), 1u); } TEST(Query, QueryFeatureExtensionsInvalidExtension) { QueryTest test; - auto unknownExt = test.frontend.getRenderer()->queryFeatureExtensions("source4"s, - {}, - "unknown"s, - "children"s); + auto unknownExt = test.frontend.getRenderer()->queryFeatureExtensions("source4"s, {}, "unknown"s, "children"s); auto unknownValue = unknownExt.get(); EXPECT_TRUE(unknownValue.is()); } @@ -206,14 +204,12 @@ TEST(Query, QueryFeatureExtensionsSuperclusterChildren) { EXPECT_EQ(topClusterFeature.size(), 1u); const auto featureProps = topClusterFeature[0].properties; auto clusterId = featureProps.find("cluster_id"s); - auto cluster = featureProps.find("cluster"s); + auto cluster = featureProps.find("cluster"s); EXPECT_TRUE(clusterId != featureProps.end()); EXPECT_TRUE(cluster != featureProps.end()); - auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "children"s); + auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "children"s); EXPECT_TRUE(queryChildren.is()); auto children = queryChildren.get(); @@ -235,22 +231,15 @@ TEST(Query, QueryFeatureExtensionsSuperclusterExpansionZoom) { auto topClusterFeature = getTopClusterFeature(test); EXPECT_EQ(topClusterFeature.size(), 1u); - auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "children"s); + auto queryChildren = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "children"s); auto children = queryChildren.get(); + auto queryExpansionZoom1 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "expansion-zoom"s); - auto queryExpansionZoom1 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "expansion-zoom"s); - - auto queryExpansionZoom2 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - children[3], - "supercluster"s, - "expansion-zoom"s); + auto queryExpansionZoom2 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, children[3], "supercluster"s, "expansion-zoom"s); auto zoomValue1 = queryExpansionZoom1.get(); auto zoomValue2 = queryExpansionZoom2.get(); EXPECT_TRUE(zoomValue1.is()); @@ -265,21 +254,16 @@ TEST(Query, QueryFeatureExtensionsSuperclusterLeaves) { EXPECT_EQ(topClusterFeature.size(), 1u); // Get leaves for cluster 1, with default limit 10, offset 0. - auto queryClusterLeaves = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "leaves"s); + auto queryClusterLeaves = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "leaves"s); EXPECT_TRUE(queryClusterLeaves.is()); auto leaves = queryClusterLeaves.get(); EXPECT_EQ(leaves.size(), 10u); // Get leaves for cluster 1, with limit 3, offset 0. - const std::map limitOpts = { {"limit"s, static_cast(3u)} }; - auto queryClusterLeavesLimit3 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "leaves"s, - limitOpts); + const std::map limitOpts = {{"limit"s, static_cast(3u)}}; + auto queryClusterLeavesLimit3 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "leaves"s, limitOpts); auto limitLeaves3 = queryClusterLeavesLimit3.get(); EXPECT_EQ(limitLeaves3.size(), 3u); @@ -288,13 +272,10 @@ TEST(Query, QueryFeatureExtensionsSuperclusterLeaves) { EXPECT_EQ(limitLeaves3[2].properties["name"].get(), "Cape Fear"s); // Get leaves for cluster 1, with limit 3, offset 3. - const std::map offsetOpts = { {"limit"s, static_cast(3u)}, - {"offset"s, static_cast(3u)} }; - auto queryClusterLeavesOffset3 = test.frontend.getRenderer()->queryFeatureExtensions("cluster_source"s, - topClusterFeature[0], - "supercluster"s, - "leaves"s, - offsetOpts); + const std::map offsetOpts = {{"limit"s, static_cast(3u)}, + {"offset"s, static_cast(3u)}}; + auto queryClusterLeavesOffset3 = test.frontend.getRenderer()->queryFeatureExtensions( + "cluster_source"s, topClusterFeature[0], "supercluster"s, "leaves"s, offsetOpts); auto offsetLeaves3 = queryClusterLeavesOffset3.get(); EXPECT_EQ(offsetLeaves3.size(), 3u); EXPECT_EQ(offsetLeaves3[0].properties["name"].get(), "Cape Hatteras"s); diff --git a/test/api/recycle_map.cpp b/test/api/recycle_map.cpp index bfccaff757d..df96ea3fa5f 100644 --- a/test/api/recycle_map.cpp +++ b/test/api/recycle_map.cpp @@ -18,28 +18,30 @@ using namespace mbgl; using namespace mbgl::style; - TEST(API, RecycleMapUpdateImages) { util::RunLoop loop; - HeadlessFrontend frontend { 1 }; - auto map = std::make_unique(frontend, MapObserver::nullObserver(), - std::make_shared(ResourceOptions::Default(), ClientOptions()), - MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())); + HeadlessFrontend frontend{1}; + auto map = std::make_unique( + frontend, + MapObserver::nullObserver(), + std::make_shared(ResourceOptions::Default(), ClientOptions()), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize())); EXPECT_TRUE(map); auto loadStyle = [&](auto markerName, auto markerPath) { auto source = std::make_unique("geometry"); - source->setGeoJSON( Geometry{ Point{ 0, 0 } } ); + source->setGeoJSON(Geometry{Point{0, 0}}); auto layer = std::make_unique("geometry", "geometry"); - layer->setIconImage({ markerName }); + layer->setIconImage({markerName}); map->getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); map->getStyle().addSource(std::move(source)); map->getStyle().addLayer(std::move(layer)); - map->getStyle().addImage(std::make_unique(markerName, decodeImage(util::read_file(markerPath)), 1.0f)); + map->getStyle().addImage( + std::make_unique(markerName, decodeImage(util::read_file(markerPath)), 1.0f)); }; // default marker diff --git a/test/geometry/dem_data.test.cpp b/test/geometry/dem_data.test.cpp index 24893d16edf..bb3e4049bb2 100644 --- a/test/geometry/dem_data.test.cpp +++ b/test/geometry/dem_data.test.cpp @@ -9,8 +9,8 @@ using namespace mbgl; auto fakeImage = [](Size s) { PremultipliedImage img = PremultipliedImage(s); - for (size_t i = 0; i < img.bytes(); i ++) { - img.data[i] = (i+1) % 4 == 0 ? 1 : std::rand() % 255; + for (size_t i = 0; i < img.bytes(); i++) { + img.data[i] = (i + 1) % 4 == 0 ? 1 : std::rand() % 255; } return img; }; @@ -21,7 +21,7 @@ TEST(DEMData, ConstructorMapbox) { EXPECT_EQ(demdata.dim, 16); EXPECT_EQ(demdata.stride, 18); - EXPECT_EQ(demdata.getImage()->bytes(), size_t(18*18*4)); + EXPECT_EQ(demdata.getImage()->bytes(), size_t(18 * 18 * 4)); }; TEST(DEMData, ConstructorTerrarium) { @@ -30,19 +30,18 @@ TEST(DEMData, ConstructorTerrarium) { EXPECT_EQ(demdata.dim, 16); EXPECT_EQ(demdata.stride, 18); - EXPECT_EQ(demdata.getImage()->bytes(), size_t(18*18*4)); + EXPECT_EQ(demdata.getImage()->bytes(), size_t(18 * 18 * 4)); }; TEST(DEMData, InitialBackfill) { - PremultipliedImage image1 = fakeImage({4, 4}); DEMData dem1(image1, Tileset::DEMEncoding::Mapbox); bool nonempty = true; // checking that a 1 px border around the fake image has been populated // with a non-empty pixel value - for (int x = -1; x < 5; x++){ - for (int y = -1; y < 5; y ++) { + for (int x = -1; x < 5; x++) { + for (int y = -1; y < 5; y++) { if (dem1.get(x, y) == -65536) { nonempty = false; break; @@ -75,7 +74,7 @@ TEST(DEMData, InitialBackfill) { } } } - //horizontal border of DEM data is initially equal to next row of data + // horizontal border of DEM data is initially equal to next row of data EXPECT_TRUE(horizontalBorderMatch); // -1, 1 corner initially equal to closest corner data @@ -97,10 +96,9 @@ TEST(DEMData, BackfillNeighbor) { dem0.backfillBorder(dem1, -1, 0); for (int y = 0; y < 4; y++) { - // dx = -1, dy = 0, so the left edge of dem1 should equal the right edge of dem0 - // backfills Left neighbor + // dx = -1, dy = 0, so the left edge of dem1 should equal the right edge + // of dem0 backfills Left neighbor EXPECT_TRUE(dem0.get(-1, y) == dem1.get(3, y)); - } dem0.backfillBorder(dem1, 0, -1); diff --git a/test/geometry/line_atlas.test.cpp b/test/geometry/line_atlas.test.cpp index 1d817220e15..f4f3f5920f9 100644 --- a/test/geometry/line_atlas.test.cpp +++ b/test/geometry/line_atlas.test.cpp @@ -22,8 +22,8 @@ TEST(LineAtlas, Random) { for (size_t i = 0; i < count; i++) { dasharray.push_back(lengthDistribution(generator)); } - const LinePatternCap patternCap = - capStyleDistribution(generator) > 0 ? LinePatternCap::Round : LinePatternCap::Square; + const LinePatternCap patternCap = capStyleDistribution(generator) > 0 ? LinePatternCap::Round + : LinePatternCap::Square; atlas.getDashPatternTexture(dasharray, dasharray, patternCap); } diff --git a/test/gl/bucket.test.cpp b/test/gl/bucket.test.cpp index fd8644bfbcb..39fd7807617 100644 --- a/test/gl/bucket.test.cpp +++ b/test/gl/bucket.test.cpp @@ -43,16 +43,16 @@ PropertyMap properties; } // namespace TEST(Buckets, CircleBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; - gl::Context context{ backend }; + gl::Context context{backend}; CircleBucket bucket{{}, MapMode::Static, 1.0}; ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); // CircleBucket::addFeature() is a no-op. - GeometryCollection point { { { 0, 0 } } }; + GeometryCollection point{{{0, 0}}}; bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Point, point, properties}, point, {}, @@ -74,16 +74,16 @@ TEST(Buckets, CircleBucket) { } TEST(Buckets, FillBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; FillBucket::PossiblyEvaluatedLayoutProperties layout; - gl::Context context{ backend }; - FillBucket bucket { layout, {}, 5.0f, 1}; + gl::Context context{backend}; + FillBucket bucket{layout, {}, 5.0f, 1}; ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); - GeometryCollection polygon { { { 0, 0 }, { 0, 1 }, { 1, 1 } } }; + GeometryCollection polygon{{{0, 0}, {0, 1}, {1, 1}}}; bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Polygon, polygon, properties}, polygon, {}, @@ -100,17 +100,17 @@ TEST(Buckets, FillBucket) { } TEST(Buckets, LineBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; LineBucket::PossiblyEvaluatedLayoutProperties layout; - gl::Context context{ backend }; - LineBucket bucket { layout, {}, 10.0f, 1 }; + gl::Context context{backend}; + LineBucket bucket{layout, {}, 10.0f, 1}; ASSERT_FALSE(bucket.hasData()); ASSERT_FALSE(bucket.needsUpload()); // Ignore invalid feature type. - GeometryCollection point { { { 0, 0 } } }; + GeometryCollection point{{{0, 0}}}; bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Point, point, properties}, point, {}, @@ -119,7 +119,7 @@ TEST(Buckets, LineBucket) { CanonicalTileID(0, 0, 0)); ASSERT_FALSE(bucket.hasData()); - GeometryCollection line { { { 0, 0 }, { 1, 1 } } }; + GeometryCollection line{{{0, 0}, {1, 1}}}; bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::LineString, line, properties}, line, {}, @@ -136,8 +136,8 @@ TEST(Buckets, LineBucket) { } TEST(Buckets, SymbolBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; auto layout = makeMutable(); bool iconsNeedLinear = false; @@ -146,7 +146,7 @@ TEST(Buckets, SymbolBucket) { std::vector symbolInstances; std::vector symbolRanges; - gl::Context context{ backend }; + gl::Context context{backend}; SymbolBucket bucket{std::move(layout), {}, 16.0f, @@ -172,7 +172,7 @@ TEST(Buckets, SymbolBucket) { ASSERT_FALSE(bucket.needsUpload()); // SymbolBucket::addFeature() is a no-op. - GeometryCollection point { { { 0, 0 } } }; + GeometryCollection point{{{0, 0}}}; bucket.addFeature(StubGeometryTileFeature{{}, FeatureType::Point, std::move(point), properties}, point, {}, @@ -194,14 +194,14 @@ TEST(Buckets, SymbolBucket) { } TEST(Buckets, RasterBucket) { - gl::HeadlessBackend backend({ 512, 256 }); - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend({512, 256}); + gfx::BackendScope scope{backend}; - gl::Context context{ backend }; - PremultipliedImage rgba({ 1, 1 }); + gl::Context context{backend}; + PremultipliedImage rgba({1, 1}); // RasterBucket::hasData() is always true. - RasterBucket bucket = { std::move(rgba) }; + RasterBucket bucket = {std::move(rgba)}; ASSERT_TRUE(bucket.hasData()); ASSERT_TRUE(bucket.needsUpload()); @@ -215,7 +215,7 @@ TEST(Buckets, RasterBucket) { } TEST(Buckets, RasterBucketMaskEmpty) { - RasterBucket bucket{ nullptr }; + RasterBucket bucket{nullptr}; bucket.setMask({}); EXPECT_EQ((std::vector{}), bucket.vertices.vector()); EXPECT_EQ((std::vector{}), bucket.indices.vector()); @@ -225,8 +225,8 @@ TEST(Buckets, RasterBucketMaskEmpty) { } TEST(Buckets, RasterBucketMaskNoChildren) { - RasterBucket bucket{ nullptr }; - bucket.setMask({ CanonicalTileID{ 0, 0, 0 } }); + RasterBucket bucket{nullptr}; + bucket.setMask({CanonicalTileID{0, 0, 0}}); // A mask of 0/0/0 doesn't produce buffers since we're instead using the global shared buffers. EXPECT_EQ((std::vector{}), bucket.vertices.vector()); @@ -234,121 +234,149 @@ TEST(Buckets, RasterBucketMaskNoChildren) { EXPECT_EQ((SegmentVector{}), bucket.segments); } - TEST(Buckets, RasterBucketMaskTwoChildren) { - RasterBucket bucket{ nullptr }; - bucket.setMask( - { CanonicalTileID{ 1, 0, 0 }, CanonicalTileID{ 1, 1, 1 } }); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - RasterProgram::layoutVertex({ 0, 0 }, { 0, 0 }), - RasterProgram::layoutVertex({ 4096, 0 }, { 4096, 0 }), - RasterProgram::layoutVertex({ 0, 4096 }, { 0, 4096 }), - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - - // 1/1/1 - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }), - RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }), - RasterProgram::layoutVertex({ 8192, 8192 }, { 8192, 8192 }), - }), - bucket.vertices.vector()); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - 0, 1, 2, - 1, 2, 3, - - // 1/1/1 - 4, 5, 6, - 5, 6, 7, - }), - bucket.indices.vector()); - - - SegmentVector expectedSegments; - expectedSegments.emplace_back(0, 0, 8, 12); - EXPECT_EQ(expectedSegments, bucket.segments); - } - - TEST(Buckets, RasterBucketMaskComplex) { - RasterBucket bucket{ nullptr }; - bucket.setMask( - { CanonicalTileID{ 1, 0, 1 }, CanonicalTileID{ 1, 1, 0 }, CanonicalTileID{ 2, 2, 3 }, - CanonicalTileID{ 2, 3, 2 }, CanonicalTileID{ 3, 6, 7 }, CanonicalTileID{ 3, 7, 6 } }); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - RasterProgram::layoutVertex({ 0, 4096 }, { 0, 4096 }), - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - RasterProgram::layoutVertex({ 0, 8192 }, { 0, 8192 }), - RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }), - - // 1/1/0 - RasterProgram::layoutVertex({ 4096, 0 }, { 4096, 0 }), - RasterProgram::layoutVertex({ 8192, 0 }, { 8192, 0 }), - RasterProgram::layoutVertex({ 4096, 4096 }, { 4096, 4096 }), - RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }), - - // 2/2/3 - RasterProgram::layoutVertex({ 4096, 6144 }, { 4096, 6144 }), - RasterProgram::layoutVertex({ 6144, 6144 }, { 6144, 6144 }), - RasterProgram::layoutVertex({ 4096, 8192 }, { 4096, 8192 }), - RasterProgram::layoutVertex({ 6144, 8192 }, { 6144, 8192 }), - - // 2/3/2 - RasterProgram::layoutVertex({ 6144, 4096 }, { 6144, 4096 }), - RasterProgram::layoutVertex({ 8192, 4096 }, { 8192, 4096 }), - RasterProgram::layoutVertex({ 6144, 6144 }, { 6144, 6144 }), - RasterProgram::layoutVertex({ 8192, 6144 }, { 8192, 6144 }), - - // 3/6/7 - RasterProgram::layoutVertex({ 6144, 7168 }, { 6144, 7168 }), - RasterProgram::layoutVertex({ 7168, 7168 }, { 7168, 7168 }), - RasterProgram::layoutVertex({ 6144, 8192 }, { 6144, 8192 }), - RasterProgram::layoutVertex({ 7168, 8192 }, { 7168, 8192 }), - - // 3/7/6 - RasterProgram::layoutVertex({ 7168, 6144 }, { 7168, 6144 }), - RasterProgram::layoutVertex({ 8192, 6144 }, { 8192, 6144 }), - RasterProgram::layoutVertex({ 7168, 7168 }, { 7168, 7168 }), - RasterProgram::layoutVertex({ 8192, 7168 }, { 8192, 7168 }), - }), - bucket.vertices.vector()); - - EXPECT_EQ( - (std::vector{ - // 1/0/1 - 0, 1, 2, - 1, 2, 3, - - // 1/1/0 - 4, 5, 6, - 5, 6, 7, - - // 2/2/3 - 8, 9, 10, - 9, 10, 11, - - // 2/3/2 - 12, 13, 14, - 13, 14, 15, - - // 3/6/7 - 16, 17, 18, - 17, 18, 19, - - // 3/7/6 - 20, 21, 22, - 21, 22, 23, - }), - bucket.indices.vector()); - - - SegmentVector expectedSegments; - expectedSegments.emplace_back(0, 0, 24, 36); - EXPECT_EQ(expectedSegments, bucket.segments); - } +TEST(Buckets, RasterBucketMaskTwoChildren) { + RasterBucket bucket{nullptr}; + bucket.setMask({CanonicalTileID{1, 0, 0}, CanonicalTileID{1, 1, 1}}); + + EXPECT_EQ((std::vector{ + // 1/0/1 + RasterProgram::layoutVertex({0, 0}, {0, 0}), + RasterProgram::layoutVertex({4096, 0}, {4096, 0}), + RasterProgram::layoutVertex({0, 4096}, {0, 4096}), + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + + // 1/1/1 + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + RasterProgram::layoutVertex({8192, 4096}, {8192, 4096}), + RasterProgram::layoutVertex({4096, 8192}, {4096, 8192}), + RasterProgram::layoutVertex({8192, 8192}, {8192, 8192}), + }), + bucket.vertices.vector()); + + EXPECT_EQ((std::vector{ + // 1/0/1 + 0, + 1, + 2, + 1, + 2, + 3, + + // 1/1/1 + 4, + 5, + 6, + 5, + 6, + 7, + }), + bucket.indices.vector()); + + SegmentVector expectedSegments; + expectedSegments.emplace_back(0, 0, 8, 12); + EXPECT_EQ(expectedSegments, bucket.segments); +} + +TEST(Buckets, RasterBucketMaskComplex) { + RasterBucket bucket{nullptr}; + bucket.setMask({CanonicalTileID{1, 0, 1}, + CanonicalTileID{1, 1, 0}, + CanonicalTileID{2, 2, 3}, + CanonicalTileID{2, 3, 2}, + CanonicalTileID{3, 6, 7}, + CanonicalTileID{3, 7, 6}}); + + EXPECT_EQ((std::vector{ + // 1/0/1 + RasterProgram::layoutVertex({0, 4096}, {0, 4096}), + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + RasterProgram::layoutVertex({0, 8192}, {0, 8192}), + RasterProgram::layoutVertex({4096, 8192}, {4096, 8192}), + + // 1/1/0 + RasterProgram::layoutVertex({4096, 0}, {4096, 0}), + RasterProgram::layoutVertex({8192, 0}, {8192, 0}), + RasterProgram::layoutVertex({4096, 4096}, {4096, 4096}), + RasterProgram::layoutVertex({8192, 4096}, {8192, 4096}), + + // 2/2/3 + RasterProgram::layoutVertex({4096, 6144}, {4096, 6144}), + RasterProgram::layoutVertex({6144, 6144}, {6144, 6144}), + RasterProgram::layoutVertex({4096, 8192}, {4096, 8192}), + RasterProgram::layoutVertex({6144, 8192}, {6144, 8192}), + + // 2/3/2 + RasterProgram::layoutVertex({6144, 4096}, {6144, 4096}), + RasterProgram::layoutVertex({8192, 4096}, {8192, 4096}), + RasterProgram::layoutVertex({6144, 6144}, {6144, 6144}), + RasterProgram::layoutVertex({8192, 6144}, {8192, 6144}), + + // 3/6/7 + RasterProgram::layoutVertex({6144, 7168}, {6144, 7168}), + RasterProgram::layoutVertex({7168, 7168}, {7168, 7168}), + RasterProgram::layoutVertex({6144, 8192}, {6144, 8192}), + RasterProgram::layoutVertex({7168, 8192}, {7168, 8192}), + + // 3/7/6 + RasterProgram::layoutVertex({7168, 6144}, {7168, 6144}), + RasterProgram::layoutVertex({8192, 6144}, {8192, 6144}), + RasterProgram::layoutVertex({7168, 7168}, {7168, 7168}), + RasterProgram::layoutVertex({8192, 7168}, {8192, 7168}), + }), + bucket.vertices.vector()); + + EXPECT_EQ((std::vector{ + // 1/0/1 + 0, + 1, + 2, + 1, + 2, + 3, + + // 1/1/0 + 4, + 5, + 6, + 5, + 6, + 7, + + // 2/2/3 + 8, + 9, + 10, + 9, + 10, + 11, + + // 2/3/2 + 12, + 13, + 14, + 13, + 14, + 15, + + // 3/6/7 + 16, + 17, + 18, + 17, + 18, + 19, + + // 3/7/6 + 20, + 21, + 22, + 21, + 22, + 23, + }), + bucket.indices.vector()); + + SegmentVector expectedSegments; + expectedSegments.emplace_back(0, 0, 24, 36); + EXPECT_EQ(expectedSegments, bucket.segments); +} diff --git a/test/gl/context.test.cpp b/test/gl/context.test.cpp index 2135ed98620..95991f7d711 100644 --- a/test/gl/context.test.cpp +++ b/test/gl/context.test.cpp @@ -73,13 +73,10 @@ struct Buffer { Buffer(std::vector data) { MBGL_CHECK_ERROR(glGenBuffers(1, &buffer)); MBGL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, buffer)); - MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), - GL_STATIC_DRAW)); + MBGL_CHECK_ERROR(glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW)); } - ~Buffer() { - MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); - } + ~Buffer() { MBGL_CHECK_ERROR(glDeleteBuffers(1, &buffer)); } GLuint buffer = 0; }; @@ -98,20 +95,20 @@ TEST(GLContextMode, Shared) { MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()), ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 37.8, -122.5 }).withZoom(10.0)); + map.jumpTo(CameraOptions().withCenter(LatLng{37.8, -122.5}).withZoom(10.0)); // Set transparent background layer. auto layer = map.getStyle().getLayer("background"); ASSERT_STREQ("background", layer->getTypeInfo()->type); - static_cast(layer)->setBackgroundColor( { { 1.0f, 0.0f, 0.0f, 0.5f } } ); + static_cast(layer)->setBackgroundColor({{1.0f, 0.0f, 0.0f, 0.5f}}); { // Custom rendering outside of GL Native render loop. - gfx::BackendScope scope { *frontend.getBackend() }; + gfx::BackendScope scope{*frontend.getBackend()}; frontend.getBackend()->getDefaultRenderable().getResource().bind(); Shader paintShader(vertexShaderSource, fragmentShaderSource); - Buffer triangleBuffer({ 0, 0.5, 0.5, -0.5, -0.5, -0.5 }); + Buffer triangleBuffer({0, 0.5, 0.5, -0.5, -0.5, -0.5}); MBGL_CHECK_ERROR(glUseProgram(paintShader.program)); MBGL_CHECK_ERROR(glBindBuffer(GL_ARRAY_BUFFER, triangleBuffer.buffer)); MBGL_CHECK_ERROR(glEnableVertexAttribArray(paintShader.a_pos)); diff --git a/test/gl/gl_functions.test.cpp b/test/gl/gl_functions.test.cpp index 762146ca908..229be216409 100644 --- a/test/gl/gl_functions.test.cpp +++ b/test/gl/gl_functions.test.cpp @@ -5,7 +5,6 @@ using namespace mbgl::platform; TEST(GLFunctions, OpenGLES) { - /* OpenGL ES 2.0 */ EXPECT_NE(glActiveTexture, nullptr); diff --git a/test/gl/object.test.cpp b/test/gl/object.test.cpp index 2e53b12a80a..2eceba84805 100644 --- a/test/gl/object.test.cpp +++ b/test/gl/object.test.cpp @@ -18,7 +18,10 @@ static bool setFlag = false; struct MockGLObject { using Type = bool; static const Type Default; - static Type Get() { getFlag = true; return true; } + static Type Get() { + getFlag = true; + return true; + } static void Set(const Type&) { setFlag = true; } }; @@ -45,10 +48,10 @@ TEST(GLObject, Value) { } TEST(GLObject, Store) { - gl::HeadlessBackend backend { { 256, 256 } }; - gfx::BackendScope scope { backend }; + gl::HeadlessBackend backend{{256, 256}}; + gfx::BackendScope scope{backend}; - gl::Context context{ backend }; + gl::Context context{backend}; EXPECT_TRUE(context.empty()); gl::UniqueTexture texture = context.createUniqueTexture(); diff --git a/test/include/mbgl/test/util.hpp b/test/include/mbgl/test/util.hpp index 2d8e5d62849..cac43570545 100644 --- a/test/include/mbgl/test/util.hpp +++ b/test/include/mbgl/test/util.hpp @@ -13,33 +13,33 @@ #endif #if TARGET_OS_SIMULATOR - #define TEST_IS_SIMULATOR 1 +#define TEST_IS_SIMULATOR 1 #else - #define TEST_IS_SIMULATOR 0 +#define TEST_IS_SIMULATOR 0 #endif #if !TEST_IS_SIMULATOR && !CI_BUILD #define TEST_REQUIRES_ACCURATE_TIMING(name) name #else -#define TEST_REQUIRES_ACCURATE_TIMING(name) DISABLED_ ## name +#define TEST_REQUIRES_ACCURATE_TIMING(name) DISABLED_##name #endif #if !TEST_READ_ONLY #define TEST_REQUIRES_WRITE(name) name #else -#define TEST_REQUIRES_WRITE(name) DISABLED_ ## name +#define TEST_REQUIRES_WRITE(name) DISABLED_##name #endif #if TEST_HAS_SERVER #define TEST_REQUIRES_SERVER(name) name #else -#define TEST_REQUIRES_SERVER(name) DISABLED_ ## name +#define TEST_REQUIRES_SERVER(name) DISABLED_##name #endif #if !CI_BUILD #define TEST_DISABLED_ON_CI(name) name #else -#define TEST_DISABLED_ON_CI(name) DISABLED_ ## name +#define TEST_DISABLED_ON_CI(name) DISABLED_##name #endif #include diff --git a/test/map/map.test.cpp b/test/map/map.test.cpp index b03d2aee188..ca0e9519826 100644 --- a/test/map/map.test.cpp +++ b/test/map/map.test.cpp @@ -51,9 +51,11 @@ class MapTest { MapAdapter map; MapTest(float pixelRatio = 1, MapMode mode = MapMode::Static) - : fileSource(std::make_shared(ResourceOptions::Default(), ClientOptions())) - , frontend(pixelRatio) - , map(frontend, observer, fileSource, + : fileSource(std::make_shared(ResourceOptions::Default(), ClientOptions())), + frontend(pixelRatio), + map(frontend, + observer, + fileSource, MapOptions().withMapMode(mode).withSize(frontend.getSize()).withPixelRatio(pixelRatio)) {} explicit MapTest(MapOptions options) @@ -67,13 +69,14 @@ class MapTest { float pixelRatio = 1, MapMode mode = MapMode::Static, typename std::enable_if_t>* = nullptr) - : fileSource(std::make_shared(ResourceOptions().withCachePath(cachePath).withAssetPath(assetPath), ClientOptions())), + : fileSource(std::make_shared(ResourceOptions().withCachePath(cachePath).withAssetPath(assetPath), + ClientOptions())), frontend(pixelRatio), map(frontend, observer, fileSource, MapOptions().withMapMode(mode).withSize(frontend.getSize()).withPixelRatio(pixelRatio)) {} - + template MapTest(const ResourceOptions& resourceOptions, const ClientOptions& clientOptions = ClientOptions(), @@ -94,13 +97,14 @@ TEST(Map, RendererState) { CameraOptions nullOptions; ASSERT_EQ(test.frontend.getCameraOptions(), nullOptions); - LatLng coordinate { 1, 1 }; + LatLng coordinate{1, 1}; double zoom = 12.0; double pitchInDegrees = 45.0; double bearingInDegrees = 30.0; test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - test.map.jumpTo(CameraOptions().withCenter(coordinate).withZoom(zoom).withPitch(pitchInDegrees).withBearing(bearingInDegrees)); + test.map.jumpTo( + CameraOptions().withCenter(coordinate).withZoom(zoom).withPitch(pitchInDegrees).withBearing(bearingInDegrees)); test.runLoop.runOnce(); test.frontend.render(test.map); @@ -114,7 +118,7 @@ TEST(Map, RendererState) { EXPECT_NEAR(*options.bearing, bearingInDegrees, 1e-7); { - const LatLng& latLng = test.frontend.latLngForPixel(ScreenCoordinate { 0, 0 }); + const LatLng& latLng = test.frontend.latLngForPixel(ScreenCoordinate{0, 0}); const ScreenCoordinate& point = test.frontend.pixelForLatLng(coordinate); EXPECT_NEAR(coordinate.latitude(), latLng.latitude(), 1e-1); EXPECT_NEAR(coordinate.longitude(), latLng.longitude(), 1e-1); @@ -124,7 +128,8 @@ TEST(Map, RendererState) { } // RendererState::hasImage - test.map.getStyle().addImage(std::make_unique("default_marker", decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f)); + test.map.getStyle().addImage(std::make_unique( + "default_marker", decodeImage(util::read_file("test/fixtures/sprites/default_marker.png")), 1.0f)); // The frontend has not yet been notified about the newly-added image. EXPECT_FALSE(test.frontend.hasImage("default_marker")); @@ -136,7 +141,7 @@ TEST(Map, RendererState) { // RendererState::hasSource auto source = std::make_unique("GeoJSONSource"); - source->setGeoJSON( Geometry{ Point{ 0, 0 } } ); + source->setGeoJSON(Geometry{Point{0, 0}}); test.map.getStyle().addSource(std::move(source)); // The frontend has not yet been notified about the newly-added source. @@ -162,10 +167,10 @@ TEST(Map, RendererState) { TEST(Map, LatLngBehavior) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 1.0, 1.0 }).withZoom(0.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{1.0, 1.0}).withZoom(0.0)); auto latLng1 = *test.map.getCameraOptions().center; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 1.0, 1.0 })); + test.map.jumpTo(CameraOptions().withCenter(LatLng{1.0, 1.0})); auto latLng2 = *test.map.getCameraOptions().center; ASSERT_DOUBLE_EQ(latLng1.latitude(), latLng2.latitude()); @@ -175,9 +180,9 @@ TEST(Map, LatLngBehavior) { TEST(Map, LatLngBoundsToCamera) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {}); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); @@ -187,9 +192,9 @@ TEST(Map, LatLngBoundsToCamera) { TEST(Map, LatLngBoundsToCameraWithExcessivePadding) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {500, 0, 1200, 0}); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); @@ -199,9 +204,9 @@ TEST(Map, LatLngBoundsToCameraWithExcessivePadding) { TEST(Map, LatLngBoundsToCameraWithBearing) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {}, 35.0); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); @@ -211,11 +216,11 @@ TEST(Map, LatLngBoundsToCameraWithBearing) { TEST(Map, LatLngBoundsToCameraWithBearingPitchAndPadding) { MapTest<> test; - - test.map.jumpTo(CameraOptions().withCenter(LatLng { 40.712730, -74.005953 }).withZoom(16.0)); - - LatLngBounds bounds = LatLngBounds::hull({15.68169,73.499857}, {53.560711, 134.77281}); - + + test.map.jumpTo(CameraOptions().withCenter(LatLng{40.712730, -74.005953}).withZoom(16.0)); + + LatLngBounds bounds = LatLngBounds::hull({15.68169, 73.499857}, {53.560711, 134.77281}); + CameraOptions virtualCamera = test.map.cameraForLatLngBounds(bounds, {}, 35, 20); ASSERT_TRUE(bounds.contains(*virtualCamera.center)); EXPECT_NEAR(*virtualCamera.zoom, 13.66272, 1e-5); @@ -239,7 +244,7 @@ TEST(Map, LatLngBoundsToCameraWithBearingPitchAndPadding) { TEST(Map, LatLngsToCamera) { MapTest<> test; - std::vector latLngs{{ 40.712730, 74.005953 }, {15.68169,73.499857}, {30.82678, 83.4082}}; + std::vector latLngs{{40.712730, 74.005953}, {15.68169, 73.499857}, {30.82678, 83.4082}}; CameraOptions virtualCamera = test.map.cameraForLatLngs(latLngs, {}, 23.0); EXPECT_NEAR(virtualCamera.bearing.value_or(0), 23.0, 1e-5); @@ -250,9 +255,9 @@ TEST(Map, LatLngsToCamera) { TEST(Map, LatLngsToCameraWithBearingAndPitch) { MapTest<> test; - - std::vector latLngs{{ 40.712730, 74.005953 }, {15.68169,73.499857}, {30.82678, 83.4082}}; - + + std::vector latLngs{{40.712730, 74.005953}, {15.68169, 73.499857}, {30.82678, 83.4082}}; + CameraOptions virtualCamera = test.map.cameraForLatLngs(latLngs, {}, 23, 20); EXPECT_NEAR(virtualCamera.bearing.value_or(0), 23.0, 1e-5); EXPECT_NEAR(virtualCamera.zoom.value_or(0), 3.04378, 1e-5); @@ -290,12 +295,11 @@ TEST(Map, LatLngsToCameraWithBearingAndPitchMinMax) { TEST(Map, CameraToLatLngBounds) { MapTest<> test; - test.map.jumpTo(CameraOptions().withCenter(LatLng { 45, 90 }).withZoom(16.0)); + test.map.jumpTo(CameraOptions().withCenter(LatLng{45, 90}).withZoom(16.0)); const Size size = test.map.getMapOptions().size(); - LatLngBounds bounds = LatLngBounds::hull( - test.map.latLngForPixel({}), - test.map.latLngForPixel({ double(size.width), double(size.height) })); + LatLngBounds bounds = LatLngBounds::hull(test.map.latLngForPixel({}), + test.map.latLngForPixel({double(size.width), double(size.height)})); CameraOptions camera = test.map.getCameraOptions(); @@ -353,17 +357,17 @@ TEST(Map, CameraToLatLngBoundsUnwrappedCrossDateLine) { TEST(Map, Offline) { MapTest test{":memory:", "."}; - auto expiredItem = [] (const std::string& path) { + auto expiredItem = [](const std::string& path) { Response response; response.data = std::make_shared(util::read_file("test/fixtures/map/offline/"s + path)); - response.expires = Timestamp{ Seconds(0) }; + response.expires = Timestamp{Seconds(0)}; return response; }; NetworkStatus::Set(NetworkStatus::Status::Offline); const std::string prefix = "http://127.0.0.1:3000/"; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource(FileSourceType::Database, + ResourceOptions{}); dbfs->forward(Resource::style(prefix + "style.json"), expiredItem("style.json"), [] {}); dbfs->forward(Resource::source(prefix + "streets.json"), expiredItem("streets.json"), [] {}); dbfs->forward(Resource::spriteJSON(prefix + "sprite", 1.0), expiredItem("sprite.json"), [] {}); @@ -390,7 +394,7 @@ TEST(Map, SetStyleDefaultCamera) { EXPECT_DOUBLE_EQ(*camera.zoom, 0.0); EXPECT_DOUBLE_EQ(*camera.pitch, 0.0); EXPECT_DOUBLE_EQ(*camera.bearing, 0.0); - EXPECT_EQ(*camera.center, LatLng {}); + EXPECT_EQ(*camera.center, LatLng{}); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty-zoomed.json")); camera = test.map.getCameraOptions(); @@ -439,13 +443,13 @@ TEST(Map, DefaultBoundOptions) { } TEST(Map, MapOptions) { - float pixelRatio { 2 }; - MapTest<> test { pixelRatio, MapMode::Continuous }; + float pixelRatio{2}; + MapTest<> test{pixelRatio, MapMode::Continuous}; test.map.setNorthOrientation(NorthOrientation::Rightwards); test.map.setConstrainMode(ConstrainMode::None); test.map.setViewportMode(ViewportMode::FlippedY); - Size size = { 512, 512 }; + Size size = {512, 512}; test.map.setSize(size); auto options = test.map.getMapOptions(); @@ -488,8 +492,9 @@ TEST(Map, SetStyleInvalidJSON) { auto observer = Log::removeObserver(); auto flo = static_cast(observer.get()); - EXPECT_EQ(1u, flo->count({ EventSeverity::Error, Event::ParseStyle, -1, - "Failed to parse style: Invalid value. at offset 0" })); + EXPECT_EQ( + 1u, + flo->count({EventSeverity::Error, Event::ParseStyle, -1, "Failed to parse style: Invalid value. at offset 0"})); auto unchecked = flo->unchecked(); EXPECT_TRUE(unchecked.empty()) << unchecked; } @@ -497,11 +502,9 @@ TEST(Map, SetStyleInvalidJSON) { TEST(Map, SetStyleInvalidURL) { MapTest<> test; - test.fileSource->styleResponse = [] (const Resource&) { + test.fileSource->styleResponse = [](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; @@ -554,19 +557,20 @@ TEST(Map, StyleExpired) { test.fileSource->respond(Resource::Style, response); EXPECT_EQ(1u, test.fileSource->requests.size()); - // Mutate layer. From now on, sending a response to the style won't overwrite it anymore, but - // we should continue to wait for a fresh response. + // Mutate layer. From now on, sending a response to the style won't + // overwrite it anymore, but we should continue to wait for a fresh + // response. test.map.getStyle().addLayer(std::make_unique("bg")); EXPECT_EQ(1u, test.fileSource->requests.size()); - // Send another expired response, and confirm that we didn't overwrite the style, but continue - // to wait for a fresh response. + // Send another expired response, and confirm that we didn't overwrite the + // style, but continue to wait for a fresh response. test.fileSource->respond(Resource::Style, response); EXPECT_EQ(1u, test.fileSource->requests.size()); EXPECT_NE(nullptr, test.map.getStyle().getLayer("bg")); - // Send a fresh response, and confirm that we didn't overwrite the style, but continue to wait - // for a fresh response. + // Send a fresh response, and confirm that we didn't overwrite the style, + // but continue to wait for a fresh response. response.expires = util::now() + 1h; test.fileSource->respond(Resource::Style, response); EXPECT_EQ(1u, test.fileSource->requests.size()); @@ -590,7 +594,7 @@ TEST(Map, StyleExpiredWithAnnotations) { test.fileSource->respond(Resource::Style, response); EXPECT_EQ(1u, test.fileSource->requests.size()); - test.map.addAnnotation(LineAnnotation { LineString {{ { 0, 0 }, { 10, 10 } }} }); + test.map.addAnnotation(LineAnnotation{LineString{{{0, 0}, {10, 10}}}}); EXPECT_EQ(1u, test.fileSource->requests.size()); test.fileSource->respond(Resource::Style, response); @@ -649,7 +653,7 @@ TEST(Map, MapLoadingSignal) { } TEST(Map, MapLoadedSignal) { - MapTest<> test { 1, MapMode::Continuous }; + MapTest<> test{1, MapMode::Continuous}; test.observer.didFinishLoadingMapCallback = [&]() { test.runLoop.stop(); @@ -703,9 +707,7 @@ TEST(Map, TEST_REQUIRES_SERVER(StyleNotFound)) { }; test.observer.didFailLoadingMapCallback = [&]() { - timer.start(Milliseconds(1100), 0s, [&] { - test.runLoop.stop(); - }); + timer.start(Milliseconds(1100), 0s, [&] { test.runLoop.stop(); }); }; test.runLoop.run(); @@ -721,7 +723,7 @@ TEST(Map, AddLayer) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); auto layer = std::make_unique("background"); - layer->setBackgroundColor({ { 1, 0, 0, 1 } }); + layer->setBackgroundColor({{1, 0, 0, 1}}); test.map.getStyle().addLayer(std::move(layer)); test::checkImage("test/fixtures/map/add_layer", test.frontend.render(test.map).image); @@ -733,7 +735,7 @@ TEST(Map, RemoveLayer) { test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); auto layer = std::make_unique("background"); - layer->setBackgroundColor({{ 1, 0, 0, 1 }}); + layer->setBackgroundColor({{1, 0, 0, 1}}); test.map.getStyle().addLayer(std::move(layer)); test.map.getStyle().removeLayer("background"); @@ -744,7 +746,7 @@ TEST(Map, DisabledSources) { MapTest<> test; // Always load the same image tile for raster layers. - test.fileSource->response = [] (const Resource& res) -> std::optional { + test.fileSource->response = [](const Resource& res) -> std::optional { if (res.url == "asset://tile.png") { Response response; response.data = std::make_shared( @@ -756,11 +758,13 @@ TEST(Map, DisabledSources) { test.map.jumpTo(CameraOptions().withZoom(1.0)); - // This stylesheet has two raster layers, one that starts at zoom 1, the other at zoom 0. - // We first render a map at zoom level 1, which should show both layers (both are "visible" due - // to an opacity of 0.5). Then, we are zooming back out to a zoom level of 0.5 and rerender. - // The "raster1" layer should not be visible anymore since it has minzoom 1, while "raster2" - // should still be there. Both layers have a distinct color through "raster-hue-rotate". + // This stylesheet has two raster layers, one that starts at zoom 1, the + // other at zoom 0. We first render a map at zoom level 1, which should show + // both layers (both are "visible" due to an opacity of 0.5). Then, we are + // zooming back out to a zoom level of 0.5 and rerender. The "raster1" layer + // should not be visible anymore since it has minzoom 1, while "raster2" + // should still be there. Both layers have a distinct color through + // "raster-hue-rotate". test.map.getStyle().loadJSON(R"STYLE( { "version": 8, @@ -829,14 +833,15 @@ TEST(Map, DontLoadUnneededTiles) { std::unordered_map referenceTiles = { // Since the layer's minzoom is 0.3, we shouldn't load tiles before z0.3 - { 0.3, { "a/0/0/0" } }, - { 1.0, { "a/1/1/0", "a/1/0/1", "a/1/0/0", "a/1/1/1" } }, + {0.3, {"a/0/0/0"}}, + {1.0, {"a/1/1/0", "a/1/0/1", "a/1/0/0", "a/1/1/1"}}, // Since the layer's maxzoom is 1.6, we should never load z2 or z3 tiles. }; - // Loop through zoom levels from 0 to 3 and check that the correct tiles are loaded at every - // step. The source is marked with maxzoom 1.0, which means that it won't be visible anymore - // after z1.0, so we should under no circumstances attempt to load z2 tiles. + // Loop through zoom levels from 0 to 3 and check that the correct tiles are + // loaded at every step. The source is marked with maxzoom 1.0, which means + // that it won't be visible anymore after z1.0, so we should under no + // circumstances attempt to load z2 tiles. for (unsigned zoom = 0; zoom <= 30; zoom++) { // times 10 // Note: using z += 0.1 in the loop doesn't produce accurate floating point numbers. const double z = double(zoom) / 10; @@ -863,16 +868,16 @@ TEST(Map, TEST_DISABLED_ON_CI(ContinuousRendering)) { HeadlessFrontend frontend(1); StubMapObserver observer; - observer.didFinishRenderingFrameCallback = [&] (MapObserver::RenderFrameStatus) { - // Start a timer that ends the test one second from now. If we are continuing to render - // indefinitely, the timer will be constantly restarted and never trigger. Instead, the - // emergency shutoff above will trigger, failing the test. - timer.start(1s, 0s, [&] { - runLoop.stop(); - }); + observer.didFinishRenderingFrameCallback = [&](MapObserver::RenderFrameStatus) { + // Start a timer that ends the test one second from now. If we are + // continuing to render indefinitely, the timer will be constantly + // restarted and never trigger. Instead, the emergency shutoff above + // will trigger, failing the test. + timer.start(1s, 0s, [&] { runLoop.stop(); }); }; - Map map(frontend, observer, + Map map(frontend, + observer, MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize()), ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets")); map.getStyle().loadJSON(util::read_file("test/fixtures/api/water.json")); @@ -889,8 +894,8 @@ TEST(Map, NoContentTiles) { Response response; response.noContent = true; response.expires = util::now() + 1h; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource(FileSourceType::Database, + ResourceOptions{}); dbfs->forward( Resource::tile("http://example.com/{z}-{x}-{y}.vector.pbf", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), response, [&] { test.map.getStyle().loadJSON(R"STYLE({ @@ -921,7 +926,7 @@ TEST(Map, NoContentTiles) { // https://github.com/mapbox/mapbox-gl-native/issues/12432 TEST(Map, Issue12432) { - MapTest<> test { 1, MapMode::Continuous }; + MapTest<> test{1, MapMode::Continuous}; test.fileSource->tileResponse = [&](const Resource&) { Response result; @@ -970,7 +975,7 @@ TEST(Map, Issue12432) { // https://github.com/mapbox/mapbox-gl-native/issues/15216 TEST(Map, Issue15216) { - MapTest<> test { 1.0f, MapMode::Continuous }; + MapTest<> test{1.0f, MapMode::Continuous}; test.map.getStyle().addSource(std::make_unique("ImageSource", std::array())); test.map.getStyle().addLayer(std::make_unique("RasterLayer", "ImageSource")); // Passes, if there is no assertion hit. @@ -978,9 +983,10 @@ TEST(Map, Issue15216) { } // https://github.com/mapbox/mapbox-gl-native/issues/15342 -// Tests the fix for constant repaint caused by `RenderSource::hasFadingTiles()` returning `true` all the time. +// Tests the fix for constant repaint caused by `RenderSource::hasFadingTiles()` +// returning `true` all the time. TEST(Map, Issue15342) { - MapTest<> test { 1, MapMode::Continuous }; + MapTest<> test{1, MapMode::Continuous}; test.fileSource->tileResponse = [&](const Resource&) { Response result; @@ -1016,7 +1022,7 @@ TEST(Map, Issue15342) { "layers": [] })STYLE"); test.map.jumpTo(CameraOptions().withZoom(20.0)); - test.observer.didFinishRenderingFrameCallback = [&] (MapObserver::RenderFrameStatus status) { + test.observer.didFinishRenderingFrameCallback = [&](MapObserver::RenderFrameStatus status) { if (!status.needsRepaint) { test.runLoop.stop(); } @@ -1204,7 +1210,8 @@ TEST(Map, PrefetchDeltaOverride) { // Custom source CustomGeometrySource::Options options; - options.cancelTileFunction = [](const CanonicalTileID&) {}; + options.cancelTileFunction = [](const CanonicalTileID&) { + }; options.fetchTileFunction = [&requestedTiles, &test](const CanonicalTileID& tileID) { ++requestedTiles; auto* customSrc = static_cast(test.map.getStyle().getSource("custom")); @@ -1217,7 +1224,9 @@ TEST(Map, PrefetchDeltaOverride) { test.map.getStyle().addSource(std::move(customSource)); test.map.jumpTo(CameraOptions().withZoom(double(16))); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); // 2 sources x 4 tiles EXPECT_EQ(8, requestedTiles); @@ -1260,7 +1269,8 @@ TEST(Map, PrefetchDeltaOverrideCustomSource) { auto makeCustomSource = [&requestedTiles, &test] { CustomGeometrySource::Options options; - options.cancelTileFunction = [](const CanonicalTileID&) {}; + options.cancelTileFunction = [](const CanonicalTileID&) { + }; options.fetchTileFunction = [&requestedTiles, &test](const CanonicalTileID& tileID) { ++requestedTiles; auto* source = static_cast(test.map.getStyle().getSource("custom")); @@ -1276,7 +1286,9 @@ TEST(Map, PrefetchDeltaOverrideCustomSource) { test.map.getStyle().addSource(std::move(customSource)); test.map.jumpTo(CameraOptions().withZoom(double(16))); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); EXPECT_EQ(4, requestedTiles); requestedTiles = 0; @@ -1293,8 +1305,8 @@ TEST(Map, PrefetchDeltaOverrideCustomSource) { test.map.getStyle().addSource(makeCustomSource()); test.runLoop.run(); - // Source was significantly mutated, therefore, tile pyramid would be cleared - // and current zoom level + parent tiles would be re-requested. + // Source was significantly mutated, therefore, tile pyramid would be + // cleared and current zoom level + parent tiles would be re-requested. EXPECT_EQ(8, requestedTiles); } @@ -1330,13 +1342,15 @@ TEST(Map, TEST_REQUIRES_SERVER(ExpiredSpriteSheet)) { NetworkStatus::Set(NetworkStatus::Status::Online); - test.observer.didBecomeIdleCallback = [&test] { test.runLoop.stop(); }; + test.observer.didBecomeIdleCallback = [&test] { + test.runLoop.stop(); + }; }; NetworkStatus::Set(NetworkStatus::Status::Offline); const std::string prefix = "http://127.0.0.1:3000/online/"; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource(FileSourceType::Database, + ResourceOptions{}); dbfs->forward(Resource::style(prefix + "style.json"), makeResponse("style.json"), [] {}); dbfs->forward(Resource::source(prefix + "streets.json"), makeResponse("streets.json"), [] {}); dbfs->forward(Resource::spriteJSON(prefix + "sprite", 1.0), makeResponse("sprite.json", true), [] {}); @@ -1398,7 +1412,9 @@ TEST(Map, SourceMinimumUpdateIntervalOverride) { }; test.map.jumpTo(CameraOptions().withZoom(double(16))); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); EXPECT_EQ(8, requestedTilesA); @@ -1473,7 +1489,7 @@ TEST(Map, DISABLED_PlacedSymbolData) { // Camera options will give exactly one tile (12/1171/1566) test.map.jumpTo(CameraOptions().withZoom(16).withCenter(LatLng{50.072317, 14.444827})); - + test.map.getStyle().loadURL("maptiler://maps/streets"); Size viewportSize = test.frontend.getSize(); test.frontend.getRenderer()->collectPlacedSymbolData(true); @@ -1558,7 +1574,9 @@ TEST(Map, VolatileSource) { test.map.getStyle().addSource(std::move(source)); test.map.jumpTo(CameraOptions().withZoom(16.0)); - test.observer.didFinishLoadingMapCallback = [&] { test.runLoop.stop(); }; + test.observer.didFinishLoadingMapCallback = [&] { + test.runLoop.stop(); + }; test.runLoop.run(); EXPECT_EQ(8, requestedTiles); } @@ -1573,10 +1591,10 @@ TEST(Map, ObserveShaderRegistration) { test.map.jumpTo(CameraOptions().withZoom(10)); test.map.getStyle().loadJSON(util::read_file("test/fixtures/api/empty.json")); - + test.frontend.render(test.map); EXPECT_EQ(observedRegistry, true); - + // Should not see it again observedRegistry = false; test.frontend.render(test.map); diff --git a/test/map/prefetch.test.cpp b/test/map/prefetch.test.cpp index 1d5b387f5d7..c9a0b84654c 100644 --- a/test/map/prefetch.test.cpp +++ b/test/map/prefetch.test.cpp @@ -30,17 +30,17 @@ TEST(Map, PrefetchTiles) { }); StubMapObserver observer; - observer.didFinishLoadingMapCallback = [&] () { + observer.didFinishLoadingMapCallback = [&]() { runLoop.stop(); }; - HeadlessFrontend frontend { { 512, 512 }, 1 }; - MapAdapter map(frontend, observer, fileSource, - MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize())); + HeadlessFrontend frontend{{512, 512}, 1}; + MapAdapter map( + frontend, observer, fileSource, MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize())); std::vector tiles; - fileSource->response = [&] (const Resource& res) -> std::optional { + fileSource->response = [&](const Resource& res) -> std::optional { static std::string tile = util::read_file("test/fixtures/map/prefetch/tile.png"); auto zoom = std::stoi(res.url); @@ -57,7 +57,7 @@ TEST(Map, PrefetchTiles) { // Force tile reloading. map.getStyle().loadJSON(util::read_file("test/fixtures/map/prefetch/empty.json")); map.getStyle().loadJSON(util::read_file("test/fixtures/map/prefetch/style.json")); - map.jumpTo(CameraOptions().withCenter(LatLng { 40.726989, -73.992857 }).withZoom(zoom)); // Manhattan + map.jumpTo(CameraOptions().withCenter(LatLng{40.726989, -73.992857}).withZoom(zoom)); // Manhattan runLoop.run(); ASSERT_EQ(tiles.size(), expected.size()); @@ -66,7 +66,7 @@ TEST(Map, PrefetchTiles) { // Check defaults, should be 4. ASSERT_EQ(map.getPrefetchZoomDelta(), 4); - checkTilesForZoom(12, { 13, 13, 13, 13, 13, 13, 13, 13, 13, 9 }); + checkTilesForZoom(12, {13, 13, 13, 13, 13, 13, 13, 13, 13, 9}); // Setting it to 0 disables prefetching. map.setPrefetchZoomDelta(0); @@ -75,16 +75,16 @@ TEST(Map, PrefetchTiles) { // tiles instead of the actual zoom level, that is // why the zoom levels for non-prefetched tiles are // not the same. - checkTilesForZoom(10, { 11, 11, 11, 11, 11, 11, 11, 11, 11 }); + checkTilesForZoom(10, {11, 11, 11, 11, 11, 11, 11, 11, 11}); map.setPrefetchZoomDelta(5); - checkTilesForZoom(12, { 13, 13, 13, 13, 13, 13, 13, 13, 13, 8 }); + checkTilesForZoom(12, {13, 13, 13, 13, 13, 13, 13, 13, 13, 8}); // Should clamp at `minzoom`. map.setPrefetchZoomDelta(20); - checkTilesForZoom(10, { 11, 11, 11, 11, 11, 11, 11, 11, 11, 0 }); + checkTilesForZoom(10, {11, 11, 11, 11, 11, 11, 11, 11, 11, 0}); // Disabled again. map.setPrefetchZoomDelta(0); - checkTilesForZoom(13, { 14, 14, 14, 14, 14, 14, 14, 14, 14 }); + checkTilesForZoom(13, {14, 14, 14, 14, 14, 14, 14, 14, 14}); } diff --git a/test/map/transform.test.cpp b/test/map/transform.test.cpp index 3d7931d4aed..4a0093a249a 100644 --- a/test/map/transform.test.cpp +++ b/test/map/transform.test.cpp @@ -40,16 +40,16 @@ TEST(Transform, InvalidZoom) { // Executing flyTo with an empty size causes frameZoom to be NaN. transform.flyTo(CameraOptions() - .withCenter(LatLng{ util::LATITUDE_MAX, util::LONGITUDE_MAX }) + .withCenter(LatLng{util::LATITUDE_MAX, util::LONGITUDE_MAX}) .withZoom(transform.getState().getMaxZoom())); transform.updateTransitions(transform.getTransitionStart() + transform.getTransitionDuration()); ASSERT_DOUBLE_EQ(transform.getZoom(), transform.getState().getMaxZoom()); // Executing flyTo with maximum zoom level to the same zoom level causes // frameZoom to be bigger than maximum zoom. - transform.resize(Size { 100, 100 }); + transform.resize(Size{100, 100}); transform.flyTo(CameraOptions() - .withCenter(LatLng{ util::LATITUDE_MAX, util::LONGITUDE_MAX }) + .withCenter(LatLng{util::LATITUDE_MAX, util::LONGITUDE_MAX}) .withZoom(transform.getState().getMaxZoom())); transform.updateTransitions(transform.getTransitionStart() + transform.getTransitionDuration()); @@ -106,10 +106,10 @@ TEST(Transform, PerspectiveProjection) { LatLng loc; Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); // 0.9 rad ~ 51.56620156 deg - transform.jumpTo(CameraOptions().withCenter(LatLng { 38.0, -77.0 }).withZoom(10.0).withPitch(51.56620156)); + transform.jumpTo(CameraOptions().withCenter(LatLng{38.0, -77.0}).withZoom(10.0).withPitch(51.56620156)); // expected values are from maplibre-gl-js @@ -117,11 +117,11 @@ TEST(Transform, PerspectiveProjection) { ASSERT_DOUBLE_EQ(-77, loc.longitude()); ASSERT_DOUBLE_EQ(38, loc.latitude()); - loc = transform.getState().screenCoordinateToLatLng({ 0, 1000 }); + loc = transform.getState().screenCoordinateToLatLng({0, 1000}); ASSERT_NEAR(-77.59198961199148, loc.longitude(), 1e-6); ASSERT_NEAR(38.74661326302018, loc.latitude(), 1e-6); - loc = transform.getState().screenCoordinateToLatLng({ 1000, 0 }); + loc = transform.getState().screenCoordinateToLatLng({1000, 0}); ASSERT_NEAR(-76.75823239205641, loc.longitude(), 1e-6); ASSERT_NEAR(37.692872969426375, loc.latitude(), 1e-6); @@ -146,10 +146,10 @@ TEST(Transform, PerspectiveProjection) { TEST(Transform, UnwrappedLatLng) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); // 0.9 rad ~ 51.56620156 deg - transform.jumpTo(CameraOptions().withCenter(LatLng { 38.0, -77.0 }).withZoom(10.0).withPitch(51.56620156)); + transform.jumpTo(CameraOptions().withCenter(LatLng{38.0, -77.0}).withZoom(10.0).withPitch(51.56620156)); const TransformState& state = transform.getState(); @@ -157,17 +157,17 @@ TEST(Transform, UnwrappedLatLng) { ASSERT_DOUBLE_EQ(fromGetLatLng.latitude(), 38.0); ASSERT_DOUBLE_EQ(fromGetLatLng.longitude(), -77.0); - LatLng fromScreenCoordinate = state.screenCoordinateToLatLng({ 500, 500 }); + LatLng fromScreenCoordinate = state.screenCoordinateToLatLng({500, 500}); ASSERT_NEAR(fromScreenCoordinate.latitude(), 38.0, 1e-8); ASSERT_NEAR(fromScreenCoordinate.longitude(), -77.0, 1e-8); - LatLng wrappedRightwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({ 38, 283 })); + LatLng wrappedRightwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({38, 283})); ASSERT_NEAR(wrappedRightwards.latitude(), 38.0, 1e-8); ASSERT_NEAR(wrappedRightwards.longitude(), 283.0, 1e-8); wrappedRightwards.wrap(); ASSERT_NEAR(wrappedRightwards.longitude(), -77.0, 1e-8); - LatLng wrappedLeftwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({ 38, -437 })); + LatLng wrappedLeftwards = state.screenCoordinateToLatLng(state.latLngToScreenCoordinate({38, -437})); ASSERT_DOUBLE_EQ(wrappedLeftwards.latitude(), wrappedRightwards.latitude()); ASSERT_NEAR(wrappedLeftwards.longitude(), -437.0, 1e-8); wrappedLeftwards.wrap(); @@ -176,7 +176,7 @@ TEST(Transform, UnwrappedLatLng) { TEST(Transform, ConstrainHeightOnly) { Transform transform(MapObserver::nullObserver(), ConstrainMode::HeightOnly); - transform.resize({ 2, 2 }); + transform.resize({2, 2}); transform.jumpTo(CameraOptions().withCenter(LatLngBounds::world().southwest()).withZoom(util::MAX_ZOOM)); ASSERT_NEAR(-util::LATITUDE_MAX, transform.getLatLng().latitude(), 1e-7); @@ -189,7 +189,7 @@ TEST(Transform, ConstrainHeightOnly) { TEST(Transform, ConstrainWidthAndHeight) { Transform transform(MapObserver::nullObserver(), ConstrainMode::WidthAndHeight); - transform.resize({ 2, 2 }); + transform.resize({2, 2}); transform.jumpTo(CameraOptions().withCenter(LatLngBounds::world().southwest()).withZoom(util::MAX_ZOOM)); ASSERT_NEAR(-util::LATITUDE_MAX, transform.getLatLng().latitude(), 1e-7); @@ -202,10 +202,10 @@ TEST(Transform, ConstrainWidthAndHeight) { TEST(Transform, Anchor) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); - const LatLng latLng { 10, -100 }; - const ScreenCoordinate anchorPoint = { 150, 150 }; + const LatLng latLng{10, -100}; + const ScreenCoordinate anchorPoint = {150, 150}; transform.jumpTo(CameraOptions().withCenter(latLng).withZoom(10.0)); ASSERT_DOUBLE_EQ(latLng.latitude(), transform.getLatLng().latitude()); @@ -299,11 +299,11 @@ TEST(Transform, Anchor) { TEST(Transform, Padding) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); ASSERT_DOUBLE_EQ(0, transform.getLatLng().latitude()); ASSERT_DOUBLE_EQ(0, transform.getLatLng().longitude()); - CameraOptions nonPaddedCameraOptions = CameraOptions().withCenter(LatLng { 10, -100 }).withZoom(10.0); + CameraOptions nonPaddedCameraOptions = CameraOptions().withCenter(LatLng{10, -100}).withZoom(10.0); transform.jumpTo(nonPaddedCameraOptions); const LatLng trueCenter = transform.getLatLng(); @@ -349,7 +349,7 @@ TEST(Transform, Padding) { TEST(Transform, MoveBy) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(10.0)); @@ -362,8 +362,8 @@ TEST(Transform, MoveBy) { bool odd = x % 2; bool forward = x % 10; - LatLng coordinate = transform.screenCoordinateToLatLng({ odd ? 400. : 600., forward ? 400. : 600 }); - transform.moveBy({ odd ? 100. : -100., forward ? 100. : -100 }); + LatLng coordinate = transform.screenCoordinateToLatLng({odd ? 400. : 600., forward ? 400. : 600}); + transform.moveBy({odd ? 100. : -100., forward ? 100. : -100}); trueCenter = transform.getLatLng(); ASSERT_NEAR(coordinate.latitude(), trueCenter.latitude(), 1e-8); @@ -377,17 +377,17 @@ TEST(Transform, MoveBy) { TEST(Transform, Antimeridian) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(1.0)); // San Francisco - const LatLng coordinateSanFrancisco { 37.7833, -122.4167 }; + const LatLng coordinateSanFrancisco{37.7833, -122.4167}; ScreenCoordinate pixelSF = transform.latLngToScreenCoordinate(coordinateSanFrancisco); ASSERT_DOUBLE_EQ(151.79249437176432, pixelSF.x); ASSERT_DOUBLE_EQ(383.76720782527661, pixelSF.y); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -181.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -181.0})); ScreenCoordinate pixelSFLongest = transform.latLngToScreenCoordinate(coordinateSanFrancisco); ASSERT_DOUBLE_EQ(-357.36306616412816, pixelSFLongest.x); @@ -399,19 +399,19 @@ TEST(Transform, Antimeridian) { ASSERT_DOUBLE_EQ(666.63694385219173, pixelSFShortest.x); ASSERT_DOUBLE_EQ(pixelSF.y, pixelSFShortest.y); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 179.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 179.0})); pixelSFShortest = transform.latLngToScreenCoordinate(coordinateSanFrancisco); ASSERT_DOUBLE_EQ(pixelSFLongest.x, pixelSFShortest.x); ASSERT_DOUBLE_EQ(pixelSFLongest.y, pixelSFShortest.y); // Waikiri - const LatLng coordinateWaikiri{ -16.9310, 179.9787 }; + const LatLng coordinateWaikiri{-16.9310, 179.9787}; transform.jumpTo(CameraOptions().withCenter(coordinateWaikiri).withZoom(10.0)); ScreenCoordinate pixelWaikiri = transform.latLngToScreenCoordinate(coordinateWaikiri); ASSERT_DOUBLE_EQ(500, pixelWaikiri.x); ASSERT_DOUBLE_EQ(500, pixelWaikiri.y); - transform.jumpTo(CameraOptions().withCenter(LatLng { coordinateWaikiri.latitude(), 180.0213 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{coordinateWaikiri.latitude(), 180.0213})); ScreenCoordinate pixelWaikiriLongest = transform.latLngToScreenCoordinate(coordinateWaikiri); ASSERT_DOUBLE_EQ(524725.96438108233, pixelWaikiriLongest.x); ASSERT_DOUBLE_EQ(pixelWaikiri.y, pixelWaikiriLongest.y); @@ -423,31 +423,31 @@ TEST(Transform, Antimeridian) { ASSERT_DOUBLE_EQ(pixelWaikiri.y, pixelWaikiriShortest.y); LatLng coordinateFromPixel = transform.screenCoordinateToLatLng(pixelWaikiriLongest); - ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); + ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); ASSERT_NEAR(coordinateWaikiri.longitude(), coordinateFromPixel.longitude(), 1e-4); - transform.jumpTo(CameraOptions().withCenter(LatLng { coordinateWaikiri.latitude(), 180.0213 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{coordinateWaikiri.latitude(), 180.0213})); pixelWaikiriShortest = transform.latLngToScreenCoordinate(coordinateWaikiri); ASSERT_DOUBLE_EQ(pixelWaikiriLongest.x, pixelWaikiriShortest.x); ASSERT_DOUBLE_EQ(pixelWaikiriLongest.y, pixelWaikiriShortest.y); coordinateFromPixel = transform.screenCoordinateToLatLng(pixelWaikiriShortest); - ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); + ASSERT_NEAR(coordinateWaikiri.latitude(), coordinateFromPixel.latitude(), 1e-4); ASSERT_NEAR(coordinateWaikiri.longitude(), coordinateFromPixel.longitude(), 1e-4); } TEST(Transform, Camera) { Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); - const LatLng latLng1 { 45, 135 }; + const LatLng latLng1{45, 135}; CameraOptions cameraOptions1 = CameraOptions().withCenter(latLng1).withZoom(20.0); transform.jumpTo(cameraOptions1); ASSERT_DOUBLE_EQ(latLng1.latitude(), transform.getLatLng().latitude()); ASSERT_DOUBLE_EQ(latLng1.longitude(), transform.getLatLng().longitude()); ASSERT_DOUBLE_EQ(20, transform.getZoom()); - const LatLng latLng2 { -45, -135 }; + const LatLng latLng2{-45, -135}; CameraOptions cameraOptions2 = CameraOptions().withCenter(latLng2).withZoom(10.0); transform.jumpTo(cameraOptions2); ASSERT_DOUBLE_EQ(latLng2.latitude(), transform.getLatLng().latitude()); @@ -498,8 +498,8 @@ TEST(Transform, Camera) { // Anchor and center points are mutually exclusive. CameraOptions camera; - camera.center = LatLng { 0, 0 }; - camera.anchor = ScreenCoordinate { 0, 0 }; // top-left + camera.center = LatLng{0, 0}; + camera.anchor = ScreenCoordinate{0, 0}; // top-left camera.zoom = transform.getState().getMaxZoom(); transform.easeTo(camera, AnimationOptions(Seconds(1))); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); @@ -521,8 +521,7 @@ TEST(Transform, ProjectionMode) { EXPECT_EQ(*options.ySkew, 0.0); } -TEST(Transform, IsPanning) -{ +TEST(Transform, IsPanning) { Transform transform; AnimationOptions easeOptions(Seconds(1)); @@ -530,7 +529,7 @@ TEST(Transform, IsPanning) ASSERT_TRUE(transform.getState().isPanning()); }; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.easeTo(CameraOptions().withCenter(LatLng(0, 360.0)), easeOptions); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(500)); @@ -540,13 +539,9 @@ TEST(Transform, IsPanning) TEST(Transform, DefaultTransform) { struct TransformObserver : public mbgl::MapObserver { - void onCameraWillChange(MapObserver::CameraChangeMode) final { - cameraWillChangeCallback(); - }; + void onCameraWillChange(MapObserver::CameraChangeMode) final { cameraWillChangeCallback(); }; - void onCameraDidChange(MapObserver::CameraChangeMode) final { - cameraDidChangeCallback(); - }; + void onCameraDidChange(MapObserver::CameraChangeMode) final { cameraDidChangeCallback(); }; std::function cameraWillChangeCallback; std::function cameraDidChangeCallback; @@ -556,8 +551,12 @@ TEST(Transform, DefaultTransform) { uint32_t cameraDidChangeCount = 0; TransformObserver observer; - observer.cameraWillChangeCallback = [&cameraWillChangeCount]() { cameraWillChangeCount++; }; - observer.cameraDidChangeCallback = [&cameraDidChangeCount]() { cameraDidChangeCount++; }; + observer.cameraWillChangeCallback = [&cameraWillChangeCount]() { + cameraWillChangeCount++; + }; + observer.cameraDidChangeCallback = [&cameraDidChangeCount]() { + cameraDidChangeCount++; + }; Transform transform(observer); const TransformState& state = transform.getState(); @@ -569,7 +568,7 @@ TEST(Transform, DefaultTransform) { const uint32_t max = 65535; // Cannot assign invalid sizes. - std::vector invalidSizes = { {}, { min, max }, { max, min } }; + std::vector invalidSizes = {{}, {min, max}, {max, min}}; for (const Size& size : invalidSizes) { try { transform.resize(size); @@ -579,7 +578,7 @@ TEST(Transform, DefaultTransform) { } } - Size validSize { max, max }; + Size validSize{max, max}; ASSERT_FALSE(validSize.isEmpty()); try { @@ -601,7 +600,7 @@ TEST(Transform, DefaultTransform) { ASSERT_TRUE(false) << "Should not throw"; } - center = { max / 2., max / 2. }; + center = {max / 2., max / 2.}; latLng = state.screenCoordinateToLatLng(center); ASSERT_NEAR(latLng.latitude(), nullIsland.latitude(), 1e-8); ASSERT_NEAR(latLng.longitude(), nullIsland.longitude(), 1e-8); @@ -612,11 +611,11 @@ TEST(Transform, DefaultTransform) { } TEST(Transform, LatLngBounds) { - const LatLng nullIsland {}; - const LatLng sanFrancisco { 37.7749, -122.4194 }; + const LatLng nullIsland{}; + const LatLng sanFrancisco{37.7749, -122.4194}; Transform transform; - transform.resize({ 1000, 1000 }); + transform.resize({1000, 1000}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(transform.getState().getMaxZoom())); @@ -646,17 +645,17 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃▓▓▓│▓▓▓┃ │ │ // └───┴───┸───┴───┸───┴───┘ - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, -180.0 }, { 0.0, 180.0 })); + transform.setLatLngBounds(LatLngBounds::hull({-90.0, -180.0}, {0.0, 180.0})); transform.jumpTo(CameraOptions().withCenter(sanFrancisco)); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), sanFrancisco.longitude()); // Try crossing the antimeridian from the left. - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -200.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -200.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -180.0); // Try crossing the antimeridian from the right. - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 200.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 200.0})); ASSERT_DOUBLE_EQ(transform.getLatLng(LatLng::Unwrapped).longitude(), 180.0); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -180.0); @@ -666,7 +665,7 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃ │▓▓▓┃ │ │ // └───┴───┸───┴───┸───┴───┘ - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, 0.0 }, { 90.0, 180.0 })); + transform.setLatLngBounds(LatLngBounds::hull({-90.0, 0.0}, {90.0, 180.0})); transform.jumpTo(CameraOptions().withCenter(sanFrancisco)); ASSERT_NEAR(transform.getLatLng().latitude(), sanFrancisco.latitude(), 1e-8); ASSERT_EQ(transform.getLatLng().longitude(), 0.0); @@ -677,7 +676,7 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃ │▓▓▓┃ │ │ // └───┴───┸───┴───┸───┴───┘ - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, 0.0 }, { 0.0, 180.0 })); + transform.setLatLngBounds(LatLngBounds::hull({-90.0, 0.0}, {0.0, 180.0})); transform.jumpTo(CameraOptions().withCenter(sanFrancisco)); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), 0.0); @@ -688,34 +687,34 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ┃ │ ┃ │ │ // └───┴───┸───┴───┸───┴───┘ - LatLng inside { 45.0, 150.0 }; - transform.setLatLngBounds(LatLngBounds::hull({ 0.0, 120.0 }, { 90.0, 240.0 })); + LatLng inside{45.0, 150.0}; + transform.setLatLngBounds(LatLngBounds::hull({0.0, 120.0}, {90.0, 240.0})); transform.jumpTo(CameraOptions().withCenter(inside)); ASSERT_EQ(transform.getLatLng().latitude(), inside.latitude()); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 140.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 140.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 140.0); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, 160.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, 160.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 160.0); // Constrain latitude only. - transform.jumpTo(CameraOptions().withCenter(LatLng { -45.0, inside.longitude() })); + transform.jumpTo(CameraOptions().withCenter(LatLng{-45.0, inside.longitude()})); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); // Crossing the antimeridian, within bounds. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 181.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 181.0})); ASSERT_EQ(transform.getLatLng().longitude(), -179.0); // Crossing the antimeridian, outside bounds. transform.jumpTo(CameraOptions().withCenter(inside)); - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 250.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 250.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); // Constrain to the left edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 119.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 119.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); // Simulate swipe to the left. @@ -726,7 +725,7 @@ TEST(Transform, LatLngBounds) { easeOptions.transitionFinishFn = [&]() { ASSERT_NEAR(transform.getLatLng().longitude(), 120.0, 1e-4); }; - transform.moveBy(ScreenCoordinate { -500, -500 }, easeOptions); + transform.moveBy(ScreenCoordinate{-500, -500}, easeOptions); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(0)); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); @@ -735,7 +734,7 @@ TEST(Transform, LatLngBounds) { transform.updateTransitions(transform.getTransitionStart() + transform.getTransitionDuration()); // Constrain to the right edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), 241.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), 241.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); // Simulate swipe to the right. @@ -745,7 +744,7 @@ TEST(Transform, LatLngBounds) { easeOptions.transitionFinishFn = [&]() { ASSERT_NEAR(transform.getLatLng().longitude(), -120.0, 1e-4); }; - transform.moveBy(ScreenCoordinate { 500, 500 }, easeOptions); + transform.moveBy(ScreenCoordinate{500, 500}, easeOptions); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(0)); transform.updateTransitions(transform.getTransitionStart() + Milliseconds(250)); @@ -759,45 +758,45 @@ TEST(Transform, LatLngBounds) { // ├───┼───╂───┼───╂───┼───┤ // │ │ ▓┃▓ │ ┃ │ │ // └───┴───┸───┴───┸───┴───┘ - inside = LatLng{ -45.0, -150.0 }; - transform.setLatLngBounds(LatLngBounds::hull({ -90.0, -240.0 }, { 0.0, -120.0 })); + inside = LatLng{-45.0, -150.0}; + transform.setLatLngBounds(LatLngBounds::hull({-90.0, -240.0}, {0.0, -120.0})); transform.jumpTo(CameraOptions().withCenter(inside)); ASSERT_DOUBLE_EQ(transform.getLatLng().latitude(), inside.latitude()); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -140.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -140.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -140.0); - transform.jumpTo(CameraOptions().withCenter(LatLng { 0.0, -160.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{0.0, -160.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -160.0); // Constrain latitude only. - transform.jumpTo(CameraOptions().withCenter(LatLng { 45.0, inside.longitude() })); + transform.jumpTo(CameraOptions().withCenter(LatLng{45.0, inside.longitude()})); ASSERT_EQ(transform.getLatLng().latitude(), 0.0); ASSERT_EQ(transform.getLatLng().longitude(), inside.longitude()); // Crossing the antimeridian, within bounds. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -181.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -181.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().latitude(), inside.latitude()); ASSERT_EQ(transform.getLatLng().longitude(), 179.0); // Crossing the antimeridian, outside bounds. transform.jumpTo(CameraOptions().withCenter(inside)); - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -250.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -250.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); // Constrain to the left edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -119.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -119.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); - transform.moveBy(ScreenCoordinate { -500, 0 }); + transform.moveBy(ScreenCoordinate{-500, 0}); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), -120.0); // Constrain to the right edge. - transform.jumpTo(CameraOptions().withCenter(LatLng { inside.latitude(), -241.0 })); + transform.jumpTo(CameraOptions().withCenter(LatLng{inside.latitude(), -241.0})); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); - transform.moveBy(ScreenCoordinate { 500, 0 }); + transform.moveBy(ScreenCoordinate{500, 0}); ASSERT_DOUBLE_EQ(transform.getLatLng().longitude(), 120.0); } @@ -1094,7 +1093,8 @@ TEST(Transform, FreeCameraOptionsStateSynchronization) { Vec3NearEquals1E5(vec3{{0.569273, 0.289453, 0.292969}})); transform.jumpTo(CameraOptions().withPitch(20.0).withBearing(77.0).withCenter(LatLng{-20.0, 20.0})); - EXPECT_THAT(transform.getFreeCameraOptions().position.value(), Vec3NearEquals1E5(vec3{{0.457922, 0.57926, 0.275301}})); + EXPECT_THAT(transform.getFreeCameraOptions().position.value(), + Vec3NearEquals1E5(vec3{{0.457922, 0.57926, 0.275301}})); // Invalid pitch transform.jumpTo(CameraOptions().withPitch(-10.0).withBearing(0.0)); diff --git a/test/programs/symbol_program.test.cpp b/test/programs/symbol_program.test.cpp index 28d734c21a8..ac33fc0b13c 100644 --- a/test/programs/symbol_program.test.cpp +++ b/test/programs/symbol_program.test.cpp @@ -13,55 +13,51 @@ TEST(SymbolProgram, SymbolSizeBinder) { EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 12.0f); - binder = SymbolSizeBinder::create(1.0f, style::PropertyExpression( - interpolate( - linear(), - zoom(), - 0., literal(8.), - 10., literal(18.))), 0.0f); + binder = SymbolSizeBinder::create( + 1.0f, + style::PropertyExpression(interpolate(linear(), zoom(), 0., literal(8.), 10., literal(18.))), + 0.0f); uniformValues = binder->uniformValues(1.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 9.5f); - - binder = SymbolSizeBinder::create(0.0f, style::PropertyExpression( - interpolate( - linear(), - zoom(), - 1., literal(8.), - 11., literal(18.))), 0.0f); + + binder = SymbolSizeBinder::create( + 0.0f, + style::PropertyExpression(interpolate(linear(), zoom(), 1., literal(8.), 11., literal(18.))), + 0.0f); uniformValues = binder->uniformValues(0.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 8.0f); - - binder = SymbolSizeBinder::create(12.0f, style::PropertyExpression( - interpolate( - linear(), - zoom(), - 1., literal(8.), - 11., literal(18.))), 0.0f); + + binder = SymbolSizeBinder::create( + 12.0f, + style::PropertyExpression(interpolate(linear(), zoom(), 1., literal(8.), 11., literal(18.))), + 0.0f); uniformValues = binder->uniformValues(12.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), 18.0f); - - binder = SymbolSizeBinder::create(0.0f, style::PropertyExpression( - interpolate( - linear(), - number(get("x")), - 1., literal(8.), - 11., literal(18.))), 0.0f); + + binder = SymbolSizeBinder::create( + 0.0f, + style::PropertyExpression(interpolate(linear(), number(get("x")), 1., literal(8.), 11., literal(18.))), + 0.0f); uniformValues = binder->uniformValues(12.5f); EXPECT_EQ(uniformValues.get(), true); EXPECT_EQ(uniformValues.get(), false); - binder = SymbolSizeBinder::create(5.0f, style::PropertyExpression( - interpolate( - linear(), - zoom(), - 1., interpolate(linear(), number(get("x")), 0., literal(8.), 100., literal(18.)), - 11., interpolate(linear(), number(get("x")), 0., literal(12.), 100., literal(24.9)))), 0.0f); + binder = SymbolSizeBinder::create( + 5.0f, + style::PropertyExpression( + interpolate(linear(), + zoom(), + 1., + interpolate(linear(), number(get("x")), 0., literal(8.), 100., literal(18.)), + 11., + interpolate(linear(), number(get("x")), 0., literal(12.), 100., literal(24.9)))), + 0.0f); uniformValues = binder->uniformValues(5.5f); EXPECT_EQ(uniformValues.get(), false); EXPECT_EQ(uniformValues.get(), false); diff --git a/test/renderer/backend_scope.test.cpp b/test/renderer/backend_scope.test.cpp index 3646afce489..18b13091363 100644 --- a/test/renderer/backend_scope.test.cpp +++ b/test/renderer/backend_scope.test.cpp @@ -9,8 +9,8 @@ using namespace mbgl; class StubRendererBackend : public gl::RendererBackend { public: - StubRendererBackend() : gl::RendererBackend(gfx::ContextMode::Unique) { - } + StubRendererBackend() + : gl::RendererBackend(gfx::ContextMode::Unique) {} void activate() override { if (activateFunction) activateFunction(); @@ -34,9 +34,9 @@ class StubRendererBackend : public gl::RendererBackend { return reinterpret_cast(*this); } - std::function activateFunction; - std::function deactivateFunction; - std::function updateAssumedStateFunction; + std::function activateFunction; + std::function deactivateFunction; + std::function updateAssumedStateFunction; }; // A scope should activate on construction @@ -47,12 +47,14 @@ TEST(BackendScope, SingleScope) { bool deactivated; StubRendererBackend backend; - backend.activateFunction = [&] { activated = true; }; - backend.deactivateFunction = [&] { deactivated = true; }; + backend.activateFunction = [&] { + activated = true; + }; + backend.deactivateFunction = [&] { + deactivated = true; + }; - { - gfx::BackendScope test { backend }; - } + { gfx::BackendScope test{backend}; } ASSERT_TRUE(activated); ASSERT_TRUE(deactivated); @@ -65,14 +67,18 @@ TEST(BackendScope, NestedScopes) { int deactivated = 0; StubRendererBackend backend; - backend.activateFunction = [&] { activated++; }; - backend.deactivateFunction = [&] { deactivated++; }; + backend.activateFunction = [&] { + activated++; + }; + backend.deactivateFunction = [&] { + deactivated++; + }; { - gfx::BackendScope outer { backend }; + gfx::BackendScope outer{backend}; ASSERT_EQ(1, activated); { - gfx::BackendScope inner { backend }; + gfx::BackendScope inner{backend}; ASSERT_EQ(1, activated); } ASSERT_EQ(0, deactivated); @@ -90,18 +96,26 @@ TEST(BackendScope, ChainedScopes) { bool activatedB = false; StubRendererBackend backendA; - backendA.activateFunction = [&] { activatedA = true; }; - backendA.deactivateFunction = [&] { activatedA = false; }; + backendA.activateFunction = [&] { + activatedA = true; + }; + backendA.deactivateFunction = [&] { + activatedA = false; + }; StubRendererBackend backendB; - backendB.activateFunction = [&] { activatedB = true; }; - backendB.deactivateFunction = [&] { activatedB = false; }; + backendB.activateFunction = [&] { + activatedB = true; + }; + backendB.deactivateFunction = [&] { + activatedB = false; + }; { - gfx::BackendScope scopeA { backendA }; + gfx::BackendScope scopeA{backendA}; ASSERT_TRUE(activatedA); { - gfx::BackendScope scopeB { backendB }; + gfx::BackendScope scopeB{backendB}; ASSERT_FALSE(activatedA); ASSERT_TRUE(activatedB); } diff --git a/test/renderer/image_manager.test.cpp b/test/renderer/image_manager.test.cpp index 13050605505..fb359bd7773 100644 --- a/test/renderer/image_manager.test.cpp +++ b/test/renderer/image_manager.test.cpp @@ -38,9 +38,9 @@ TEST(ImageManager, AddRemove) { FixtureLog log; ImageManager imageManager; - imageManager.addImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); - imageManager.addImage(makeMutable("two", PremultipliedImage({ 16, 16 }), 2.0f)); - imageManager.addImage(makeMutable("three", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.addImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); + imageManager.addImage(makeMutable("two", PremultipliedImage({16, 16}), 2.0f)); + imageManager.addImage(makeMutable("three", PremultipliedImage({16, 16}), 2.0f)); imageManager.removeImage("one"); imageManager.removeImage("two"); @@ -54,9 +54,9 @@ TEST(ImageManager, Update) { FixtureLog log; ImageManager imageManager; - imageManager.addImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.addImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); EXPECT_EQ(0, imageManager.updatedImageVersions.size()); - imageManager.updateImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.updateImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); EXPECT_EQ(1, imageManager.updatedImageVersions.size()); imageManager.removeImage("one"); EXPECT_EQ(0, imageManager.updatedImageVersions.size()); @@ -66,25 +66,29 @@ TEST(ImageManager, RemoveReleasesBinPackRect) { FixtureLog log; ImageManager imageManager; - imageManager.addImage(makeMutable("big", PremultipliedImage({ 32, 32 }), 1.0f)); + imageManager.addImage(makeMutable("big", PremultipliedImage({32, 32}), 1.0f)); EXPECT_TRUE(imageManager.getImage("big")); imageManager.removeImage("big"); - imageManager.addImage(makeMutable("big", PremultipliedImage({ 32, 32 }), 1.0f)); + imageManager.addImage(makeMutable("big", PremultipliedImage({32, 32}), 1.0f)); EXPECT_TRUE(imageManager.getImage("big")); EXPECT_TRUE(log.empty()); } class StubImageRequestor : public ImageRequestor { public: - StubImageRequestor(ImageManager& imageManager_) : ImageRequestor(imageManager_) {} + StubImageRequestor(ImageManager& imageManager_) + : ImageRequestor(imageManager_) {} - void onImagesAvailable(ImageMap icons, ImageMap patterns, std::unordered_map versionMap, uint64_t imageCorrelationID_) final { + void onImagesAvailable(ImageMap icons, + ImageMap patterns, + std::unordered_map versionMap, + uint64_t imageCorrelationID_) final { if (imagesAvailable && imageCorrelationID == imageCorrelationID_) imagesAvailable(icons, patterns, versionMap); } - std::function)> imagesAvailable; + std::function)> imagesAvailable; uint64_t imageCorrelationID = 0; }; @@ -97,7 +101,7 @@ TEST(ImageManager, NotifiesRequestorWhenSpriteIsLoaded) { ImageManagerObserver observer; imageManager.setObserver(&observer); - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; @@ -122,31 +126,32 @@ TEST(ImageManager, NotifiesRequestorImmediatelyIfDependenciesAreSatisfied) { StubImageRequestor requestor(imageManager); bool notified = false; - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; uint64_t imageCorrelationID = 0; ImageDependencies dependencies; dependencies.emplace("one", ImageType::Icon); - imageManager.addImage(makeMutable("one", PremultipliedImage({ 16, 16 }), 2.0f)); + imageManager.addImage(makeMutable("one", PremultipliedImage({16, 16}), 2.0f)); imageManager.getImages(requestor, std::make_pair(dependencies, imageCorrelationID)); ASSERT_TRUE(notified); } - class StubImageManagerObserver : public ImageManagerObserver { - public: +public: int count = 0; - std::function imageMissing = [](const std::string&){}; + std::function imageMissing = [](const std::string&) { + }; void onStyleImageMissing(const std::string& id, const std::function& done) override { count++; imageMissing(id); done(); } - std::function&)> removeUnusedStyleImages = [](const std::vector&){}; + std::function&)> removeUnusedStyleImages = [](const std::vector&) { + }; void onRemoveUnusedStyleImages(const std::vector& unusedImageIDs) override { removeUnusedStyleImages(unusedImageIDs); } @@ -162,7 +167,7 @@ TEST(ImageManager, OnStyleImageMissingBeforeSpriteLoaded) { bool notified = false; - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; @@ -217,7 +222,7 @@ TEST(ImageManager, OnStyleImageMissingAfterSpriteLoaded) { bool notified = false; - requestor.imagesAvailable = [&] (ImageMap, ImageMap, std::unordered_map) { + requestor.imagesAvailable = [&](ImageMap, ImageMap, std::unordered_map) { notified = true; }; @@ -250,11 +255,11 @@ TEST(ImageManager, RemoveUnusedStyleImages) { imageManager.setObserver(&observer); imageManager.setLoaded(true); - observer.imageMissing = [&imageManager] (const std::string& id) { + observer.imageMissing = [&imageManager](const std::string& id) { if (id == "1024px") { - imageManager.addImage(makeMutable(id, PremultipliedImage({ 1024, 1024 }), 1.0f)); + imageManager.addImage(makeMutable(id, PremultipliedImage({1024, 1024}), 1.0f)); } else { - imageManager.addImage(makeMutable(id, PremultipliedImage({ 16, 16 }), 1.0f)); + imageManager.addImage(makeMutable(id, PremultipliedImage({16, 16}), 1.0f)); } }; @@ -266,7 +271,7 @@ TEST(ImageManager, RemoveUnusedStyleImages) { }; // Style sprite. - imageManager.addImage(makeMutable("sprite", PremultipliedImage({ 16, 16 }), 1.0f)); + imageManager.addImage(makeMutable("sprite", PremultipliedImage({16, 16}), 1.0f)); // Single requestor { @@ -322,11 +327,14 @@ TEST(ImageManager, RemoveUnusedStyleImages) { runLoop.runOnce(); ASSERT_TRUE(imageManager.getImage("missing") == nullptr); - // Multiple requestors, check that image resource is not destroyed if there is at least 1 requestor that uses it. + // Multiple requestors, check that image resource is not destroyed if there + // is at least 1 requestor that uses it. std::unique_ptr requestor = std::make_unique(imageManager); { std::unique_ptr requestor1 = std::make_unique(imageManager); - imageManager.getImages(*requestor, std::make_pair(ImageDependencies{{"missing", ImageType::Icon}, {"1024px", ImageType::Icon}}, 0ull)); + imageManager.getImages( + *requestor, + std::make_pair(ImageDependencies{{"missing", ImageType::Icon}, {"1024px", ImageType::Icon}}, 0ull)); imageManager.getImages(*requestor1, std::make_pair(ImageDependencies{{"missing", ImageType::Icon}}, 1ull)); runLoop.runOnce(); EXPECT_EQ(observer.count, 5); diff --git a/test/renderer/pattern_atlas.test.cpp b/test/renderer/pattern_atlas.test.cpp index 52c04b9e0d9..0c170175368 100644 --- a/test/renderer/pattern_atlas.test.cpp +++ b/test/renderer/pattern_atlas.test.cpp @@ -44,7 +44,7 @@ TEST(PatternAtlas, Basic) { TEST(PatternAtlas, Updates) { PatternAtlas patternAtlas; - PremultipliedImage imageA({ 16, 12 }); + PremultipliedImage imageA({16, 12}); imageA.fill(255); auto added = patternAtlas.addPattern(*makeMutable("one", std::move(imageA), 1.0f)); @@ -63,12 +63,12 @@ TEST(PatternAtlas, Updates) { EXPECT_EQ(1.0f, a.pixelRatio); test::checkImage("test/fixtures/image_manager/updates_before", patternAtlas.getAtlasImageForTests()); - auto imageB = makeMutable("one", PremultipliedImage({ 5, 5 }), 1.0f); + auto imageB = makeMutable("one", PremultipliedImage({5, 5}), 1.0f); EXPECT_FALSE(patternAtlas.addPattern(*imageB)); // Already added. patternAtlas.removePattern("one"); ASSERT_FALSE(patternAtlas.getPattern("one")); - EXPECT_TRUE(patternAtlas.addPattern(*imageB)); + EXPECT_TRUE(patternAtlas.addPattern(*imageB)); auto b = *patternAtlas.getPattern("one"); EXPECT_EQ(1, b.tl()[0]); diff --git a/test/renderer/shader_registry.test.cpp b/test/renderer/shader_registry.test.cpp index 68e449ca7d0..eef5aa37128 100644 --- a/test/renderer/shader_registry.test.cpp +++ b/test/renderer/shader_registry.test.cpp @@ -28,81 +28,68 @@ using namespace mbgl; namespace { class MapInstance { +public: + class ShaderAndStyleObserver : public MapObserver { public: - class ShaderAndStyleObserver : public MapObserver { - public: - public: - void onDidFinishLoadingStyle() override { - styleLoaded(); - } - - void onRegisterShaders(gfx::ShaderRegistry& registry) override { - registerShaders(registry); - }; - - std::function styleLoaded; - std::function registerShaders; - }; - - MapInstance(float pixelRatio, MapObserver& observer) : - frontend(pixelRatio), - adapter(frontend, observer, std::make_shared( - ResourceOptions() - .withCachePath(":memory:") - .withAssetPath("test/fixtures/api/assets"), - ClientOptions() - ), - MapOptions() - .withMapMode(MapMode::Static) - .withSize(frontend.getSize()) - .withPixelRatio(pixelRatio)) - {} - public: - HeadlessFrontend frontend; - MapAdapter adapter; + void onDidFinishLoadingStyle() override { styleLoaded(); } + + void onRegisterShaders(gfx::ShaderRegistry& registry) override { registerShaders(registry); }; + + std::function styleLoaded; + std::function registerShaders; + }; + + MapInstance(float pixelRatio, MapObserver& observer) + : frontend(pixelRatio), + adapter(frontend, + observer, + std::make_shared( + ResourceOptions().withCachePath(":memory:").withAssetPath("test/fixtures/api/assets"), + ClientOptions()), + MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()).withPixelRatio(pixelRatio)) {} + +public: + HeadlessFrontend frontend; + MapAdapter adapter; }; -template +template class StubProgramBase : public gfx::Shader { - public: - static constexpr auto Token = token_value; - virtual uint32_t draw() { return token; } +public: + static constexpr auto Token = token_value; + virtual uint32_t draw() { return token; } - protected: - uint32_t token{token_value}; +protected: + uint32_t token{token_value}; }; class StubProgram_1 final : public StubProgramBase<10> { - public: - static constexpr std::string_view Name{"StubProgram_1"}; - const std::string_view typeName() const noexcept override { - return Name; - } +public: + static constexpr std::string_view Name{"StubProgram_1"}; + const std::string_view typeName() const noexcept override { return Name; } - void setToken(uint32_t tok) { token = tok; } + void setToken(uint32_t tok) { token = tok; } }; class StubProgram_2 final : public StubProgramBase<20> { - public: - static constexpr std::string_view Name{"StubProgram_2"}; - const std::string_view typeName() const noexcept override { - return Name; - } +public: + static constexpr std::string_view Name{"StubProgram_2"}; + const std::string_view typeName() const noexcept override { return Name; } }; class StubShaderConsumer { - public: - template - uint32_t useShader(gfx::ShaderRegistry& registry) { - auto program = registry.get(); - return program ? program->draw() : 0; - } +public: + template + uint32_t useShader(gfx::ShaderRegistry& registry) { + auto program = registry.get(); + return program ? program->draw() : 0; + } }; } // namespace -// Ensure we can register a gfx::Shader-based type with a registry object +// Ensure we can register a gfx::Shader-based type with a registry object TEST(ShaderRegistry, RegisterShader) { gfx::ShaderRegistry registry; @@ -170,16 +157,13 @@ TEST(ShaderRegistry, MultiRegister) { gfx::ShaderRegistry registry; ASSERT_TRUE(registry.registerShader(std::make_shared())); - ASSERT_TRUE(registry.registerShader(std::make_shared(), - "SecondProgram")); - + ASSERT_TRUE(registry.registerShader(std::make_shared(), "SecondProgram")); + // Default option, register as the type name ASSERT_NE(registry.get(), nullptr); // Register with an explicit name ASSERT_NE(registry.get("SecondProgram"), nullptr); - ASSERT_NE( - registry.get(), - registry.get("SecondProgram")); + ASSERT_NE(registry.get(), registry.get("SecondProgram")); } // Test fetching @@ -187,9 +171,8 @@ TEST(ShaderRegistry, RegistryFetch) { gfx::ShaderRegistry registry; ASSERT_TRUE(registry.registerShader(std::make_shared())); - ASSERT_TRUE(registry.registerShader(std::make_shared(), - "SecondProgram")); - + ASSERT_TRUE(registry.registerShader(std::make_shared(), "SecondProgram")); + std::shared_ptr progA; std::shared_ptr progB; @@ -205,21 +188,19 @@ TEST(ShaderRegistry, NamedReplace) { gfx::ShaderRegistry registry; // Register - ASSERT_TRUE(registry.registerShader(std::make_shared(), - "CustomName")); - + ASSERT_TRUE(registry.registerShader(std::make_shared(), "CustomName")); + std::shared_ptr progA; ASSERT_TRUE(registry.populate(progA, "CustomName")); ASSERT_NE(progA, nullptr); // Replace it with a new instance - ASSERT_TRUE(registry.replaceShader(std::make_shared(), - "CustomName")); - + ASSERT_TRUE(registry.replaceShader(std::make_shared(), "CustomName")); + std::shared_ptr progB; ASSERT_TRUE(registry.populate(progB, "CustomName")); ASSERT_NE(progB, nullptr); - + // Should be different instances ASSERT_NE(progA, progB); } @@ -232,9 +213,7 @@ TEST(ShaderRegistry, GLSLReplacement_NoOp) { // Just replace with a default instance observer.registerShaders = [&](gfx::ShaderRegistry& registry) { - if (!registry.replaceShader(std::make_shared( - ProgramParameters(1.0f, false)))) - { + if (!registry.replaceShader(std::make_shared(ProgramParameters(1.0f, false)))) { throw std::runtime_error("Failed to register shader!"); } }; @@ -251,8 +230,8 @@ TEST(ShaderRegistry, GLSLReplacement_NoOp) { test::checkImage("test/fixtures/shader_registry/glsl_replace_noop", img, 0.005, 0.1); } -// Test replacing an actual program with a similar instance using a different fragment -// shader +// Test replacing an actual program with a similar instance using a different +// fragment shader TEST(ShaderRegistry, GLSLReplacement1) { MapInstance::ShaderAndStyleObserver observer; util::RunLoop runLoop; @@ -261,19 +240,14 @@ TEST(ShaderRegistry, GLSLReplacement1) { // Replace with an instance that only renders blue observer.registerShaders = [&](gfx::ShaderRegistry& registry) { if (!registry.replaceShader(std::make_shared( - ProgramParameters(1.0f, false).withShaderSource( - ProgramParameters::ProgramSource( - gfx::Backend::Type::OpenGL, - "", - R"( + ProgramParameters(1.0f, false) + .withShaderSource(ProgramParameters::ProgramSource(gfx::Backend::Type::OpenGL, + "", + R"( void main() { fragColor = vec4(0.0, 0.0, 1.0, 1.0); } - )" - ) - ) - ))) - { + )"))))) { throw std::runtime_error("Failed to register shader!"); } }; @@ -290,8 +264,8 @@ void main() { test::checkImage("test/fixtures/shader_registry/glsl_replace_1", img, 0.005, 0.1); } -// Test replacing an actual program with a similar instance using a different fragment -// shader +// Test replacing an actual program with a similar instance using a different +// fragment shader TEST(ShaderRegistry, GLSLReplacement2) { MapInstance::ShaderAndStyleObserver observer; util::RunLoop runLoop; @@ -300,11 +274,10 @@ TEST(ShaderRegistry, GLSLReplacement2) { // Replace with an instance that adds some red and green observer.registerShaders = [&](gfx::ShaderRegistry& registry) { if (!registry.replaceShader(std::make_shared( - ProgramParameters(1.0f, false).withShaderSource( - ProgramParameters::ProgramSource( - gfx::Backend::Type::OpenGL, - "", - R"( + ProgramParameters(1.0f, false) + .withShaderSource(ProgramParameters::ProgramSource(gfx::Backend::Type::OpenGL, + "", + R"( #ifndef HAS_UNIFORM_u_color varying highp vec4 color; #else @@ -332,11 +305,7 @@ void main() { fragColor = vec4(1.0); #endif } - )" - ) - ) - ))) - { + )"))))) { throw std::runtime_error("Failed to register shader!"); } }; diff --git a/test/sprite/sprite_loader.test.cpp b/test/sprite/sprite_loader.test.cpp index 2c37e687e36..8b5ad25d9cf 100644 --- a/test/sprite/sprite_loader.test.cpp +++ b/test/sprite/sprite_loader.test.cpp @@ -26,7 +26,7 @@ class StubSpriteLoaderObserver : public SpriteLoaderObserver { } std::function>)> spriteLoaded; - std::function spriteError; + std::function spriteError; }; class SpriteLoaderTest { @@ -36,7 +36,7 @@ class SpriteLoaderTest { util::RunLoop loop; StubFileSource fileSource; StubSpriteLoaderObserver observer; - SpriteLoader spriteLoader{ 1 }; + SpriteLoader spriteLoader{1}; void run() { // Squelch logging. @@ -48,9 +48,7 @@ class SpriteLoaderTest { loop.run(); } - void end() { - loop.stop(); - } + void end() { loop.stop(); } }; Response successfulSpriteImageResponse(const Resource& resource) { @@ -69,9 +67,7 @@ Response successfulSpriteJSONResponse(const Resource& resource) { Response failedSpriteResponse(const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; } @@ -87,7 +83,7 @@ TEST(SpriteLoader, LoadingSuccess) { test.fileSource.spriteImageResponse = successfulSpriteImageResponse; test.fileSource.spriteJSONResponse = successfulSpriteJSONResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { FAIL() << util::toString(error); test.end(); }; @@ -106,7 +102,7 @@ TEST(SpriteLoader, JSONLoadingFail) { test.fileSource.spriteImageResponse = successfulSpriteImageResponse; test.fileSource.spriteJSONResponse = failedSpriteResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); EXPECT_EQ("Failed by the test case", util::toString(error)); test.end(); @@ -121,7 +117,7 @@ TEST(SpriteLoader, ImageLoadingFail) { test.fileSource.spriteImageResponse = failedSpriteResponse; test.fileSource.spriteJSONResponse = successfulSpriteJSONResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); EXPECT_EQ("Failed by the test case", util::toString(error)); test.end(); @@ -136,7 +132,7 @@ TEST(SpriteLoader, JSONLoadingCorrupted) { test.fileSource.spriteImageResponse = successfulSpriteImageResponse; test.fileSource.spriteJSONResponse = corruptSpriteResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); EXPECT_EQ("Failed to parse JSON: Invalid value. at offset 0", util::toString(error)); test.end(); @@ -151,7 +147,7 @@ TEST(SpriteLoader, ImageLoadingCorrupted) { test.fileSource.spriteImageResponse = corruptSpriteResponse; test.fileSource.spriteJSONResponse = successfulSpriteJSONResponse; - test.observer.spriteError = [&] (std::exception_ptr error) { + test.observer.spriteError = [&](std::exception_ptr error) { EXPECT_TRUE(error != nullptr); // Not asserting on platform-specific error text. test.end(); @@ -163,8 +159,7 @@ TEST(SpriteLoader, ImageLoadingCorrupted) { TEST(SpriteLoader, LoadingCancel) { SpriteLoaderTest test; - test.fileSource.spriteImageResponse = - test.fileSource.spriteJSONResponse = [&] (const Resource&) { + test.fileSource.spriteImageResponse = test.fileSource.spriteJSONResponse = [&](const Resource&) { test.end(); return std::optional(); }; diff --git a/test/sprite/sprite_parser.test.cpp b/test/sprite/sprite_parser.test.cpp index 0579604b8f3..3599c564cb7 100644 --- a/test/sprite/sprite_parser.test.cpp +++ b/test/sprite/sprite_parser.test.cpp @@ -34,7 +34,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 0x16@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 0x16@0,0 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -44,7 +45,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 16x0@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 16x0@0,0 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -54,7 +56,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: -1x16@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: -1x16@0,0 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -64,7 +67,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 16x-1@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 16x-1@0,0 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -74,7 +78,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 1x1@0,0 in 200x299@0x sprite", + "Can't create image with invalid metrics: 1x1@0,0 in 200x299@0x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -84,7 +89,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 1x1@0,0 in 200x299@-1x sprite", + "Can't create image with invalid metrics: 1x1@0,0 in 200x299@-1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -94,7 +100,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 1x1@0,0 in 200x299@23x sprite", + "Can't create image with invalid metrics: 1x1@0,0 in 200x299@23x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -104,7 +111,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 2048x16@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 2048x16@0,0 in " + "200x299@1x sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -114,7 +122,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 16x1025@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 16x1025@0,0 in " + "200x299@1x sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -124,7 +133,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 16x16@-1,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 16x16@-1,0 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -134,7 +144,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 16x16@0,-1 in 200x299@1x sprite", + "Can't create image with invalid metrics: 16x16@0,-1 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -146,7 +157,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 201x16@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 201x16@0,0 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -158,7 +170,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 16x300@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 16x300@0,0 in 200x299@1x " + "sprite", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -168,7 +181,8 @@ TEST(Sprite, SpriteImageCreationInvalid) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metadata: stretchX is out of bounds or overlapping", + "Can't create image with invalid metadata: stretchX is out of " + "bounds or overlapping", })); EXPECT_EQ(0u, log.uncheckedCount()); @@ -196,7 +210,8 @@ TEST(Sprite, SpriteImageCreation1x) { EXPECT_EQ(18u, sprite->getImage().size.width); EXPECT_EQ(18u, sprite->getImage().size.height); EXPECT_EQ(1, sprite->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1x-museum.png"), + EXPECT_EQ(readImage("test/fixtures/annotations/" + "result-spriteimagecreation1x-museum.png"), sprite->getImage()); } } @@ -210,8 +225,7 @@ TEST(Sprite, SpriteImageCreation2x) { EXPECT_EQ(36u, sprite->getImage().size.width); EXPECT_EQ(36u, sprite->getImage().size.height); EXPECT_EQ(2, sprite->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation2x.png"), - sprite->getImage()); + EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation2x.png"), sprite->getImage()); } TEST(Sprite, SpriteImageCreation1_5x) { @@ -223,7 +237,8 @@ TEST(Sprite, SpriteImageCreation1_5x) { EXPECT_EQ(36u, sprite->getImage().size.width); EXPECT_EQ(36u, sprite->getImage().size.height); EXPECT_EQ(1.5, sprite->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1_5x-museum.png"), + EXPECT_EQ(readImage("test/fixtures/annotations/" + "result-spriteimagecreation1_5x-museum.png"), sprite->getImage()); // "hospital_icon":{"x":314,"y":518,"width":36,"height":36,"pixelRatio":2,"sdf":false} @@ -232,7 +247,8 @@ TEST(Sprite, SpriteImageCreation1_5x) { EXPECT_EQ(35u, sprite2->getImage().size.width); EXPECT_EQ(35u, sprite2->getImage().size.height); EXPECT_EQ(1.5, sprite2->getPixelRatio()); - EXPECT_EQ(readImage("test/fixtures/annotations/result-spriteimagecreation1_5x-hospital.png"), + EXPECT_EQ(readImage("test/fixtures/annotations/" + "result-spriteimagecreation1_5x-hospital.png"), sprite2->getImage()); } @@ -246,84 +262,84 @@ TEST(Sprite, SpriteParsing) { std::transform( images.begin(), images.end(), std::inserter(names, names.begin()), [](const auto& image) { return image->id; }); - EXPECT_EQ(std::set({ "airfield_icon", - "airport_icon", - "background", - "cemetery_icon", - "college_icon", - "default_1", - "default_2", - "default_3", - "default_4", - "default_5", - "default_6", - "default_marker", - "dlr", - "dlr.london-overground.london-underground.national-rail", - "dlr.london-underground", - "dlr.london-underground.national-rail", - "dlr.national-rail", - "dot", - "embassy_icon", - "fire-station_icon", - "generic-metro", - "generic-rail", - "generic_icon", - "golf_icon", - "government_icon", - "grass_pattern", - "harbor_icon", - "hospital_icon", - "hospital_striped", - "interstate_1", - "interstate_2", - "interstate_3", - "library_icon", - "london-overground", - "london-overground.london-underground", - "london-overground.london-underground.national-rail", - "london-overground.national-rail", - "london-underground", - "london-underground.national-rail", - "marker_icon", - "metro", - "metro.rer", - "monument_icon", - "moscow-metro", - "museum_icon", - "national-rail", - "oneway_motorway", - "oneway_road", - "park_icon", - "police_icon", - "post_icon", - "prison_icon", - "religious-christian_icon", - "religious-jewish_icon", - "religious-muslim_icon", - "rer", - "rer.transilien", - "s-bahn", - "s-bahn.u-bahn", - "sand_noise", - "school_icon", - "school_striped", - "secondary_marker", - "u-bahn", - "us_highway_1", - "us_highway_2", - "us_highway_3", - "us_state_1", - "us_state_2", - "us_state_3", - "washington-metro", - "wiener-linien", - "zoo_icon" }), + EXPECT_EQ(std::set({"airfield_icon", + "airport_icon", + "background", + "cemetery_icon", + "college_icon", + "default_1", + "default_2", + "default_3", + "default_4", + "default_5", + "default_6", + "default_marker", + "dlr", + "dlr.london-overground.london-underground.national-rail", + "dlr.london-underground", + "dlr.london-underground.national-rail", + "dlr.national-rail", + "dot", + "embassy_icon", + "fire-station_icon", + "generic-metro", + "generic-rail", + "generic_icon", + "golf_icon", + "government_icon", + "grass_pattern", + "harbor_icon", + "hospital_icon", + "hospital_striped", + "interstate_1", + "interstate_2", + "interstate_3", + "library_icon", + "london-overground", + "london-overground.london-underground", + "london-overground.london-underground.national-rail", + "london-overground.national-rail", + "london-underground", + "london-underground.national-rail", + "marker_icon", + "metro", + "metro.rer", + "monument_icon", + "moscow-metro", + "museum_icon", + "national-rail", + "oneway_motorway", + "oneway_road", + "park_icon", + "police_icon", + "post_icon", + "prison_icon", + "religious-christian_icon", + "religious-jewish_icon", + "religious-muslim_icon", + "rer", + "rer.transilien", + "s-bahn", + "s-bahn.u-bahn", + "sand_noise", + "school_icon", + "school_striped", + "secondary_marker", + "u-bahn", + "us_highway_1", + "us_highway_2", + "us_highway_3", + "us_state_1", + "us_state_2", + "us_state_3", + "washington-metro", + "wiener-linien", + "zoo_icon"}), names); { - auto& sprite = - *std::find_if(images.begin(), images.end(), [](const auto& image) { return image->id == "generic-metro"; }); + auto& sprite = *std::find_if( + images.begin(), images.end(), [](const auto& image) { return image->id == "generic-metro"; }); EXPECT_EQ(18u, sprite->image.size.width); EXPECT_EQ(18u, sprite->image.size.height); EXPECT_EQ(1, sprite->pixelRatio); @@ -340,7 +356,8 @@ TEST(Sprite, SpriteParsingInvalidJSON) { FAIL() << "Expected exception"; } catch (std::runtime_error& err) { EXPECT_STREQ( - "Failed to parse JSON: Missing a closing quotation mark in string. at offset 14", + "Failed to parse JSON: Missing a closing quotation mark in string. " + "at offset 14", err.what()); } } @@ -364,7 +381,8 @@ TEST(Sprite, SpriteParsingInvalidStretches) { log.count({EventSeverity::Warning, Event::Sprite, int64_t(-1), - "Invalid sprite image 'interstate_1': value of 'stretchX' must be an array"})); + "Invalid sprite image 'interstate_1': value of 'stretchX' must be " + "an array"})); EXPECT_EQ(0u, log.uncheckedCount()); parseSprite(image_1x, R"JSON({ @@ -377,12 +395,12 @@ TEST(Sprite, SpriteParsingInvalidStretches) { "stretchX": [[[]]] } })JSON"); - EXPECT_EQ( - 1u, - log.count({EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'interstate_1': members of 'stretchX' must be an array of two numbers"})); + EXPECT_EQ(1u, + log.count({EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'interstate_1': members of 'stretchX' must " + "be an array of two numbers"})); EXPECT_EQ(0u, log.uncheckedCount()); parseSprite(image_1x, R"JSON({ @@ -395,12 +413,12 @@ TEST(Sprite, SpriteParsingInvalidStretches) { "stretchX": [[4, false]] } })JSON"); - EXPECT_EQ( - 1u, - log.count({EventSeverity::Warning, - Event::Sprite, - int64_t(-1), - "Invalid sprite image 'interstate_1': members of 'stretchX' must be an array of two numbers"})); + EXPECT_EQ(1u, + log.count({EventSeverity::Warning, + Event::Sprite, + int64_t(-1), + "Invalid sprite image 'interstate_1': members of 'stretchX' must " + "be an array of two numbers"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -423,7 +441,8 @@ TEST(Sprite, SpriteParsingInvalidContent) { log.count({EventSeverity::Warning, Event::Sprite, int64_t(-1), - "Invalid sprite image 'interstate_1': value of 'content' must be an array of four numbers"})); + "Invalid sprite image 'interstate_1': value of 'content' must be " + "an array of four numbers"})); EXPECT_EQ(0u, log.uncheckedCount()); parseSprite(image_1x, R"JSON({ @@ -440,7 +459,8 @@ TEST(Sprite, SpriteParsingInvalidContent) { log.count({EventSeverity::Warning, Event::Sprite, int64_t(-1), - "Invalid sprite image 'interstate_1': value of 'content' must be an array of four numbers"})); + "Invalid sprite image 'interstate_1': value of 'content' must be " + "an array of four numbers"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -482,7 +502,8 @@ TEST(Sprite, SpriteParsingEmptyImage) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 0x0@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 0x0@0,0 in 200x299@1x " + "sprite", })); } @@ -510,14 +531,16 @@ TEST(Sprite, SpriteParsingWidthTooBig) { EventSeverity::Warning, Event::Sprite, int64_t(-1), - "Invalid sprite image 'image': value of 'width' must be an integer between 0 and 65535", + "Invalid sprite image 'image': value of 'width' must be an integer " + "between 0 and 65535", })); EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x " + "sprite", })); } @@ -535,14 +558,16 @@ TEST(Sprite, SpriteParsingNegativeWidth) { EventSeverity::Warning, Event::Sprite, int64_t(-1), - "Invalid sprite image 'image': value of 'width' must be an integer between 0 and 65535", + "Invalid sprite image 'image': value of 'width' must be an integer " + "between 0 and 65535", })); EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x sprite", + "Can't create image with invalid metrics: 0x32@0,0 in 200x299@1x " + "sprite", })); } @@ -560,6 +585,7 @@ TEST(Sprite, SpriteParsingNullRatio) { EventSeverity::Error, Event::Sprite, int64_t(-1), - "Can't create image with invalid metrics: 32x32@0,0 in 200x299@0x sprite", + "Can't create image with invalid metrics: 32x32@0,0 in 200x299@0x " + "sprite", })); } diff --git a/test/src/mbgl/test/fake_file_source.hpp b/test/src/mbgl/test/fake_file_source.hpp index 276ebb895d1..95752b0037c 100644 --- a/test/src/mbgl/test/fake_file_source.hpp +++ b/test/src/mbgl/test/fake_file_source.hpp @@ -10,16 +10,17 @@ #include #include - namespace mbgl { /* - FakeFileSource is similar to StubFileSource, but it follows a post hoc, "push" model rather than - a pre hoc, "pull" model. You pass it to code that makes requests, it records what requests are - made, then you can examine them, make assertions about them, and respond as desired. - - This is particularly useful if you want to simulate multiple responses, e.g. as part of a resource - revalidation flow. StubFileSource allows only a single response. + FakeFileSource is similar to StubFileSource, but it follows a post hoc, + "push" model rather than a pre hoc, "pull" model. You pass it to code that + makes requests, it records what requests are made, then you can examine them, + make assertions about them, and respond as desired. + + This is particularly useful if you want to simulate multiple responses, e.g. + as part of a resource revalidation flow. StubFileSource allows only a single + response. */ class FakeFileSource : public FileSource { public: @@ -35,17 +36,16 @@ class FakeFileSource : public FileSource { : resource(std::move(resource_)), callback(std::move(callback_)), list(list_), - link((list.push_back(this), std::prev(list.end()))) { - } + link((list.push_back(this), std::prev(list.end()))) {} - ~FakeFileRequest() override { - list.erase(link); - } + ~FakeFileRequest() override { list.erase(link); } }; FakeFileSource(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) - : resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) {} - FakeFileSource() : FakeFileSource(ResourceOptions::Default(), ClientOptions()) {} + : resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) {} + FakeFileSource() + : FakeFileSource(ResourceOptions::Default(), ClientOptions()) {} std::unique_ptr request(const Resource& resource, Callback callback) override { return std::make_unique(resource, callback, requests); @@ -54,7 +54,7 @@ class FakeFileSource : public FileSource { bool canRequest(const Resource&) const override { return true; } bool respond(Resource::Kind kind, const Response& response) { - auto it = std::find_if(requests.begin(), requests.end(), [&] (FakeFileRequest* fakeRequest) { + auto it = std::find_if(requests.begin(), requests.end(), [&](FakeFileRequest* fakeRequest) { return fakeRequest->resource.kind == kind; }); @@ -71,19 +71,11 @@ class FakeFileSource : public FileSource { std::list requests; - void setResourceOptions(ResourceOptions options) override { - resourceOptions = options; - } - ResourceOptions getResourceOptions() override { - return resourceOptions.clone(); - } + void setResourceOptions(ResourceOptions options) override { resourceOptions = options; } + ResourceOptions getResourceOptions() override { return resourceOptions.clone(); } - void setClientOptions(ClientOptions options) override { - clientOptions = options; - } - ClientOptions getClientOptions() override { - return clientOptions.clone(); - } + void setClientOptions(ClientOptions options) override { clientOptions = options; } + ClientOptions getClientOptions() override { return clientOptions.clone(); } private: ResourceOptions resourceOptions; @@ -92,7 +84,8 @@ class FakeFileSource : public FileSource { class FakeOnlineFileSource : public FakeFileSource { public: - FakeOnlineFileSource() : FakeOnlineFileSource(ResourceOptions::Default(), ClientOptions()) {} + FakeOnlineFileSource() + : FakeOnlineFileSource(ResourceOptions::Default(), ClientOptions()) {} FakeOnlineFileSource(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_) : FakeFileSource(resourceOptions_, clientOptions_) {} @@ -100,15 +93,14 @@ class FakeOnlineFileSource : public FakeFileSource { return FakeFileSource::request(resource, callback); } - bool respond(Resource::Kind kind, const Response& response) { - return FakeFileSource::respond(kind, response); - } + bool respond(Resource::Kind kind, const Response& response) { return FakeFileSource::respond(kind, response); } mapbox::base::Value getProperty(const std::string& property) const override { return onlineFs->getProperty(property); } - std::unique_ptr onlineFs = std::make_unique(ResourceOptions::Default(), ClientOptions()); + std::unique_ptr onlineFs = std::make_unique(ResourceOptions::Default(), + ClientOptions()); }; } // namespace mbgl diff --git a/test/src/mbgl/test/fixture_log_observer.cpp b/test/src/mbgl/test/fixture_log_observer.cpp index b27795abb45..e78705e04ae 100644 --- a/test/src/mbgl/test/fixture_log_observer.cpp +++ b/test/src/mbgl/test/fixture_log_observer.cpp @@ -4,20 +4,19 @@ namespace mbgl { -FixtureLog::Message::Message(EventSeverity severity_, - Event event_, - int64_t code_, - std::string msg_) - : severity(severity_), event(event_), code(code_), msg(std::move(msg_)) { -} +FixtureLog::Message::Message(EventSeverity severity_, Event event_, int64_t code_, std::string msg_) + : severity(severity_), + event(event_), + code(code_), + msg(std::move(msg_)) {} bool FixtureLog::Message::matches(const Message& rhs, bool substring) const { return severity == rhs.severity && event == rhs.event && code == rhs.code && (substring ? msg.find(rhs.msg) != std::string::npos : msg == rhs.msg); } -FixtureLog::Observer::Observer(FixtureLog* log_) : log(log_) { -} +FixtureLog::Observer::Observer(FixtureLog* log_) + : log(log_) {} FixtureLog::Observer::~Observer() { if (log) { @@ -26,10 +25,7 @@ FixtureLog::Observer::~Observer() { std::cerr << unchecked(); } -bool FixtureLog::Observer::onRecord(EventSeverity severity, - Event event, - int64_t code, - const std::string& msg) { +bool FixtureLog::Observer::onRecord(EventSeverity severity, Event event, int64_t code, const std::string& msg) { std::lock_guard lock(messagesMutex); if (severity != EventSeverity::Debug) { @@ -58,7 +54,8 @@ size_t FixtureLog::Observer::count(const Message& message, bool substring) const return message_count; } -FixtureLog::FixtureLog() : observer(new FixtureLogObserver(this)) { +FixtureLog::FixtureLog() + : observer(new FixtureLogObserver(this)) { Log::setObserver(std::unique_ptr(observer)); Log::useLogThread(false); } diff --git a/test/src/mbgl/test/fixture_log_observer.hpp b/test/src/mbgl/test/fixture_log_observer.hpp index 791337584d1..8454c875fe7 100644 --- a/test/src/mbgl/test/fixture_log_observer.hpp +++ b/test/src/mbgl/test/fixture_log_observer.hpp @@ -17,10 +17,10 @@ class FixtureLog { bool matches(const Message& rhs, bool substring = false) const; - const EventSeverity severity {}; - const Event event {}; - const int64_t code {}; - const std::string msg {}; + const EventSeverity severity{}; + const Event event{}; + const int64_t code{}; + const std::string msg{}; mutable bool checked = false; }; @@ -33,10 +33,7 @@ class FixtureLog { ~Observer() override; // Log::Observer implementation - bool onRecord(EventSeverity severity, - Event event, - int64_t code, - const std::string& msg) override; + bool onRecord(EventSeverity severity, Event event, int64_t code, const std::string& msg) override; bool empty() const; size_t uncheckedCount() const; @@ -61,9 +58,8 @@ class FixtureLog { Observer* observer; }; -::std::ostream &operator<<(::std::ostream &os, - const std::vector &messages); -::std::ostream &operator<<(::std::ostream &os, const FixtureLog::Observer::LogMessage &message); +::std::ostream& operator<<(::std::ostream& os, const std::vector& messages); +::std::ostream& operator<<(::std::ostream& os, const FixtureLog::Observer::LogMessage& message); using FixtureLogObserver = FixtureLog::Observer; diff --git a/test/src/mbgl/test/getrss.cpp b/test/src/mbgl/test/getrss.cpp index c21b653eaaa..9becc5c0826 100644 --- a/test/src/mbgl/test/getrss.cpp +++ b/test/src/mbgl/test/getrss.cpp @@ -18,41 +18,39 @@ namespace test { * memory use) measured in bytes, or zero if the value cannot be * determined on this OS. */ -size_t getPeakRSS( ) -{ +size_t getPeakRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.PeakWorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.PeakWorkingSetSize; -#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) - /* AIX and Solaris ------------------------------------------ */ - struct psinfo psinfo; - int fd = -1; - if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) - return (size_t)0L; /* Can't open? */ - if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) - { - close( fd ); - return (size_t)0L; /* Can't read? */ - } - close( fd ); - return (size_t)(psinfo.pr_rssize * 1024L); +#elif (defined(_AIX) || defined(__TOS__AIX__)) || \ + (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) + /* AIX and Solaris ------------------------------------------ */ + struct psinfo psinfo; + int fd = -1; + if ((fd = open("/proc/self/psinfo", O_RDONLY)) == -1) return (size_t)0L; /* Can't open? */ + if (read(fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo)) { + close(fd); + return (size_t)0L; /* Can't read? */ + } + close(fd); + return (size_t)(psinfo.pr_rssize * 1024L); #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) - /* BSD, Linux, and OSX -------------------------------------- */ - struct rusage rusage; - getrusage( RUSAGE_SELF, &rusage ); + /* BSD, Linux, and OSX -------------------------------------- */ + struct rusage rusage; + getrusage(RUSAGE_SELF, &rusage); #if defined(__APPLE__) && defined(__MACH__) - return (size_t)rusage.ru_maxrss; + return (size_t)rusage.ru_maxrss; #else - return (size_t)(rusage.ru_maxrss * 1024L); + return (size_t)(rusage.ru_maxrss * 1024L); #endif #else - /* Unknown OS ----------------------------------------------- */ - return (size_t)0L; /* Unsupported. */ + /* Unknown OS ----------------------------------------------- */ + return (size_t)0L; /* Unsupported. */ #endif } @@ -60,43 +58,38 @@ size_t getPeakRSS( ) * Returns the current resident set size (physical memory use) measured * in bytes, or zero if the value cannot be determined on this OS. */ -size_t getCurrentRSS( ) -{ +size_t getCurrentRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.WorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.WorkingSetSize; #elif defined(__APPLE__) && defined(__MACH__) - /* OSX ------------------------------------------------------ */ - struct mach_task_basic_info info; - mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; - if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, - (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) - return (size_t)0L; /* Can't access? */ - return (size_t)info.resident_size; + /* OSX ------------------------------------------------------ */ + struct mach_task_basic_info info; + mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &infoCount) != KERN_SUCCESS) + return (size_t)0L; /* Can't access? */ + return (size_t)info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) - /* Linux ---------------------------------------------------- */ - long rss = 0L; - FILE* fp = nullptr; - if ( (fp = fopen( "/proc/self/statm", "r" )) == nullptr ) - return (size_t)0L; /* Can't open? */ - if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) - { - fclose( fp ); - return (size_t)0L; /* Can't read? */ - } - fclose( fp ); - return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); + /* Linux ---------------------------------------------------- */ + long rss = 0L; + FILE* fp = nullptr; + if ((fp = fopen("/proc/self/statm", "r")) == nullptr) return (size_t)0L; /* Can't open? */ + if (fscanf(fp, "%*s%ld", &rss) != 1) { + fclose(fp); + return (size_t)0L; /* Can't read? */ + } + fclose(fp); + return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE); #else - /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ - return (size_t)0L; /* Unsupported. */ + /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ + return (size_t)0L; /* Unsupported. */ #endif } } // namespace test } // namespace mbgl - diff --git a/test/src/mbgl/test/getrss.hpp b/test/src/mbgl/test/getrss.hpp index 27b538b0240..82b4fff6f0b 100644 --- a/test/src/mbgl/test/getrss.hpp +++ b/test/src/mbgl/test/getrss.hpp @@ -8,10 +8,11 @@ #if defined(__APPLE__) && defined(__MACH__) #include -#include // for mach_port_t +#include // for mach_port_t #include -#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) +#elif (defined(_AIX) || defined(__TOS__AIX__)) || \ + (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) #include #include @@ -26,7 +27,6 @@ namespace mbgl { namespace test { - /** * Returns the peak (maximum so far) resident set size (physical diff --git a/test/src/mbgl/test/http_server.cpp b/test/src/mbgl/test/http_server.cpp index 2c48cf7faac..abd9e2f5d65 100644 --- a/test/src/mbgl/test/http_server.cpp +++ b/test/src/mbgl/test/http_server.cpp @@ -42,7 +42,8 @@ void runServer(std::unique_ptr& server) { std::atomic_int cacheCounter(0); server->Get("/cache", [&](const Request&, Response& res) { - res.set_header("Cache-Control", "max-age=30"); // Allow caching for 30 seconds + res.set_header("Cache-Control", + "max-age=30"); // Allow caching for 30 seconds res.set_content("Response " + std::to_string(++cacheCounter), "text/plain"); }); @@ -205,6 +206,5 @@ HttpServer::~HttpServer() { serverThread.join(); } - } // namespace test } // namespace mbgl diff --git a/test/src/mbgl/test/mock.hpp b/test/src/mbgl/test/mock.hpp index c61cdf56f4e..418c3eaf4d6 100644 --- a/test/src/mbgl/test/mock.hpp +++ b/test/src/mbgl/test/mock.hpp @@ -12,7 +12,7 @@ struct MockTileData; struct MockSource { - mbgl::Range zoomRange { 0, 16 }; + mbgl::Range zoomRange{0, 16}; std::map> dataTiles; std::set idealTiles; @@ -22,21 +22,15 @@ struct MockSource { struct MockBucket {}; - struct MockTileData { - MockTileData(const mbgl::OverscaledTileID& tileID_) : tileID(tileID_) {} + MockTileData(const mbgl::OverscaledTileID& tileID_) + : tileID(tileID_) {} - bool hasTriedCache() const { - return triedOptional; - } + bool hasTriedCache() const { return triedOptional; } - bool isRenderable() const { - return renderable; - } + bool isRenderable() const { return renderable; } - bool isLoaded() const { - return loaded; - } + bool isLoaded() const { return loaded; } bool renderable = false; bool triedOptional = false; diff --git a/test/src/mbgl/test/sqlite3_test_fs.cpp b/test/src/mbgl/test/sqlite3_test_fs.cpp index 068ae9e1cfc..e4ec9e776e1 100644 --- a/test/src/mbgl/test/sqlite3_test_fs.cpp +++ b/test/src/mbgl/test/sqlite3_test_fs.cpp @@ -216,7 +216,7 @@ static int sqlite3_test_fs_open(sqlite3_vfs* vfs, const char* zName, sqlite3_fil return status; } -static int sqlite3_test_fs_delete(sqlite3_vfs* vfs, const char *zPath, int dirSync) { +static int sqlite3_test_fs_delete(sqlite3_vfs* vfs, const char* zPath, int dirSync) { if (sqlite3_test_fs_debug) { fprintf(stderr, "SQLite3: delete(name=%s, sync=%d)\n", zPath, dirSync); } @@ -227,7 +227,7 @@ static int sqlite3_test_fs_delete(sqlite3_vfs* vfs, const char *zPath, int dirSy return unix_fs->xDelete(unix_fs, zPath, dirSync); } -static int sqlite3_test_fs_access(sqlite3_vfs* vfs, const char *zPath, int flags, int *pResOut) { +static int sqlite3_test_fs_access(sqlite3_vfs* vfs, const char* zPath, int flags, int* pResOut) { if (sqlite3_test_fs_debug) { fprintf(stderr, "SQLite3: access(name=%s, flags=%d)\n", zPath, flags); } diff --git a/test/src/mbgl/test/sqlite3_test_fs.hpp b/test/src/mbgl/test/sqlite3_test_fs.hpp index 00351f49ac2..3d472f2dd50 100644 --- a/test/src/mbgl/test/sqlite3_test_fs.hpp +++ b/test/src/mbgl/test/sqlite3_test_fs.hpp @@ -13,24 +13,25 @@ class SQLite3TestFS { // When enabled, the VFS will log all I/O operations to stdout. void setDebug(bool); - // Allow any type of I/O. Will fail with SQLITE_AUTH if set to false. This is useful to simulate - // scenarios where the OS blocks an entire app's I/O, e.g. when it's in the background. + // Allow any type of I/O. Will fail with SQLITE_AUTH if set to false. This + // is useful to simulate scenarios where the OS blocks an entire app's I/O, + // e.g. when it's in the background. void allowIO(bool); - + // Allow files to be opened. Will fail with SQLITE_CANTOPEN if set to false. void allowFileOpen(bool); - + // Allow files to be created. Will fail with SQLITE_CANTOPEN if set to false. void allowFileCreate(bool); - - // Allow N bytes to be read, then fail reads with SQLITE_IOERR. -1 == unlimited - // This limit is global, not per file. + + // Allow N bytes to be read, then fail reads with SQLITE_IOERR. -1 == + // unlimited This limit is global, not per file. void setReadLimit(int64_t); - - // Allow N bytes to be written, then fail writes with SQLITE_FULL. -1 == unlimited - // This limit is global, not per file. + + // Allow N bytes to be written, then fail writes with SQLITE_FULL. -1 == + // unlimited This limit is global, not per file. void setWriteLimit(int64_t); - + // Reset all restrictions. void reset(); }; diff --git a/test/src/mbgl/test/stub_file_source.cpp b/test/src/mbgl/test/stub_file_source.cpp index 8b89e9581c1..598b20b666a 100644 --- a/test/src/mbgl/test/stub_file_source.cpp +++ b/test/src/mbgl/test/stub_file_source.cpp @@ -10,21 +10,24 @@ using namespace std::chrono_literals; class StubFileRequest : public AsyncRequest { public: StubFileRequest(StubFileSource& fileSource_) - : fileSource(fileSource_) { - } + : fileSource(fileSource_) {} - ~StubFileRequest() override { - fileSource.remove(this); - } + ~StubFileRequest() override { fileSource.remove(this); } StubFileSource& fileSource; }; -StubFileSource::StubFileSource(ResponseType type_): - StubFileSource::StubFileSource(ResourceOptions().withTileServerOptions(TileServerOptions::MapTilerConfiguration()), ClientOptions(), type_) {} +StubFileSource::StubFileSource(ResponseType type_) + : StubFileSource::StubFileSource( + ResourceOptions().withTileServerOptions(TileServerOptions::MapTilerConfiguration()), ClientOptions(), type_) { +} -StubFileSource::StubFileSource(const ResourceOptions& resourceOptions_, const ClientOptions& clientOptions_, ResponseType type_) - : type(type_), resourceOptions(resourceOptions_.clone()), clientOptions(clientOptions_.clone()) { +StubFileSource::StubFileSource(const ResourceOptions& resourceOptions_, + const ClientOptions& clientOptions_, + ResponseType type_) + : type(type_), + resourceOptions(resourceOptions_.clone()), + clientOptions(clientOptions_.clone()) { if (type == ResponseType::Synchronous) { return; } @@ -35,14 +38,16 @@ StubFileSource::StubFileSource(const ResourceOptions& resourceOptions_, const Cl for (auto& pair : pending_) { std::optional res = std::get<1>(pair.second)(std::get<0>(pair.second)); if (res) { - // This must be before calling the callback, because it's possible that the callback - // could: + // This must be before calling the callback, because it's + // possible that the callback could: // - // 1. Deallocate the AsyncRequest itself, thus removing it from pending + // 1. Deallocate the AsyncRequest itself, thus removing it + // from pending // 2. Allocate a new AsyncRequest at the same memory location // - // If remove(pair.first) was called after both those things happened, it would - // remove the newly allocated request rather than the intended request. + // If remove(pair.first) was called after both those things + // happened, it would remove the newly allocated request rather + // than the intended request. if (!res->error) { remove(pair.first); } @@ -86,29 +91,29 @@ mapbox::base::Value StubFileSource::getProperty(const std::string& key) const { std::optional StubFileSource::defaultResponse(const Resource& resource) { switch (resource.kind) { - case Resource::Kind::Style: - if (!styleResponse) throw std::runtime_error("unexpected style request"); - return styleResponse(resource); - case Resource::Kind::Source: - if (!sourceResponse) throw std::runtime_error("unexpected source request"); - return sourceResponse(resource); - case Resource::Kind::Tile: - if (!tileResponse) throw std::runtime_error("unexpected tile request"); - return tileResponse(resource); - case Resource::Kind::Glyphs: - if (!glyphsResponse) throw std::runtime_error("unexpected glyphs request"); - return glyphsResponse(resource); - case Resource::Kind::SpriteJSON: - if (!spriteJSONResponse) throw std::runtime_error("unexpected sprite JSON request"); - return spriteJSONResponse(resource); - case Resource::Kind::SpriteImage: - if (!spriteImageResponse) throw std::runtime_error("unexpected sprite image request"); - return spriteImageResponse(resource); - case Resource::Kind::Image: - if (!imageResponse) throw std::runtime_error("unexpected image request"); - return imageResponse(resource); - case Resource::Kind::Unknown: - throw std::runtime_error("unknown resource type"); + case Resource::Kind::Style: + if (!styleResponse) throw std::runtime_error("unexpected style request"); + return styleResponse(resource); + case Resource::Kind::Source: + if (!sourceResponse) throw std::runtime_error("unexpected source request"); + return sourceResponse(resource); + case Resource::Kind::Tile: + if (!tileResponse) throw std::runtime_error("unexpected tile request"); + return tileResponse(resource); + case Resource::Kind::Glyphs: + if (!glyphsResponse) throw std::runtime_error("unexpected glyphs request"); + return glyphsResponse(resource); + case Resource::Kind::SpriteJSON: + if (!spriteJSONResponse) throw std::runtime_error("unexpected sprite JSON request"); + return spriteJSONResponse(resource); + case Resource::Kind::SpriteImage: + if (!spriteImageResponse) throw std::runtime_error("unexpected sprite image request"); + return spriteImageResponse(resource); + case Resource::Kind::Image: + if (!imageResponse) throw std::runtime_error("unexpected image request"); + return imageResponse(resource); + case Resource::Kind::Unknown: + throw std::runtime_error("unknown resource type"); } // The above switch is exhaustive, but placate GCC nonetheless: diff --git a/test/src/mbgl/test/stub_file_source.hpp b/test/src/mbgl/test/stub_file_source.hpp index 63c5ee08c52..1bad4a74d22 100644 --- a/test/src/mbgl/test/stub_file_source.hpp +++ b/test/src/mbgl/test/stub_file_source.hpp @@ -29,10 +29,10 @@ class StubFileSource : public FileSource { void setProperty(const std::string&, const mapbox::base::Value&) override; mapbox::base::Value getProperty(const std::string&) const override; - using ResponseFunction = std::function (const Resource&)>; + using ResponseFunction = std::function(const Resource&)>; // You can set the response callback on a global level by assigning this callback: - ResponseFunction response = [this] (const Resource& resource) { + ResponseFunction response = [this](const Resource& resource) { return defaultResponse(resource); }; diff --git a/test/src/mbgl/test/stub_geometry_tile_feature.hpp b/test/src/mbgl/test/stub_geometry_tile_feature.hpp index e77692fc72b..92f4b8c0aa8 100644 --- a/test/src/mbgl/test/stub_geometry_tile_feature.hpp +++ b/test/src/mbgl/test/stub_geometry_tile_feature.hpp @@ -6,39 +6,35 @@ namespace mbgl { class StubGeometryTileFeature : public GeometryTileFeature { public: StubGeometryTileFeature(PropertyMap properties_) - : properties(std::move(properties_)) { - } + : properties(std::move(properties_)) {} - StubGeometryTileFeature(FeatureIdentifier id_, FeatureType type_, GeometryCollection geometry_, PropertyMap properties_) + StubGeometryTileFeature(FeatureIdentifier id_, + FeatureType type_, + GeometryCollection geometry_, + PropertyMap properties_) : properties(std::move(properties_)), id(std::move(id_)), type(type_), - geometry(std::move(geometry_)) { - } + geometry(std::move(geometry_)) {} StubGeometryTileFeature(FeatureType type_, GeometryCollection geometry_) - : type(type_), geometry(std::move(geometry_)) {} + : type(type_), + geometry(std::move(geometry_)) {} PropertyMap properties; FeatureIdentifier id; FeatureType type = FeatureType::Point; GeometryCollection geometry; - FeatureType getType() const override { - return type; - } + FeatureType getType() const override { return type; } - FeatureIdentifier getID() const override { - return id; - } + FeatureIdentifier getID() const override { return id; } std::optional getValue(const std::string& key) const override { return properties.count(key) ? properties.at(key) : std::optional(); } - const GeometryCollection& getGeometries() const override { - return geometry; - } + const GeometryCollection& getGeometries() const override { return geometry; } }; } // namespace mbgl diff --git a/test/src/mbgl/test/stub_layer_observer.hpp b/test/src/mbgl/test/stub_layer_observer.hpp index 0fa413aefe4..36a6d31379b 100644 --- a/test/src/mbgl/test/stub_layer_observer.hpp +++ b/test/src/mbgl/test/stub_layer_observer.hpp @@ -6,7 +6,8 @@ using namespace mbgl; using namespace mbgl::style; /** - * An implementation of style::LayerObserver that forwards all methods to dynamically-settable lambas. + * An implementation of style::LayerObserver that forwards all methods to + * dynamically-settable lambas. */ class StubLayerObserver : public style::LayerObserver { public: @@ -14,5 +15,5 @@ class StubLayerObserver : public style::LayerObserver { if (layerChanged) layerChanged(layer); } - std::function layerChanged; + std::function layerChanged; }; diff --git a/test/src/mbgl/test/stub_map_observer.hpp b/test/src/mbgl/test/stub_map_observer.hpp index f93c0d64788..6967f8d7972 100644 --- a/test/src/mbgl/test/stub_map_observer.hpp +++ b/test/src/mbgl/test/stub_map_observer.hpp @@ -59,5 +59,4 @@ class StubMapObserver : public MapObserver { std::function onRegisterShadersCallback; }; - } // namespace mbgl diff --git a/test/src/mbgl/test/stub_render_source_observer.hpp b/test/src/mbgl/test/stub_render_source_observer.hpp index ff20fff80c4..942af4f9fc1 100644 --- a/test/src/mbgl/test/stub_render_source_observer.hpp +++ b/test/src/mbgl/test/stub_render_source_observer.hpp @@ -5,7 +5,8 @@ using namespace mbgl; /** - * An implementation of style::Observer that forwards all methods to dynamically-settable lambdas. + * An implementation of style::Observer that forwards all methods to + * dynamically-settable lambdas. */ class StubRenderSourceObserver : public RenderSourceObserver { public: @@ -13,11 +14,10 @@ class StubRenderSourceObserver : public RenderSourceObserver { if (tileChanged) tileChanged(source, tileID); }; - void - onTileError(RenderSource& source, const OverscaledTileID& tileID, std::exception_ptr error) override { + void onTileError(RenderSource& source, const OverscaledTileID& tileID, std::exception_ptr error) override { if (tileError) tileError(source, tileID, error); } - std::function tileChanged; - std::function tileError; + std::function tileChanged; + std::function tileError; }; diff --git a/test/src/mbgl/test/stub_style_observer.hpp b/test/src/mbgl/test/stub_style_observer.hpp index b97911cdb07..abdaf889606 100644 --- a/test/src/mbgl/test/stub_style_observer.hpp +++ b/test/src/mbgl/test/stub_style_observer.hpp @@ -6,7 +6,8 @@ using namespace mbgl; using namespace mbgl::style; /** - * An implementation of style::Observer that forwards all methods to dynamically-settable lambdas. + * An implementation of style::Observer that forwards all methods to + * dynamically-settable lambdas. */ class StubStyleObserver : public style::Observer { public: @@ -30,9 +31,9 @@ class StubStyleObserver : public style::Observer { if (resourceError) resourceError(error); }; - std::function sourceLoaded; - std::function sourceChanged; - std::function sourceError; - std::function sourceDescriptionChanged; - std::function resourceError; + std::function sourceLoaded; + std::function sourceChanged; + std::function sourceError; + std::function sourceDescriptionChanged; + std::function resourceError; }; diff --git a/test/src/mbgl/test/stub_tile_observer.hpp b/test/src/mbgl/test/stub_tile_observer.hpp index 43ae4d8360e..57237c4c779 100644 --- a/test/src/mbgl/test/stub_tile_observer.hpp +++ b/test/src/mbgl/test/stub_tile_observer.hpp @@ -5,7 +5,8 @@ using namespace mbgl; /** - * An implementation of TileObserver that forwards all methods to dynamically-settable lambas. + * An implementation of TileObserver that forwards all methods to + * dynamically-settable lambas. */ class StubTileObserver : public TileObserver { public: @@ -17,6 +18,6 @@ class StubTileObserver : public TileObserver { if (tileError) tileError(tile, error); } - std::function tileChanged; - std::function tileError; + std::function tileChanged; + std::function tileError; }; diff --git a/test/src/mbgl/test/test.cpp b/test/src/mbgl/test/test.cpp index 4c47094dbc4..5b37ba19131 100644 --- a/test/src/mbgl/test/test.cpp +++ b/test/src/mbgl/test/test.cpp @@ -8,7 +8,7 @@ namespace mbgl { int runTests(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); - + // In order to run specific tests // testing::GTEST_FLAG(filter) = "TileServerOptions*"; // testing::GTEST_FLAG(filter) = "MainResourceLoader.ResourceOptions"; diff --git a/test/src/mbgl/test/util.cpp b/test/src/mbgl/test/util.cpp index 74298926521..79de8bd4447 100644 --- a/test/src/mbgl/test/util.cpp +++ b/test/src/mbgl/test/util.cpp @@ -15,7 +15,6 @@ #pragma warning(pop) #endif - namespace mbgl { namespace test { @@ -39,8 +38,7 @@ void checkImage(const std::string& base, } PremultipliedImage expected = decodeImage(expected_image); - PremultipliedImage diff { expected.size }; - + PremultipliedImage diff{expected.size}; #if !TEST_READ_ONLY util::write_file(base + "/actual.png", encodePNG(actual)); diff --git a/test/storage/asset_file_source.test.cpp b/test/storage/asset_file_source.test.cpp index bb25a3acdab..efe9d36facd 100644 --- a/test/storage/asset_file_source.test.cpp +++ b/test/storage/asset_file_source.test.cpp @@ -29,7 +29,8 @@ TEST(AssetFileSource, Load) { class TestWorker { public: - TestWorker(ActorRef, mbgl::AssetFileSource* fs_) : fs(fs_) {} + TestWorker(ActorRef, mbgl::AssetFileSource* fs_) + : fs(fs_) {} void run(std::function endCallback) { const std::string asset("asset://nonempty"); @@ -43,11 +44,11 @@ TEST(AssetFileSource, Load) { endCallback(); request.reset(); } else { - request = fs->request({ mbgl::Resource::Unknown, asset }, requestCallback); + request = fs->request({mbgl::Resource::Unknown, asset}, requestCallback); } }; - request = fs->request({ mbgl::Resource::Unknown, asset }, requestCallback); + request = fs->request({mbgl::Resource::Unknown, asset}, requestCallback); } private: @@ -62,10 +63,11 @@ TEST(AssetFileSource, Load) { std::vector>> threads; for (unsigned i = 0; i < numThreads; ++i) { - std::unique_ptr> thread = - std::make_unique>("Test", &fs); + std::unique_ptr> thread = std::make_unique>("Test", &fs); - thread->actor().invoke(&TestWorker::run, [&] { if (!--completed) loop.stop(); }); + thread->actor().invoke(&TestWorker::run, [&] { + if (!--completed) loop.stop(); + }); threads.push_back(std::move(thread)); } @@ -87,7 +89,7 @@ TEST(AssetFileSource, EmptyFile) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://empty" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://empty"}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -103,7 +105,7 @@ TEST(AssetFileSource, NonEmptyFile) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://nonempty" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://nonempty"}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -119,7 +121,7 @@ TEST(AssetFileSource, NonExistentFile) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://does_not_exist" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://does_not_exist"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); @@ -136,7 +138,7 @@ TEST(AssetFileSource, InvalidURL) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "test://wrong-scheme" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "test://wrong-scheme"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::Other, res.error->reason); @@ -153,7 +155,7 @@ TEST(AssetFileSource, ReadDirectory) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://directory" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://directory"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); @@ -170,7 +172,7 @@ TEST(AssetFileSource, URLEncoding) { AssetFileSource fs(ResourceOptions::Default().withAssetPath("test/fixtures/storage/assets"), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "asset://%6eonempty" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "asset://%6eonempty"}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); diff --git a/test/storage/database_file_source.test.cpp b/test/storage/database_file_source.test.cpp index f9f538c2f5e..492caa440a2 100644 --- a/test/storage/database_file_source.test.cpp +++ b/test/storage/database_file_source.test.cpp @@ -12,8 +12,8 @@ using namespace mbgl; TEST(DatabaseFileSource, PauseResume) { util::RunLoop loop; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource(FileSourceType::Database, + ResourceOptions{}); dbfs->pause(); const Resource res{Resource::Unknown, "http://127.0.0.1:3000/test", {}, Resource::LoadingMethod::CacheOnly}; @@ -28,8 +28,8 @@ TEST(DatabaseFileSource, PauseResume) { TEST(DatabaseFileSource, VolatileResource) { util::RunLoop loop; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource(FileSourceType::Database, + ResourceOptions{}); Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test", {}, Resource::LoadingMethod::CacheOnly}; Response response{}; diff --git a/test/storage/http_file_source.test.cpp b/test/storage/http_file_source.test.cpp index 7e9ba966d72..d4f1b3c9dcb 100644 --- a/test/storage/http_file_source.test.cpp +++ b/test/storage/http_file_source.test.cpp @@ -13,9 +13,8 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(Cancel)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - fs.request({ Resource::Unknown, "http://127.0.0.1:3000/test" }, [&](Response) { - ADD_FAILURE() << "Callback should not be called"; - }); + fs.request({Resource::Unknown, "http://127.0.0.1:3000/test"}, + [&](Response) { ADD_FAILURE() << "Callback should not be called"; }); loop.runOnce(); } @@ -24,7 +23,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP200)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/test" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/test"}, [&](Response res) { EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); EXPECT_EQ("Hello World!", *res.data); @@ -42,7 +41,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP404)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/doesnotexist" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/doesnotexist"}, [&](Response res) { ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); EXPECT_EQ("HTTP status code 404", res.error->message); @@ -61,7 +60,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTPTile404)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Tile, "http://127.0.0.1:3000/doesnotexist" }, [&](Response res) { + auto req = fs.request({Resource::Tile, "http://127.0.0.1:3000/doesnotexist"}, [&](Response res) { EXPECT_TRUE(res.noContent); EXPECT_FALSE(bool(res.error)); EXPECT_FALSE(bool(res.data)); @@ -79,7 +78,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP200EmptyData)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/empty-data" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/empty-data"}, [&](Response res) { EXPECT_FALSE(res.noContent); EXPECT_FALSE(bool(res.error)); EXPECT_EQ(*res.data, std::string()); @@ -97,7 +96,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP204)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/no-content" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/no-content"}, [&](Response res) { EXPECT_TRUE(res.noContent); EXPECT_FALSE(bool(res.error)); EXPECT_FALSE(bool(res.data)); @@ -115,7 +114,7 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(HTTP500)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/permanent-error" }, [&](Response res) { + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/permanent-error"}, [&](Response res) { ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::Server, res.error->reason); EXPECT_EQ("HTTP status code 500", res.error->message); @@ -134,17 +133,19 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(ExpiresParsing)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, - "http://127.0.0.1:3000/test?modified=1420794326&expires=1420797926&etag=foo" }, [&](Response res) { - EXPECT_EQ(nullptr, res.error); - ASSERT_TRUE(res.data.get()); - EXPECT_EQ("Hello World!", *res.data); - EXPECT_EQ(Timestamp{ Seconds(1420797926) }, res.expires); - EXPECT_FALSE(res.mustRevalidate); - EXPECT_EQ(Timestamp{ Seconds(1420794326) }, res.modified); - EXPECT_EQ("foo", *res.etag); - loop.stop(); - }); + auto req = fs.request({Resource::Unknown, + "http://127.0.0.1:3000/" + "test?modified=1420794326&expires=1420797926&etag=foo"}, + [&](Response res) { + EXPECT_EQ(nullptr, res.error); + ASSERT_TRUE(res.data.get()); + EXPECT_EQ("Hello World!", *res.data); + EXPECT_EQ(Timestamp{Seconds(1420797926)}, res.expires); + EXPECT_FALSE(res.mustRevalidate); + EXPECT_EQ(Timestamp{Seconds(1420794326)}, res.modified); + EXPECT_EQ("foo", *res.etag); + loop.stop(); + }); loop.run(); } @@ -153,16 +154,18 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(CacheControlParsing)) { util::RunLoop loop; HTTPFileSource fs(ResourceOptions::Default(), ClientOptions()); - auto req = fs.request({ Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=120" }, [&](Response res) { - EXPECT_EQ(nullptr, res.error); - ASSERT_TRUE(res.data.get()); - EXPECT_EQ("Hello World!", *res.data); - EXPECT_GT(Seconds(2), util::abs(*res.expires - util::now() - Seconds(120))) << "Expiration date isn't about 120 seconds in the future"; - EXPECT_FALSE(res.mustRevalidate); - EXPECT_FALSE(bool(res.modified)); - EXPECT_FALSE(bool(res.etag)); - loop.stop(); - }); + auto req = fs.request({Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=120"}, + [&](Response res) { + EXPECT_EQ(nullptr, res.error); + ASSERT_TRUE(res.data.get()); + EXPECT_EQ("Hello World!", *res.data); + EXPECT_GT(Seconds(2), util::abs(*res.expires - util::now() - Seconds(120))) + << "Expiration date isn't about 120 seconds in the future"; + EXPECT_FALSE(res.mustRevalidate); + EXPECT_FALSE(bool(res.modified)); + EXPECT_FALSE(bool(res.etag)); + loop.stop(); + }); loop.run(); } @@ -179,24 +182,23 @@ TEST(HTTPFileSource, TEST_REQUIRES_SERVER(Load)) { std::function req = [&](int i) { const auto current = number++; - reqs[i] = fs.request({ Resource::Unknown, - std::string("http://127.0.0.1:3000/load/") + util::toString(current) }, - [&, i, current](Response res) { - reqs[i].reset(); - EXPECT_EQ(nullptr, res.error); - ASSERT_TRUE(res.data.get()); - EXPECT_EQ(std::string("Request ") + util::toString(current), *res.data); - EXPECT_FALSE(bool(res.expires)); - EXPECT_FALSE(res.mustRevalidate); - EXPECT_FALSE(bool(res.modified)); - EXPECT_FALSE(bool(res.etag)); - - if (number <= max) { - req(i); - } else if (current == max) { - loop.stop(); - } - }); + reqs[i] = fs.request({Resource::Unknown, std::string("http://127.0.0.1:3000/load/") + util::toString(current)}, + [&, i, current](Response res) { + reqs[i].reset(); + EXPECT_EQ(nullptr, res.error); + ASSERT_TRUE(res.data.get()); + EXPECT_EQ(std::string("Request ") + util::toString(current), *res.data); + EXPECT_FALSE(bool(res.expires)); + EXPECT_FALSE(res.mustRevalidate); + EXPECT_FALSE(bool(res.modified)); + EXPECT_FALSE(bool(res.etag)); + + if (number <= max) { + req(i); + } else if (current == max) { + loop.stop(); + } + }); }; for (int i = 0; i < concurrency; i++) { diff --git a/test/storage/local_file_source.test.cpp b/test/storage/local_file_source.test.cpp index 60655a469cf..c845d5bf8be 100644 --- a/test/storage/local_file_source.test.cpp +++ b/test/storage/local_file_source.test.cpp @@ -21,11 +21,11 @@ namespace { std::string toAbsoluteURL(const std::string& fileName) { char buff[PATH_MAX + 1]; #ifdef _MSC_VER - char* cwd = _getcwd( buff, PATH_MAX + 1 ); + char* cwd = _getcwd(buff, PATH_MAX + 1); #else - char* cwd = getcwd( buff, PATH_MAX + 1 ); + char* cwd = getcwd(buff, PATH_MAX + 1); #endif - std::string url = { "file://" + std::string(cwd) + "/test/fixtures/storage/assets/" + fileName }; + std::string url = {"file://" + std::string(cwd) + "/test/fixtures/storage/assets/" + fileName}; assert(url.size() <= PATH_MAX); return url; } @@ -49,7 +49,7 @@ TEST(LocalFileSource, EmptyFile) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("empty") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("empty")}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -65,7 +65,7 @@ TEST(LocalFileSource, NonEmptyFile) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("nonempty") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("nonempty")}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -81,14 +81,15 @@ TEST(LocalFileSource, NonExistentFile) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("does_not_exist") }, [&](Response res) { - req.reset(); - ASSERT_NE(nullptr, res.error); - EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); - ASSERT_FALSE(res.data.get()); - // Do not assert on platform-specific error message. - loop.stop(); - }); + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("does_not_exist")}, + [&](Response res) { + req.reset(); + ASSERT_NE(nullptr, res.error); + EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); + ASSERT_FALSE(res.data.get()); + // Do not assert on platform-specific error message. + loop.stop(); + }); loop.run(); } @@ -98,7 +99,7 @@ TEST(LocalFileSource, InvalidURL) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, "test://wrong-scheme" }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, "test://wrong-scheme"}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::Other, res.error->reason); @@ -115,7 +116,7 @@ TEST(LocalFileSource, ReadDirectory) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("directory") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("directory")}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); @@ -132,7 +133,7 @@ TEST(LocalFileSource, URLEncoding) { LocalFileSource fs(ResourceOptions::Default(), ClientOptions()); - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL("%6eonempty") }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL("%6eonempty")}, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); @@ -155,11 +156,12 @@ TEST(LocalFileSource, URLLimit) { delete[] filename; - std::unique_ptr req = fs.request({ Resource::Unknown, toAbsoluteURL(url) }, [&](Response res) { + std::unique_ptr req = fs.request({Resource::Unknown, toAbsoluteURL(url)}, [&](Response res) { req.reset(); ASSERT_NE(nullptr, res.error); #if defined(_MSC_VER) && !defined(__clang__) - // Microsoft Visual Studio defines PATH_MAX as 260, less than the limit to trigger an error with reason "Other" + // Microsoft Visual Studio defines PATH_MAX as 260, less than the + // limit to trigger an error with reason "Other" EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); #else EXPECT_EQ(Response::Error::Reason::Other, res.error->reason); diff --git a/test/storage/main_resource_loader.test.cpp b/test/storage/main_resource_loader.test.cpp index 88012b58a6c..fd945a1965d 100644 --- a/test/storage/main_resource_loader.test.cpp +++ b/test/storage/main_resource_loader.test.cpp @@ -35,8 +35,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CacheResponse)) { EXPECT_FALSE(bool(res.etag)); response = res; - // Now test that we get the same values as in the previous request. If we'd go to the server - // again, we'd get different values. + // Now test that we get the same values as in the previous request. If + // we'd go to the server again, we'd get different values. req2 = fs.request(resource, [&](Response res2) { req2.reset(); EXPECT_EQ(response.error, res2.error); @@ -103,15 +103,17 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CacheRevalidateSame)) { EXPECT_FALSE(bool(res.modified)); EXPECT_EQ("snowfall", *res.etag); - // The first response is stored in the cache, but it has 'must-revalidate' set. This means - // it can't return the cached response right away and we must wait for the revalidation - // request to complete. We can distinguish the cached response from the revalided response - // because the latter has an expiration date, while the cached response doesn't. + // The first response is stored in the cache, but it has + // 'must-revalidate' set. This means it can't return the cached response + // right away and we must wait for the revalidation request to complete. + // We can distinguish the cached response from the revalided response because + // the latter has an expiration date, while the cached response doesn't. req2 = fs.request(revalidateSame, [&](Response res2) { if (!gotResponse) { - // Even though we could find the response in the database, we send a revalidation - // request and get a 304 response. Since we haven't sent a reply yet, we're forcing - // notModified to be false so that implementations can continue to use the + // Even though we could find the response in the database, we + // send a revalidation request and get a 304 response. Since we + // haven't sent a reply yet, we're forcing notModified to be + // false so that implementations can continue to use the // notModified flag to skip parsing new data. gotResponse = true; EXPECT_EQ(nullptr, res2.error); @@ -123,10 +125,12 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CacheRevalidateSame)) { EXPECT_FALSE(bool(res2.modified)); EXPECT_EQ("snowfall", *res2.etag); } else { - // The test server sends a Cache-Control header with a max-age of 1 second. This - // means that our OnlineFileSource implementation will request the tile again after - // 1 second. This time, our request already had a prior response, so we don't need - // to send the data again, and instead can actually forward the notModified flag. + // The test server sends a Cache-Control header with a max-age + // of 1 second. This means that our OnlineFileSource + // implementation will request the tile again after 1 second. + // This time, our request already had a prior response, so we + // don't need to send the data again, and instead can actually + // forward the notModified flag. req2.reset(); EXPECT_EQ(nullptr, res2.error); EXPECT_TRUE(res2.notModified); @@ -165,15 +169,17 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CacheRevalidateModified)) { EXPECT_EQ(Timestamp{Seconds(1420070400)}, *res.modified); EXPECT_FALSE(res.etag); - // The first response is stored in the cache, but it has 'must-revalidate' set. This means - // it can't return the cached response right away and we must wait for the revalidation - // request to complete. We can distinguish the cached response from the revalided response - // because the latter has an expiration date, while the cached response doesn't. + // The first response is stored in the cache, but it has + // 'must-revalidate' set. This means it can't return the cached response + // right away and we must wait for the revalidation request to complete. + // We can distinguish the cached response from the revalided response because + // the latter has an expiration date, while the cached response doesn't. req2 = fs.request(revalidateModified, [&, res](Response res2) { if (!gotResponse) { - // Even though we could find the response in the database, we send a revalidation - // request and get a 304 response. Since we haven't sent a reply yet, we're forcing - // notModified to be false so that implementations can continue to use the + // Even though we could find the response in the database, we + // send a revalidation request and get a 304 response. Since we + // haven't sent a reply yet, we're forcing notModified to be + // false so that implementations can continue to use the // notModified flag to skip parsing new data. gotResponse = true; EXPECT_EQ(nullptr, res2.error); @@ -185,10 +191,12 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CacheRevalidateModified)) { EXPECT_EQ(Timestamp{Seconds(1420070400)}, *res2.modified); EXPECT_FALSE(res2.etag); } else { - // The test server sends a Cache-Control header with a max-age of 1 second. This - // means that our OnlineFileSource implementation will request the tile again after - // 1 second. This time, our request already had a prior response, so we don't need - // to send the data again, and instead can actually forward the notModified flag. + // The test server sends a Cache-Control header with a max-age + // of 1 second. This means that our OnlineFileSource + // implementation will request the tile again after 1 second. + // This time, our request already had a prior response, so we + // don't need to send the data again, and instead can actually + // forward the notModified flag. req2.reset(); EXPECT_EQ(nullptr, res2.error); EXPECT_TRUE(res2.notModified); @@ -225,7 +233,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CacheRevalidateEtag)) { EXPECT_FALSE(bool(res.modified)); EXPECT_EQ("response-1", *res.etag); - // Second request does not return the cached response, since it had Cache-Control: must-revalidate set. + // Second request does not return the cached response, since it had + // Cache-Control: must-revalidate set. req2 = fs.request(revalidateEtag, [&, res](Response res2) { req2.reset(); @@ -247,14 +256,15 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CacheRevalidateEtag)) { // Test for https://github.com/mapbox/mapbox-gl-native/issue/1369 // -// A request for http://example.com is made. This triggers a cache get. While the cache get is -// pending, the request is canceled. This removes it from pending. Then, still while the cache get -// is pending, a second request is made for the same resource. This adds an entry back to pending -// and queues another cache request, even though the first one is still pending. Now both cache -// requests resolve to misses, resulting in two HTTP requests for the same resource. The first one -// will notify as expected, the second one will have bound a DefaultFileRequest* in the lambda that -// gets invalidated by the first notify's pending.erase, and when it gets notified, the crash -// occurs. +// A request for http://example.com is made. This triggers a cache get. While +// the cache get is pending, the request is canceled. This removes it from +// pending. Then, still while the cache get is pending, a second request is made +// for the same resource. This adds an entry back to pending and queues another +// cache request, even though the first one is still pending. Now both cache +// requests resolve to misses, resulting in two HTTP requests for the same +// resource. The first one will notify as expected, the second one will have +// bound a DefaultFileRequest* in the lambda that gets invalidated by the first +// notify's pending.erase, and when it gets notified, the crash occurs. TEST(MainResourceLoader, TEST_REQUIRES_SERVER(HTTPIssue1369)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); @@ -292,8 +302,8 @@ TEST(MainResourceLoader, OptionalNonExpired) { response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(optionalResource, response, [&] { req = fs.request(optionalResource, [&](Response res) { req.reset(); @@ -324,8 +334,8 @@ TEST(MainResourceLoader, OptionalExpired) { Response response; response.data = std::make_shared("Cached value"); response.expires = util::now() - 1h; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); std::unique_ptr req; dbfs->forward(optionalResource, response, [&] { req = fs.request(optionalResource, [&](Response res) { @@ -376,7 +386,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagNotModified)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorEtag.emplace("snowfall"); @@ -387,8 +397,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagNotModified)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -413,7 +423,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagModified)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorEtag.emplace("sunshine"); @@ -424,8 +434,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshEtagModified)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -450,7 +460,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheFull)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; using namespace std::chrono_literals; @@ -460,8 +470,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheFull)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -481,13 +491,13 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheFull)) { loop.run(); } -// Test that we can make a request with a Modified field that doesn't first try to load -// from cache like a regular request +// Test that we can make a request with a Modified field that doesn't first try +// to load from cache like a regular request TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedNotModified)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorModified.emplace(Seconds(1420070400)); // January 1, 2015 @@ -498,8 +508,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedNotModified) response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -519,13 +529,13 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedNotModified) loop.run(); } -// Test that we can make a request with a Modified field that doesn't first try to load -// from cache like a regular request +// Test that we can make a request with a Modified field that doesn't first try +// to load from cache like a regular request TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedModified)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-modified"}; resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorModified.emplace(Seconds(1417392000)); // December 1, 2014 @@ -536,8 +546,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedModified)) { response.data = std::make_shared("Cached value"); response.expires = util::now() + 1h; std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -559,8 +569,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoCacheRefreshModifiedModified)) { TEST(MainResourceLoader, TEST_REQUIRES_SERVER(SetResourceTransform)) { util::RunLoop loop; MainResourceLoader resourceLoader(ResourceOptions{}, ClientOptions{}); - std::shared_ptr onlinefs = - FileSourceManager::get()->getFileSource(FileSourceType::Network, ResourceOptions{}, ClientOptions{}); + std::shared_ptr onlinefs = FileSourceManager::get()->getFileSource( + FileSourceType::Network, ResourceOptions{}, ClientOptions{}); // Translates the URL "localhost://test to http://127.0.0.1:3000/test Actor transform( @@ -615,8 +625,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(SetResourceTransform)) { TEST(MainResourceLoader, SetResourceCachePath) { util::RunLoop loop; MainResourceLoader resourceLoader(ResourceOptions{}, ClientOptions{}); - std::shared_ptr fs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr fs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); auto dbfs = std::static_pointer_cast(fs); dbfs->setDatabasePath("./new_offline.db", [&loop] { loop.stop(); }); loop.run(); @@ -627,7 +637,7 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(RespondToStaleMustRevalidate)) { util::RunLoop loop; MainResourceLoader fs(ResourceOptions{}, ClientOptions{}); - Resource resource { Resource::Unknown, "http://127.0.0.1:3000/revalidate-same" }; + Resource resource{Resource::Unknown, "http://127.0.0.1:3000/revalidate-same"}; resource.loadingMethod = Resource::LoadingMethod::CacheOnly; // using namespace std::chrono_literals; @@ -640,8 +650,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(RespondToStaleMustRevalidate)) { response.mustRevalidate = true; response.etag.emplace("snowfall"); std::unique_ptr req; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { req.reset(); @@ -670,30 +680,32 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(RespondToStaleMustRevalidate)) { loop.run(); - // Now run this request again, with the data we gathered from the previous stale/unusable - // request. We're replacing the data so that we can check that the MainResourceLoader doesn't - // attempt another database access if we already have the value. + // Now run this request again, with the data we gathered from the previous + // stale/unusable request. We're replacing the data so that we can check + // that the MainResourceLoader doesn't attempt another database access if we + // already have the value. resource.loadingMethod = Resource::LoadingMethod::NetworkOnly; resource.priorData = std::make_shared("Prior value"); req = fs.request(resource, [&](Response res) { req.reset(); ASSERT_EQ(nullptr, res.error.get()); - // Since the data was found in the cache, we're doing a revalidation request. Yet, since - // this request hasn't returned data before, we're setting notModified to false in the - // OnlineFileSource to ensure that requestors know that this is the first time they're - // seeing this data. + // Since the data was found in the cache, we're doing a revalidation + // request. Yet, since this request hasn't returned data before, we're + // setting notModified to false in the OnlineFileSource to ensure that + // requestors know that this is the first time they're seeing this data. EXPECT_FALSE(res.notModified); ASSERT_TRUE(res.data.get()); - // Ensure that it's the value that we manually inserted into the cache rather than the value - // the server returns, since we should be executing a revalidation request which doesn't - // return new data, only a 304 Not Modified response. + // Ensure that it's the value that we manually inserted into the cache + // rather than the value the server returns, since we should be + // executing a revalidation request which doesn't return new data, only + // a 304 Not Modified response. EXPECT_EQ("Prior value", *res.data); ASSERT_TRUE(res.expires); EXPECT_LE(util::now(), *res.expires); EXPECT_TRUE(res.mustRevalidate); ASSERT_TRUE(res.modified); - EXPECT_EQ(Timestamp{ Seconds(1417392000) }, *res.modified); + EXPECT_EQ(Timestamp{Seconds(1417392000)}, *res.modified); ASSERT_TRUE(res.etag); EXPECT_EQ("snowfall", *res.etag); loop.stop(); @@ -713,10 +725,10 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CachedResourceLowPriority)) { using namespace std::chrono_literals; response.expires = util::now() - 1h; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); - std::shared_ptr onlineFs = - FileSourceManager::get()->getFileSource(FileSourceType::Network, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr onlineFs = FileSourceManager::get()->getFileSource( + FileSourceType::Network, ResourceOptions{}, ClientOptions{}); // Put existing values into the cache. Resource resource1{Resource::Unknown, "http://127.0.0.1:3000/load/3", {}, Resource::LoadingMethod::All}; @@ -735,7 +747,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CachedResourceLowPriority)) { Resource nonCached0{Resource::Unknown, "http://127.0.0.1:3000/load/0", {}, Resource::LoadingMethod::All}; std::unique_ptr req0 = fs.request(nonCached0, [&](Response res) { req0.reset(); - EXPECT_EQ(online_response_counter, 0); // make sure this is responded first + EXPECT_EQ(online_response_counter, + 0); // make sure this is responded first EXPECT_EQ("Request 0", *res.data); }); @@ -743,7 +756,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CachedResourceLowPriority)) { std::unique_ptr req1 = fs.request(nonCached1, [&](Response res) { online_response_counter++; req1.reset(); - EXPECT_EQ(online_response_counter, 1); // make sure this is responded second + EXPECT_EQ(online_response_counter, + 1); // make sure this is responded second EXPECT_EQ("Request 1", *res.data); }); @@ -780,7 +794,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(CachedResourceLowPriority)) { std::unique_ptr req2 = fs.request(nonCached2, [&](Response res) { online_response_counter++; req2.reset(); - EXPECT_EQ(online_response_counter, 2); // make sure this is responded third + EXPECT_EQ(online_response_counter, + 2); // make sure this is responded third EXPECT_EQ("Request 2", *res.data); }); @@ -801,8 +816,8 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoDoubleDispatch)) { std::unique_ptr req; unsigned responseCount = 0u; - std::shared_ptr dbfs = - FileSourceManager::get()->getFileSource(FileSourceType::Database, ResourceOptions{}, ClientOptions{}); + std::shared_ptr dbfs = FileSourceManager::get()->getFileSource( + FileSourceType::Database, ResourceOptions{}, ClientOptions{}); dbfs->forward(resource, response, [&] { req = fs.request(resource, [&](Response res) { EXPECT_EQ(nullptr, res.error); @@ -827,25 +842,17 @@ TEST(MainResourceLoader, TEST_REQUIRES_SERVER(NoDoubleDispatch)) { } TEST(MainResourceLoader, ResourceOptions) { - MainResourceLoader fs( - ResourceOptions().withTileServerOptions( - TileServerOptions() - .withBaseURL("originalBaseURL") - .withUriSchemeAlias("originalAlias") - ), - ClientOptions() - ); - - fs.setResourceOptions(ResourceOptions() - .withTileServerOptions( - TileServerOptions() - .withBaseURL("updatedBaseURL") - .withUriSchemeAlias("updatedAlias") - ).clone() - ); - + MainResourceLoader fs(ResourceOptions().withTileServerOptions( + TileServerOptions().withBaseURL("originalBaseURL").withUriSchemeAlias("originalAlias")), + ClientOptions()); + + fs.setResourceOptions( + ResourceOptions() + .withTileServerOptions(TileServerOptions().withBaseURL("updatedBaseURL").withUriSchemeAlias("updatedAlias")) + .clone()); + auto updatedOptions = fs.getResourceOptions().tileServerOptions(); - + EXPECT_EQ(updatedOptions.baseURL(), "updatedBaseURL"); - EXPECT_EQ(updatedOptions.uriSchemeAlias(), "updatedAlias"); + EXPECT_EQ(updatedOptions.uriSchemeAlias(), "updatedAlias"); } diff --git a/test/storage/mbtiles_file_source.test.cpp b/test/storage/mbtiles_file_source.test.cpp index c3246844799..2153f7c7307 100644 --- a/test/storage/mbtiles_file_source.test.cpp +++ b/test/storage/mbtiles_file_source.test.cpp @@ -8,12 +8,12 @@ #include #if defined(WIN32) -# include -# ifndef PATH_MAX -# define PATH_MAX MAX_PATH -# endif /* PATH_MAX */ +#include +#ifndef PATH_MAX +#define PATH_MAX MAX_PATH +#endif /* PATH_MAX */ #else -# include +#include #endif namespace { @@ -25,8 +25,7 @@ std::string toAbsoluteURL(const std::string &fileName) { #else char *cwd = getcwd(buff, PATH_MAX + 1); #endif - std::string url - = {"mbtiles://" + std::string(cwd) + "/test/fixtures/storage/mbtiles/" + fileName}; + std::string url = {"mbtiles://" + std::string(cwd) + "/test/fixtures/storage/mbtiles/" + fileName}; assert(url.size() <= PATH_MAX); return url; } @@ -70,13 +69,13 @@ TEST(MBTilesFileSource, NonExistentFile) { std::unique_ptr req = mbtiles.request( {Resource::Unknown, toAbsoluteURL("does_not_exist")}, [&](Response res) { - req.reset(); - ASSERT_NE(nullptr, res.error); - EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); - EXPECT_NE((res.error->message).find("path not found"), std::string::npos); - ASSERT_FALSE(res.data.get()); - loop.stop(); - }); + req.reset(); + ASSERT_NE(nullptr, res.error); + EXPECT_EQ(Response::Error::Reason::NotFound, res.error->reason); + EXPECT_NE((res.error->message).find("path not found"), std::string::npos); + ASSERT_FALSE(res.data.get()); + loop.stop(); + }); loop.run(); } @@ -93,8 +92,7 @@ TEST(MBTilesFileSource, TileJSON) { EXPECT_EQ(nullptr, res.error); ASSERT_TRUE(res.data.get()); // basic test that TileJSON included a tile URL - EXPECT_NE((*res.data).find("geography-class-png.mbtiles?file={x}/{y}/{z}"), - std::string::npos); + EXPECT_NE((*res.data).find("geography-class-png.mbtiles?file={x}/{y}/{z}"), std::string::npos); loop.stop(); }); @@ -108,7 +106,8 @@ TEST(MBTilesFileSource, Tile) { MBTilesFileSource mbtiles(ResourceOptions::Default(), ClientOptions()); std::unique_ptr req = mbtiles.request( - Resource::tile(toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 0, Tileset::Scheme::XYZ), + Resource::tile( + toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 0, Tileset::Scheme::XYZ), [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); @@ -127,7 +126,8 @@ TEST(MBTilesFileSource, NonExistentTile) { MBTilesFileSource mbtiles(ResourceOptions::Default(), ClientOptions()); std::unique_ptr req = mbtiles.request( - Resource::tile(toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 4, Tileset::Scheme::XYZ), + Resource::tile( + toAbsoluteURL("geography-class-png.mbtiles?file={z}/{x}/{y}.png"), 1.0, 0, 0, 4, Tileset::Scheme::XYZ), [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); @@ -138,5 +138,3 @@ TEST(MBTilesFileSource, NonExistentTile) { loop.run(); } - - diff --git a/test/storage/offline.test.cpp b/test/storage/offline.test.cpp index eb7cbf705b1..99ed8ff70d6 100644 --- a/test/storage/offline.test.cpp +++ b/test/storage/offline.test.cpp @@ -6,13 +6,13 @@ using namespace mbgl; using SourceType = mbgl::style::SourceType; - TEST(OfflineTilePyramidRegionDefinition, EncodeDecode) { - OfflineTilePyramidRegionDefinition region("maptiler://style", LatLngBounds::hull({ 37.6609, -122.5744 }, { 37.8271, -122.3204 }), 0, 20, 1.0, true); + OfflineTilePyramidRegionDefinition region( + "maptiler://style", LatLngBounds::hull({37.6609, -122.5744}, {37.8271, -122.3204}), 0, 20, 1.0, true); auto encoded = encodeOfflineRegionDefinition(region); auto decoded = decodeOfflineRegionDefinition(encoded).get(); - + EXPECT_EQ(decoded.styleURL, region.styleURL); EXPECT_EQ(decoded.minZoom, region.minZoom); EXPECT_EQ(decoded.maxZoom, region.maxZoom); @@ -27,7 +27,7 @@ TEST(OfflineGeometryRegionDefinition, EncodeDecode) { auto encoded = encodeOfflineRegionDefinition(region); auto decoded = decodeOfflineRegionDefinition(encoded).get(); - + EXPECT_EQ(decoded.styleURL, region.styleURL); EXPECT_EQ(decoded.minZoom, region.minZoom); EXPECT_EQ(decoded.maxZoom, region.maxZoom); diff --git a/test/storage/offline_database.test.cpp b/test/storage/offline_database.test.cpp index 297211610ea..2ebfce09316 100644 --- a/test/storage/offline_database.test.cpp +++ b/test/storage/offline_database.test.cpp @@ -47,41 +47,41 @@ static std::shared_ptr randomString(size_t size) { } static FixtureLog::Message error(ResultCode code, const char* message) { - return { EventSeverity::Error, Event::Database, static_cast(code), message }; + return {EventSeverity::Error, Event::Database, static_cast(code), message}; } static MBGL_UNUSED FixtureLog::Message warning(ResultCode code, const char* message) { - return { EventSeverity::Warning, Event::Database, static_cast(code), message }; + return {EventSeverity::Warning, Event::Database, static_cast(code), message}; } static int databasePageCount(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma page_count" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma page_count"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } static int databaseUserVersion(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma user_version" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma user_version"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } static std::string databaseJournalMode(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma journal_mode" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma journal_mode"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } static int databaseSyncMode(const std::string& path) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); - mapbox::sqlite::Statement stmt{ db, "pragma synchronous" }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, "pragma synchronous"}; + mapbox::sqlite::Query query{stmt}; query.run(); return query.get(0); } @@ -89,8 +89,8 @@ static int databaseSyncMode(const std::string& path) { static std::vector databaseTableColumns(const std::string& path, const std::string& name) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(path, mapbox::sqlite::ReadOnly); const auto sql = std::string("pragma table_info(") + name + ")"; - mapbox::sqlite::Statement stmt{ db, sql.c_str() }; - mapbox::sqlite::Query query{ stmt }; + mapbox::sqlite::Statement stmt{db, sql.c_str()}; + mapbox::sqlite::Query query{stmt}; std::vector columns; while (query.run()) { columns.push_back(query.get(1)); @@ -108,7 +108,7 @@ static int databaseAutoVacuum(const std::string& path) { namespace fixture { -const Resource resource{ Resource::Style, "maptiler://test" }; +const Resource resource{Resource::Style, "maptiler://test"}; const Resource tile = Resource::tile("maptiler://test", 1, 0, 0, 0, Tileset::Scheme::XYZ); const Response response = [] { Response res; @@ -124,7 +124,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(Create)) { FixtureLog log; deleteDatabaseFiles(); OfflineDatabase db(filename, fixture::tileServerOptions); - EXPECT_FALSE(bool(db.get({ Resource::Unknown, "maptiler://test" }))); + EXPECT_FALSE(bool(db.get({Resource::Unknown, "maptiler://test"}))); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -135,34 +135,38 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { deleteDatabaseFiles(); test::SQLite3TestFS fs; - // Opening the database will fail because our mock VFS returns a SQLITE_CANTOPEN error because - // it is not allowed to create the file. The OfflineDatabase object should handle this gracefully - // and treat it like an empty cache that can't be written to. + // Opening the database will fail because our mock VFS returns a + // SQLITE_CANTOPEN error because it is not allowed to create the file. The + // OfflineDatabase object should handle this gracefully and treat it like an + // empty cache that can't be written to. fs.allowFileCreate(false); OfflineDatabase db(filename_test_fs, fixture::tileServerOptions); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't open database: unable to open database file"))); EXPECT_EQ(0u, log.uncheckedCount()); - // We can try to insert things into the cache, but since the cache database isn't open, it won't be stored. - for (const auto& res : { fixture::resource, fixture::tile }) { + // We can try to insert things into the cache, but since the cache database + // isn't open, it won't be stored. + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(false, uint64_t(0)), db.put(res, fixture::response)); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't write resource: unable to open database file"))); EXPECT_EQ(0u, log.uncheckedCount()); } - // We can also still "query" the database even though it is not open, and we will always get an empty result. - for (const auto& res : { fixture::resource, fixture::tile }) { + // We can also still "query" the database even though it is not open, and we + // will always get an empty result. + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_FALSE(bool(db.get(res))); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't update timestamp: unable to open database file"))); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't read resource: unable to open database file"))); EXPECT_EQ(0u, log.uncheckedCount()); } - // Now, we're "freeing up" some space on the disk, and try to insert and query again. This time, we should - // be opening the datbase, creating the schema, and writing the data so that we can retrieve it again. + // Now, we're "freeing up" some space on the disk, and try to insert and + // query again. This time, we should be opening the datbase, creating the + // schema, and writing the data so that we can retrieve it again. fs.allowFileCreate(true); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); auto result = db.get(res); EXPECT_EQ(0u, log.uncheckedCount()); @@ -170,12 +174,13 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { EXPECT_EQ("first", *result->data); } - // Next, set the file system to read only mode and try to read the data again. While we can't - // write anymore, we should still be able to read, and the query that tries to update the last - // accessed timestamp may fail without crashing. + // Next, set the file system to read only mode and try to read the data + // again. While we can't write anymore, we should still be able to read, and + // the query that tries to update the last accessed timestamp may fail + // without crashing. fs.allowFileCreate(false); fs.setWriteLimit(0); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { auto result = db.get(res); EXPECT_EQ(1u, log.count(warning(ResultCode::CantOpen, "Can't update timestamp: unable to open database file"))); EXPECT_EQ(0u, log.uncheckedCount()); @@ -185,12 +190,12 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { } fs.setDebug(false); - // We're allowing SQLite to create a journal file, but restrict the number of bytes it - // can write so that it can start writing the journal file, but eventually fails during the - // timestamp update. + // We're allowing SQLite to create a journal file, but restrict the number + // of bytes it can write so that it can start writing the journal file, but + // eventually fails during the timestamp update. fs.allowFileCreate(true); fs.setWriteLimit(8192); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { auto result = db.get(res); EXPECT_EQ(1u, log.count(warning(ResultCode::Full, "Can't update timestamp: database or disk is full"))); EXPECT_EQ(0u, log.uncheckedCount()); @@ -198,11 +203,11 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(CreateFail)) { EXPECT_EQ("first", *result->data); } - // Lastly, we're disabling all I/O to simulate a backgrounded app that is restricted from doing - // any disk I/O at all. + // Lastly, we're disabling all I/O to simulate a backgrounded app that is + // restricted from doing any disk I/O at all. fs.setWriteLimit(-1); fs.allowIO(false); - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { // First, try reading. auto result = db.get(res); EXPECT_EQ(1u, log.count(warning(ResultCode::Auth, "Can't update timestamp: authorization denied"))); @@ -231,15 +236,13 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(SchemaVersion)) { db.exec("PRAGMA user_version = 1"); } - { - OfflineDatabase db(filename, fixture::tileServerOptions); - } + { OfflineDatabase db(filename, fixture::tileServerOptions); } EXPECT_EQ(6, databaseUserVersion(filename)); OfflineDatabase db(filename, fixture::tileServerOptions); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -257,13 +260,18 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(Invalid)) { util::write_file(filename, "this is an invalid file"); OfflineDatabase db(filename, fixture::tileServerOptions); - // Checking two possibilities for the error string because it apparently changes between SQLite versions. - EXPECT_EQ(1u, log.count(error(ResultCode::NotADB, "Can't open database: file is encrypted or is not a database"), true) + - log.count(error(ResultCode::NotADB, "Can't open database: file is not a database"), true)); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + // Checking two possibilities for the error string because it apparently + // changes between SQLite versions. + EXPECT_EQ( + 1u, + log.count(error(ResultCode::NotADB, "Can't open database: file is encrypted or is not a database"), true) + + log.count(error(ResultCode::NotADB, "Can't open database: file is not a database"), true)); + EXPECT_EQ( + 1u, + log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"})); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -277,7 +285,7 @@ TEST(OfflineDatabase, PutDoesNotStoreConnectionErrors) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Unknown, "http://example.com/" }; + Resource resource{Resource::Unknown, "http://example.com/"}; Response response; response.error = std::make_unique(Response::Error::Reason::Connection); @@ -291,7 +299,7 @@ TEST(OfflineDatabase, PutDoesNotStoreServerErrors) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Unknown, "http://example.com/" }; + Resource resource{Resource::Unknown, "http://example.com/"}; Response response; response.error = std::make_unique(Response::Error::Reason::Server); @@ -305,7 +313,7 @@ TEST(OfflineDatabase, PutResource) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Style, "http://example.com/" }; + Resource resource{Resource::Style, "http://example.com/"}; Response response; response.data = std::make_shared("first"); @@ -364,14 +372,8 @@ TEST(OfflineDatabase, PutTile) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Tile, "http://example.com/" }; - resource.tileData = Resource::TileData { - "http://example.com/", - 1, - 0, - 0, - 0 - }; + Resource resource{Resource::Tile, "http://example.com/"}; + resource.tileData = Resource::TileData{"http://example.com/", 1, 0, 0, 0}; Response response; response.data = std::make_shared("first"); @@ -399,7 +401,7 @@ TEST(OfflineDatabase, PutResourceNoContent) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Style, "http://example.com/" }; + Resource resource{Resource::Style, "http://example.com/"}; Response response; response.noContent = true; @@ -416,14 +418,8 @@ TEST(OfflineDatabase, PutTileNotFound) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - Resource resource { Resource::Tile, "http://example.com/" }; - resource.tileData = Resource::TileData { - "http://example.com/", - 1, - 0, - 0, - 0 - }; + Resource resource{Resource::Tile, "http://example.com/"}; + resource.tileData = Resource::TileData{"http://example.com/", 1, 0, 0, 0}; Response response; response.noContent = true; @@ -439,37 +435,37 @@ TEST(OfflineDatabase, PutTileNotFound) { TEST(OfflineDatabase, CreateRegion) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); EXPECT_EQ(0u, log.uncheckedCount()); region->getDefinition().match( - [&](OfflineTilePyramidRegionDefinition& def) { - EXPECT_EQ(definition.styleURL, def.styleURL); - EXPECT_EQ(definition.bounds, def.bounds); - EXPECT_EQ(definition.minZoom, def.minZoom); - EXPECT_EQ(definition.maxZoom, def.maxZoom); - EXPECT_EQ(definition.pixelRatio, def.pixelRatio); - EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); - }, [](auto&) { - EXPECT_FALSE(false); - } - ); + [&](OfflineTilePyramidRegionDefinition& def) { + EXPECT_EQ(definition.styleURL, def.styleURL); + EXPECT_EQ(definition.bounds, def.bounds); + EXPECT_EQ(definition.minZoom, def.minZoom); + EXPECT_EQ(definition.maxZoom, def.maxZoom); + EXPECT_EQ(definition.pixelRatio, def.pixelRatio); + EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); + }, + [](auto&) { EXPECT_FALSE(false); }); EXPECT_EQ(metadata, region->getMetadata()); } TEST(OfflineDatabase, UpdateMetadata) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); - OfflineRegionMetadata newmetadata {{ 4, 5, 6 }}; + OfflineRegionMetadata newmetadata{{4, 5, 6}}; db.updateMetadata(region->getID(), newmetadata); auto regions = db.listRegions().value(); EXPECT_EQ(regions.at(0).getMetadata(), newmetadata); @@ -480,8 +476,9 @@ TEST(OfflineDatabase, UpdateMetadata) { TEST(OfflineDatabase, ListRegions) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); @@ -491,17 +488,15 @@ TEST(OfflineDatabase, ListRegions) { EXPECT_EQ(region->getID(), regions.at(0).getID()); regions.at(0).getDefinition().match( - [&](OfflineTilePyramidRegionDefinition& def) { - EXPECT_EQ(definition.styleURL, def.styleURL); - EXPECT_EQ(definition.bounds, def.bounds); - EXPECT_EQ(definition.minZoom, def.minZoom); - EXPECT_EQ(definition.maxZoom, def.maxZoom); - EXPECT_EQ(definition.pixelRatio, def.pixelRatio); - EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); - }, - [&](auto&) { - EXPECT_FALSE(false); - }); + [&](OfflineTilePyramidRegionDefinition& def) { + EXPECT_EQ(definition.styleURL, def.styleURL); + EXPECT_EQ(definition.bounds, def.bounds); + EXPECT_EQ(definition.minZoom, def.minZoom); + EXPECT_EQ(definition.maxZoom, def.maxZoom); + EXPECT_EQ(definition.pixelRatio, def.pixelRatio); + EXPECT_EQ(definition.includeIdeographs, def.includeIdeographs); + }, + [&](auto&) { EXPECT_FALSE(false); }); EXPECT_EQ(metadata, regions.at(0).getMetadata()); EXPECT_EQ(0u, log.uncheckedCount()); @@ -510,13 +505,15 @@ TEST(OfflineDatabase, ListRegions) { TEST(OfflineDatabase, GetRegionDefinition) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false}; + OfflineRegionMetadata metadata{{1, 2, 3}}; EXPECT_EQ(0u, log.uncheckedCount()); auto region = db.createRegion(definition, metadata); - db.getRegionDefinition(region->getID())->match( + db.getRegionDefinition(region->getID()) + ->match( [&](OfflineTilePyramidRegionDefinition& result) { EXPECT_EQ(definition.styleURL, result.styleURL); EXPECT_EQ(definition.bounds, result.bounds); @@ -525,10 +522,7 @@ TEST(OfflineDatabase, GetRegionDefinition) { EXPECT_EQ(definition.pixelRatio, result.pixelRatio); EXPECT_EQ(definition.includeIdeographs, result.includeIdeographs); }, - [&](auto&) { - EXPECT_FALSE(false); - } - ); + [&](auto&) { EXPECT_FALSE(false); }); } // Disabled due to flakiness: https://github.com/mapbox/mapbox-gl-native/issues/14966 @@ -540,9 +534,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { return util::read_file(filename).size(); }; - { - OfflineDatabase db(filename, fixture::tileServerOptions); - } + { OfflineDatabase db(filename, fixture::tileServerOptions); } size_t initialSize = util::read_file(filename).size(); size_t maximumSize = 50 * 1024 * 1024; @@ -554,20 +546,23 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { OfflineDatabase db(filename, fixture::tileServerOptions); db.setMaximumAmbientCacheSize(maximumSize); // 50 MB - OfflineTilePyramidRegionDefinition definition{ "maptiler://masp/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "maptiler://masp/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region = db.createRegion(definition, metadata); // Add 100 MB of resources (50/50 ambient/region) for (unsigned i = 0; i < 250; ++i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambientTile, response); const Resource ambientStyle = Resource::style("maptiler://maps/ambient_style_" + std::to_string(i)); db.put(ambientStyle, response); - const Resource regionTile = Resource::tile("maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource regionTile = Resource::tile( + "maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.putRegionResource(region->getID(), regionTile, response); const Resource regionStyle = Resource::style("maptiler://maps/region_style_" + std::to_string(i)); @@ -622,7 +617,8 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { // Add ~50 MB in ambient cache data. for (unsigned i = 0; i < 250; ++i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambientTile, response); const Resource ambientStyle = Resource::style("maptiler://mas/ambient_style_" + std::to_string(i)); @@ -651,7 +647,8 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DISABLED_MaximumAmbientCacheSize)) { db.setMaximumAmbientCacheSize(0); for (unsigned i = 0; i < 5; ++i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambientTile, response); ASSERT_FALSE(db.get(ambientTile)); @@ -686,9 +683,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DeleteRegion)) { FixtureLog log; deleteDatabaseFiles(); - { - OfflineDatabase dbCreate(filename, fixture::tileServerOptions); - } + { OfflineDatabase dbCreate(filename, fixture::tileServerOptions); } size_t initialSize = util::read_file(filename).size(); @@ -698,15 +693,18 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DeleteRegion)) { OfflineDatabase db(filename, fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition{ "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region1 = db.createRegion(definition, metadata); auto region2 = db.createRegion(definition, metadata); OfflineRegionStatus status; - db.putRegionResources(region1->getID(), generateResources("maptiler://tiles/tiles/tile_1", "maptiler://maps/style_1"), status); - db.putRegionResources(region2->getID(), generateResources("maptiler://tiles/tiles/tile_2", "maptiler://maps/style_2"), status); + db.putRegionResources( + region1->getID(), generateResources("maptiler://tiles/tiles/tile_1", "maptiler://maps/style_1"), status); + db.putRegionResources( + region2->getID(), generateResources("maptiler://tiles/tiles/tile_2", "maptiler://maps/style_2"), status); const size_t sizeWithTwoRegions = util::read_file(filename).size(); db.runPackDatabaseAutomatically(false); @@ -756,7 +754,8 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(Pack)) { response.data = randomString(512 * 1024); for (unsigned i = 0; i < 50; ++i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(tile, response); const Resource style = Resource::style("maptiler://maps/style_" + std::to_string(i)); @@ -786,20 +785,24 @@ TEST(OfflineDatabase, MapboxTileLimitExceeded) { response.data = randomString(4096); auto insertAmbientTile = [&](unsigned i) { - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/ambient_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambientTile, response); }; auto insertRegionTile = [&](int64_t regionID, uint64_t i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/region_tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.putRegionResource(regionID, tile, response); }; - OfflineTilePyramidRegionDefinition definition1{ "maptiler://maps/style1", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata1{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition1{ + "maptiler://maps/style1", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata1{{1, 2, 3}}; - OfflineTilePyramidRegionDefinition definition2{ "maptiler://maps/style2", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata2{{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition2{ + "maptiler://maps/style2", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata2{{1, 2, 3}}; auto region1 = db.createRegion(definition1, metadata1); auto region2 = db.createRegion(definition2, metadata2); @@ -883,24 +886,28 @@ TEST(OfflineDatabase, Invalidate) { response.mustRevalidate = false; response.expires = util::now() + 1h; - const Resource ambientTile = Resource::tile("maptiler://tiles/tiles/tile_ambient", 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource ambientTile = Resource::tile( + "maptiler://tiles/tiles/tile_ambient", 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(ambientTile, response); - const Resource ambientStyle = Resource::style("maptiler://maps/style_ambient"); + const Resource ambientStyle = Resource::style("maptiler://maps/style_ambient"); db.put(ambientStyle, response); - OfflineTilePyramidRegionDefinition definition { "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true }; - OfflineRegionMetadata metadata {{ 1, 2, 3 }}; + OfflineTilePyramidRegionDefinition definition{ + "maptiler://maps/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; + OfflineRegionMetadata metadata{{1, 2, 3}}; auto region1 = db.createRegion(definition, metadata); - const Resource region1Tile = Resource::tile("maptiler://tiles/tiles/tile_offline_region1", 1.0, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource region1Tile = Resource::tile( + "maptiler://tiles/tiles/tile_offline_region1", 1.0, 0, 0, 0, Tileset::Scheme::XYZ); db.putRegionResource(region1->getID(), region1Tile, response); const Resource region1Style = Resource::style("maptiler://maps/style_offline_region1"); db.putRegionResource(region1->getID(), region1Style, response); auto region2 = db.createRegion(definition, metadata); - const Resource region2Tile = Resource::tile("maptiler://tiles/tiles/tile_offline_region2", 1.0, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource region2Tile = Resource::tile( + "maptiler://tiles/tiles/tile_offline_region2", 1.0, 0, 0, 0, Tileset::Scheme::XYZ); db.putRegionResource(region2->getID(), region2Tile, response); const Resource region2Style = Resource::style("maptiler://maps/style_offline_region2"); @@ -967,9 +974,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(ClearAmbientCache)) { FixtureLog log; deleteDatabaseFiles(); - { - OfflineDatabase dbCreate(filename, fixture::tileServerOptions); - } + { OfflineDatabase dbCreate(filename, fixture::tileServerOptions); } size_t initialSize = util::read_file(filename).size(); @@ -980,7 +985,8 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(ClearAmbientCache)) { OfflineDatabase db(filename, fixture::tileServerOptions); for (unsigned i = 0; i < 50; ++i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.put(tile, response); const Resource style = Resource::style("maptiler://maps/style_" + std::to_string(i)); @@ -997,7 +1003,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(ClearAmbientCache)) { TEST(OfflineDatabase, CreateRegionInfiniteMaxZoom) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, false }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, false}; OfflineRegionMetadata metadata; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); @@ -1105,7 +1111,8 @@ TEST(OfflineDatabase, OfflineRegionDoesNotAffectAmbientCacheSize) { // 1MB of offline region data. for (std::size_t i = 0; i < 5; ++i) { - const Resource tile = Resource::tile("maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); + const Resource tile = Resource::tile( + "maptiler://tiles/tiles/tile_" + std::to_string(i), 1, 0, 0, 0, Tileset::Scheme::XYZ); db.putRegionResource(region->getID(), tile, response); const Resource style = Resource::style("maptiler://maps/style_" + std::to_string(i)); @@ -1126,7 +1133,7 @@ TEST(OfflineDatabase, PutRegionResourceDoesNotEvict) { OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, true}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1154,7 +1161,7 @@ TEST(OfflineDatabase, PutFailsWhenEvictionInsuffices) { EXPECT_FALSE(db.put(Resource::style("http://example.com/big"), big).first); - EXPECT_EQ(1u, log.count({ EventSeverity::Info, Event::Database, -1, "Unable to make space for entry" })); + EXPECT_EQ(1u, log.count({EventSeverity::Info, Event::Database, -1, "Unable to make space for entry"})); EXPECT_EQ(0u, log.uncheckedCount()); EXPECT_FALSE(bool(db.get(Resource::style("http://example.com/big")))); @@ -1165,7 +1172,8 @@ TEST(OfflineDatabase, PutFailsWhenEvictionInsuffices) { TEST(OfflineDatabase, GetRegionCompletedStatus) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false }; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, false}; OfflineRegionMetadata metadata; auto region = db.createRegion(definition, metadata); ASSERT_TRUE(region); @@ -1189,7 +1197,8 @@ TEST(OfflineDatabase, GetRegionCompletedStatus) { EXPECT_EQ(0u, status2->completedTileCount); EXPECT_EQ(0u, status2->completedTileSize); - uint64_t tileSize = db.putRegionResource(region->getID(), Resource::tile("http://example.com/", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), response); + uint64_t tileSize = db.putRegionResource( + region->getID(), Resource::tile("http://example.com/", 1.0, 0, 0, 0, Tileset::Scheme::XYZ), response); auto status3 = db.getRegionCompletedStatus(region->getID()); ASSERT_TRUE(status3); @@ -1206,7 +1215,7 @@ TEST(OfflineDatabase, HasRegionResource) { OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, true}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1232,18 +1241,12 @@ TEST(OfflineDatabase, HasRegionResourceTile) { OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, false }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, false}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); - Resource resource { Resource::Tile, "http://example.com/" }; - resource.tileData = Resource::TileData { - "http://example.com/", - 1, - 0, - 0, - 0 - }; + Resource resource{Resource::Tile, "http://example.com/"}; + resource.tileData = Resource::TileData{"http://example.com/", 1, 0, 0, 0}; Response response; response.data = std::make_shared("first"); @@ -1260,13 +1263,13 @@ TEST(OfflineDatabase, HasRegionResourceTile) { EXPECT_EQ(5, *(db.hasRegionResource(resource))); EXPECT_EQ(0u, log.uncheckedCount()); - } TEST(OfflineDatabase, OfflineMapboxTileCount) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); - OfflineTilePyramidRegionDefinition definition { "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0 , true}; + OfflineTilePyramidRegionDefinition definition{ + "http://example.com/style", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 2.0, true}; OfflineRegionMetadata metadata; auto region1 = db.createRegion(definition, metadata); @@ -1323,13 +1326,12 @@ TEST(OfflineDatabase, OfflineMapboxTileCount) { EXPECT_EQ(0u, log.uncheckedCount()); } - TEST(OfflineDatabase, BatchInsertion) { FixtureLog log; OfflineDatabase db(":memory:", fixture::tileServerOptions); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, true}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1357,7 +1359,7 @@ TEST(OfflineDatabase, BatchInsertionMapboxTileCountExceeded) { db.setOfflineMapboxTileCountLimit(1); db.setMaximumAmbientCacheSize(1024 * 100); - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::world(), 0, INFINITY, 1.0, false }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::world(), 0, INFINITY, 1.0, false}; auto region = db.createRegion(definition, OfflineRegionMetadata()); ASSERT_TRUE(region); @@ -1404,8 +1406,7 @@ TEST(OfflineDatabase, MigrateFromV2Schema) { } EXPECT_EQ(6, databaseUserVersion(filename)); - EXPECT_LT(databasePageCount(filename), - databasePageCount("test/fixtures/offline_database/v2.db")); + EXPECT_LT(databasePageCount(filename), databasePageCount("test/fixtures/offline_database/v2.db")); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1432,7 +1433,8 @@ TEST(OfflineDatabase, MigrateFromV3Schema) { } TEST(OfflineDatabase, MigrateFromV4Schema) { - // v4.db is a v4 database, migrated from v2 & v3. This database used `journal_mode = WAL` and `synchronous = NORMAL`. + // v4.db is a v4 database, migrated from v2 & v3. This database used + // `journal_mode = WAL` and `synchronous = NORMAL`. FixtureLog log; deleteDatabaseFiles(); util::copyFile(filename, "test/fixtures/offline_database/v4.db"); @@ -1458,7 +1460,6 @@ TEST(OfflineDatabase, MigrateFromV4Schema) { EXPECT_EQ(0u, log.uncheckedCount()); } - TEST(OfflineDatabase, MigrateFromV5Schema) { // v5.db is a v5 database, migrated from v2, v3 & v4. FixtureLog log; @@ -1534,15 +1535,28 @@ TEST(OfflineDatabase, DowngradeSchema) { EXPECT_EQ(6, databaseUserVersion(filename)); - EXPECT_EQ((std::vector{ "id", "url_template", "pixel_ratio", "z", "x", "y", - "expires", "modified", "etag", "data", "compressed", - "accessed", "must_revalidate" }), + EXPECT_EQ((std::vector{"id", + "url_template", + "pixel_ratio", + "z", + "x", + "y", + "expires", + "modified", + "etag", + "data", + "compressed", + "accessed", + "must_revalidate"}), databaseTableColumns(filename, "tiles")); - EXPECT_EQ((std::vector{ "id", "url", "kind", "expires", "modified", "etag", "data", - "compressed", "accessed", "must_revalidate" }), - databaseTableColumns(filename, "resources")); + EXPECT_EQ( + (std::vector{ + "id", "url", "kind", "expires", "modified", "etag", "data", "compressed", "accessed", "must_revalidate"}), + databaseTableColumns(filename, "resources")); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, + log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1554,11 +1568,13 @@ TEST(OfflineDatabase, CorruptDatabaseOnOpen) { // This database is corrupt in a way that will prevent opening the database. OfflineDatabase db(filename, fixture::tileServerOptions); EXPECT_EQ(1u, log.count(error(ResultCode::Corrupt, "Can't open database: database disk image is malformed"), true)); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, + log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"})); EXPECT_EQ(0u, log.uncheckedCount()); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -1573,22 +1589,24 @@ TEST(OfflineDatabase, CorruptDatabaseOnQuery) { util::deleteFile(filename); util::copyFile(filename, "test/fixtures/offline_database/corrupt-delayed.db"); - // This database is corrupt in a way that won't manifest itself until we start querying it, - // so just opening it will not cause an error. + // This database is corrupt in a way that won't manifest itself until we + // start querying it, so just opening it will not cause an error. OfflineDatabase db(filename, fixture::tileServerOptions); - // Just opening this corrupt database should not have produced an error yet, since - // PRAGMA user_version still succeeds with this database. + // Just opening this corrupt database should not have produced an error yet, + // since PRAGMA user_version still succeeds with this database. EXPECT_EQ(0u, log.uncheckedCount()); // The first request fails because the database is corrupt and has to be recreated. EXPECT_EQ(std::nullopt, db.get(fixture::tile)); EXPECT_EQ(1u, log.count(error(ResultCode::Corrupt, "Can't read resource: database disk image is malformed"), true)); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, + log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"})); EXPECT_EQ(0u, log.uncheckedCount()); // Now try inserting and reading back to make sure we have a valid database. - for (const auto& res : { fixture::resource, fixture::tile }) { + for (const auto& res : {fixture::resource, fixture::tile}) { EXPECT_EQ(std::make_pair(true, uint64_t(5)), db.put(res, fixture::response)); EXPECT_EQ(0u, log.uncheckedCount()); auto result = db.get(res); @@ -1609,7 +1627,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DisallowedIO)) { // First, create a region object so that we can try deleting it later. OfflineTilePyramidRegionDefinition definition( - "maptiler://maps/style", LatLngBounds::hull({ 37.66, -122.57 }, { 37.83, -122.32 }), 0, 8, 2, false); + "maptiler://maps/style", LatLngBounds::hull({37.66, -122.57}, {37.83, -122.32}), 0, 8, 2, false); auto region = db.createRegion(definition, {}); ASSERT_TRUE(region); @@ -1651,7 +1669,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(DisallowedIO)) { EXPECT_EQ(0u, log.uncheckedCount()); OfflineRegionStatus status; - db.putRegionResources(region->getID(), { std::make_tuple(fixture::resource, fixture::response) }, status); + db.putRegionResources(region->getID(), {std::make_tuple(fixture::resource, fixture::response)}, status); EXPECT_EQ(1u, log.count(warning(ResultCode::Auth, "Can't write region resources: authorization denied"))); EXPECT_EQ(0u, log.uncheckedCount()); @@ -1681,15 +1699,15 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegion_New) { OfflineDatabase db(":memory:", fixture::tileServerOptions); EXPECT_EQ(0u, db.listRegions()->size()); - + OfflineDatabase db_sideload(filename_sideload, fixture::tileServerOptions); auto newRegionsCount = db_sideload.listRegions()->size(); - + auto result = db.mergeDatabase(filename_sideload); EXPECT_EQ(newRegionsCount, db.listRegions()->size()); auto regionId = result->front().getID(); - auto status = db.getRegionCompletedStatus(regionId); + auto status = db.getRegionCompletedStatus(regionId); EXPECT_EQ(398u, status->completedResourceCount); EXPECT_EQ(5u, status->completedTileCount); } @@ -1704,10 +1722,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithSingleRegion_Update)) { std::string tileURL = "maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg"; OfflineDatabase db1(filename_sideload, fixture::tileServerOptions); - auto originalTile = db1.getRegionResource( - Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); + auto originalTile = db1.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); auto originalStamp = originalTile->first.modified; - + OfflineDatabase db(filename, fixture::tileServerOptions); auto regions = db.listRegions(); EXPECT_EQ(1u, db.listRegions()->size()); @@ -1720,10 +1737,9 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithSingleRegion_Update)) EXPECT_EQ(395u, status->completedResourceCount); EXPECT_EQ(2u, status->completedTileCount); - //Verify the modified timestamp matches the tile in the sideloaded db. - auto updatedTile = db.getRegionResource( - Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); - + // Verify the modified timestamp matches the tile in the sideloaded db. + auto updatedTile = db.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); + auto updatedStamp = updatedTile->first.modified; EXPECT_EQ(*originalStamp, *updatedStamp); } @@ -1732,24 +1748,24 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithSingleRegion_Update)) TEST(OfflineDatabase, MergeDatabaseWithSingleRegion_NoUpdate) { deleteDatabaseFiles(); util::deleteFile(filename_sideload); - - //Swap sideload/main database from update test and ensure that an older tile is not copied over + + // Swap sideload/main database from update test and ensure that an older tile is not copied over util::copyFile(filename_sideload, "test/fixtures/offline_database/satellite_test.db"); util::copyFile(filename, "test/fixtures/offline_database/sideload_sat.db"); OfflineDatabase db(filename, fixture::tileServerOptions); - + std::string tileURL = "maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg"; auto originalTile = db.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); auto originalStamp = originalTile->first.modified; - + auto result = db.mergeDatabase(filename_sideload); EXPECT_EQ(1u, result->size()); EXPECT_EQ(2u, db.listRegions()->size()); - auto updatedTile = db.getRegionResource(Resource::tile(tileURL,1, 0, 0, 1, Tileset::Scheme::XYZ)); + auto updatedTile = db.getRegionResource(Resource::tile(tileURL, 1, 0, 0, 1, Tileset::Scheme::XYZ)); - //Verify the modified timestamp matches the tile in the main db. + // Verify the modified timestamp matches the tile in the main db. EXPECT_EQ(originalStamp, updatedTile->first.modified); } @@ -1760,12 +1776,15 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegion_AmbientTiles) { OfflineDatabase db(":memory:", fixture::tileServerOptions); auto result = db.mergeDatabase(filename_sideload); - EXPECT_TRUE(bool(db.hasRegionResource(Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 0, 1, Tileset::Scheme::XYZ)))); + EXPECT_TRUE(bool(db.hasRegionResource( + Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 0, 1, Tileset::Scheme::XYZ)))); - //Ambient resources should not be copied + // Ambient resources should not be copied EXPECT_FALSE(bool(db.hasRegionResource(Resource::style("maptiler://maps/streets")))); - EXPECT_FALSE(bool(db.hasRegionResource(Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 1, 2, Tileset::Scheme::XYZ)))); - EXPECT_FALSE(bool(db.hasRegionResource(Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 1, 1, 2, Tileset::Scheme::XYZ)))); + EXPECT_FALSE(bool(db.hasRegionResource( + Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 0, 1, 2, Tileset::Scheme::XYZ)))); + EXPECT_FALSE(bool(db.hasRegionResource( + Resource::tile("maptiler://tiles/tiles/satellite/{z}/{x}/{y}{ratio}.jpg", 1, 1, 1, 2, Tileset::Scheme::XYZ)))); } TEST(OfflineDatabase, MergeDatabaseWithMultipleRegions_New) { @@ -1778,7 +1797,7 @@ TEST(OfflineDatabase, MergeDatabaseWithMultipleRegions_New) { auto result = db.mergeDatabase(filename_sideload); EXPECT_EQ(2u, result->size()); EXPECT_EQ(2u, db.listRegions()->size()); - + auto region1Id = result->front().getID(); auto status = db.getRegionCompletedStatus(region1Id); EXPECT_EQ(398u, status->completedResourceCount); @@ -1812,7 +1831,7 @@ TEST(OfflineDatabase, MergeDatabaseWithMultipleRegionsWithOverlap) { "FROM region_tiles " "JOIN tiles WHERE tile_id = id" }; // clang-format on - mapbox::sqlite::Query query { stmt }; + mapbox::sqlite::Query query{stmt}; query.run(); // Ensure multiple entries for tiles shared between regions @@ -1824,7 +1843,7 @@ TEST(OfflineDatabase, MergeDatabaseWithMultipleRegionsWithOverlap) { "FROM region_resources " "JOIN resources WHERE resource_id = id" }; // clang-format on - mapbox::sqlite::Query query { stmt }; + mapbox::sqlite::Query query{stmt}; query.run(); // Ensure multiple entries for resources shared between regions @@ -1842,7 +1861,7 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegionTooManyNewTiles) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded" })); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1859,7 +1878,7 @@ TEST(OfflineDatabase, MergeDatabaseWithSingleRegionTooManyExistingTiles) { auto result = db.mergeDatabase(filename_sideload); EXPECT_THROW(std::rethrow_exception(result.error()), MapboxTileLimitExceededException); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded" })); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "Mapbox tile limit exceeded"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1875,7 +1894,7 @@ TEST(OfflineDatabase, MergeDatabaseWithInvalidPath) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "Merge database has incorrect user_version" })); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "Merge database has incorrect user_version"})); EXPECT_EQ(0u, log.uncheckedCount()); } #endif @@ -1891,7 +1910,11 @@ TEST(OfflineDatabase, MergeDatabaseWithInvalidDb) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result); - EXPECT_EQ(1u, log.count(error(ResultCode::Corrupt, "Can't attach database (test/fixtures/offline_database/offline_sideload.db) for merge: database disk image is malformed"))); + EXPECT_EQ(1u, + log.count(error(ResultCode::Corrupt, + "Can't attach database " + "(test/fixtures/offline_database/offline_sideload.db) for merge: " + "database disk image is malformed"))); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1899,7 +1922,7 @@ TEST(OfflineDatabase, MergeDatabaseWithInvalidDb) { TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithDiskFull)) { FixtureLog log; test::SQLite3TestFS fs; - + deleteDatabaseFiles(); util::deleteFile(filename_sideload); util::copyFile(filename, "test/fixtures/offline_database/satellite_test.db"); @@ -1912,7 +1935,7 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(MergeDatabaseWithDiskFull)) { auto result = db.mergeDatabase(filename_sideload); EXPECT_FALSE(result.has_value()); - EXPECT_EQ(1u, log.count({ EventSeverity::Error, Event::Database, -1, "database or disk is full"})); + EXPECT_EQ(1u, log.count({EventSeverity::Error, Event::Database, -1, "database or disk is full"})); EXPECT_EQ(0u, log.uncheckedCount()); } #endif // __QT__ @@ -1938,7 +1961,9 @@ TEST(OfflineDatabase, ResetDatabase) { auto regions = db.listRegions().value(); EXPECT_EQ(0u, regions.size()); - EXPECT_EQ(1u, log.count({ EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database" })); + EXPECT_EQ( + 1u, + log.count({EventSeverity::Warning, Event::Database, -1, "Removing existing incompatible offline database"})); EXPECT_EQ(0u, log.uncheckedCount()); } @@ -1980,7 +2005,8 @@ TEST(OfflineDatabase, TEST_REQUIRES_WRITE(UpdateDatabaseReadOnlyMode)) { log.count({EventSeverity::Error, Event::Database, -1, - "Can't clear ambient cache: Cannot modify database in read-only mode"})); + "Can't clear ambient cache: Cannot modify database in read-only " + "mode"})); EXPECT_EQ(0u, log.uncheckedCount()); } diff --git a/test/storage/offline_download.test.cpp b/test/storage/offline_download.test.cpp index 1f7c033d9bc..50fb6404e5f 100644 --- a/test/storage/offline_download.test.cpp +++ b/test/storage/offline_download.test.cpp @@ -34,7 +34,7 @@ static void deleteDatabaseFiles() { } static FixtureLog::Message warning(ResultCode code, const char* message) { - return { EventSeverity::Warning, Event::Database, static_cast(code), message }; + return {EventSeverity::Warning, Event::Database, static_cast(code), message}; } #endif @@ -52,15 +52,15 @@ class MockObserver : public OfflineRegionObserver { if (mapboxTileCountLimitExceededFn) mapboxTileCountLimitExceededFn(limit); } - std::function statusChangedFn; - std::function responseErrorFn; - std::function mapboxTileCountLimitExceededFn; + std::function statusChangedFn; + std::function responseErrorFn; + std::function mapboxTileCountLimitExceededFn; }; class OfflineTest { public: - OfflineTest(const std::string& path = ":memory:") : db(path, TileServerOptions::MapTilerConfiguration()) { - } + OfflineTest(const std::string& path = ":memory:") + : db(path, TileServerOptions::MapTilerConfiguration()) {} util::RunLoop loop; StubFileSource fileSource; @@ -68,14 +68,12 @@ class OfflineTest { std::size_t size = 0; auto createRegion() { - OfflineTilePyramidRegionDefinition definition { "", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 1.0, true }; + OfflineTilePyramidRegionDefinition definition{"", LatLngBounds::hull({1, 2}, {3, 4}), 5, 6, 1.0, true}; OfflineRegionMetadata metadata; return db.createRegion(definition, metadata); } - auto invalidateRegion(int64_t region) { - return db.invalidateRegion(region); - } + auto invalidateRegion(int64_t region) { return db.invalidateRegion(region); } Response response(const std::string& path) { Response result; @@ -91,12 +89,13 @@ TEST(OfflineDownload, NoSubresources) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("empty.style.json"); }; @@ -104,7 +103,7 @@ TEST(OfflineDownload, NoSubresources) { auto observer = std::make_unique(); bool expectsInactiveStatus = false; - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { if (!expectsInactiveStatus) { expectsInactiveStatus = true; @@ -132,17 +131,18 @@ TEST(OfflineDownload, InlineSource) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("inline_source.style.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -154,7 +154,7 @@ TEST(OfflineDownload, InlineSource) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(1u, status.completedTileCount); EXPECT_EQ(2u, status.completedResourceCount); @@ -174,24 +174,25 @@ TEST(OfflineDownload, GeoJSONSource) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("geojson_source.style.json"); }; - test.fileSource.sourceResponse = [&] (const Resource& resource) { + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/geojson.json", resource.url); return test.response("geojson.json"); }; auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(2u, status.completedResourceCount); EXPECT_EQ(test.size, status.completedResourceSize); @@ -210,43 +211,44 @@ TEST(OfflineDownload, Activate) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("style.json"); }; - test.fileSource.spriteImageResponse = [&] (const Resource& resource) { + test.fileSource.spriteImageResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.png" || resource.url == "http://127.0.0.1:3000/sprite@2x.png"); return test.response("sprite.png"); }; - test.fileSource.imageResponse = [&] (const Resource& resource) { + test.fileSource.imageResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/radar.gif", resource.url); return test.response("radar.gif"); }; - test.fileSource.spriteJSONResponse = [&] (const Resource& resource) { + test.fileSource.spriteJSONResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.json" || resource.url == "http://127.0.0.1:3000/sprite@2x.json"); return test.response("sprite.json"); }; - test.fileSource.glyphsResponse = [&] (const Resource&) { + test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; - test.fileSource.sourceResponse = [&] (const Resource& resource) { + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); return test.response("streets.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -258,10 +260,13 @@ TEST(OfflineDownload, Activate) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(status.completedTileCount, status.requiredTileCount); - EXPECT_EQ(264u, status.completedResourceCount); // 256 glyphs, 2 sprite images, 2 sprite jsons, 1 tile, 1 style, source, image + EXPECT_EQ(264u, + status.completedResourceCount); // 256 glyphs, 2 sprite images, + // 2 sprite jsons, 1 tile, 1 + // style, source, image EXPECT_EQ(test.size, status.completedResourceSize); download.setState(OfflineRegionDownloadState::Inactive); @@ -289,43 +294,44 @@ TEST(OfflineDownload, ExcludeIdeographs) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); - - test.fileSource.styleResponse = [&] (const Resource& resource) { + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); + + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("style.json"); }; - - test.fileSource.spriteImageResponse = [&] (const Resource& resource) { + + test.fileSource.spriteImageResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.png" || resource.url == "http://127.0.0.1:3000/sprite@2x.png"); return test.response("sprite.png"); }; - - test.fileSource.imageResponse = [&] (const Resource& resource) { + + test.fileSource.imageResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/radar.gif", resource.url); return test.response("radar.gif"); }; - - test.fileSource.spriteJSONResponse = [&] (const Resource& resource) { + + test.fileSource.spriteJSONResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.url == "http://127.0.0.1:3000/sprite.json" || resource.url == "http://127.0.0.1:3000/sprite@2x.json"); return test.response("sprite.json"); }; - - test.fileSource.glyphsResponse = [&] (const Resource&) { + + test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; - - test.fileSource.sourceResponse = [&] (const Resource& resource) { + + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); return test.response("streets.json"); }; - - test.fileSource.tileResponse = [&] (const Resource& resource) { + + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -334,15 +340,18 @@ TEST(OfflineDownload, ExcludeIdeographs) { EXPECT_EQ(0, tile.z); return test.response("0-0-0.vector.pbf"); }; - + auto observer = std::make_unique(); - - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(status.completedTileCount, status.requiredTileCount); - EXPECT_EQ(138u, status.completedResourceCount); // 130 glyphs, 2 sprite images, 2 sprite jsons, 1 tile, 1 style, source, image + EXPECT_EQ(138u, + status.completedResourceCount); // 130 glyphs, 2 sprite images, + // 2 sprite jsons, 1 tile, 1 + // style, source, image EXPECT_EQ(test.size, status.completedResourceSize); - + download.setState(OfflineRegionDownloadState::Inactive); OfflineRegionStatus computedStatus = download.getStatus(); EXPECT_EQ(OfflineRegionDownloadState::Inactive, computedStatus.downloadState); @@ -353,14 +362,14 @@ TEST(OfflineDownload, ExcludeIdeographs) { EXPECT_EQ(status.completedTileCount, computedStatus.completedTileCount); EXPECT_EQ(status.completedTileSize, computedStatus.completedTileSize); EXPECT_TRUE(status.requiredResourceCountIsPrecise); - + test.loop.stop(); } }; - + download.setObserver(std::move(observer)); download.setState(OfflineRegionDownloadState::Active); - + test.loop.run(); } @@ -369,10 +378,11 @@ TEST(OfflineDownload, DoesNotFloodTheFileSourceWithRequests) { FakeOnlineFileSource fileSource; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + fileSource); auto observer = std::make_unique(); @@ -392,10 +402,11 @@ TEST(OfflineDownload, GetStatusNoResources) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); OfflineRegionStatus status = download.getStatus(); EXPECT_EQ(OfflineRegionDownloadState::Inactive, status.downloadState); @@ -412,14 +423,13 @@ TEST(OfflineDownload, GetStatusStyleComplete) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); - test.db.putRegionResource(1, - Resource::style("http://127.0.0.1:3000/style.json"), - test.response("style.json")); + test.db.putRegionResource(1, Resource::style("http://127.0.0.1:3000/style.json"), test.response("style.json")); OfflineRegionStatus status = download.getStatus(); @@ -437,18 +447,15 @@ TEST(OfflineDownload, GetStatusStyleAndSourceComplete) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); - test.db.putRegionResource(1, - Resource::style("http://127.0.0.1:3000/style.json"), - test.response("style.json")); + test.db.putRegionResource(1, Resource::style("http://127.0.0.1:3000/style.json"), test.response("style.json")); - test.db.putRegionResource(1, - Resource::source("http://127.0.0.1:3000/streets.json"), - test.response("streets.json")); + test.db.putRegionResource(1, Resource::source("http://127.0.0.1:3000/streets.json"), test.response("streets.json")); OfflineRegionStatus status = download.getStatus(); @@ -466,12 +473,13 @@ TEST(OfflineDownload, RequestError) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource&) { + test.fileSource.styleResponse = [&](const Resource&) { Response response; response.error = std::make_unique(Response::Error::Reason::Connection, "connection error"); return response; @@ -479,7 +487,7 @@ TEST(OfflineDownload, RequestError) { auto observer = std::make_unique(); - observer->responseErrorFn = [&] (Response::Error error) { + observer->responseErrorFn = [&](Response::Error error) { EXPECT_EQ(Response::Error::Reason::Connection, error.reason); EXPECT_EQ("connection error", error.message); test.loop.stop(); @@ -495,13 +503,14 @@ TEST(OfflineDownload, RequestErrorsAreRetried) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource&) { - test.fileSource.styleResponse = [&] (const Resource&) { + test.fileSource.styleResponse = [&](const Resource&) { + test.fileSource.styleResponse = [&](const Resource&) { return test.response("empty.style.json"); }; @@ -512,7 +521,7 @@ TEST(OfflineDownload, RequestErrorsAreRetried) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(1u, status.completedResourceCount); test.loop.stop(); @@ -529,34 +538,35 @@ TEST(OfflineDownload, TileCountLimitExceededNoTileResponse) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); uint64_t tileLimit = 0; test.db.setOfflineMapboxTileCountLimit(tileLimit); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("mapbox_source.style.json"); }; -// test.fileSource.tileResponse = [&] (const Resource& resource) { -// EXPECT_EQ("maptiler://0-0-0.vector.pbf", resource.url); -// return test.response("0-0-0.vector.pbf"); -// }; + // test.fileSource.tileResponse = [&] (const Resource& resource) { + // EXPECT_EQ("maptiler://0-0-0.vector.pbf", resource.url); + // return test.response("0-0-0.vector.pbf"); + // }; auto observer = std::make_unique(); bool mapboxTileCountLimitExceededCalled = false; - observer->mapboxTileCountLimitExceededFn = [&] (uint64_t limit) { + observer->mapboxTileCountLimitExceededFn = [&](uint64_t limit) { EXPECT_FALSE(mapboxTileCountLimitExceededCalled); EXPECT_EQ(tileLimit, limit); mapboxTileCountLimitExceededCalled = true; }; - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (!mapboxTileCountLimitExceededCalled) { EXPECT_FALSE(status.complete()); EXPECT_EQ(OfflineRegionDownloadState::Active, status.downloadState); @@ -576,21 +586,22 @@ TEST(OfflineDownload, TileCountLimitExceededWithTileResponse) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); uint64_t tileLimit = 1; test.db.setOfflineMapboxTileCountLimit(tileLimit); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("mapbox_source.style.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { const Resource::TileData& tile = *resource.tileData; EXPECT_EQ("maptiler://{z}-{x}-{y}.vector.pbf", tile.urlTemplate); EXPECT_EQ(1, tile.pixelRatio); @@ -603,13 +614,13 @@ TEST(OfflineDownload, TileCountLimitExceededWithTileResponse) { auto observer = std::make_unique(); bool mapboxTileCountLimitExceededCalled = false; - observer->mapboxTileCountLimitExceededFn = [&] (uint64_t limit) { + observer->mapboxTileCountLimitExceededFn = [&](uint64_t limit) { EXPECT_FALSE(mapboxTileCountLimitExceededCalled); EXPECT_EQ(tileLimit, limit); mapboxTileCountLimitExceededCalled = true; }; - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (!mapboxTileCountLimitExceededCalled) { EXPECT_EQ(OfflineRegionDownloadState::Active, status.downloadState); } else { @@ -631,23 +642,23 @@ TEST(OfflineDownload, WithPreviouslyExistingTile) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("inline_source.style.json"); }; - test.db.put( - Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 0, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); + test.db.put(Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 0, Tileset::Scheme::XYZ), + test.response("0-0-0.vector.pbf")); auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(2u, status.completedResourceCount); EXPECT_EQ(test.size, status.completedResourceSize); @@ -666,22 +677,22 @@ TEST(OfflineDownload, ReactivatePreviouslyCompletedDownload) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("inline_source.style.json"); }; - test.db.put( - Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 0, Tileset::Scheme::XYZ), - test.response("0-0-0.vector.pbf")); + test.db.put(Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 0, Tileset::Scheme::XYZ), + test.response("0-0-0.vector.pbf")); auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { test.loop.stop(); } @@ -692,15 +703,16 @@ TEST(OfflineDownload, ReactivatePreviouslyCompletedDownload) { test.loop.run(); - OfflineDownload redownload( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload redownload(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); std::vector statusesAfterReactivate; observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { statusesAfterReactivate.push_back(status); if (status.complete()) { test.loop.stop(); @@ -734,19 +746,20 @@ TEST(OfflineDownload, Deactivate) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); return test.response("mapbox_source.style.json"); }; auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.downloadState == OfflineRegionDownloadState::Inactive) { test.loop.stop(); } else { @@ -764,48 +777,49 @@ TEST(OfflineDownload, AllOfflineRequestsHaveLowPriorityAndOfflineUsage) { OfflineTest test; auto region = test.createRegion(); ASSERT_TRUE(region); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, true), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("style.json"); }; - test.fileSource.spriteImageResponse = [&] (const Resource& resource) { + test.fileSource.spriteImageResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("sprite.png"); }; - test.fileSource.imageResponse = [&] (const Resource& resource) { + test.fileSource.imageResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("radar.gif"); }; - test.fileSource.spriteJSONResponse = [&] (const Resource& resource) { + test.fileSource.spriteJSONResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("sprite.json"); }; - test.fileSource.glyphsResponse = [&] (const Resource& resource) { + test.fileSource.glyphsResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("glyph.pbf"); }; - test.fileSource.sourceResponse = [&] (const Resource& resource) { + test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("streets.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("0-0-0.vector.pbf"); @@ -813,7 +827,7 @@ TEST(OfflineDownload, AllOfflineRequestsHaveLowPriorityAndOfflineUsage) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { test.loop.stop(); } @@ -831,7 +845,7 @@ TEST(OfflineDownload, DiskFull) { deleteDatabaseFiles(); test::SQLite3TestFS fs; - OfflineTest test{ filename_test_fs }; + OfflineTest test{filename_test_fs}; EXPECT_EQ(0u, log.uncheckedCount()); auto region = test.createRegion(); @@ -841,14 +855,15 @@ TEST(OfflineDownload, DiskFull) { // Simulate a full disk. fs.setWriteLimit(8192); - OfflineDownload download( - region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineDownload download(region->getID(), + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); bool hasRequestedStyle = false; - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/style.json", resource.url); hasRequestedStyle = true; return test.response("empty.style.json"); @@ -856,7 +871,7 @@ TEST(OfflineDownload, DiskFull) { auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { EXPECT_EQ(OfflineRegionDownloadState::Active, status.downloadState); EXPECT_EQ(0u, status.completedResourceCount); EXPECT_EQ(0u, status.completedResourceSize); @@ -864,7 +879,8 @@ TEST(OfflineDownload, DiskFull) { EXPECT_FALSE(status.complete()); if (hasRequestedStyle) { - EXPECT_EQ(1u, log.count(warning(ResultCode::Full, "Can't write region resources: database or disk is full"))); + EXPECT_EQ(1u, + log.count(warning(ResultCode::Full, "Can't write region resources: database or disk is full"))); EXPECT_EQ(0u, log.uncheckedCount()); test.loop.stop(); } @@ -883,30 +899,31 @@ TEST(OfflineDownload, ResourceOfflineUsageUnset) { deleteDatabaseFiles(); test::SQLite3TestFS fs; - OfflineTest test{ filename_test_fs }; + OfflineTest test{filename_test_fs}; auto region = test.createRegion(); ASSERT_TRUE(region); OfflineDownload download( region->getID(), - OfflineTilePyramidRegionDefinition("http://127.0.0.1:3000/inline_source.style.json", - LatLngBounds::world(), 0.0, 0.0, 1.0, false), - test.db, test.fileSource); + OfflineTilePyramidRegionDefinition( + "http://127.0.0.1:3000/inline_source.style.json", LatLngBounds::world(), 0.0, 0.0, 1.0, false), + test.db, + test.fileSource); - test.fileSource.styleResponse = [&] (const Resource& resource) { + test.fileSource.styleResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("inline_source.style.json"); }; - test.fileSource.tileResponse = [&] (const Resource& resource) { + test.fileSource.tileResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.priority == Resource::Priority::Low); EXPECT_TRUE(resource.usage == Resource::Usage::Offline); return test.response("0-0-0.vector.pbf"); }; auto observer = std::make_unique(); - observer->statusChangedFn = [&] (OfflineRegionStatus status) { + observer->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { // Once download completes, invalidate region and try rendering map. // Resource requests must not have Offline usage tag. @@ -920,28 +937,28 @@ TEST(OfflineDownload, ResourceOfflineUsageUnset) { test.loop.run(); std::shared_ptr stubfileSource = std::make_shared(); - stubfileSource->styleResponse = [&] (const Resource& resource) { + stubfileSource->styleResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.usage != Resource::Usage::Offline); return test.response("inline_source.style.json"); }; - stubfileSource->tileResponse = [&] (const Resource& resource) { + stubfileSource->tileResponse = [&](const Resource& resource) { EXPECT_TRUE(resource.usage != Resource::Usage::Offline); return test.response("0-0-0.vector.pbf"); }; StubMapObserver mapObserver; - mapObserver.didFinishRenderingFrameCallback = [&] (MapObserver::RenderFrameStatus status) { + mapObserver.didFinishRenderingFrameCallback = [&](MapObserver::RenderFrameStatus status) { if (status.mode == MapObserver::RenderMode::Full) { test.loop.stop(); } }; - HeadlessFrontend frontend { 1 }; - MapAdapter map { frontend, mapObserver, stubfileSource, - MapOptions() - .withMapMode(MapMode::Continuous) - .withSize(frontend.getSize())}; + HeadlessFrontend frontend{1}; + MapAdapter map{frontend, + mapObserver, + stubfileSource, + MapOptions().withMapMode(MapMode::Continuous).withSize(frontend.getSize())}; map.getStyle().loadURL("http://127.0.0.1:3000/inline_source.style.json"); map.jumpTo(CameraOptions().withCenter(LatLng{0.0, 0.0}).withZoom(0)); @@ -982,7 +999,9 @@ TEST(OfflineDownload, InterruptAndResume) { return test.response("sprite.json"); }; - test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; + test.fileSource.glyphsResponse = [&](const Resource&) { + return test.response("glyph.pbf"); + }; test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); @@ -1020,8 +1039,10 @@ TEST(OfflineDownload, InterruptAndResume) { newObserver->statusChangedFn = [&](OfflineRegionStatus status) { if (status.complete()) { EXPECT_EQ(status.completedTileCount, status.requiredTileCount); - EXPECT_EQ(264u, status.completedResourceCount); // 256 glyphs, 2 sprite images, 2 sprite jsons, 1 tile, 1 - // style, source, image + EXPECT_EQ(264u, + status.completedResourceCount); // 256 glyphs, 2 sprite images, + // 2 sprite jsons, 1 tile, 1 + // style, source, image test.loop.stop(); } }; @@ -1042,7 +1063,9 @@ TEST(OfflineDownload, NoFreezingOnCachedTilesAndNewStyle) { test.fileSource); test.fileSource.setProperty(MAX_CONCURRENT_REQUESTS_KEY, 2u); - test.fileSource.styleResponse = [&](const Resource&) { return test.response("inline_source.style.json"); }; + test.fileSource.styleResponse = [&](const Resource&) { + return test.response("inline_source.style.json"); + }; // Number of resources must exceed MAX_CONCURRENT_REQUESTS_KEY test.db.put(Resource::tile("http://127.0.0.1:3000/{z}-{x}-{y}.vector.pbf", 1, 0, 0, 1, Tileset::Scheme::XYZ), test.response("0-0-0.vector.pbf")); @@ -1099,7 +1122,9 @@ TEST(OfflineDownload, NoFreezingOnNotFoundError) { return response; }; - test.fileSource.glyphsResponse = [&](const Resource&) { return test.response("glyph.pbf"); }; + test.fileSource.glyphsResponse = [&](const Resource&) { + return test.response("glyph.pbf"); + }; test.fileSource.sourceResponse = [&](const Resource& resource) { EXPECT_EQ("http://127.0.0.1:3000/streets.json", resource.url); diff --git a/test/storage/online_file_source.test.cpp b/test/storage/online_file_source.test.cpp index f3662b978fd..5525b189917 100644 --- a/test/storage/online_file_source.test.cpp +++ b/test/storage/online_file_source.test.cpp @@ -27,10 +27,10 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(CancelMultiple)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test"}; - std::unique_ptr req2 = - fs->request(resource, [&](Response) { ADD_FAILURE() << "Callback should not be called"; }); + std::unique_ptr req2 = fs->request( + resource, [&](Response) { ADD_FAILURE() << "Callback should not be called"; }); std::unique_ptr req = fs->request(resource, [&](Response res) { req.reset(); EXPECT_EQ(nullptr, res.error); @@ -124,7 +124,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(Timeout)) { int counter = 0; - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=1" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test?cachecontrol=max-age=1"}; std::unique_ptr req = fs->request(resource, [&](Response res) { counter++; EXPECT_EQ(nullptr, res.error); @@ -151,7 +151,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(RetryDelayOnExpiredTile)) { int counter = 0; - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test?expires=10000" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test?expires=10000"}; std::unique_ptr req = fs->request(resource, [&](Response res) { counter++; EXPECT_EQ(nullptr, res.error); @@ -171,7 +171,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(RetryOnClockSkew)) { int counter = 0; - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/clockskew" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/clockskew"}; std::unique_ptr req1 = fs->request(resource, [&](Response res) { EXPECT_FALSE(res.mustRevalidate); switch (counter++) { @@ -199,18 +199,18 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(RespectPriorExpires)) { std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); // Very long expiration time, should never arrive. - Resource resource1{ Resource::Unknown, "http://127.0.0.1:3000/test" }; + Resource resource1{Resource::Unknown, "http://127.0.0.1:3000/test"}; resource1.priorExpires = util::now() + Seconds(100000); std::unique_ptr req1 = fs->request(resource1, [&](Response) { FAIL() << "Should never be called"; }); // No expiration time, should be requested immediately. - Resource resource2{ Resource::Unknown, "http://127.0.0.1:3000/test" }; + Resource resource2{Resource::Unknown, "http://127.0.0.1:3000/test"}; std::unique_ptr req2 = fs->request(resource2, [&](Response) { loop.stop(); }); // Very long expiration time, should never arrive. - Resource resource3{ Resource::Unknown, "http://127.0.0.1:3000/test" }; + Resource resource3{Resource::Unknown, "http://127.0.0.1:3000/test"}; resource3.priorExpires = util::now() + Seconds(100000); std::unique_ptr req3 = fs->request(resource3, [&](Response) { FAIL() << "Should never be called"; }); @@ -276,15 +276,16 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(Load)) { // Test for https://github.com/mapbox/mapbox-gl-native/issues/2123 // -// A request is made. While the request is in progress, the network status changes. This should -// trigger an immediate retry of all requests that are not in progress. This test makes sure that -// we don't accidentally double-trigger the request. +// A request is made. While the request is in progress, the network status +// changes. This should trigger an immediate retry of all requests that are not +// in progress. This test makes sure that we don't accidentally double-trigger +// the request. TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChange)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/delayed" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/delayed"}; // This request takes 200 milliseconds to answer. std::unique_ptr req = fs->request(resource, [&](Response res) { @@ -301,15 +302,13 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChange)) { // After 50 milliseconds, we're going to trigger a NetworkStatus change. util::Timer reachableTimer; - reachableTimer.start(Milliseconds(50), Duration::zero(), [] () { - mbgl::NetworkStatus::Reachable(); - }); + reachableTimer.start(Milliseconds(50), Duration::zero(), []() { mbgl::NetworkStatus::Reachable(); }); loop.run(); } -// Tests that a change in network status preempts requests that failed due to connection or -// reachability issues. +// Tests that a change in network status preempts requests that failed due to +// connection or reachability issues. TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChangePreempt)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); @@ -318,7 +317,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChangePreempt)) { const auto start = Clock::now(); int counter = 0; - const Resource resource{ Resource::Unknown, "http://127.0.0.1:3001/test" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3001/test"}; std::unique_ptr req = fs->request(resource, [&](Response res) { const auto duration = std::chrono::duration(Clock::now() - start).count(); if (counter == 0) { @@ -345,9 +344,7 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusChangePreempt)) { // After 400 milliseconds, we're going to trigger a NetworkStatus change. util::Timer reachableTimer; - reachableTimer.start(Milliseconds(400), Duration::zero(), [] () { - mbgl::NetworkStatus::Reachable(); - }); + reachableTimer.start(Milliseconds(400), Duration::zero(), []() { mbgl::NetworkStatus::Reachable(); }); fs->resume(); loop.run(); @@ -357,15 +354,14 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(NetworkStatusOnlineOffline)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - const Resource resource { Resource::Unknown, "http://127.0.0.1:3000/test" }; + const Resource resource{Resource::Unknown, "http://127.0.0.1:3000/test"}; EXPECT_EQ(NetworkStatus::Get(), NetworkStatus::Status::Online) << "Default status should be Online"; NetworkStatus::Set(NetworkStatus::Status::Offline); util::Timer onlineTimer; - onlineTimer.start(Milliseconds(100), Duration::zero(), [&] () { - NetworkStatus::Set(NetworkStatus::Status::Online); - }); + onlineTimer.start( + Milliseconds(100), Duration::zero(), [&]() { NetworkStatus::Set(NetworkStatus::Status::Online); }); std::unique_ptr req = fs->request(resource, [&](Response res) { req.reset(); @@ -441,7 +437,7 @@ TEST(OnlineFileSource, GetBaseURLAndApiKeyWhilePaused) { EXPECT_EQ(*fs->getProperty(API_KEY_KEY).getString(), apiKey); } -TEST(OnlineFileSource, ChangeAPIBaseURL){ +TEST(OnlineFileSource, ChangeAPIBaseURL) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); EXPECT_EQ(ResourceOptions::Default().tileServerOptions().baseURL(), *fs->getProperty(API_BASE_URL_KEY).getString()); @@ -453,10 +449,10 @@ TEST(OnlineFileSource, ChangeAPIBaseURL){ EXPECT_EQ(customURL, updatedTileServerOptions.baseURL()); } -TEST(OnlineFileSource, ChangeTileServerOptions){ +TEST(OnlineFileSource, ChangeTileServerOptions) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); - + TileServerOptions tileServerOptsChanged; tileServerOptsChanged.withApiKeyParameterName("apiKeyChanged") .withBaseURL("baseURLChanged") @@ -468,8 +464,7 @@ TEST(OnlineFileSource, ChangeTileServerOptions){ .withTileTemplate("tileTemplateChanged", "tileDomainChanged", {}) .withUriSchemeAlias("uriSchemeAliasChanged"); ResourceOptions resOpts; - resOpts.withApiKey("changedAPIKey") - .withTileServerOptions(tileServerOptsChanged); + resOpts.withApiKey("changedAPIKey").withTileServerOptions(tileServerOptsChanged); fs->setResourceOptions(resOpts.clone()); @@ -498,7 +493,6 @@ TEST(OnlineFileSource, ChangeTileServerOptions){ EXPECT_EQ(resOpts.tileServerOptions().styleVersionPrefix(), tileServerOptsChanged.styleVersionPrefix()); } - TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequests)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); @@ -524,12 +518,13 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequests)) { std::unique_ptr req_1 = fs->request(low_prio, [&](Response) { response_counter++; req_1.reset(); - EXPECT_EQ(response_counter, NUM_REQUESTS); // make sure this is responded last + EXPECT_EQ(response_counter, + NUM_REQUESTS); // make sure this is responded last loop.stop(); }); // Second regular priority request that should de-preoritize low priority request. - Resource regular2{ Resource::Unknown, "http://127.0.0.1:3000/load/3" }; + Resource regular2{Resource::Unknown, "http://127.0.0.1:3000/load/3"}; std::unique_ptr req_2 = fs->request(regular2, [&](Response) { response_counter++; req_2.reset(); @@ -540,7 +535,6 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequests)) { loop.run(); } - TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequestsMany)) { util::RunLoop loop; std::unique_ptr fs = std::make_unique(ResourceOptions::Default(), ClientOptions()); @@ -565,9 +559,8 @@ TEST(OnlineFileSource, TEST_REQUIRES_SERVER(LowHighPriorityRequestsMany)) { } }); collector.push_back(std::move(req)); - } - else { - Resource resource = { Resource::Unknown, "http://127.0.0.1:3000/load/" + std::to_string(num_reqs) }; + } else { + Resource resource = {Resource::Unknown, "http://127.0.0.1:3000/load/" + std::to_string(num_reqs)}; resource.setPriority(Resource::Priority::Low); std::unique_ptr req = fs->request(std::move(resource), [&](Response) { diff --git a/test/storage/resource.test.cpp b/test/storage/resource.test.cpp index e03f339a97f..e777e7bffa7 100644 --- a/test/storage/resource.test.cpp +++ b/test/storage/resource.test.cpp @@ -19,7 +19,8 @@ TEST(Resource, Source) { TEST(Resource, Tile) { using namespace mbgl; - Resource rasterTile = Resource::tile("http://example.com/{z}/{x}/{y}{ratio}.png", 2.0, 1, 2, 3, Tileset::Scheme::XYZ); + Resource rasterTile = Resource::tile( + "http://example.com/{z}/{x}/{y}{ratio}.png", 2.0, 1, 2, 3, Tileset::Scheme::XYZ); EXPECT_EQ(Resource::Kind::Tile, rasterTile.kind); EXPECT_EQ("http://example.com/3/1/2@2x.png", rasterTile.url); EXPECT_EQ("http://example.com/{z}/{x}/{y}{ratio}.png", rasterTile.tileData->urlTemplate); @@ -28,7 +29,8 @@ TEST(Resource, Tile) { EXPECT_EQ(2, rasterTile.tileData->y); EXPECT_EQ(3, rasterTile.tileData->z); - Resource vectorTile = Resource::tile("http://example.com/{prefix}/{z}/{x}/{y}.mvt", 2.0, 1, 2, 3, Tileset::Scheme::XYZ); + Resource vectorTile = Resource::tile( + "http://example.com/{prefix}/{z}/{x}/{y}.mvt", 2.0, 1, 2, 3, Tileset::Scheme::XYZ); EXPECT_EQ(Resource::Kind::Tile, vectorTile.kind); EXPECT_EQ("http://example.com/12/3/1/2.mvt", vectorTile.url); EXPECT_EQ("http://example.com/{prefix}/{z}/{x}/{y}.mvt", vectorTile.tileData->urlTemplate); diff --git a/test/storage/sqlite.test.cpp b/test/storage/sqlite.test.cpp index 1e2cc5488e4..b71024ab795 100644 --- a/test/storage/sqlite.test.cpp +++ b/test/storage/sqlite.test.cpp @@ -11,8 +11,8 @@ TEST(SQLite, Statement) { mapbox::sqlite::Database db = mapbox::sqlite::Database::open(":memory:", mapbox::sqlite::ReadWriteCreate); db.exec("CREATE TABLE test (id INTEGER);"); - mapbox::sqlite::Statement stmt1{ db, "INSERT INTO test (id) VALUES (?1);" }; - mapbox::sqlite::Query query1{ stmt1 }; + mapbox::sqlite::Statement stmt1{db, "INSERT INTO test (id) VALUES (?1);"}; + mapbox::sqlite::Query query1{stmt1}; ASSERT_EQ(query1.lastInsertRowId(), 0); ASSERT_EQ(query1.changes(), 0u); query1.bind(1, 10); @@ -20,8 +20,8 @@ TEST(SQLite, Statement) { ASSERT_EQ(query1.lastInsertRowId(), 1); ASSERT_EQ(query1.changes(), 1u); - mapbox::sqlite::Statement stmt2{ db, "INSERT INTO test (id) VALUES (?1);" }; - mapbox::sqlite::Query query2{ stmt2 }; + mapbox::sqlite::Statement stmt2{db, "INSERT INTO test (id) VALUES (?1);"}; + mapbox::sqlite::Query query2{stmt2}; ASSERT_EQ(query2.lastInsertRowId(), 0); ASSERT_EQ(query2.changes(), 0u); query2.bind(1, 20); @@ -35,24 +35,24 @@ TEST(SQLite, TEST_REQUIRES_WRITE(TryOpen)) { // Should return a CANTOPEN exception when the database doesn't exist, // make sure all the backends behave the same way. - auto result = mapbox::sqlite::Database::tryOpen("test/fixtures/offline_database/foobar123.db", mapbox::sqlite::ReadOnly); + auto result = mapbox::sqlite::Database::tryOpen("test/fixtures/offline_database/foobar123.db", + mapbox::sqlite::ReadOnly); ASSERT_TRUE(result.is()); ASSERT_EQ(result.get().code, mapbox::sqlite::ResultCode::CantOpen); EXPECT_EQ(0u, log.uncheckedCount()); } TEST(SQLite, CloseDatabaseWithPendingTransaction) { - auto db = std::make_unique(mapbox::sqlite::Database::open( - ":memory:", mapbox::sqlite::ReadWriteCreate)); + auto db = std::make_unique( + mapbox::sqlite::Database::open(":memory:", mapbox::sqlite::ReadWriteCreate)); mapbox::sqlite::Transaction transaction(*db); transaction.commit(); } TEST(SQLite, CloseMovedDatabaseWithPendingTransaction) { - // Verifies that we can correctly commit a transaction even if we move the Database object to - // another address. - auto db1 = mapbox::sqlite::Database::open(":memory:", - mapbox::sqlite::ReadWriteCreate); + // Verifies that we can correctly commit a transaction even if we move the + // Database object to another address. + auto db1 = mapbox::sqlite::Database::open(":memory:", mapbox::sqlite::ReadWriteCreate); std::unique_ptr db2; mapbox::sqlite::Transaction transaction(db1); db2 = std::make_unique(std::move(db1)); diff --git a/test/storage/sync_file_source.test.cpp b/test/storage/sync_file_source.test.cpp index 6ce2d26348d..8144cd408bb 100644 --- a/test/storage/sync_file_source.test.cpp +++ b/test/storage/sync_file_source.test.cpp @@ -19,8 +19,8 @@ class SyncFileSource : public FileSource { Response response; auto it = assets.find(resource.url); if (it == assets.end()) { - response.error = std::make_unique( - Response::Error::Reason::NotFound, std::string{ "Not Found: " } + resource.url); + response.error = std::make_unique(Response::Error::Reason::NotFound, + std::string{"Not Found: "} + resource.url); } else { response.data = it->second; } @@ -41,11 +41,9 @@ class SyncFileSource : public FileSource { TEST(SyncFileSource, LoadSyncRender) { util::RunLoop loop; auto fs = std::make_shared(); - fs->add("maptiler://maps/streets", - util::read_file("test/fixtures/resources/source_vector.json")); - fs->add("maptiler://sprites/streets/sprite", - util::read_file("test/fixtures/resources/sprite.png")); - HeadlessFrontend frontend{ { 512, 512 }, 1.0 }; - MapAdapter map{ frontend, MapObserver::nullObserver(), fs, MapOptions() }; + fs->add("maptiler://maps/streets", util::read_file("test/fixtures/resources/source_vector.json")); + fs->add("maptiler://sprites/streets/sprite", util::read_file("test/fixtures/resources/sprite.png")); + HeadlessFrontend frontend{{512, 512}, 1.0}; + MapAdapter map{frontend, MapObserver::nullObserver(), fs, MapOptions()}; map.getStyle().loadJSON(util::read_file("test/fixtures/resources/style_vector.json")); } diff --git a/test/style/conversion/conversion_impl.test.cpp b/test/style/conversion/conversion_impl.test.cpp index 1a6c1a030c6..b561bf654a5 100644 --- a/test/style/conversion/conversion_impl.test.cpp +++ b/test/style/conversion/conversion_impl.test.cpp @@ -8,13 +8,13 @@ namespace conversion { class MockConvertible { public: MockConvertible() = default; - MockConvertible(int* counter_) : counter(counter_) {} + MockConvertible(int* counter_) + : counter(counter_) {} - MockConvertible(MockConvertible&& other) noexcept : counter(other.counter) {} + MockConvertible(MockConvertible&& other) noexcept + : counter(other.counter) {} - ~MockConvertible() { - ++*counter; - } + ~MockConvertible() { ++*counter; } int* counter = nullptr; }; @@ -22,58 +22,34 @@ class MockConvertible { template <> class ConversionTraits { public: - static bool isUndefined(const MockConvertible&) { - return false; - } + static bool isUndefined(const MockConvertible&) { return false; } - static bool isArray(const MockConvertible&) { - return false; - } + static bool isArray(const MockConvertible&) { return false; } - static bool isObject(const MockConvertible&) { - return false; - } + static bool isObject(const MockConvertible&) { return false; } - static std::size_t arrayLength(const MockConvertible&) { - return 0u; - } + static std::size_t arrayLength(const MockConvertible&) { return 0u; } - static MockConvertible arrayMember(const MockConvertible&, std::size_t) { - return {}; - } + static MockConvertible arrayMember(const MockConvertible&, std::size_t) { return {}; } - static std::optional objectMember(const MockConvertible&, const char *) { - return std::nullopt; - } + static std::optional objectMember(const MockConvertible&, const char*) { return std::nullopt; } template static std::optional eachMember(const MockConvertible&, Fn&&) { return std::nullopt; } - static std::optional toBool(const MockConvertible&) { - return std::nullopt; - } + static std::optional toBool(const MockConvertible&) { return std::nullopt; } - static std::optional toNumber(const MockConvertible&) { - return std::nullopt; - } + static std::optional toNumber(const MockConvertible&) { return std::nullopt; } - static std::optional toDouble(const MockConvertible&) { - return std::nullopt; - } + static std::optional toDouble(const MockConvertible&) { return std::nullopt; } - static std::optional toString(const MockConvertible&) { - return std::nullopt; - } + static std::optional toString(const MockConvertible&) { return std::nullopt; } - static std::optional toValue(const MockConvertible&) { - return std::nullopt; - } + static std::optional toValue(const MockConvertible&) { return std::nullopt; } - static std::optional toGeoJSON(const MockConvertible&, Error&) { - return std::nullopt; - } + static std::optional toGeoJSON(const MockConvertible&, Error&) { return std::nullopt; } }; } // namespace conversion diff --git a/test/style/conversion/function.test.cpp b/test/style/conversion/function.test.cpp index 5c96e5124b8..3ad353a8d26 100644 --- a/test/style/conversion/function.test.cpp +++ b/test/style/conversion/function.test.cpp @@ -62,18 +62,23 @@ TEST(StyleConversion, CompositeFunctionExpression) { auto fn1 = parseFunction(R"(["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10])"); ASSERT_TRUE(fn1); - auto fn2 = parseFunction(R"(["coalesce", ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10], 0])"); + auto fn2 = parseFunction( + R"(["coalesce", ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10], 0])"); ASSERT_TRUE(fn2); - auto fn3 = parseFunction(R"(["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10] ])"); + auto fn3 = parseFunction( + R"(["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10] ])"); ASSERT_TRUE(fn3); - auto fn4 = parseFunction(R"(["coalesce", ["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10]], 0])"); + auto fn4 = parseFunction( + R"(["coalesce", ["let", "a", 0, ["interpolate", ["linear"], ["zoom"], 0, ["number", ["get", "x"]], 10, 10]], 0])"); ASSERT_TRUE(fn4); - auto fn5 = parseFunction(R"(["coalesce", ["interpolate", ["linear"], ["number", ["get", "x"]], 0, ["zoom"], 10, 10], 0])"); + auto fn5 = parseFunction( + R"(["coalesce", ["interpolate", ["linear"], ["number", ["get", "x"]], 0, ["zoom"], 10, 10], 0])"); ASSERT_FALSE(fn5); - ASSERT_EQ(R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", error.message); + ASSERT_EQ(R"("zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.)", + error.message); } TEST(StyleConversion, TokenStrings) { @@ -88,12 +93,14 @@ TEST(StyleConversion, TokenStrings) { ASSERT_EQ(*convertTokenStringToExpression("{token}"), *toString(get(literal("token")))); ASSERT_EQ(*convertTokenStringToExpression("token {token}"), *concat(vec(literal("token "), get(literal("token"))))); ASSERT_EQ(*convertTokenStringToExpression("{token} token"), *concat(vec(get(literal("token")), literal(" token")))); - ASSERT_EQ(*convertTokenStringToExpression("{token} {token}"), *concat(vec(get(literal("token")), literal(" "), get(literal("token"))))); - ASSERT_EQ(*convertTokenStringToExpression("{token} {token"), *concat(vec(get(literal("token")), literal(" "), literal("{token")))); - ASSERT_EQ(*convertTokenStringToExpression("{token {token}"), *concat(vec(literal("{token "), get(literal("token"))))); + ASSERT_EQ(*convertTokenStringToExpression("{token} {token}"), + *concat(vec(get(literal("token")), literal(" "), get(literal("token"))))); + ASSERT_EQ(*convertTokenStringToExpression("{token} {token"), + *concat(vec(get(literal("token")), literal(" "), literal("{token")))); + ASSERT_EQ(*convertTokenStringToExpression("{token {token}"), + *concat(vec(literal("{token "), get(literal("token"))))); } - TEST(StyleConversion, FormattedIdentityFunction) { // See https://github.com/mapbox/mapbox-gl-js/issues/7311 // We never introduced this bug on gl-native, but we _almost_ did @@ -102,7 +109,7 @@ TEST(StyleConversion, FormattedIdentityFunction) { auto parseFunction = [&](const std::string& json) { return convertJSON>(json, error, true, false); }; - + using namespace mbgl::style::expression::dsl; auto fn1 = parseFunction(R"({ "property": "name", "type": "identity" })"); diff --git a/test/style/conversion/geojson_options.test.cpp b/test/style/conversion/geojson_options.test.cpp index cc5341e6ee2..0832255dccf 100644 --- a/test/style/conversion/geojson_options.test.cpp +++ b/test/style/conversion/geojson_options.test.cpp @@ -11,15 +11,17 @@ using namespace mbgl::style::conversion; TEST(GeoJSONOptions, Basic) { Error error; std::optional converted = convertJSON("{}", error); - ASSERT_TRUE((bool) converted); + ASSERT_TRUE((bool)converted); } TEST(GeoJSONOptions, ErrorHandling) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "maxzoom": "should not be a string" - })JSON", error); - ASSERT_FALSE((bool) converted); + })JSON", + error); + ASSERT_FALSE((bool)converted); } TEST(GeoJSONOptions, RetainsDefaults) { @@ -43,7 +45,8 @@ TEST(GeoJSONOptions, RetainsDefaults) { TEST(GeoJSONOptions, FullConversion) { Error error; - GeoJSONOptions converted = *convertJSON(R"JSON({ + GeoJSONOptions converted = *convertJSON( + R"JSON({ "maxzoom": 1, "buffer": 2, "tolerance": 3, @@ -56,7 +59,8 @@ TEST(GeoJSONOptions, FullConversion) { "sum": [["+", ["accumulated"], ["get", "sum"]], ["get", "scalerank"]], "has_island": ["any", ["==", ["get", "featureclass"], "island"]] } - })JSON", error); + })JSON", + error); // GeoJSON-VT ASSERT_EQ(converted.minzoom, 0); diff --git a/test/style/conversion/layer.test.cpp b/test/style/conversion/layer.test.cpp index 079d7ce5a5f..248c98579ae 100644 --- a/test/style/conversion/layer.test.cpp +++ b/test/style/conversion/layer.test.cpp @@ -44,10 +44,8 @@ TEST(StyleConversion, LayerTransition) { } })JSON"); ASSERT_STREQ("background", layer->getTypeInfo()->type); - ASSERT_EQ(400ms, *static_cast(layer.get())->impl().paint - .get().options.duration); - ASSERT_EQ(500ms, *static_cast(layer.get())->impl().paint - .get().options.delay); + ASSERT_EQ(400ms, *static_cast(layer.get())->impl().paint.get().options.duration); + ASSERT_EQ(500ms, *static_cast(layer.get())->impl().paint.get().options.delay); } TEST(StyleConversion, SerializeDefaults) { diff --git a/test/style/conversion/light.test.cpp b/test/style/conversion/light.test.cpp index e49667f319a..cf522eb249a 100644 --- a/test/style/conversion/light.test.cpp +++ b/test/style/conversion/light.test.cpp @@ -25,7 +25,7 @@ TEST(StyleConversion, Light) { { auto light = parseLight("{}"); - ASSERT_TRUE((bool) light); + ASSERT_TRUE((bool)light); const mbgl::JSValue colorValue("blue"); light->setProperty("color", &colorValue); @@ -41,17 +41,21 @@ TEST(StyleConversion, Light) { ASSERT_EQ(light->getIntensity().asConstant(), 0.5); mbgl::JSValue::AllocatorType allocator; - const mbgl::JSValue positionValue(std::move(mbgl::JSValue(rapidjson::kArrayType).PushBack(1.f, allocator).PushBack(2.f, allocator).PushBack(3.f, allocator).Move())); + const mbgl::JSValue positionValue(std::move(mbgl::JSValue(rapidjson::kArrayType) + .PushBack(1.f, allocator) + .PushBack(2.f, allocator) + .PushBack(3.f, allocator) + .Move())); light->setProperty("position", &positionValue); ASSERT_FALSE(light->getPosition().isUndefined()); ASSERT_TRUE(light->getPosition().isConstant()); - std::array expected{{ 1.f, 2.f, 3.f }}; - ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({ expected })); + std::array expected{{1.f, 2.f, 3.f}}; + ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({expected})); } { auto light = parseLight(R"({"color":{"stops":[[14,"blue"],[16,"red"]]},"intensity":0.3,"position":[3,90,90]})"); - ASSERT_TRUE((bool) light); + ASSERT_TRUE((bool)light); ASSERT_TRUE(light->getAnchor().isUndefined()); ASSERT_FALSE(light->getAnchor().isConstant()); @@ -69,54 +73,54 @@ TEST(StyleConversion, Light) { ASSERT_FALSE(light->getPosition().isUndefined()); ASSERT_TRUE(light->getPosition().isConstant()); - std::array expected{{ 3, 90, 90 }}; - ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({ expected })); + std::array expected{{3, 90, 90}}; + ASSERT_EQ(light->getPosition().asConstant(), mbgl::style::Position({expected})); ASSERT_FALSE(light->getPosition().isExpression()); } { auto light = parseLight(R"({"color":"blue","intensity":0.3,"color-transition":{"duration":1000}})"); - ASSERT_TRUE((bool) light); + ASSERT_TRUE((bool)light); ASSERT_FALSE(light->getColor().isUndefined()); ASSERT_TRUE(light->getColor().isConstant()); ASSERT_FALSE(light->getColor().isExpression()); ASSERT_EQ(light->getColorTransition().duration, mbgl::Duration(mbgl::Milliseconds(1000))); - ASSERT_FALSE((bool) light->getColorTransition().delay); + ASSERT_FALSE((bool)light->getColorTransition().delay); } { auto light = parseLight(R"({"intensity":false})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a number", error.message); } { auto light = parseLight(R"({"intensity":{"stops":[[15,"red"],[17,"blue"]]}})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a number", error.message); } { auto light = parseLight(R"({"color":5})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a string", error.message); } { auto light = parseLight(R"({"position":[0,5]})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be an array of 3 numbers", error.message); } { auto light = parseLight(R"({"anchor":"something"})"); - ASSERT_FALSE((bool) light); + ASSERT_FALSE((bool)light); ASSERT_EQ("value must be a valid enumeration value", error.message); } } diff --git a/test/style/conversion/property_value.test.cpp b/test/style/conversion/property_value.test.cpp index e8a7d844cd3..f6281034b6a 100644 --- a/test/style/conversion/property_value.test.cpp +++ b/test/style/conversion/property_value.test.cpp @@ -9,7 +9,8 @@ using namespace mbgl::style; using namespace mbgl::style::conversion; TEST(StyleConversion, PropertyValue) { - // PropertyValue accepts a constant expression: https://github.com/mapbox/mapbox-gl-native/issues/11940 + // PropertyValue accepts a constant expression: + // https://github.com/mapbox/mapbox-gl-native/issues/11940 Error error; JSDocument doc; doc.Parse<0>(R"(["literal", [1, 2]])"); diff --git a/test/style/conversion/stringify.test.cpp b/test/style/conversion/stringify.test.cpp index 144c26aa9d4..cc79b753383 100644 --- a/test/style/conversion/stringify.test.cpp +++ b/test/style/conversion/stringify.test.cpp @@ -59,15 +59,15 @@ TEST(Stringify, Color) { } TEST(Stringify, Array) { - ASSERT_EQ(stringify(std::array {{ 1, 2 }}), "[1.0,2.0]"); + ASSERT_EQ(stringify(std::array{{1, 2}}), "[1.0,2.0]"); } TEST(Stringify, Vector) { - ASSERT_EQ(stringify(std::vector {{ 1, 2 }}), "[1.0,2.0]"); + ASSERT_EQ(stringify(std::vector{{1, 2}}), "[1.0,2.0]"); } TEST(Stringify, Map) { - ASSERT_EQ(stringify(std::unordered_map {{ "a", 1.0f }}), "{\"a\":1.0}"); + ASSERT_EQ(stringify(std::unordered_map{{"a", 1.0f}}), "{\"a\":1.0}"); } TEST(Stringify, Value) { @@ -84,53 +84,40 @@ TEST(Stringify, Filter) { TEST(Stringify, PropertyExpression) { using namespace mbgl::style::expression::dsl; - ASSERT_EQ(stringify(PropertyExpression( - interpolate( - linear(), - zoom(), - 0.0, literal(1.0), - 1.0, literal(2.0) - ))), - "[\"interpolate\",[\"linear\"],[\"zoom\"],0.0,1.0,1.0,2.0]"); - - ASSERT_EQ(stringify(PropertyExpression( - interpolate( - exponential(2.0), - number(get("property")), - 0.0, literal(1.0), - 1.0, literal(2.0) - ))), - "[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]"); + ASSERT_EQ(stringify(PropertyExpression(interpolate(linear(), zoom(), 0.0, literal(1.0), 1.0, literal(2.0)))), + "[\"interpolate\",[\"linear\"],[\"zoom\"],0.0,1.0,1.0,2.0]"); ASSERT_EQ(stringify(PropertyExpression( - interpolate( - linear(), - zoom(), - 0.0, interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)), - 1.0, interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)) - ))), - "[\"interpolate\"," - "[\"linear\"]," - "[\"zoom\"]," - "0.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]," - "1.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\",\"property\"]],0.0,1.0,1.0,2.0]]"); + interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)))), + "[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\"," + "\"property\"]],0.0,1.0,1.0,2.0]"); + + ASSERT_EQ(stringify(PropertyExpression(interpolate( + linear(), + zoom(), + 0.0, + interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0)), + 1.0, + interpolate(exponential(2.0), number(get("property")), 0.0, literal(1.0), 1.0, literal(2.0))))), + "[\"interpolate\"," + "[\"linear\"]," + "[\"zoom\"]," + "0.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\"," + "\"property\"]],0.0,1.0,1.0,2.0]," + "1.0,[\"interpolate\",[\"exponential\",2.0],[\"number\",[\"get\"," + "\"property\"]],0.0,1.0,1.0,2.0]]"); } TEST(Stringify, PropertyValue) { using namespace mbgl::style::expression::dsl; ASSERT_EQ(stringify(PropertyValue(1)), "1.0"); ASSERT_EQ(stringify(PropertyValue(PropertyExpression( - interpolate( - exponential(2.0), - zoom(), - 0.0, literal(1.0), - 1.0, literal(2.0) - )))), - "[\"interpolate\",[\"exponential\",2.0],[\"zoom\"],0.0,1.0,1.0,2.0]"); + interpolate(exponential(2.0), zoom(), 0.0, literal(1.0), 1.0, literal(2.0))))), + "[\"interpolate\",[\"exponential\",2.0],[\"zoom\"],0.0,1.0,1.0,2.0]"); } TEST(Stringify, Layout) { - auto stringify = [] (const SymbolLayoutProperties::Unevaluated& layout) { + auto stringify = [](const SymbolLayoutProperties::Unevaluated& layout) { rapidjson::StringBuffer s; rapidjson::Writer writer(s); layout.stringify(writer); diff --git a/test/style/conversion/tileset.test.cpp b/test/style/conversion/tileset.test.cpp index 8812c475205..331ebae5ca3 100644 --- a/test/style/conversion/tileset.test.cpp +++ b/test/style/conversion/tileset.test.cpp @@ -11,87 +11,103 @@ using namespace mbgl::style::conversion; TEST(Tileset, Empty) { Error error; std::optional converted = convertJSON("{}", error); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } TEST(Tileset, ErrorHandling) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": "should not be a string" - })JSON", error); - EXPECT_FALSE((bool) converted); + })JSON", + error); + EXPECT_FALSE((bool)converted); } TEST(Tileset, InvalidBounds) { { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [73, -180, -73, -120] - })JSON", error); + })JSON", + error); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [-120] - })JSON", error); + })JSON", + error); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": "should not be a string" - })JSON", error); + })JSON", + error); - EXPECT_FALSE((bool) converted); + EXPECT_FALSE((bool)converted); } } TEST(Tileset, ValidWorldBounds) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [-180, -90, 180, 90] - })JSON", error); - EXPECT_TRUE((bool) converted); + })JSON", + error); + EXPECT_TRUE((bool)converted); EXPECT_EQ(converted->bounds, LatLngBounds::hull({90, -180}, {-90, 180})); } TEST(Tileset, PointBounds) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [0, 0, 0, 0] - })JSON", error); - EXPECT_TRUE((bool) converted); + })JSON", + error); + EXPECT_TRUE((bool)converted); EXPECT_EQ(converted->bounds, LatLngBounds::hull({0, 0}, {0, 0})); } TEST(Tileset, BoundsAreClamped) { Error error; - std::optional converted = convertJSON(R"JSON({ + std::optional converted = convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "bounds": [-181.0000005,-90.000000006,180.00000000000006,91] - })JSON", error); - EXPECT_TRUE((bool) converted); + })JSON", + error); + EXPECT_TRUE((bool)converted); EXPECT_EQ(converted->bounds, LatLngBounds::hull({90, -180}, {-90, 180})); } TEST(Tileset, FullConversion) { Error error; - Tileset converted = *convertJSON(R"JSON({ + Tileset converted = *convertJSON( + R"JSON({ "tiles": ["http://mytiles"], "scheme": "xyz", "minzoom": 1, "maxzoom": 2, "attribution": "mapbox", "bounds": [-180, -73, -120, 73] - })JSON", error); + })JSON", + error); EXPECT_EQ(converted.tiles[0], "http://mytiles"); EXPECT_EQ(converted.scheme, Tileset::Scheme::XYZ); diff --git a/test/style/expression/expression.test.cpp b/test/style/expression/expression.test.cpp index 85945fb5345..72abf4be0ad 100644 --- a/test/style/expression/expression.test.cpp +++ b/test/style/expression/expression.test.cpp @@ -19,7 +19,6 @@ #include #endif - using namespace mbgl; using namespace mbgl::style; @@ -27,16 +26,13 @@ TEST(Expression, IsExpression) { rapidjson::GenericDocument, rapidjson::CrtAllocator> spec; spec.Parse<0>(util::read_file("scripts/style-spec-reference/v8.json").c_str()); ASSERT_FALSE(spec.HasParseError()); - ASSERT_TRUE(spec.IsObject() && - spec.HasMember("expression_name") && - spec["expression_name"].IsObject() && - spec["expression_name"].HasMember("values") && - spec["expression_name"]["values"].IsObject()); + ASSERT_TRUE(spec.IsObject() && spec.HasMember("expression_name") && spec["expression_name"].IsObject() && + spec["expression_name"].HasMember("values") && spec["expression_name"]["values"].IsObject()); const auto& allExpressions = spec["expression_name"]["values"]; - for(auto& entry : allExpressions.GetObject()) { - const std::string name { entry.name.GetString(), entry.name.GetStringLength() }; + for (auto& entry : allExpressions.GetObject()) { + const std::string name{entry.name.GetString(), entry.name.GetStringLength()}; JSDocument document; document.Parse<0>(R"([")" + name + R"("])"); const JSValue* expression = &document; @@ -45,7 +41,8 @@ TEST(Expression, IsExpression) { // TODO: "interpolate-lab": https://github.com/mapbox/mapbox-gl-native/issues/8720 if (name == "interpolate-hcl" || name == "interpolate-lab") { if (expression::isExpression(conversion::Convertible(expression))) { - ASSERT_TRUE(false) << "Expression name" << name << "is implemented - please update Expression.IsExpression test."; + ASSERT_TRUE(false) << "Expression name" << name + << "is implemented - please update Expression.IsExpression test."; } continue; } @@ -82,7 +79,6 @@ TEST_P(ExpressionEqualityTest, ExpressionEquality) { std::unique_ptr expression_b = parse(base + ".b.json", error); ASSERT_TRUE(expression_b) << GetParam() << ": " << error; - EXPECT_TRUE(*expression_a1 == *expression_a2); EXPECT_TRUE(*expression_a1 != *expression_b); } diff --git a/test/style/filter.test.cpp b/test/style/filter.test.cpp index ad397bfecaf..57e346b4b65 100644 --- a/test/style/filter.test.cpp +++ b/test/style/filter.test.cpp @@ -19,7 +19,7 @@ using namespace mbgl; using namespace mbgl::style; -bool filter(const char * json, +bool filter(const char* json, const PropertyMap& featureProperties = {{}}, FeatureIdentifier featureId = {}, FeatureType featureType = FeatureType::Point, @@ -29,14 +29,14 @@ bool filter(const char * json, std::optional filter = conversion::convertJSON(json, error); EXPECT_TRUE(bool(filter)); EXPECT_EQ(error.message, ""); - - StubGeometryTileFeature feature { featureId, featureType, featureGeometry, featureProperties }; - expression::EvaluationContext context = { zoom, &feature }; - + + StubGeometryTileFeature feature{featureId, featureType, featureGeometry, featureProperties}; + expression::EvaluationContext context = {zoom, &feature}; + return (*filter)(context); } -void invalidFilter(const char * json) { +void invalidFilter(const char* json) { conversion::Error error; std::optional filter = conversion::convertJSON(json, error); EXPECT_FALSE(bool(filter)); @@ -44,28 +44,26 @@ void invalidFilter(const char * json) { } void writeJSON(rapidjson::Writer& writer, const Value& value) { - value.match( - [&] (const NullValue&) { writer.Null(); }, - [&] (bool b) { writer.Bool(b); }, - [&] (uint64_t t) { writer.Uint64(t); }, - [&] (int64_t t) { writer.Int64(t); }, - [&] (double f) { - // make sure integer values are stringified without trailing ".0". - f == std::floor(f) ? writer.Int(static_cast(f)) : writer.Double(f); - }, - [&] (const std::string& s) { writer.String(s); }, - [&] (const std::vector& arr) { - writer.StartArray(); - for(const auto& item : arr) { - writeJSON(writer, item); - } - writer.EndArray(); - }, - [](const auto&) { - }); + value.match([&](const NullValue&) { writer.Null(); }, + [&](bool b) { writer.Bool(b); }, + [&](uint64_t t) { writer.Uint64(t); }, + [&](int64_t t) { writer.Int64(t); }, + [&](double f) { + // make sure integer values are stringified without trailing ".0". + f == std::floor(f) ? writer.Int(static_cast(f)) : writer.Double(f); + }, + [&](const std::string& s) { writer.String(s); }, + [&](const std::vector& arr) { + writer.StartArray(); + for (const auto& item : arr) { + writeJSON(writer, item); + } + writer.EndArray(); + }, + [](const auto&) {}); } -std::string stringifyFilter(const char * json) { +std::string stringifyFilter(const char* json) { conversion::Error error; std::optional filter = conversion::convertJSON(json, error); EXPECT_TRUE(bool(filter)); @@ -81,33 +79,33 @@ std::string stringifyFilter(const char * json) { TEST(Filter, EqualsNull) { auto f = R"(["==", "foo", null])"; - ASSERT_TRUE(filter(f, {{ "foo", mapbox::feature::null_value }})); - - ASSERT_FALSE(filter(f, {{ "foo", int64_t(0) }})); - ASSERT_FALSE(filter(f, {{ "foo", int64_t(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", std::string("0") }})); - ASSERT_FALSE(filter(f, {{ "foo", true }})); - ASSERT_FALSE(filter(f, {{ "foo", false }})); - ASSERT_FALSE(filter(f, {{ }})); + ASSERT_TRUE(filter(f, {{"foo", mapbox::feature::null_value}})); + + ASSERT_FALSE(filter(f, {{"foo", int64_t(0)}})); + ASSERT_FALSE(filter(f, {{"foo", int64_t(1)}})); + ASSERT_FALSE(filter(f, {{"foo", std::string("0")}})); + ASSERT_FALSE(filter(f, {{"foo", true}})); + ASSERT_FALSE(filter(f, {{"foo", false}})); + ASSERT_FALSE(filter(f, {{}})); } TEST(Filter, EqualsString) { auto f = R"(["==", "foo", "bar"])"; - ASSERT_TRUE(filter(f, {{ "foo", std::string("bar") }})); - ASSERT_FALSE(filter(f, {{ "foo", std::string("baz") }})); + ASSERT_TRUE(filter(f, {{"foo", std::string("bar")}})); + ASSERT_FALSE(filter(f, {{"foo", std::string("baz")}})); } TEST(Filter, EqualsNumber) { auto f = R"(["==", "foo", 0])"; - ASSERT_TRUE(filter(f, {{ "foo", int64_t(0) }})); - ASSERT_TRUE(filter(f, {{ "foo", uint64_t(0) }})); - ASSERT_TRUE(filter(f, {{ "foo", double(0) }})); - ASSERT_FALSE(filter(f, {{ "foo", int64_t(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", uint64_t(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", double(1) }})); - ASSERT_FALSE(filter(f, {{ "foo", std::string("0") }})); - ASSERT_FALSE(filter(f, {{ "foo", false }})); - ASSERT_FALSE(filter(f, {{ "foo", true }})); - ASSERT_FALSE(filter(f, {{ "foo", mapbox::feature::null_value }})); + ASSERT_TRUE(filter(f, {{"foo", int64_t(0)}})); + ASSERT_TRUE(filter(f, {{"foo", uint64_t(0)}})); + ASSERT_TRUE(filter(f, {{"foo", double(0)}})); + ASSERT_FALSE(filter(f, {{"foo", int64_t(1)}})); + ASSERT_FALSE(filter(f, {{"foo", uint64_t(1)}})); + ASSERT_FALSE(filter(f, {{"foo", double(1)}})); + ASSERT_FALSE(filter(f, {{"foo", std::string("0")}})); + ASSERT_FALSE(filter(f, {{"foo", false}})); + ASSERT_FALSE(filter(f, {{"foo", true}})); + ASSERT_FALSE(filter(f, {{"foo", mapbox::feature::null_value}})); ASSERT_FALSE(filter(f, {{}})); } @@ -133,70 +131,76 @@ TEST(Filter, InType) { TEST(Filter, InID) { auto f = R"(["in", "$id", "123", "1234", 1234])"; ASSERT_FALSE(filter(f)); - ASSERT_TRUE(filter(f, {{}}, { uint64_t(1234) })); - ASSERT_TRUE(filter(f, {{}}, { std::string("1234") })); - ASSERT_FALSE(filter(f, {{}}, { std::string("4321") })); + ASSERT_TRUE(filter(f, {{}}, {uint64_t(1234)})); + ASSERT_TRUE(filter(f, {{}}, {std::string("1234")})); + ASSERT_FALSE(filter(f, {{}}, {std::string("4321")})); } TEST(Filter, Any) { ASSERT_FALSE(filter("[\"any\"]")); - ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"any\", [\"==\", \"foo\", 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"any\", [\"==\", \"foo\", 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE(filter("[\"any\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); } TEST(Filter, AnyExpression) { ASSERT_FALSE(filter("[\"any\"]")); - ASSERT_TRUE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"any\", [\"==\", [\"get\", \"foo\"], 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE( + filter("[\"any\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", " + "\"foo\"], 1]]", + {{std::string("foo"), int64_t(1)}})); } TEST(Filter, All) { ASSERT_TRUE(filter("[\"all\"]", {{}})); - ASSERT_TRUE(filter("[\"all\", [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"all\", [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"all\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); } TEST(Filter, AllExpression) { - ASSERT_TRUE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", \"foo\"], 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_TRUE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"all\", [\"==\", [\"get\", \"foo\"], 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE( + filter("[\"all\", [\"==\", [\"get\", \"foo\"], 0], [\"==\", [\"get\", " + "\"foo\"], 1]]", + {{std::string("foo"), int64_t(1)}})); } TEST(Filter, None) { ASSERT_TRUE(filter("[\"none\"]")); - ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"none\", [\"==\", \"foo\", 0]]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{ std::string("foo"), int64_t(1) }})); + ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE(filter("[\"none\", [\"==\", \"foo\", 0]]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"none\", [\"==\", \"foo\", 0], [\"==\", \"foo\", 1]]", {{std::string("foo"), int64_t(1)}})); } TEST(Filter, Has) { - ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{ std::string("foo"), int64_t(0) }})); - ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{ std::string("foo"), false }})); + ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{std::string("foo"), int64_t(1)}})); + ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{std::string("foo"), int64_t(0)}})); + ASSERT_TRUE(filter("[\"has\", \"foo\"]", {{std::string("foo"), false}})); ASSERT_FALSE(filter("[\"has\", \"foo\"]")); ASSERT_FALSE(filter("[\"has\", \"$id\"]")); } TEST(Filter, NotHas) { - ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{ std::string("foo"), int64_t(1) }})); - ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{ std::string("foo"), int64_t(0) }})); - ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{ std::string("foo"), false }})); + ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{std::string("foo"), int64_t(1)}})); + ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{std::string("foo"), int64_t(0)}})); + ASSERT_FALSE(filter("[\"!has\", \"foo\"]", {{std::string("foo"), false}})); ASSERT_TRUE(filter("[\"!has\", \"foo\"]")); } TEST(Filter, ID) { - FeatureIdentifier id1 { uint64_t{ 1234 } }; + FeatureIdentifier id1{uint64_t{1234}}; ASSERT_TRUE(filter("[\"==\", \"$id\", 1234]", {{}}, id1)); ASSERT_FALSE(filter("[\"==\", \"$id\", \"1234\"]", {{}}, id1)); - FeatureIdentifier id2 { std::string{ "1" } }; + FeatureIdentifier id2{std::string{"1"}}; ASSERT_FALSE(filter("[\"<\", \"$id\", \"0\"]", {{}}, id2)); ASSERT_TRUE(filter("[\"<\", \"$id\", \"1234\"]", {{}}, id2)); - ASSERT_FALSE(filter("[\"==\", \"$id\", 1234]", {{ "id", uint64_t(1234) }})); + ASSERT_FALSE(filter("[\"==\", \"$id\", 1234]", {{"id", uint64_t(1234)}})); } TEST(Filter, Expression) { @@ -224,11 +228,11 @@ TEST(Filter, LegacyProperty) { TEST(Filter, Serialize) { std::string json = R"(["any",["==","foo",0],["==","foo",1]])"; EXPECT_EQ(stringifyFilter(json.c_str()), std::string(json)); - + json = R"(["<=","two",2])"; EXPECT_EQ(stringifyFilter(json.c_str()), std::string(json)); - //Constant folding for Expression filters + // Constant folding for Expression filters json = R"(["==",["+",1,1],2])"; EXPECT_EQ(stringifyFilter(json.c_str()), std::string("true")); @@ -238,14 +242,16 @@ TEST(Filter, Serialize) { TEST(Filter, ExpressionLegacyMix) { conversion::Error error; - std::optional filter = conversion::convertJSON(R"(["any", ["all", ["==", ["geometry-type"], "LineString"]], ["==", "x", 1]])", error); + std::optional filter = conversion::convertJSON( + R"(["any", ["all", ["==", ["geometry-type"], "LineString"]], ["==", "x", 1]])", error); EXPECT_FALSE(bool(filter)); EXPECT_TRUE(error.message.size() > 0); } TEST(Filter, ZoomExpressionNested) { ASSERT_TRUE(filter(R"(["==", ["get", "two"], ["zoom"]])", {{"two", int64_t(2)}}, {}, FeatureType::Point, {}, 2.0f)); - ASSERT_FALSE(filter(R"(["==", ["get", "two"], ["+", ["zoom"], 1]])", {{"two", int64_t(2)}}, {}, FeatureType::Point, {}, 2.0f)); + ASSERT_FALSE(filter( + R"(["==", ["get", "two"], ["+", ["zoom"], 1]])", {{"two", int64_t(2)}}, {}, FeatureType::Point, {}, 2.0f)); } TEST(Filter, Internal) { diff --git a/test/style/properties.test.cpp b/test/style/properties.test.cpp index f3af1a92b27..35db67ad7ac 100644 --- a/test/style/properties.test.cpp +++ b/test/style/properties.test.cpp @@ -13,34 +13,21 @@ float evaluate(Transitioning>& property, Duration delta = D ZoomHistory zoomHistory; zoomHistory.update(0, TimePoint::min() + delta); - PropertyEvaluationParameters parameters { - zoomHistory, - TimePoint::min() + delta, - Duration::zero() - }; + PropertyEvaluationParameters parameters{zoomHistory, TimePoint::min() + delta, Duration::zero()}; - PropertyEvaluator evaluator { - parameters, - 0.0f - }; + PropertyEvaluator evaluator{parameters, 0.0f}; return property.evaluate(evaluator, parameters.now); } -PossiblyEvaluatedPropertyValue evaluateDataExpression(Transitioning>& property, Duration delta = Duration::zero()) { +PossiblyEvaluatedPropertyValue evaluateDataExpression(Transitioning>& property, + Duration delta = Duration::zero()) { ZoomHistory zoomHistory; zoomHistory.update(0, TimePoint::min() + delta); - PropertyEvaluationParameters parameters { - zoomHistory, - TimePoint::min() + delta, - Duration::zero() - }; + PropertyEvaluationParameters parameters{zoomHistory, TimePoint::min() + delta, Duration::zero()}; - DataDrivenPropertyEvaluator evaluator { - parameters, - 0.0f - }; + DataDrivenPropertyEvaluator evaluator{parameters, 0.0f}; return property.evaluate(evaluator, parameters.now); } @@ -51,33 +38,20 @@ TEST(TransitioningPropertyValue, EvaluateDefaultValue) { } TEST(TransitioningPropertyValue, EvaluateUntransitionedConstant) { - Transitioning> property { - PropertyValue(1.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; + Transitioning> property{ + PropertyValue(1.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; ASSERT_EQ(1.0f, evaluate(property)); } TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithoutDelay) { TransitionOptions transition; - transition.duration = { 1000ms }; - - Transitioning> t0 { - PropertyValue(0.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; - - Transitioning> t1 { - PropertyValue(1.0f), - t0, - transition, - TimePoint::min() - }; + transition.duration = {1000ms}; + + Transitioning> t0{ + PropertyValue(0.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; + + Transitioning> t1{PropertyValue(1.0f), t0, transition, TimePoint::min()}; ASSERT_FLOAT_EQ(0.0f, evaluate(t1, 0ms)); ASSERT_FLOAT_EQ(0.823099f, evaluate(t1, 500ms)); @@ -86,22 +60,13 @@ TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithoutDelay) { TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithDelay) { TransitionOptions transition; - transition.delay = { 1000ms }; - transition.duration = { 1000ms }; - - Transitioning> t0 { - PropertyValue(0.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; - - Transitioning> t1 { - PropertyValue(1.0f), - t0, - transition, - TimePoint::min() - }; + transition.delay = {1000ms}; + transition.duration = {1000ms}; + + Transitioning> t0{ + PropertyValue(0.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; + + Transitioning> t1{PropertyValue(1.0f), t0, transition, TimePoint::min()}; ASSERT_FLOAT_EQ(0.0f, evaluate(t1, 0ms)); ASSERT_FLOAT_EQ(0.0f, evaluate(t1, 500ms)); @@ -112,27 +77,20 @@ TEST(TransitioningPropertyValue, EvaluateTransitionedConstantWithDelay) { TEST(TransitioningDataDrivenPropertyValue, Evaluate) { TransitionOptions transition; - transition.delay = { 1000ms }; - transition.duration = { 1000ms }; + transition.delay = {1000ms}; + transition.duration = {1000ms}; - Transitioning> t0 { - PropertyValue(0.0f), - Transitioning>(), - TransitionOptions(), - TimePoint::min() - }; + Transitioning> t0{ + PropertyValue(0.0f), Transitioning>(), TransitionOptions(), TimePoint::min()}; using namespace mbgl::style::expression::dsl; PropertyExpression expression(number(get("property_name"))); - Transitioning> t1 { - PropertyValue(expression), - t0, - transition, - TimePoint::min() - }; + Transitioning> t1{PropertyValue(expression), t0, transition, TimePoint::min()}; ASSERT_TRUE(evaluateDataExpression(t0, 0ms).isConstant()); - ASSERT_FALSE(evaluateDataExpression(t1, 0ms).isConstant()) << - "A paint property transition to a data-driven evaluates immediately to the final value (see https://github.com/mapbox/mapbox-gl-native/issues/8237)."; + ASSERT_FALSE(evaluateDataExpression(t1, 0ms).isConstant()) + << "A paint property transition to a data-driven evaluates immediately " + "to the final value (see " + "https://github.com/mapbox/mapbox-gl-native/issues/8237)."; } diff --git a/test/style/property_expression.test.cpp b/test/style/property_expression.test.cpp index 8556a22dd54..45e14dc14a2 100644 --- a/test/style/property_expression.test.cpp +++ b/test/style/property_expression.test.cpp @@ -35,13 +35,11 @@ float evaluate(PropertyValue value, float zoom) { return value.evaluate(PropertyEvaluator(PropertyEvaluationParameters(zoom), 0)); } -template +template auto createOverride(expression::type::Type exprType, PossiblyEvaluatedPropertyValue propValue, std::string propName) { - return std::make_unique>(std::move(exprType), - std::move(propValue), - std::move(propName)); + return std::make_unique>(std::move(exprType), std::move(propValue), std::move(propName)); } TEST(PropertyExpression, Constant) { @@ -63,74 +61,96 @@ TEST(PropertyExpression, Expression) { } TEST(PropertyExpression, Defaults) { - EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f) - .evaluate(oneInteger, 2.0f)); - EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f) - .evaluate(oneDouble, 2.0f)); - EXPECT_EQ(0.0f, PropertyExpression(number(get("property")), 0.0f) - .evaluate(oneString, 2.0f)); - EXPECT_EQ(2.0f, PropertyExpression(number(get("property"))) - .evaluate(oneString, 2.0f)); + EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f).evaluate(oneInteger, 2.0f)); + EXPECT_EQ(1.0f, PropertyExpression(number(get("property")), 0.0f).evaluate(oneDouble, 2.0f)); + EXPECT_EQ(0.0f, PropertyExpression(number(get("property")), 0.0f).evaluate(oneString, 2.0f)); + EXPECT_EQ(2.0f, PropertyExpression(number(get("property"))).evaluate(oneString, 2.0f)); } TEST(PropertyExpression, ZoomInterpolation) { - EXPECT_EQ(40.0f, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(24.0)), - 1.5, interpolate(linear(), number(get("property")), 1.0, literal(36.0)), - 3.0, interpolate(linear(), number(get("property")), 1.0, literal(48.0)) - ), 0.0f) - .evaluate(2.0f, oneInteger, -1.0f)) << "Should interpolate between stops"; - - EXPECT_EQ(33.0, PropertyExpression( - interpolate(linear(), zoom(), - 5.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(0.0f, oneInteger, -1.0f)) << "Use first stop output for input values from -inf to first stop"; - - EXPECT_EQ(66.0, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(20.0f, oneInteger, -1.0f)) << "Use last stop output for input values from last stop to +inf"; - - EXPECT_EQ(66.0f, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(10.0f, oneInteger, -1.0f)) << "Should interpolate TO the last stop."; - - EXPECT_EQ(33.0f, PropertyExpression( - interpolate(linear(), zoom(), - 0.0, interpolate(linear(), number(get("property")), 1.0, literal(33.0)), - 10.0, interpolate(linear(), number(get("property")), 1.0, literal(66.0)) - ), 0.0f) - .evaluate(0.0f, oneInteger, -1.0f)) << "Should interpolate TO the first stop"; + EXPECT_EQ(40.0f, + PropertyExpression(interpolate(linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(24.0)), + 1.5, + interpolate(linear(), number(get("property")), 1.0, literal(36.0)), + 3.0, + interpolate(linear(), number(get("property")), 1.0, literal(48.0))), + 0.0f) + .evaluate(2.0f, oneInteger, -1.0f)) + << "Should interpolate between stops"; + + EXPECT_EQ(33.0, + PropertyExpression(interpolate(linear(), + zoom(), + 5.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0))), + 0.0f) + .evaluate(0.0f, oneInteger, -1.0f)) + << "Use first stop output for input values from -inf to first stop"; + + EXPECT_EQ(66.0, + PropertyExpression(interpolate(linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0))), + 0.0f) + .evaluate(20.0f, oneInteger, -1.0f)) + << "Use last stop output for input values from last stop to +inf"; + + EXPECT_EQ(66.0f, + PropertyExpression(interpolate(linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0))), + 0.0f) + .evaluate(10.0f, oneInteger, -1.0f)) + << "Should interpolate TO the last stop."; + + EXPECT_EQ(33.0f, + PropertyExpression(interpolate(linear(), + zoom(), + 0.0, + interpolate(linear(), number(get("property")), 1.0, literal(33.0)), + 10.0, + interpolate(linear(), number(get("property")), 1.0, literal(66.0))), + 0.0f) + .evaluate(0.0f, oneInteger, -1.0f)) + << "Should interpolate TO the first stop"; } TEST(PropertyExpression, Issue8460) { - PropertyExpression fn1( - interpolate(linear(), zoom(), - 15.0, interpolate(linear(), number(get("property")), 1.0, literal(0.0)), - 15.2, interpolate(linear(), number(get("property")), 1.0, literal(600.0)) - ), 0.0f); - - EXPECT_NEAR( 0.0f, fn1.evaluate(15.0f, oneInteger, -1.0f), 0.00); + PropertyExpression fn1(interpolate(linear(), + zoom(), + 15.0, + interpolate(linear(), number(get("property")), 1.0, literal(0.0)), + 15.2, + interpolate(linear(), number(get("property")), 1.0, literal(600.0))), + 0.0f); + + EXPECT_NEAR(0.0f, fn1.evaluate(15.0f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(300.0f, fn1.evaluate(15.1f, oneInteger, -1.0f), 0.01); EXPECT_NEAR(600.0f, fn1.evaluate(15.2f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(600.0f, fn1.evaluate(16.0f, oneInteger, -1.0f), 0.00); - PropertyExpression fn2( - interpolate(linear(), zoom(), - 15.0, interpolate(linear(), number(get("property")), 1.0, literal(0.0)), - 15.2, interpolate(linear(), number(get("property")), 1.0, literal(300.0)), - 18.0, interpolate(linear(), number(get("property")), 1.0, literal(600.0)) - ), 0.0f); - - EXPECT_NEAR( 0.0f, fn2.evaluate(15.0f, oneInteger, -1.0f), 0.00); + PropertyExpression fn2(interpolate(linear(), + zoom(), + 15.0, + interpolate(linear(), number(get("property")), 1.0, literal(0.0)), + 15.2, + interpolate(linear(), number(get("property")), 1.0, literal(300.0)), + 18.0, + interpolate(linear(), number(get("property")), 1.0, literal(600.0))), + 0.0f); + + EXPECT_NEAR(0.0f, fn2.evaluate(15.0f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(150.0f, fn2.evaluate(15.1f, oneInteger, -1.0f), 0.01); EXPECT_NEAR(300.0f, fn2.evaluate(15.2f, oneInteger, -1.0f), 0.00); EXPECT_NEAR(385.71f, fn2.evaluate(16.0f, oneInteger, -1.0f), 0.01); @@ -140,8 +160,7 @@ TEST(PropertyExpression, Issue8460) { TEST(PropertyExpression, FormatSectionOverride) { using Value = expression::Value; - Value formattedSection = - std::unordered_map{ {"text-color", Value{Color::blue()}} }; + Value formattedSection = std::unordered_map{{"text-color", Value{Color::blue()}}}; auto ctx = expression::EvaluationContext(&oneDouble).withFormattedSection(&formattedSection); PossiblyEvaluatedPropertyValue constantValueRed(Color::red()); PossiblyEvaluatedPropertyValue constantValueGreen(Color::green()); @@ -268,8 +287,8 @@ TEST(PropertyExpression, WithinExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - // evaluation test with valid geojson source but FeatureType is not Point/LineString (currently only support - // FeatureType::Point and FeatureType::LineString) + // evaluation test with valid geojson source but FeatureType is not Point/LineString + // (currently only support FeatureType::Point and FeatureType::LineString) { // testPoly is inside polygon, but will return false Polygon testRing{{{-9.228515625, -17.560246503294888}, @@ -293,8 +312,8 @@ TEST(PropertyExpression, WithinExpression) { auto geoLine1 = convertGeometry(testLine1, canonicalTileID); StubGeometryTileFeature lineFeature1(FeatureType::LineString, geoLine1); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID)); EXPECT_TRUE(evaluatedResult); evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID)); EXPECT_FALSE(evaluatedResult); @@ -302,7 +321,7 @@ TEST(PropertyExpression, WithinExpression) { // evaluation test with valid geojson source and valid point features { - auto getPointFeature = [&canonicalTileID](const Point& testPoint) -> StubGeometryTileFeature { + auto getPointFeature = [&canonicalTileID](const Point &testPoint) -> StubGeometryTileFeature { auto geoPoint = convertGeometry(testPoint, canonicalTileID); StubGeometryTileFeature pointFeature(FeatureType::Point, geoPoint); return pointFeature; @@ -310,8 +329,8 @@ TEST(PropertyExpression, WithinExpression) { // check `within` algorithm auto pointFeature = getPointFeature(Point(-10.72265625, -7.27529233637217)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID)); EXPECT_FALSE(evaluatedResult); pointFeature = getPointFeature(Point(-7.646484374999999, -12.382928338487396)); @@ -418,8 +437,8 @@ TEST(PropertyExpression, WithinExpressionAntiMeridian) { auto geoLine1 = convertGeometry(testLine1, canonicalTileID); StubGeometryTileFeature lineFeature1(FeatureType::LineString, geoLine1); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&lineFeature0).withCanonicalTileID(&canonicalTileID)); EXPECT_TRUE(evaluatedResult); evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID)); EXPECT_FALSE(evaluatedResult); @@ -439,7 +458,7 @@ TEST(PropertyExpression, WithinExpressionAntiMeridian) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - auto getPointFeature = [&canonicalTileID](const Point& testPoint) -> StubGeometryTileFeature { + auto getPointFeature = [&canonicalTileID](const Point &testPoint) -> StubGeometryTileFeature { auto geoPoint = convertGeometry(testPoint, canonicalTileID); StubGeometryTileFeature pointFeature(FeatureType::Point, geoPoint); return pointFeature; @@ -447,8 +466,8 @@ TEST(PropertyExpression, WithinExpressionAntiMeridian) { // check `within` algorithm auto pointFeature = getPointFeature(Point(177, 62.5)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID)); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID)); EXPECT_TRUE(evaluatedResult); pointFeature = getPointFeature(Point(180, 62.5)); @@ -517,10 +536,9 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&pointFeature).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(491.307, evaluatedResult, 0.01); - } // Evaluation test with Point to MultiPoint distance @@ -544,8 +562,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoPoint = convertGeometry(featurePoint, canonicalTileID); StubGeometryTileFeature feature(FeatureType::Point, geoPoint); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&feature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&feature).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(158.541, evaluatedResult, 0.01); } @@ -571,8 +589,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoLine = convertGeometry(line, canonicalTileID); StubGeometryTileFeature lineFeature(FeatureType::LineString, geoLine); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(107.211, evaluatedResult, 0.01); } @@ -600,8 +618,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoLine = convertGeometry(lines, canonicalTileID); StubGeometryTileFeature lineFeature(FeatureType::LineString, geoLine); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(59.845, evaluatedResult, 0.01); } @@ -671,16 +689,16 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(180.408, evaluatedResult, 0.01); } // Evaluation test with MultiPoints to MutltiLineString distance { const auto multiPoints = mbgl::util::read_file("test/fixtures/geometry_data/multi_point_2.geojson"); - const auto multiLineFeature = - getFeature("multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature = getFeature( + "multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID); std::stringstream ss; ss << std::string(R"(["distance", )") << multiPoints << std::string(R"( ])"); auto expression = createExpression(ss.str().c_str()); @@ -695,8 +713,8 @@ TEST(PropertyExpression, DistanceExpression) { // Evaluation test with LineString to MutltiLineString distance { const auto LineString1 = mbgl::util::read_file("test/fixtures/geometry_data/line_string_1.geojson"); - const auto multiLineFeature = - getFeature("multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature = getFeature( + "multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); std::stringstream ss; ss << std::string(R"(["distance", )") << LineString1 << std::string(R"( ])"); auto expression = createExpression(ss.str().c_str()); @@ -711,8 +729,8 @@ TEST(PropertyExpression, DistanceExpression) { // Evaluation test with MultiLineString to MutltiLineString distance { const auto multiLineString1 = mbgl::util::read_file("test/fixtures/geometry_data/multi_line_string_1.geojson"); - const auto multiLineFeature = - getFeature("multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature = getFeature( + "multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); std::stringstream ss; ss << std::string(R"(["distance", )") << multiLineString1 << std::string(R"( ])"); auto expression = createExpression(ss.str().c_str()); @@ -753,14 +771,14 @@ TEST(PropertyExpression, DistanceExpression) { ASSERT_TRUE(expression); PropertyExpression propExpr(std::move(expression)); - const auto multiLineFeature1 = - getFeature("multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature1 = getFeature( + "multi_line_string_1.geojson", FeatureType::LineString, canonicalTileID); auto evaluatedResult = propExpr.evaluate( EvaluationContext(&multiLineFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); EXPECT_NEAR(193.450, evaluatedResult, 0.01); - const auto multiLineFeature2 = - getFeature("multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); + const auto multiLineFeature2 = getFeature( + "multi_line_string_2.geojson", FeatureType::LineString, canonicalTileID); evaluatedResult = propExpr.evaluate(EvaluationContext(&multiLineFeature2).withCanonicalTileID(&canonicalTileID), invalidResult); EXPECT_NEAR(0.0, evaluatedResult, 0.01); @@ -783,8 +801,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoPolygon = convertGeometry(polygon, canonicalTileID); StubGeometryTileFeature polygonFeature(FeatureType::Polygon, geoPolygon); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&polygonFeature).withCanonicalTileID(&canonicalTileID), invalidResult); EXPECT_NEAR(203.876, evaluatedResult, 0.01); } @@ -827,8 +845,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoPolygon1 = convertGeometry(polygon1, canonicalTileID); StubGeometryTileFeature polygonFeature1(FeatureType::Polygon, geoPolygon1); - auto evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); + auto evaluatedResult = propExpr.evaluate( + EvaluationContext(&polygonFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // polygon2's line is intersecting polygon, but no point is inside polygon @@ -840,8 +858,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoPolygon2 = convertGeometry(polygon2, canonicalTileID); StubGeometryTileFeature polygonFeature2(FeatureType::Polygon, geoPolygon2); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature2).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate(EvaluationContext(&polygonFeature2).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // one of polygon3's point is inside polygon @@ -853,8 +871,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoPolygon3 = convertGeometry(polygon3, canonicalTileID); StubGeometryTileFeature polygonFeature3(FeatureType::Polygon, geoPolygon3); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&polygonFeature3).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate(EvaluationContext(&polygonFeature3).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // lineString1 is within polygon @@ -862,8 +880,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoLineString1 = convertGeometry(lineString1, canonicalTileID); StubGeometryTileFeature lineFeature1(FeatureType::LineString, geoLineString1); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature1).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(0.0, evaluatedResult, 0.01); // lineString2 is intersecting the polygon but its points are outside the polygon @@ -871,8 +889,8 @@ TEST(PropertyExpression, DistanceExpression) { auto geoLineString2 = convertGeometry(lineString2, canonicalTileID); StubGeometryTileFeature lineFeature2(FeatureType::LineString, geoLineString2); - evaluatedResult = - propExpr.evaluate(EvaluationContext(&lineFeature2).withCanonicalTileID(&canonicalTileID), invalidResult); + evaluatedResult = propExpr.evaluate(EvaluationContext(&lineFeature2).withCanonicalTileID(&canonicalTileID), + invalidResult); EXPECT_NEAR(0.0, evaluatedResult, 0.01); } } diff --git a/test/style/source.test.cpp b/test/style/source.test.cpp index baee9e8144f..1aefe5332ff 100644 --- a/test/style/source.test.cpp +++ b/test/style/source.test.cpp @@ -61,7 +61,7 @@ class SourceTest { Transform transform; TransformState transformState; Style style{fileSource, 1}; - AnnotationManager annotationManager { style }; + AnnotationManager annotationManager{style}; ImageManager imageManager; GlyphManager glyphManager; @@ -81,34 +81,28 @@ class SourceTest { // Squelch logging. Log::setObserver(std::make_unique()); - transform.resize({ 512, 512 }); + transform.resize({512, 512}); transform.jumpTo(CameraOptions().withCenter(LatLng()).withZoom(0.0)); transformState = transform.getState(); } - void run() { - loop.run(); - } + void run() { loop.run(); } - void end() { - loop.stop(); - } + void end() { loop.stop(); } }; TEST(Source, LoadingFail) { SourceTest test; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; - test.styleObserver.sourceError = [&] (Source& source, std::exception_ptr error) { + test.styleObserver.sourceError = [&](Source& source, std::exception_ptr error) { EXPECT_EQ("source", source.getID()); EXPECT_EQ("Failed by the test case", util::toString(error)); test.end(); @@ -124,14 +118,14 @@ TEST(Source, LoadingFail) { TEST(Source, LoadingCorrupt) { SourceTest test; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; response.data = std::make_unique("CORRUPTED"); return response; }; - test.styleObserver.sourceError = [&] (Source& source, std::exception_ptr error) { + test.styleObserver.sourceError = [&](Source& source, std::exception_ptr error) { EXPECT_EQ("source", source.getID()); EXPECT_EQ("Invalid value. at offset 0", util::toString(error)); test.end(); @@ -147,28 +141,29 @@ TEST(Source, LoadingCorrupt) { TEST(Source, RasterTileEmpty) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -182,28 +177,29 @@ TEST(Source, RasterTileEmpty) { TEST(Source, RasterDEMTileEmpty) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -217,7 +213,7 @@ TEST(Source, RasterDEMTileEmpty) { TEST(Source, VectorTileEmpty) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; @@ -226,21 +222,22 @@ TEST(Source, VectorTileEmpty) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -254,30 +251,30 @@ TEST(Source, VectorTileEmpty) { TEST(Source, RasterTileFail) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(SourceType::Raster, source_.baseImpl->type); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ("Failed by the test case", util::toString(error)); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(SourceType::Raster, source_.baseImpl->type); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ("Failed by the test case", util::toString(error)); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -289,30 +286,30 @@ TEST(Source, RasterTileFail) { TEST(Source, RasterDEMTileFail) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(SourceType::RasterDEM, source_.baseImpl->type); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ("Failed by the test case", util::toString(error)); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(SourceType::RasterDEM, source_.baseImpl->type); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ("Failed by the test case", util::toString(error)); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -324,32 +321,32 @@ TEST(Source, RasterDEMTileFail) { TEST(Source, VectorTileFail) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; - response.error = std::make_unique( - Response::Error::Reason::Other, - "Failed by the test case"); + response.error = std::make_unique(Response::Error::Reason::Other, "Failed by the test case"); return response; }; LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(SourceType::Vector, source_.baseImpl->type); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ("Failed by the test case", util::toString(error)); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(SourceType::Vector, source_.baseImpl->type); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ("Failed by the test case", util::toString(error)); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -361,29 +358,31 @@ TEST(Source, VectorTileFail) { TEST(Source, RasterTileCorrupt) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.data = std::make_unique("CORRUPTED"); return response; }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(source_.baseImpl->type, SourceType::Raster); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_TRUE(bool(error)); - // Not asserting on platform-specific error text. - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(source_.baseImpl->type, SourceType::Raster); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_TRUE(bool(error)); + // Not asserting on platform-specific error text. + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -395,29 +394,32 @@ TEST(Source, RasterTileCorrupt) { TEST(Source, RasterDEMTileCorrupt) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.data = std::make_unique("CORRUPTED"); return response; }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties };; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; + ; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(source_.baseImpl->type, SourceType::RasterDEM); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_TRUE(bool(error)); - // Not asserting on platform-specific error text. - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(source_.baseImpl->type, SourceType::RasterDEM); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_TRUE(bool(error)); + // Not asserting on platform-specific error text. + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -429,7 +431,7 @@ TEST(Source, RasterDEMTileCorrupt) { TEST(Source, VectorTileCorrupt) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.data = std::make_unique("CORRUPTED"); return response; @@ -438,21 +440,23 @@ TEST(Source, VectorTileCorrupt) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileError = [&] (RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { - EXPECT_EQ(source_.baseImpl->type, SourceType::Vector); - EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); - EXPECT_EQ(util::toString(error), "unknown pbf field type exception"); - test.end(); - }; + test.renderSourceObserver.tileError = + [&](RenderSource& source_, const OverscaledTileID& tileID, std::exception_ptr error) { + EXPECT_EQ(source_.baseImpl->type, SourceType::Vector); + EXPECT_EQ(OverscaledTileID(0, 0, 0), tileID); + EXPECT_EQ(util::toString(error), "unknown pbf field type exception"); + test.end(); + }; auto renderSource = RenderSource::create(source.baseImpl); renderSource->setObserver(&test.renderSourceObserver); @@ -464,26 +468,27 @@ TEST(Source, VectorTileCorrupt) { TEST(Source, RasterTileCancel) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { test.end(); return std::optional(); }; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource&, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource&, const OverscaledTileID&) { FAIL() << "Should never be called"; }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -497,26 +502,27 @@ TEST(Source, RasterTileCancel) { TEST(Source, RasterDEMTileCancel) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { test.end(); return std::optional(); }; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; RasterDEMSource source("source", tileset, 512); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource&, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource&, const OverscaledTileID&) { FAIL() << "Should never be called"; }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -530,7 +536,7 @@ TEST(Source, RasterDEMTileCancel) { TEST(Source, VectorTileCancel) { SourceTest test; - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { test.end(); return std::optional(); }; @@ -538,20 +544,21 @@ TEST(Source, VectorTileCancel) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; Tileset tileset; - tileset.tiles = { "tiles" }; + tileset.tiles = {"tiles"}; VectorSource source("source", tileset); source.loadDescription(*test.fileSource); - test.renderSourceObserver.tileChanged = [&] (RenderSource&, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource&, const OverscaledTileID&) { FAIL() << "Should never be called"; }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -566,28 +573,31 @@ TEST(Source, RasterTileAttribution) { SourceTest test; RasterLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; - std::string mapboxOSM = ("© Mapbox " - "©️ OpenStreetMap"); + std::string mapboxOSM = + ("© " + "Mapbox " + "©️ " + "OpenStreetMap"); - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; response.data = std::make_unique(R"TILEJSON({ "tilejson": "2.1.0", "attribution": ")TILEJSON" + - mapboxOSM + - R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON"); + mapboxOSM + R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON"); return response; }; - test.styleObserver.sourceChanged = [&] (Source& source) { + test.styleObserver.sourceChanged = [&](Source& source) { EXPECT_EQ(mapboxOSM, source.getAttribution()); EXPECT_FALSE(mapboxOSM.find("©️ OpenStreetMap") == std::string::npos); test.end(); @@ -607,27 +617,29 @@ TEST(Source, RasterDEMTileAttribution) { SourceTest test; HillshadeLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; - std::string mapbox = ("© Mapbox "); + std::string mapbox = + ("© " + "Mapbox "); - test.fileSource->tileResponse = [&] (const Resource&) { + test.fileSource->tileResponse = [&](const Resource&) { Response response; response.noContent = true; return response; }; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; response.data = std::make_unique(R"TILEJSON({ "tilejson": "2.1.0", "attribution": ")TILEJSON" + - mapbox + - R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON"); + mapbox + R"TILEJSON(", "tiles": [ "tiles" ] })TILEJSON"); return response; }; - test.styleObserver.sourceChanged = [&] (Source& source) { + test.styleObserver.sourceChanged = [&](Source& source) { EXPECT_EQ(mapbox, source.getAttribution()); test.end(); }; @@ -645,14 +657,15 @@ TEST(Source, RasterDEMTileAttribution) { TEST(Source, GeoJSonSourceUrlUpdate) { SourceTest test; - test.fileSource->sourceResponse = [&] (const Resource& resource) { + test.fileSource->sourceResponse = [&](const Resource& resource) { EXPECT_EQ("url", resource.url); Response response; - response.data = std::make_unique(R"({"geometry": {"type": "Point", "coordinates": [1.1, 1.1]}, "type": "Feature", "properties": {}})"); + response.data = std::make_unique( + R"({"geometry": {"type": "Point", "coordinates": [1.1, 1.1]}, "type": "Feature", "properties": {}})"); return response; }; - test.styleObserver.sourceDescriptionChanged = [&] (Source&) { + test.styleObserver.sourceDescriptionChanged = [&](Source&) { // Should be called (test will hang if it doesn't) test.end(); }; @@ -664,7 +677,7 @@ TEST(Source, GeoJSonSourceUrlUpdate) { source.loadDescription(*test.fileSource); // Schedule an update - test.loop.invoke([&] () { + test.loop.invoke([&]() { // Update the url source.setURL(std::string("http://source-url.ext")); }); @@ -675,13 +688,13 @@ TEST(Source, GeoJSonSourceUrlUpdate) { TEST(Source, ImageSourceImageUpdate) { SourceTest test; - test.fileSource->response = [&] (const Resource& resource) { + test.fileSource->response = [&](const Resource& resource) { EXPECT_EQ("http://url", resource.url); Response response; response.data = std::make_unique(util::read_file("test/fixtures/image/no_profile.png")); return response; }; - test.styleObserver.sourceChanged = [&] (Source&) { + test.styleObserver.sourceChanged = [&](Source&) { // Should be called (test will hang if it doesn't) test.end(); }; @@ -693,14 +706,14 @@ TEST(Source, ImageSourceImageUpdate) { // Load initial, so the source state will be loaded=true source.loadDescription(*test.fileSource); - PremultipliedImage rgba({ 1, 1 }); + PremultipliedImage rgba({1, 1}); rgba.data[0] = 255; rgba.data[1] = 254; rgba.data[2] = 253; rgba.data[3] = 0; // Schedule an update - test.loop.invoke([&] () { + test.loop.invoke([&]() { // Update the url source.setImage(std::move(rgba)); }); @@ -715,15 +728,16 @@ TEST(Source, CustomGeometrySourceSetTileData) { LineLayer layer("id", "source"); layer.setSourceLayer("water"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; - test.renderSourceObserver.tileChanged = [&] (RenderSource& source_, const OverscaledTileID&) { + test.renderSourceObserver.tileChanged = [&](RenderSource& source_, const OverscaledTileID&) { EXPECT_EQ("source", source_.baseImpl->id); test.end(); }; - test.renderSourceObserver.tileError = [&] (RenderSource&, const OverscaledTileID&, std::exception_ptr) { + test.renderSourceObserver.tileError = [&](RenderSource&, const OverscaledTileID&, std::exception_ptr) { FAIL() << "Should never be called"; }; @@ -731,9 +745,9 @@ TEST(Source, CustomGeometrySourceSetTileData) { renderSource->setObserver(&test.renderSourceObserver); renderSource->update(source.baseImpl, layers, true, true, test.tileParameters()); - test.loop.invoke([&] () { + test.loop.invoke([&]() { // Set Tile Data - source.setTileData(CanonicalTileID(0, 0, 0), GeoJSON{ FeatureCollection{} }); + source.setTileData(CanonicalTileID(0, 0, 0), GeoJSON{FeatureCollection{}}); }); test.run(); @@ -745,7 +759,8 @@ class FakeTileSource; class FakeTile : public Tile { public: FakeTile(FakeTileSource& source_, const OverscaledTileID& tileID) - : Tile(Tile::Kind::Geometry, tileID), source(source_) { + : Tile(Tile::Kind::Geometry, tileID), + source(source_) { renderable = true; } void setNecessity(TileNecessity necessity) override; @@ -763,7 +778,8 @@ class FakeTileSource : public RenderTileSetSource { MOCK_METHOD1(tileSetNecessity, void(TileNecessity)); MOCK_METHOD1(tileSetMinimumUpdateInterval, void(Duration)); - explicit FakeTileSource(Immutable impl_) : RenderTileSetSource(std::move(impl_)) {} + explicit FakeTileSource(Immutable impl_) + : RenderTileSetSource(std::move(impl_)) {} void updateInternal(const Tileset& tileset, const std::vector>& layers, const bool needsRendering, @@ -803,8 +819,8 @@ TEST(Source, InvisibleSourcesTileNecessity) { FakeTileSource renderTilesetSource{initialized.baseImpl}; RenderSource* renderSource = &renderTilesetSource; LineLayer layer("id", "source"); - Immutable layerProperties = - makeMutable(staticImmutableCast(layer.baseImpl)); + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); std::vector> layers{layerProperties}; EXPECT_CALL(renderTilesetSource, tileSetNecessity(TileNecessity::Required)).Times(1); renderSource->update(initialized.baseImpl, layers, true, true, test.tileParameters()); @@ -826,8 +842,8 @@ TEST(Source, SourceMinimumUpdateInterval) { FakeTileSource renderTilesetSource{initialized.baseImpl}; RenderSource* renderSource = &renderTilesetSource; LineLayer layer("id", "source"); - Immutable layerProperties = - makeMutable(staticImmutableCast(layer.baseImpl)); + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); std::vector> layers{layerProperties}; Duration minimumTileUpdateInterval = initialized.getMinimumTileUpdateInterval(); @@ -873,7 +889,9 @@ TEST(Source, RenderTileSetSourceUpdate) { void updateInternal(const Tileset&, const std::vector>&, - const bool, const bool, const TileParameters&) override { + const bool, + const bool, + const TileParameters&) override { mockedUpdateInternal(); } @@ -882,14 +900,15 @@ TEST(Source, RenderTileSetSourceUpdate) { } }; - VectorSource initialized("source", Tileset{ {"tiles"} }); + VectorSource initialized("source", Tileset{{"tiles"}}); initialized.loadDescription(*test.fileSource); - FakeRenderTileSetSource renderTilesetSource { initialized.baseImpl }; + FakeRenderTileSetSource renderTilesetSource{initialized.baseImpl}; LineLayer layer("id", "source"); - Immutable layerProperties = makeMutable(staticImmutableCast(layer.baseImpl)); - std::vector> layers { layerProperties }; + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); + std::vector> layers{layerProperties}; // Check that `updateInternal()` is called even if the updated source has not yet loaded description. EXPECT_CALL(renderTilesetSource, mockedUpdateInternal()).Times(2); @@ -909,12 +928,13 @@ TEST(Source, GeoJSONSourceTilesAfterDataReset) { RenderGeoJSONSource renderSource{staticImmutableCast(source.baseImpl)}; CircleLayer layer("id", "source"); - Immutable layerProperties = - makeMutable(staticImmutableCast(layer.baseImpl)); + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); std::vector> layers{layerProperties}; static_cast(renderSource).update(source.baseImpl, layers, true, true, test.tileParameters()); - EXPECT_FALSE(renderSource.isLoaded()); // loaded == false, means that the source contains pending tiles. + EXPECT_FALSE(renderSource.isLoaded()); // loaded == false, means that the + // source contains pending tiles. source.setGeoJSONData(nullptr); static_cast(renderSource).update(source.baseImpl, layers, true, true, test.tileParameters()); @@ -949,8 +969,8 @@ TEST(Source, SetMaxParentOverscaleFactor) { }; RasterLayer layer("id", "source"); - Immutable layerProperties = - makeMutable(staticImmutableCast(layer.baseImpl)); + Immutable layerProperties = makeMutable( + staticImmutableCast(layer.baseImpl)); std::vector> layers{layerProperties}; Tileset tileset; diff --git a/test/style/style.test.cpp b/test/style/style.test.cpp index c02c274d893..cfcb145a1a7 100644 --- a/test/style/style.test.cpp +++ b/test/style/style.test.cpp @@ -23,7 +23,7 @@ TEST(Style, Properties) { util::RunLoop loop; auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(R"STYLE({"name": "Test"})STYLE"); ASSERT_EQ("Test", style.getName()); @@ -34,7 +34,7 @@ TEST(Style, Properties) { style.loadJSON(R"STYLE({"bearing": 24})STYLE"); ASSERT_EQ("", style.getName()); - ASSERT_EQ(LatLng {}, *style.getDefaultCamera().center); + ASSERT_EQ(LatLng{}, *style.getDefaultCamera().center); ASSERT_EQ(24, *style.getDefaultCamera().bearing); style.loadJSON(R"STYLE({"zoom": 13.3})STYLE"); @@ -55,7 +55,7 @@ TEST(Style, Properties) { style.loadJSON(R"STYLE({"name": 23, "center": {}, "bearing": "north", "zoom": null, "pitch": "wide"})STYLE"); ASSERT_EQ("", style.getName()); - ASSERT_EQ(LatLng {}, *style.getDefaultCamera().center); + ASSERT_EQ(LatLng{}, *style.getDefaultCamera().center); ASSERT_EQ(0, *style.getDefaultCamera().zoom); ASSERT_EQ(0, *style.getDefaultCamera().bearing); ASSERT_EQ(0, *style.getDefaultCamera().pitch); @@ -65,12 +65,12 @@ TEST(Style, DuplicateSource) { util::RunLoop loop; auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(util::read_file("test/fixtures/resources/style-unused-sources.json")); style.addSource(std::make_unique("sourceId", "mptiler://tiles/contours")); - + try { style.addSource(std::make_unique("sourceId", "mptiler://tiles/contours")); FAIL() << "Should not have been allowed to add a duplicate source id"; @@ -86,7 +86,7 @@ TEST(Style, RemoveSourceInUse) { Log::setObserver(std::unique_ptr(log)); auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(util::read_file("test/fixtures/resources/style-unused-sources.json")); @@ -98,11 +98,11 @@ TEST(Style, RemoveSourceInUse) { ASSERT_EQ(nullptr, removed); ASSERT_NE(nullptr, style.getSource("sourceId")); - const FixtureLogObserver::LogMessage logMessage { - EventSeverity::Warning, - Event::General, - int64_t(-1), - "Source 'sourceId' is in use, cannot remove", + const FixtureLogObserver::LogMessage logMessage{ + EventSeverity::Warning, + Event::General, + int64_t(-1), + "Source 'sourceId' is in use, cannot remove", }; #if defined(WIN32) diff --git a/test/style/style_image.test.cpp b/test/style/style_image.test.cpp index 7bc58592417..e64f4b0f035 100644 --- a/test/style/style_image.test.cpp +++ b/test/style/style_image.test.cpp @@ -8,7 +8,7 @@ using namespace mbgl; TEST(StyleImage, ZeroWidth) { try { - style::Image("test", PremultipliedImage({ 0, 16 }), 2.0f); + style::Image("test", PremultipliedImage({0, 16}), 2.0f); FAIL() << "Expected exception"; } catch (util::StyleImageException& ex) { EXPECT_STREQ("dimensions may not be zero", ex.what()); @@ -17,7 +17,7 @@ TEST(StyleImage, ZeroWidth) { TEST(StyleImage, ZeroHeight) { try { - style::Image("test", PremultipliedImage({ 16, 0 }), 2.0f); + style::Image("test", PremultipliedImage({16, 0}), 2.0f); FAIL() << "Expected exception"; } catch (util::StyleImageException& ex) { EXPECT_STREQ("dimensions may not be zero", ex.what()); @@ -26,7 +26,7 @@ TEST(StyleImage, ZeroHeight) { TEST(StyleImage, ZeroRatio) { try { - style::Image("test", PremultipliedImage({ 16, 16 }), 0.0f); + style::Image("test", PremultipliedImage({16, 16}), 0.0f); FAIL() << "Expected exception"; } catch (util::StyleImageException& ex) { EXPECT_STREQ("pixelRatio may not be <= 0", ex.what()); @@ -34,14 +34,14 @@ TEST(StyleImage, ZeroRatio) { } TEST(StyleImage, Retina) { - style::Image image("test", PremultipliedImage({ 32, 24 }), 2.0f); + style::Image image("test", PremultipliedImage({32, 24}), 2.0f); EXPECT_EQ(32u, image.getImage().size.width); EXPECT_EQ(24u, image.getImage().size.height); EXPECT_EQ(2, image.getPixelRatio()); } TEST(StyleImage, FractionalRatio) { - style::Image image("test", PremultipliedImage({ 20, 12 }), 1.5f); + style::Image image("test", PremultipliedImage({20, 12}), 1.5f); EXPECT_EQ(20u, image.getImage().size.width); EXPECT_EQ(12u, image.getImage().size.height); EXPECT_EQ(1.5, image.getPixelRatio()); @@ -110,8 +110,12 @@ TEST(StyleImage, InvalidContent) { } TEST(StyleImage, StretchContent) { - style::Image image( - "test", PremultipliedImage({16, 16}), 1, {{2.0f, 14.0f}}, {{0.0f, 4.0f}, {12.0f, 16.0f}}, style::ImageContent{2, 2, 14, 14}); + style::Image image("test", + PremultipliedImage({16, 16}), + 1, + {{2.0f, 14.0f}}, + {{0.0f, 4.0f}, {12.0f, 16.0f}}, + style::ImageContent{2, 2, 14, 14}); EXPECT_EQ(16u, image.getImage().size.width); EXPECT_EQ(16u, image.getImage().size.height); EXPECT_EQ(1.0, image.getPixelRatio()); diff --git a/test/style/style_layer.test.cpp b/test/style/style_layer.test.cpp index 1417fd1d673..c6c5478baaf 100644 --- a/test/style/style_layer.test.cpp +++ b/test/style/style_layer.test.cpp @@ -37,13 +37,13 @@ using namespace std::literals::string_literals; namespace { -const auto color = Color { 1, 0, 0, 1 }; +const auto color = Color{1, 0, 0, 1}; const auto opacity = 1.0f; const auto radius = 1.0f; const auto blur = 1.0f; const auto pattern = PropertyValue{"foo"}; const auto antialias = false; -const auto translate = std::array {{ 0, 0 }}; +const auto translate = std::array{{0, 0}}; const auto translateAnchor = TranslateAnchorType::Map; const auto lineCap = LineCapType::Round; const auto lineJoin = LineJoinType::Miter; @@ -52,7 +52,7 @@ const auto roundLimit = 1.0f; const auto width = 1.0f; const auto gapWidth = 1.0f; const auto offset = 1.0f; -const auto dashArray = std::vector {}; +const auto dashArray = std::vector{}; const auto hueRotate = 1.0f; const auto brightness = 1.0f; const auto saturation = 1.0f; @@ -225,7 +225,7 @@ TEST(Layer, Observer) { // Notifies observer on filter change. bool filterChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); filterChanged = true; }; @@ -234,7 +234,7 @@ TEST(Layer, Observer) { // Notifies observer on visibility change. bool visibilityChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); visibilityChanged = true; }; @@ -243,7 +243,7 @@ TEST(Layer, Observer) { // Notifies observer on paint property change. bool paintPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); paintPropertyChanged = true; }; @@ -252,7 +252,7 @@ TEST(Layer, Observer) { // Notifies observer on layout property change. bool layoutPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); layoutPropertyChanged = true; }; @@ -261,7 +261,7 @@ TEST(Layer, Observer) { // Does not notify observer on no-op visibility change. visibilityChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); visibilityChanged = true; }; @@ -270,7 +270,7 @@ TEST(Layer, Observer) { // Does not notify observer on no-op paint property change. paintPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); paintPropertyChanged = true; }; @@ -279,7 +279,7 @@ TEST(Layer, Observer) { // Does not notify observer on no-op layout property change. layoutPropertyChanged = false; - observer.layerChanged = [&] (Layer& layer_) { + observer.layerChanged = [&](Layer& layer_) { EXPECT_EQ(layer.get(), &layer_); layoutPropertyChanged = true; }; @@ -292,7 +292,7 @@ TEST(Layer, DuplicateLayer) { // Setup style auto fileSource = std::make_shared(); - Style::Impl style { fileSource, 1.0 }; + Style::Impl style{fileSource, 1.0}; style.loadJSON(util::read_file("test/fixtures/resources/style-unused-sources.json")); // Add initial layer @@ -319,7 +319,8 @@ TEST(Layer, IncompatibleLayer) { // Try to add duplicate try { style.addLayer(std::make_unique("raster", "unusedsource")); - FAIL() << "Should not have been allowed to add an incompatible layer to the source"; + FAIL() << "Should not have been allowed to add an incompatible layer " + "to the source"; } catch (const std::runtime_error& e) { // Expected ASSERT_STREQ("Layer 'raster' is not compatible with source 'unusedsource'", e.what()); @@ -328,7 +329,7 @@ TEST(Layer, IncompatibleLayer) { namespace { -template class PropertyValueType, typename LayoutType> +template