[general] moving ios and android project under ./platform folder

This commit is contained in:
Petr Pokorny
2020-12-20 12:38:56 +01:00
parent 8e759a51e4
commit 41f0be34e7
9877 changed files with 141 additions and 2889 deletions

284
platform/node/CHANGELOG.md Normal file
View File

@@ -0,0 +1,284 @@
# master
* 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))
# 5.0.0
* No longer supporting source-compile fallback ([#15748](https://github.com/mapbox/mapbox-gl-native/pull/15748))
* Add support for feature state APIs. ([#15480](https://github.com/mapbox/mapbox-gl-native/pull/15480))
# 4.3.0
* Introduce `text-writing-mode` layout property for symbol layer ([#14932](https://github.com/mapbox/mapbox-gl-native/pull/14932)). The `text-writing-mode` layout property allows control over symbol's preferred writing mode. The new property value is an array, whose values are enumeration values from a ( `horizontal` | `vertical` ) set.
* Fixed rendering and collision detection issues with using `text-variable-anchor` and `icon-text-fit` properties on the same layer ([#15367](https://github.com/mapbox/mapbox-gl-native/pull/15367)).
* Fixed a rendering issue that non-SDF icon would be treated as SDF icon if they are in the same layer. ([#15456](https://github.com/mapbox/mapbox-gl-native/pull/15456))
* Fixed a rendering issue of `collisionBox` when `text-translate` or `icon-translate` is enabled. ([#15467](https://github.com/mapbox/mapbox-gl-native/pull/15467))
* Fixed an issue of integer overflow when converting `tileCoordinates` to `LatLon`, which caused issues such as `queryRenderedFeatures` and `querySourceFeatures` returning incorrect coordinates at zoom levels 20 and higher. ([#15560](https://github.com/mapbox/mapbox-gl-native/pull/15560))
* Add typechecking while constructing legacy filter to prevent converting an unexpected filter type [#15389](https://github.com/mapbox/mapbox-gl-native/pull/15389).
* Fixed an issue that `maxzoom` in style `Sources` option was ignored when URL resource is provided. It may cause problems such as extra tiles downloading at higher zoom level than `maxzoom`, or problems that wrong setting of `overscaledZ` in `OverscaledTileID` that will be passed to `SymbolLayout`, leading wrong rendering appearance. ([#15581](https://github.com/mapbox/mapbox-gl-native/pull/15581))
# 4.2.0
- Add an option to set whether or not an image should be treated as a SDF ([#15054](https://github.com/mapbox/mapbox-gl-native/issues/15054))
- Fix problems associated with node 10 and NAN ([#14847](https://github.com/mapbox/mapbox-gl-native/pull/14847))
# 4.1.0
- Add `symbol-z-order` symbol layout property to style spec ([#12783](https://github.com/mapbox/mapbox-gl-native/pull/12783))
- Add `crossSourceCollisions` map option, with default of `true`. When set to `false`, cross-source collision detection is disabled. ([#12820](https://github.com/mapbox/mapbox-gl-native/issues/12820))
- Fixed bugs in coercion expression operators ("to-array" applied to empty arrays, "to-color" applied to colors, and "to-number" applied to null) ([#12864](https://github.com/mapbox/mapbox-gl-native/pull/12864))
- Fixed an issue where fill and line layers would occasionally flicker on zoom ([#12982](https://github.com/mapbox/mapbox-gl-native/pull/12982))
# 4.0.0
- Many new features and enhancements, including:
- Expressions
- Hillshade layer type
- Heatmap layer type
- Line gradients
- Improve label collision
- Support for data-driven values for more style properties
- Support for rendering with SwiftShader rather than hardware GPU
- Improved performance and stability
- Don't default-show text/icons that depend on the placement of a paired icon/text [#12483](https://github.com/mapbox/mapbox-gl-native/issues/12483)
- Fix symbol querying for annotations near tile boundaries at high zoom. ([#12472](https://github.com/mapbox/mapbox-gl-native/issues/12472))
- The `Map` constructor now accepts a `mode` option which can be either `"static"` (default) or `"tile"`. It must be set to `"tile"` when rendering individual tiles in order for the symbols to match across tiles.
- Remove unnecessary memory use when collision debug mode is not enabled ([#12294](https://github.com/mapbox/mapbox-gl-native/issues/12294))
- Added support for rendering `symbol-placement: line-center` ([#12337](https://github.com/mapbox/mapbox-gl-native/pull/12337))
- Fix rendering of fill outlines that have a different color than the fill itself ([#9699](https://github.com/mapbox/mapbox-gl-native/pull/9699))
- Add support for feature expressions in `line-pattern`, `fill-pattern`, and `fill-extrusion-pattern` properties. [#12284](https://github.com/mapbox/mapbox-gl-native/pull/12284)
# 3.5.8 - October 19, 2017
- Fixes an issue that causes memory leaks when not deleting the frontend object
in NodeMap::release()
- Fixes a crash in Earcut: [#10245](https://github.com/mapbox/mapbox-gl-native/pull/10245)
# 3.5.7 - October 9, 2017
- Fixed an issue causing synchronous resource requests to stall [#10153](https://github.com/mapbox/mapbox-gl-native/pull/10153)
# 3.5.6 - September 29, 2017
- Protects against requests which throw [#9554](https://github.com/mapbox/mapbox-gl-native/pull/9554)
- Fixed an issue around reusing a map object [#9554](https://github.com/mapbox/mapbox-gl-native/pull/9554)
- Fixed an issue in test [#9553](https://github.com/mapbox/mapbox-gl-native/pull/9553)
- Increased the default maximum zoom level from 20 to 22 ([#9835](https://github.com/mapbox/mapbox-gl-native/pull/9835))
# 3.5.5 - July 14, 2017
- Provide debuggable release builds for node packages [#9497](https://github.com/mapbox/mapbox-gl-native/pull/9497)
# 3.5.4 - June 6, 2017
- Add support for ImageSource [#8968](https://github.com/mapbox/mapbox-gl-native/pull/8968)
- Fixed an issue with `map.addImage()` which would cause added images to randomly be replaced with images found the style's sprite sheet ([#9119](https://github.com/mapbox/mapbox-gl-native/pull/9119))
# 3.5.3 - May 30, 2017
- Fixed a regression around `line-dasharrary` and `fill-pattern` that caused these properties to sometimes not render correctly ([#9130](https://github.com/mapbox/mapbox-gl-native/pull/9130))
# 3.5.2 - May 18, 2017
- Fixed a memory leak ([#8884](https://github.com/mapbox/mapbox-gl-native/pull/9035))
# 3.5.1 - May 8, 2017
- Adds Node v6 binaries. **Note, Node v4 binaries will be removed on August 1st.** ([#8884](https://github.com/mapbox/mapbox-gl-native/pull/8884))
- Adds linux debug binaries ([#8865](https://github.com/mapbox/mapbox-gl-native/pull/8865))
# 3.5.0 - April 20, 2017
- Fixed an issue where raster tiles that were not found caused `map.render()` to hang ([#8769](https://github.com/mapbox/mapbox-gl-native/pull/8769))
- Adds method `map.cancel()` which cancels an ongoing `render` call. ([#8249](https://github.com/mapbox/mapbox-gl-native/pull/8249))
# 3.4.7 - March 15, 2017
- Fixed MacOS Release builds ([8409](https://github.com/mapbox/mapbox-gl-native/pull/8409))
# 3.4.6 - March 14, 2017
- Publishes `Release` build on Mac ([#8407](https://github.com/mapbox/mapbox-gl-native/pull/8407))
- Fixes the publish binary build process ([#8406](https://github.com/mapbox/mapbox-gl-native/pull/8406))
# 3.4.5 - March 14, 2017
- Fixed a memory hang issue after GlyphAtlas was refactored ([#8394](https://github.com/mapbox/mapbox-gl-native/pull/8394))
# 3.4.4 - January 10, 2017
- Updates the node binary publish location on s3 to reflect new package name ([#7653](https://github.com/mapbox/mapbox-gl-native/pull/7653))
# 3.4.3 - January 9, 2017
- Adds `map.addImage()` and `map.removeImage()` APIs ([#7610](https://github.com/mapbox/mapbox-gl-native/pull/7610))
# 3.4.2 - November 15, 2016
- Switches back to publishing Linux binaries with GLX, to eliminate a runtime dependency on `libOSMesa.so.8` and enable dynamically linking against `libGL.so` provided by an alternate implementation, such as the NVIDIA proproetary drivers ([#7503](https://github.com/mapbox/mapbox-gl-native/pull/7053))
# 3.4.1 - November 10, 2016
- Skips assigning clip IDs to tiles that won't be rendered, mitigating a `stencil mask overflow` error ([#6871](https://github.com/mapbox/mapbox-gl-native/pull/6871))
- Fixes camera logic to avoid unnecessary or redundant setting of camera options ([#6990](https://github.com/mapbox/mapbox-gl-native/pull/6990))
# 3.4.0 - November 2, 2016
- Fixes Bitrise configuration to automatically publish macOS binaries ([#6789](https://github.com/mapbox/mapbox-gl-native/pull/6789))
- Switches from using individual thread pools for each `mbgl::Map` object to sharing the built-in Node.js thread pool for NodeMap implementations ([#6687](https://github.com/mapbox/mapbox-gl-native/pull/6687))
# 3.3.3 - September 6, 2016
- Switches to using a NodeRequest member function (with a JavaScript shim in front to preserve the API) instead of a new `v8::Context` to avoid a memory leak ([#5704](https://github.com/mapbox/mapbox-gl-native/pull/5704))
- `map.load` can now throw when failing to parse an invalid style ([#6151](https://github.com/mapbox/mapbox-gl-native/pull/6151))
- Explicitly links the OpenGL framework for compatibility with macOS Sierra ([#6015](https://github.com/mapbox/mapbox-gl-native/pull/6015))
# 3.3.2 - August 1, 2016
- Fixes Node.js binary publishing to build with `BUILDTYPE=Release` ([#5838](https://github.com/mapbox/mapbox-gl-native/pull/5838))
# 3.3.1 - July 29, 2016
- Fixes `minzoom` and `maxzoom` properties ([#5828](https://github.com/mapbox/mapbox-gl-native/pull/5828))
- Fixes `RunLoop::runOnce()` to use `UV_RUN_NOWAIT` instead of `UV_RUN_ONCE` (which can block the libuv threadpool) ([#5758](https://github.com/mapbox/mapbox-gl-native/pull/5758))
- Map debug options 'overdraw' and 'stencil clip' are now disabled (no-ops) in release mode ([#5555](https://github.com/mapbox/mapbox-gl-native/pull/5555))
# 3.3.0 - July 14, 2016
- Adds runtime styling API ([#5318](https://github.com/mapbox/mapbox-gl-native/pull/5318), [#5380](https://github.com/mapbox/mapbox-gl-native/pull/5380), [#5428](https://github.com/mapbox/mapbox-gl-native/pull/5428), [#5429](https://github.com/mapbox/mapbox-gl-native/pull/5429), [#5462](https://github.com/mapbox/mapbox-gl-native/pull/5462), [#5614](https://github.com/mapbox/mapbox-gl-native/pull/5614), [#5670](https://github.com/mapbox/mapbox-gl-native/pull/5670))
- Adds `BUILDTYPE=Debug` support to `make node` ([#5474](https://github.com/mapbox/mapbox-gl-native/pull/5474))
- Fixes a memory leak in `NodeRequest` ([#5529](https://github.com/mapbox/mapbox-gl-native/pull/5529))
# 3.2.1 - June 7, 2016
- Fixes a memory leak in raster image data ([#5269](https://github.com/mapbox/mapbox-gl-native/pull/5269))
# 3.2.0 - June 3, 2016
- Switches to [earcut.hpp](https://github.com/mapbox/earcut.hpp) for tessellation ([#2444](https://github.com/mapbox/mapbox-gl-native/pull/2444))
# 3.1.3 - May 27, 2016
- Fixes a leak in TexturePoolHolder ([#5141](https://github.com/mapbox/mapbox-gl-native/pull/5141))
- Fixes a bug where a callback would be fired after an AsyncRequest had been cancelled ([#5162](https://github.com/mapbox/mapbox-gl-native/pull/5162))
# 3.1.2 - April 26, 2016
- Fixes a race condition with animated transitions ([#4836](https://github.com/mapbox/mapbox-gl-native/pull/4836))
# 3.1.1 - April 11, 2016
- Moves node-pre-gyp from `bundledDependencies` to `preinstall` ([#4680](https://github.com/mapbox/mapbox-gl-native/pull/4680))
# 3.1.0 - April 8, 2016
- Adds debug render options ([#3840](https://github.com/mapbox/mapbox-gl-native/pull/3840))
- Fixes circle bucket rendering on tile boundaries ([#3764](https://github.com/mapbox/mapbox-gl-native/issues/3764))
- Fixes a segfault caused by improperly disposing the entire module in the `NodeLog` destructor ([#4639](https://github.com/mapbox/mapbox-gl-native/pull/4639))
- Fixes an issue with vanishing GeoJSON layers at high zoom levels ([#4632](https://github.com/mapbox/mapbox-gl-native/issues/4632))
- Fixes inheritance from EventEmitter ([#4567](https://github.com/mapbox/mapbox-gl-native/pull/4576))
- Fixes intermittent `stencil mask overflow` error ([#962](https://github.com/mapbox/mapbox-gl-native/issues/962))
- Drops support for Node.js v5.x prebuilt binaries due to ongoing npm3 instability ([#4370](https://github.com/mapbox/mapbox-gl-native/issues/4370))
# 3.0.2 - February 4, 2016
- Fixes a memory leak in `NodeMap::request` ([#3829](https://github.com/mapbox/mapbox-gl-native/pull/3829))
- Increases default max zoom level from 18 to 20 ([#3712](https://github.com/mapbox/mapbox-gl-native/pull/3712))
- Support tiles with non-4096 extents ([#3766](https://github.com/mapbox/mapbox-gl-native/pull/3766))
# 3.0.1 - January 26, 2016
- Fixes missing icon collision boxes ([#3672](https://github.com/mapbox/mapbox-gl-native/pull/3672))
- Fixes texture filtering to draw sharper icons ([#3669](https://github.com/mapbox/mapbox-gl-native/pull/3669))
# 3.0.0 - January 21, 2016
- Drops support for Node.js v0.10.x ([#3635](https://github.com/mapbox/mapbox-gl-native/pull/3635))
- Fixes label clipping issues with `symbol-avoid-edges` ([#3623](https://github.com/mapbox/mapbox-gl-native/pull/3623))
- Avoids label placement around sharp zig-zags ([#3640](https://github.com/mapbox/mapbox-gl-native/pull/3640))
# 2.2.2 - January 19, 2016
- Fixes a bug with non-deterministic label placement [#3543](https://github.com/mapbox/mapbox-gl-native/pull/3543)
# 2.2.1 - January 7, 2016
- Fixes a bug which clipped labels at tile boundaries [#2829](https://github.com/mapbox/mapbox-gl-native/pull/2829)
# 2.2.0 - December 16, 2015
- Adds support for GeoJSON sources [#2161](https://github.com/mapbox/mapbox-gl-native/pull/2161)
# 2.1.0 - December 8, 2015
- Adds [`line-offset`](https://github.com/mapbox/mapbox-gl/issues/3) style property support
# 2.0.1 - November 25, 2015
- Test and publish binaries for Node.js v5.x. ([#3129](https://github.com/mapbox/mapbox-gl-native/pull/3129))
# 2.0.0 - November 24, 2015
- Integrates Node.js bindings into core mapbox-gl-native project. ([#2179](https://github.com/mapbox/mapbox-gl-native/pull/2179))
- Adds Node.js v4.x and io.js v3.x support. ([#2261](https://github.com/mapbox/mapbox-gl-native/pull/2261))
- Requires an options object argument to `new mbgl.Map()`
(with required `request` and optional `cancel` methods),
drops `mbgl.FileSource`. ([mapbox/node-mapbox-gl-native#143](https://github.com/mapbox/node-mapbox-gl-native/pull/143))
- Changes `request` semantics to pass a second, callback argument instead
of needing to call `req.respond`. ([#2299](https://github.com/mapbox/mapbox-gl-native/pull/2299))
- Accepts optional `ratio` (defaults to `1.0`) in `mbgl.Map` options
argument. Map pixel ratio is now immutable and can no longer be set with
render options. ([`a8d9b92`](https://github.com/mapbox/mapbox-gl-native/commit/a8d9b921d71a91d7f8eff82e5a584aaab8b7d1c6), [#1799](https://github.com/mapbox/mapbox-gl-native/pull/1799), [#2937](https://github.com/mapbox/mapbox-gl-native/pull/2937))
- Swaps array order in render options `center` argument to `[lng, lat]` for consistency with GeoJSON and mapbox-gl-js. ([#2935](https://github.com/mapbox/mapbox-gl-native/pull/2935))
- Adds render option `pitch`. ([#2702](https://github.com/mapbox/mapbox-gl-native/pull/2702))
- `map.render` now returns a raw image buffer instead of an object with
`width`, `height` and `pixels` properties. ([#2262](https://github.com/mapbox/mapbox-gl-native/pull/2262))
- Adds support for rendering [mapbox-gl-style-spec](https://github.com/mapbox/mapbox-gl-style-spec) v8 styles.
- No longer loads resources before a render request is made. ([`55d25a8`](https://github.com/mapbox/mapbox-gl-native/commit/55d25a80a77c06ef5e66acc0d8518867b03fe8a4))
- Fixes a bug which prevented raster tiles that `404`'ed from rendering. ([#2458](https://github.com/mapbox/mapbox-gl-native/pull/2458))
- Fade transitions are now ignored to prevent half faded labels. ([#942](https://github.com/mapbox/mapbox-gl-native/pull/942))
- Labels can now line wrap on hyphens and other punctuation. ([#2598](https://github.com/mapbox/mapbox-gl-native/pull/2598))
# 1.1.3 - June 25, 2015
- Removes deprecated mbgl::Environment from NodeLogObserver.
# 1.1.2 - June 22, 2015
- Check libuv version semver-ishly, fixes segfaults in Node.js 0.12.x
and io.js.
- Fixes segfault, throws JavaScript error instead when attempting to
render without first loading a style.
- Bumps mbgl submodule to v0.4.0
# 1.1.1 - June 16, 2015
- Bumps mbgl submodule to v0.3.5
# 1.1.0 - June 15, 2015
- Adds Node.js v0.12.x and io.js support.
- Adds `map.release()` method for manual cleanup of map resources.
- Fixes garbage collection of NodeMap objects.
- Returns an error callback for failed NodeFileSource requests.
- Fixes handling of corrupt NodeFileSource request data.
- Implements request coalescing to fix NodeRequest cancellation.
- Removes `setAccessToken` method from NodeMap, `mapbox://` URLs
should be handled through `NodeFileSource` now.
- Updates build scripts and Travis CI configuration.
- Logs Environment ID and thread name when in an Environment scope.
- Refactors NodeLog to implement mbgl::Log::Observer.
- Fixes uncaught exception from missing sprites.
- Fixes Unicode glyph range end.
# 1.0.3 - April 3, 2015
- Fixes crash during garbage collection by assigning FileSource handle
to a v8::Persistent in NodeMap constructor.
# 1.0.2 - April 2, 2015
- Initialize shared display connection at module load time to avoid
race condition when display connection is initialized on-demand.
# 1.0.1 - March 19, 2015
- Adapts NodeFileSource around mbgl::Environment additions.
- Adapts to minor changes in mapbox-gl-test-suite.
- Adds tests for gzipped vector tile handling.
- Cleans up documentation.
# 1.0.0 - February 25, 2015
- Initial release.

View File

@@ -0,0 +1,53 @@
if(NOT EXISTS ${PROJECT_SOURCE_DIR}/node_modules/@mapbox/cmake-node-module/module.cmake)
message("-- Not building node bindings, dependencies not found. Run 'npm update'.")
return()
endif()
set(NODE_MODULE_CACHE_DIR ${CMAKE_SOURCE_DIR}/build/headers)
include(${PROJECT_SOURCE_DIR}/node_modules/@mapbox/cmake-node-module/module.cmake)
add_node_module(
mbgl-node
INSTALL_PATH ${PROJECT_SOURCE_DIR}/lib/{node_abi}/mbgl.node
NAN_VERSION 2.10.0
EXCLUDE_NODE_ABIS
46
47
48
51
59
67
72
79
83
)
target_sources(
mbgl-node
INTERFACE
${PROJECT_SOURCE_DIR}/platform/node/src/node_conversion.hpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_expression.cpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_expression.hpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_feature.cpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_feature.hpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_logging.cpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_logging.hpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_map.cpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_map.hpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_mapbox_gl_native.cpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_request.cpp
${PROJECT_SOURCE_DIR}/platform/node/src/node_request.hpp
${PROJECT_SOURCE_DIR}/platform/node/src/util/async_queue.hpp
)
target_link_libraries(
mbgl-node
INTERFACE Mapbox::Map
)
# 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)
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()

View File

@@ -0,0 +1,58 @@
# Developing the Mapbox GL Native Node.js module
This document explains how to build the [Node.js](https://nodejs.org/) bindings for [Mapbox GL Native](../../README.md) for contributing to the development of the bindings themselves. If you just want to use the module, you can simply install it via `npm`; see [README.md](README.md) for installation and usage instructions.
## Building
To develop these bindings, you’ll need to build them from source. Building requires the prerequisites listed in either
the [macOS](../macos/INSTALL.md#requirements) or [Linux](../linux/README.md#prerequisites) install documentation, depending
on the target platform.
To compile the Node.js bindings and install module dependencies, from the repository root directory, first run:
```
make distclean
```
If you are rebuilding after time has passed.
Then do:
```bash
make node
```
## Testing
To test the Node.js bindings:
```bash
npm test
```
## Merging your pull request
To clean up your pull request and prepare it for merging, update your local `master` branch, then run `git rebase -i master` from your pull request branch to squash/fixup commits as needed. When your work is ready to be merged, you can run `git merge --ff-only YOUR_BRANCH` from `master` or click the green merge button in the GitHub UI, which will automatically squash your branch down into a single commit before merging it.
## Publishing
We aim to publish the `@mapbox/mapbox-gl-native` package on the same four-week cadence as the iOS, Android, and JavaScript SDKs, including a beta release one week prior to the final release. Responsibility for publishing rotates between team members.
To publish a new version of the package:
- [ ] make a commit in the release branch which includes:
- [ ] an updated version number in [`package.json`](../../package.json#L3)
- [ ] an entry in [`platform/node/CHANGELOG.md`](CHANGELOG.md) describing the changes in the release
- [ ] run `git tag node-v{VERSION}` where `{VERSION}` matches the version in `package.json`, e.g. `git tag node-v3.3.2`
- [ ] run `git push && git push --tags`
The CI builds for tag pushes will check if the tag matches the version listed in `package.json`, and if so, will run with `BUILDTYPE=Release` and publish a binary with `node-pre-gyp`.
Once binaries have been published for Linux and macOS (which can be verified with `./node_modules/.bin/node-pre-gyp info`), you can run a quick final check to ensure they're being fetched properly by simply running `rm -rf lib && npm install`.
If everything looks good:
- [ ] run `mbx npm publish`
### Preleases
Publishing a prerelease binary can be useful for testing downstream integrations - the workflow is pretty much the same except that you'll be making your version number commit and `git tag node-v{VERSION}` (like `git tag node-v3.3.2-pre.1`) on a pull request branch before merging it rather than on `master`.

201
platform/node/README.md Normal file
View File

@@ -0,0 +1,201 @@
# node-mapbox-gl-native
[![NPM](https://nodei.co/npm/@mapbox/mapbox-gl-native.png)](https://npmjs.org/package/@mapbox/mapbox-gl-native)
## Installing
Requires a modern C++ runtime that supports C++14.
By default, installs binaries. On these platforms no additional dependencies are needed.
- 64 bit macOS or 64 bit Linux
- Node.js v10.x
Run:
```
npm install @mapbox/mapbox-gl-native
```
Other platforms will fall back to a source compile with `make node`; see [DEVELOPING.md](DEVELOPING.md) for details on
building from source.
## Testing
```
npm test
npm run test-suite
```
## Rendering a map tile
```js
var fs = require('fs');
var path = require('path');
var mbgl = require('@mapbox/mapbox-gl-native');
var sharp = require('sharp');
var options = {
request: function(req, callback) {
fs.readFile(path.join(__dirname, 'test', req.url), function(err, data) {
callback(err, { data: data });
});
},
ratio: 1
};
var map = new mbgl.Map(options);
map.load(require('./test/fixtures/style.json'));
map.render({zoom: 0}, function(err, buffer) {
if (err) throw err;
map.release();
var image = sharp(buffer, {
raw: {
width: 512,
height: 512,
channels: 4
}
});
// Convert raw image buffer to PNG
image.toFile('image.png', function(err) {
if (err) throw err;
});
});
```
The first argument passed to `map.render` is an options object, all keys are optional:
```js
{
zoom: {zoom}, // number, defaults to 0
width: {width}, // number (px), defaults to 512
height: {height}, // number (px), defaults to 512
center: [{longitude}, {latitude}], // array of numbers (coordinates), defaults to [0,0]
bearing: {bearing}, // number (in degrees, counter-clockwise from north), defaults to 0
pitch: {pitch}, // number (in degrees, arcing towards the horizon), defaults to 0
classes: {classes} // array of strings
}
```
When you are finished using a map object, you can call `map.release()` to permanently dispose the internal map resources. This is not necessary, but can be helpful to optimize resource usage (memory, file sockets) on a more granular level than V8's garbage collector. Calling `map.release()` will prevent a map object from being used for any further render calls, but can be safely called as soon as the `map.render()` callback returns, as the returned pixel buffer will always be retained for the scope of the callback.
## Implementing a file source
When creating a `Map`, you must pass an options object (with a required `request` method and optional 'ratio' number) as the first parameter.
```js
var map = new mbgl.Map({
request: function(req) {
// TODO
},
ratio: 2.0
});
```
The `request()` method handles a request for a resource. The `ratio` sets the scale at which the map will render tiles, such as `2.0` for rendering images for high pixel density displays. The `req` parameter has two properties:
```json
{
"url": "http://example.com",
"kind": 1
}
```
The `kind` is an enum and defined in [`mbgl.Resource`](https://github.com/mapbox/mapbox-gl-native/blob/master/include/mbgl/storage/resource.hpp):
```json
{
"Unknown": 0,
"Style": 1,
"Source": 2,
"Tile": 3,
"Glyphs": 4,
"SpriteImage": 5,
"SpriteJSON": 6
}
```
The `kind` enum has no significance for anything but serves as a hint to your implemention as to what sort of resource to expect. E.g., your implementation could choose caching strategies based on the expected file type.
The `request` implementation should pass uncompressed data to `callback`. If you are downloading assets from a source that applies gzip transport encoding, the implementation must decompress the results before passing them on.
A sample implementation that reads files from disk would look like the following:
```js
var map = new mbgl.Map({
request: function(req, callback) {
fs.readFile(path.join('base/path', req.url), function(err, data) {
callback(err, { data: data });
});
}
});
```
This is a very barebones implementation and you'll probably want a better implementation. E.g. it passes the url verbatim to the file system, but you'd want add some logic that normalizes `http` URLs. You'll notice that once your implementation has obtained the requested file, you have to deliver it to the requestee by calling `callback()`, which takes either an error object or `null` and an object with several keys:
```js
{
modified: new Date(),
expires: new Date(),
etag: "string",
data: new Buffer()
}
```
A sample implementation that uses [`request`](https://github.com/request/request) to fetch data from a remote source:
```js
var mbgl = require('mapbox-gl-native');
var request = require('request');
var map = new mbgl.Map({
request: function(req, callback) {
request({
url: req.url,
encoding: null,
gzip: true
}, function (err, res, body) {
if (err) {
callback(err);
} else if (res.statusCode == 200) {
var response = {};
if (res.headers.modified) { response.modified = new Date(res.headers.modified); }
if (res.headers.expires) { response.expires = new Date(res.headers.expires); }
if (res.headers.etag) { response.etag = res.headers.etag; }
response.data = body;
callback(null, response);
} else {
callback(new Error(JSON.parse(body).message));
}
});
}
});
```
Stylesheets are free to use any protocols, but your implementation of `request` must support these; e.g. you could use `s3://` to indicate that files are supposed to be loaded from S3.
## Listening for log events
The module imported with `require('mapbox-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/mapbox/mapbox-gl-native/blob/node-v2.1.0/include/mbgl/platform/event.hpp#L43-L60), [`severity`](https://github.com/mapbox/mapbox-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.
```js
var mbgl = require('mapbox-gl-native');
mbgl.on('message', function(msg) {
t.ok(msg, 'emits error');
t.equal(msg.class, 'Style');
t.equal(msg.severity, 'ERROR');
t.ok(msg.text.match(/Failed to load/), 'error text matches');
});
```
## Contributing
See [DEVELOPING.md](DEVELOPING.md) for instructions on building this module for development.

51
platform/node/index.js Normal file
View File

@@ -0,0 +1,51 @@
"use strict";
// Shim to wrap req.respond while preserving callback-passing API
var mbgl = require('../../lib/node-v' + process.versions.modules + '/mbgl');
var constructor = mbgl.Map.prototype.constructor;
var Map = function(options) {
if (!(options instanceof Object)) {
throw TypeError("Requires an options object as first argument");
}
if (!options.hasOwnProperty('request') || !(options.request instanceof Function)) {
throw TypeError("Options object must have a 'request' method");
}
var request = options.request;
return new constructor(Object.assign(options, {
request: function(req) {
// Protect against `request` implementations that call the callback synchronously,
// call it multiple times, or throw exceptions.
// http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
var responded = false;
var callback = function() {
var args = arguments;
if (!responded) {
responded = true;
process.nextTick(function() {
req.respond.apply(req, args);
});
} else {
console.warn('request function responded multiple times; it should call the callback only once');
}
};
try {
request(req, callback);
} catch (e) {
console.warn('request function threw an exception; it should call the callback with an error instead');
callback(e);
}
}
}));
};
Map.prototype = mbgl.Map.prototype;
Map.prototype.constructor = Map;
module.exports = Object.assign(mbgl, { Map: Map });

View File

@@ -0,0 +1,22 @@
#!/bin/bash
set -e
set -o pipefail
PACKAGE_JSON_VERSION=`node -e "console.log(require('./package.json').version)"`
if [[ "${CIRCLE_TAG}" == "node-v${PACKAGE_JSON_VERSION}" ]] || [[ "${PUBLISH:-}" == true ]]; then
# Changes to the version targets here should happen in tandem with updates to the
# EXCLUDE_NODE_ABIS property in cmake/node.cmake and the "node" engines property in
# package.json.
for TARGET in 6.0.0 8.0.0 10.0.0; do
if [[ "${BUILDTYPE}" == "RelWithDebInfo" ]]; then
./node_modules/.bin/node-pre-gyp package publish info --target="${TARGET}"
elif [[ "${BUILDTYPE}" == "Debug" ]]; then
./node_modules/.bin/node-pre-gyp package publish info --target="${TARGET}" --debug
else
echo "error: must provide either Debug or RelWithDebInfo for BUILDTYPE"
exit 1
fi
done
fi

View File

@@ -0,0 +1,146 @@
#pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
#include <mbgl/util/optional.hpp>
#include <mbgl/util/feature.hpp>
#include <mbgl/style/conversion/geojson.hpp>
#include <mbgl/style/conversion_impl.hpp>
namespace mbgl {
namespace style {
namespace conversion {
template <>
class ConversionTraits<v8::Local<v8::Value>> {
public:
static bool isUndefined(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
return value->IsUndefined() || value->IsNull();
}
static bool isArray(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
return value->IsArray();
}
static std::size_t arrayLength(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
// const_cast because v8::Local<T>::As is not marked const until node v8.0
v8::Local<v8::Array> array = const_cast<v8::Local<v8::Value>&>(value).As<v8::Array>();
return array->Length();
}
static v8::Local<v8::Value> arrayMember(const v8::Local<v8::Value>& value, std::size_t i) {
Nan::EscapableHandleScope scope;
// const_cast because v8::Local<T>::As is not marked const until node v8.0
v8::Local<v8::Array> array = const_cast<v8::Local<v8::Value>&>(value).As<v8::Array>();
return scope.Escape(Nan::Get(array, i).ToLocalChecked());
}
static bool isObject(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
return value->IsObject() && !value->IsArray();
}
static optional<v8::Local<v8::Value>> objectMember(const v8::Local<v8::Value>& value, const char * name) {
Nan::EscapableHandleScope scope;
if (!Nan::Has(Nan::To<v8::Object>(value).ToLocalChecked(), Nan::New(name).ToLocalChecked()).FromJust()) {
return {};
}
Nan::MaybeLocal<v8::Value> result = Nan::Get(Nan::To<v8::Object>(value).ToLocalChecked(), Nan::New(name).ToLocalChecked());
if (result.IsEmpty()) {
return {};
}
return {scope.Escape(result.ToLocalChecked())};
}
template <class Fn>
static optional<Error> eachMember(const v8::Local<v8::Value>& value, Fn&& fn) {
Nan::HandleScope scope;
v8::Local<v8::Array> names = Nan::GetOwnPropertyNames(Nan::To<v8::Object>(value).ToLocalChecked()).ToLocalChecked();
for (uint32_t i = 0; i < names->Length(); ++i) {
v8::Local<v8::Value> k = Nan::Get(names, i).ToLocalChecked();
v8::Local<v8::Value> v = Nan::Get(Nan::To<v8::Object>(value).ToLocalChecked(), k).ToLocalChecked();
optional<Error> result = fn(*Nan::Utf8String(k), std::move(v)); // NOLINT(performance-move-const-arg)
if (result) {
return result;
}
}
return {};
}
static optional<bool> toBool(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsBoolean()) {
return {};
}
return value->BooleanValue();
}
static optional<float> toNumber(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsNumber()) {
return {};
}
return value->NumberValue();
}
static optional<double> toDouble(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsNumber()) {
return {};
}
return value->NumberValue();
}
static optional<std::string> toString(const v8::Local<v8::Value>& value) {
Nan::HandleScope scope;
if (!value->IsString()) {
return {};
}
return std::string(*Nan::Utf8String(value));
}
static optional<Value> toValue(const v8::Local<v8::Value>& value) {
if (value->IsFalse()) {
return { false };
} else if (value->IsTrue()) {
return { true };
} else if (value->IsString()) {
return { std::string(*Nan::Utf8String(value)) };
} else if (value->IsUint32()) {
return { std::uint64_t(value->Uint32Value()) };
} else if (value->IsInt32()) {
return { std::int64_t(value->Int32Value()) };
} else if (value->IsNumber()) {
return { value->NumberValue() };
} else {
return {};
}
}
static optional<GeoJSON> toGeoJSON(const v8::Local<v8::Value>& value, Error& error) {
try {
Nan::JSON JSON;
std::string string = *Nan::Utf8String(JSON.Stringify(value->ToObject()).ToLocalChecked());
return parseGeoJSON(string, error);
} catch (const std::exception& ex) {
error = { ex.what() };
return {};
}
}
};
template <class T, class...Args>
optional<T> convert(const v8::Local<v8::Value>& value, Error& error, Args&&...args) {
return convert<T>(Convertible(value), error, std::forward<Args>(args)...);
}
} // namespace conversion
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,302 @@
#include "node_conversion.hpp"
#include "node_expression.hpp"
#include "node_feature.hpp"
#include <mbgl/style/expression/parsing_context.hpp>
#include <mbgl/style/expression/is_constant.hpp>
#include <mbgl/style/conversion/function.hpp>
#include <mbgl/style/conversion/geojson.hpp>
#include <mbgl/util/geojson.hpp>
#include <nan.h>
using namespace mbgl::style;
using namespace mbgl::style::expression;
namespace node_mbgl {
Nan::Persistent<v8::Function> NodeExpression::constructor;
void NodeExpression::Init(v8::Local<v8::Object> target) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Expression").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1); // what is this doing?
Nan::SetPrototypeMethod(tpl, "evaluate", Evaluate);
Nan::SetPrototypeMethod(tpl, "getType", GetType);
Nan::SetPrototypeMethod(tpl, "isFeatureConstant", IsFeatureConstant);
Nan::SetPrototypeMethod(tpl, "isZoomConstant", IsZoomConstant);
Nan::SetPrototypeMethod(tpl, "serialize", Serialize);
Nan::SetMethod(tpl, "parse", Parse);
constructor.Reset(tpl->GetFunction()); // what is this doing?
Nan::Set(target, Nan::New("Expression").ToLocalChecked(), tpl->GetFunction());
}
type::Type parseType(v8::Local<v8::Object> type) {
static std::unordered_map<std::string, type::Type> types = {{"string", type::String},
{"number", type::Number},
{"boolean", type::Boolean},
{"object", type::Object},
{"color", type::Color},
{"value", type::Value},
{"formatted", type::Formatted},
{"number-format", type::String},
{"resolvedImage", type::Image}};
v8::Local<v8::Value> v8kind = Nan::Get(type, Nan::New("kind").ToLocalChecked()).ToLocalChecked();
std::string kind(*v8::String::Utf8Value(v8kind));
if (kind == "array") {
type::Type itemType = parseType(Nan::Get(type, Nan::New("itemType").ToLocalChecked()).ToLocalChecked()->ToObject());
mbgl::optional<std::size_t> N;
v8::Local<v8::String> Nkey = Nan::New("N").ToLocalChecked();
if (Nan::Has(type, Nkey).FromMaybe(false)) {
N = Nan::To<v8::Int32>(Nan::Get(type, Nkey).ToLocalChecked()).ToLocalChecked()->Value();
}
return type::Array(itemType, N);
}
return types[kind];
}
void NodeExpression::Parse(const Nan::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Function> cons = Nan::New(constructor);
if (info.Length() < 1 || info[0]->IsUndefined()) {
return Nan::ThrowTypeError("Requires a JSON style expression argument.");
}
mbgl::optional<type::Type> expected;
if (info.Length() > 1 && info[1]->IsObject()) {
expected = parseType(info[1]->ToObject());
}
auto success = [&cons, &info](std::unique_ptr<Expression> result) {
auto nodeExpr = new NodeExpression(std::move(result));
const int argc = 0;
v8::Local<v8::Value> argv[0] = {};
auto wrapped = Nan::NewInstance(cons, argc, argv).ToLocalChecked();
nodeExpr->Wrap(wrapped);
info.GetReturnValue().Set(wrapped);
};
auto fail = [&info](const std::vector<ParsingError>& errors) {
v8::Local<v8::Array> result = Nan::New<v8::Array>();
for (std::size_t i = 0; i < errors.size(); ++i) {
const auto& error = errors[i];
v8::Local<v8::Object> err = Nan::New<v8::Object>();
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<uint32_t>(i)), err);
}
info.GetReturnValue().Set(result);
};
auto expr = info[0];
try {
mbgl::style::conversion::Convertible convertible(expr);
if (expr->IsObject() && !expr->IsArray() && expected) {
mbgl::style::conversion::Error error;
auto func = convertFunctionToExpression(*expected, convertible, error, false);
if (func) {
return success(std::move(*func));
}
return fail({ { error.message, "" } });
}
ParsingContext ctx = expected ? ParsingContext(*expected) : ParsingContext();
ParseResult parsed = ctx.parseLayerPropertyExpression(mbgl::style::conversion::Convertible(expr));
if (parsed) {
assert(ctx.getErrors().empty());
return success(std::move(*parsed));
}
return fail(ctx.getErrors());
} catch(std::exception &ex) {
return Nan::ThrowError(ex.what());
}
}
void NodeExpression::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to create new Expression objects");
}
info.GetReturnValue().Set(info.This());
}
struct ToValue {
v8::Local<v8::Value> operator()(mbgl::NullValue) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Null());
}
v8::Local<v8::Value> operator()(bool t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(double t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(const std::string& t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t).ToLocalChecked());
}
v8::Local<v8::Value> operator()(const std::vector<Value>& array) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> result = Nan::New<v8::Array>();
for (std::size_t i = 0; i < array.size(); i++) {
result->Set(i, toJS(array[i]));
}
return scope.Escape(result);
}
v8::Local<v8::Value> operator()(const Collator&) {
// Collators are excluded from constant folding and there's no Literal parser
// for them so there shouldn't be any way to serialize this value.
assert(false);
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Null());
}
v8::Local<v8::Value> operator()(const Formatted& formatted) {
// This mimics the internal structure of the Formatted class in formatted.js
// A better approach might be to use the explicit serialized form
// both here and on the JS side? e.g. toJS(fromExpressionValue<mbgl::Value>(formatted))
std::unordered_map<std::string, mbgl::Value> serialized;
std::vector<mbgl::Value> sections;
for (const auto& section : formatted.sections) {
std::unordered_map<std::string, mbgl::Value> serializedSection;
serializedSection.emplace("text", section.text);
if (section.fontScale) {
serializedSection.emplace("scale", *section.fontScale);
} else {
serializedSection.emplace("scale", mbgl::NullValue());
}
if (section.fontStack) {
std::string fontStackString;
serializedSection.emplace("fontStack", mbgl::fontStackToString(*section.fontStack));
} else {
serializedSection.emplace("fontStack", mbgl::NullValue());
}
if (section.textColor) {
serializedSection.emplace("textColor", section.textColor->toObject());
} else {
serializedSection.emplace("textColor", mbgl::NullValue());
}
sections.emplace_back(serializedSection);
}
serialized.emplace("sections", sections);
return toJS(serialized);
}
v8::Local<v8::Value> operator()(const mbgl::Color& color) {
return operator()(std::vector<Value> {
static_cast<double>(color.r),
static_cast<double>(color.g),
static_cast<double>(color.b),
static_cast<double>(color.a)
});
}
v8::Local<v8::Value> operator()(const std::unordered_map<std::string, Value>& map) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> result = Nan::New<v8::Object>();
for (const auto& entry : map) {
Nan::Set(result, Nan::New(entry.first).ToLocalChecked(), toJS(entry.second));
}
return scope.Escape(result);
}
v8::Local<v8::Value> operator()(const Image& image) { return toJS(image.toValue()); }
};
v8::Local<v8::Value> toJS(const Value& value) {
return Value::visit(value, ToValue());
}
void NodeExpression::Evaluate(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
if (info.Length() < 2 || !info[0]->IsObject()) {
return Nan::ThrowTypeError("Requires globals and feature arguments.");
}
mbgl::optional<float> zoom;
v8::Local<v8::Value> v8zoom = Nan::Get(info[0]->ToObject(), Nan::New("zoom").ToLocalChecked()).ToLocalChecked();
if (v8zoom->IsNumber()) zoom = v8zoom->NumberValue();
mbgl::optional<double> heatmapDensity;
v8::Local<v8::Value> v8heatmapDensity = Nan::Get(info[0]->ToObject(), Nan::New("heatmapDensity").ToLocalChecked()).ToLocalChecked();
if (v8heatmapDensity->IsNumber()) heatmapDensity = v8heatmapDensity->NumberValue();
Nan::JSON NanJSON;
conversion::Error conversionError;
mbgl::optional<mbgl::GeoJSON> geoJSON = conversion::convert<mbgl::GeoJSON>(info[1], conversionError);
if (!geoJSON) {
Nan::ThrowTypeError(conversionError.message.c_str());
return;
}
try {
mapbox::geojson::feature feature = geoJSON->get<mapbox::geojson::feature>();
auto result = expression->evaluate(zoom, feature, heatmapDensity);
if (result) {
info.GetReturnValue().Set(toJS(*result));
} else {
v8::Local<v8::Object> res = Nan::New<v8::Object>();
Nan::Set(res,
Nan::New("error").ToLocalChecked(),
Nan::New(result.error().message.c_str()).ToLocalChecked());
info.GetReturnValue().Set(res);
}
} catch(std::exception &ex) {
return Nan::ThrowTypeError(ex.what());
}
}
void NodeExpression::GetType(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
const type::Type type = expression->getType();
const std::string name = type.match([&] (const auto& t) { return t.getName(); });
info.GetReturnValue().Set(Nan::New(name.c_str()).ToLocalChecked());
}
void NodeExpression::IsFeatureConstant(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
info.GetReturnValue().Set(Nan::New(isFeatureConstant(*expression)));
}
void NodeExpression::IsZoomConstant(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
info.GetReturnValue().Set(Nan::New(isZoomConstant(*expression)));
}
void NodeExpression::Serialize(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto* nodeExpr = ObjectWrap::Unwrap<NodeExpression>(info.Holder());
const std::unique_ptr<Expression>& expression = nodeExpr->expression;
const mbgl::Value serialized = expression->serialize();
info.GetReturnValue().Set(toJS(serialized));
}
} // namespace node_mbgl

View File

@@ -0,0 +1,40 @@
#pragma once
#include <mbgl/style/conversion_impl.hpp>
#include <mbgl/style/expression/expression.hpp>
#include <exception>
#include <memory>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace node_mbgl {
v8::Local<v8::Value> toJS(const mbgl::style::expression::Value&);
class NodeExpression : public Nan::ObjectWrap {
public:
static void Init(v8::Local<v8::Object>);
private:
NodeExpression(std::unique_ptr<mbgl::style::expression::Expression> expression_)
: expression(std::move(expression_)){};
static void New(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Parse(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Evaluate(const Nan::FunctionCallbackInfo<v8::Value>&);
static void GetType(const Nan::FunctionCallbackInfo<v8::Value>&);
static void IsFeatureConstant(const Nan::FunctionCallbackInfo<v8::Value>&);
static void IsZoomConstant(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Serialize(const Nan::FunctionCallbackInfo<v8::Value>&);
static Nan::Persistent<v8::Function> constructor;
std::unique_ptr<mbgl::style::expression::Expression> expression;
};
} // namespace node_mbgl

View File

@@ -0,0 +1,179 @@
#include "node_feature.hpp"
namespace node_mbgl {
using namespace mapbox::geometry;
using Value = mbgl::Value;
using Feature = mbgl::Feature;
using FeatureIdentifier = mbgl::FeatureIdentifier;
using Geometry = mbgl::Feature::geometry_type;
using GeometryCollection = mapbox::geometry::geometry_collection<double>;
using Properties = mbgl::PropertyMap;
template <class T>
struct ToType {
public:
v8::Local<v8::String> operator()(const empty&) {
return type("Empty");
}
v8::Local<v8::String> operator()(const point<T>&) {
return type("Point");
}
v8::Local<v8::String> operator()(const line_string<T>&) {
return type("LineString");
}
v8::Local<v8::String> operator()(const polygon<T>&) {
return type("Polygon");
}
v8::Local<v8::String> operator()(const multi_point<T>&) {
return type("MultiPoint");
}
v8::Local<v8::String> operator()(const multi_line_string<T>&) {
return type("MultiLineString");
}
v8::Local<v8::String> operator()(const multi_polygon<T>&) {
return type("MultiPolygon");
}
v8::Local<v8::String> operator()(const geometry_collection<T>&) {
return type("GeometryCollection");
}
private:
v8::Local<v8::String> type(const char* type_) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(type_).ToLocalChecked());
}
};
template <class T>
struct ToCoordinatesOrGeometries {
public:
// Handles line_string, polygon, multi_point, multi_line_string, multi_polygon, and geometry_collection.
template <class E>
v8::Local<v8::Object> operator()(const std::vector<E>& vector) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> result = Nan::New<v8::Array>(vector.size());
for (std::size_t i = 0; i < vector.size(); ++i) {
Nan::Set(result, i, operator()(vector[i]));
}
return scope.Escape(result);
}
v8::Local<v8::Object> operator()(const point<T>& point) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> result = Nan::New<v8::Array>(2);
Nan::Set(result, 0, Nan::New(point.x));
Nan::Set(result, 1, Nan::New(point.y));
return scope.Escape(result);
}
v8::Local<v8::Object> operator()(const geometry<T>& geometry) {
return toJS(geometry);
}
};
struct ToValue {
v8::Local<v8::Value> operator()(mbgl::NullValue) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Null());
}
v8::Local<v8::Value> operator()(bool t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(int64_t t) {
return operator()(double(t));
}
v8::Local<v8::Value> operator()(uint64_t t) {
return operator()(double(t));
}
v8::Local<v8::Value> operator()(double t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t));
}
v8::Local<v8::Value> operator()(const std::string& t) {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(t).ToLocalChecked());
}
v8::Local<v8::Value> operator()(const std::vector<mbgl::Value>& array) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> result = Nan::New<v8::Array>();
for (std::size_t i = 0; i < array.size(); i++) {
result->Set(i, toJS(array[i]));
}
return scope.Escape(result);
}
v8::Local<v8::Value> operator()(const std::unordered_map<std::string, mbgl::Value>& map) {
return toJS(map);
}
};
v8::Local<v8::Object> toJS(const Geometry& geometry) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> result = Nan::New<v8::Object>();
Nan::Set(result,
Nan::New("type").ToLocalChecked(),
Geometry::visit(geometry, ToType<double>()));
Nan::Set(result,
Nan::New(geometry.is<GeometryCollection>() ? "geometries" : "coordinates").ToLocalChecked(),
Geometry::visit(geometry, ToCoordinatesOrGeometries<double>()));
return scope.Escape(result);
}
v8::Local<v8::Value> toJS(const Value& value) {
return Value::visit(value, ToValue());
}
v8::Local<v8::Object> toJS(const Properties& properties) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> result = Nan::New<v8::Object>();
for (const auto& property : properties) {
Nan::Set(result, Nan::New(property.first).ToLocalChecked(), toJS(property.second));
}
return scope.Escape(result);
}
v8::Local<v8::Object> toJS(const Feature& feature) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> result = Nan::New<v8::Object>();
Nan::Set(result, Nan::New("type").ToLocalChecked(), Nan::New("Feature").ToLocalChecked());
Nan::Set(result, Nan::New("geometry").ToLocalChecked(), toJS(feature.geometry));
Nan::Set(result, Nan::New("properties").ToLocalChecked(), toJS(feature.properties));
if (!feature.id.is<mbgl::NullValue>()) {
Nan::Set(result, Nan::New("id").ToLocalChecked(), FeatureIdentifier::visit(feature.id, ToValue()));
}
Nan::Set(result, Nan::New("source").ToLocalChecked(), toJS(feature.source));
if (!feature.sourceLayer.empty()) {
Nan::Set(result, Nan::New("sourceLayer").ToLocalChecked(), toJS(feature.sourceLayer));
}
Nan::Set(result, Nan::New("state").ToLocalChecked(), toJS(feature.state));
return scope.Escape(result);
}
} // namespace node_mbgl

View File

@@ -0,0 +1,18 @@
#pragma once
#include <mbgl/util/feature.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace node_mbgl {
v8::Local<v8::Value> toJS(const mbgl::Value&);
v8::Local<v8::Object> toJS(const mbgl::Feature&);
v8::Local<v8::Object> toJS(const mbgl::Feature::geometry_type&);
v8::Local<v8::Object> toJS(const mbgl::PropertyMap&);
}

View File

@@ -0,0 +1,63 @@
#include "node_logging.hpp"
#include <mbgl/util/enum.hpp>
namespace node_mbgl {
struct NodeLogObserver::LogMessage {
mbgl::EventSeverity severity;
mbgl::Event event;
int64_t code;
std::string text;
LogMessage(mbgl::EventSeverity severity_, mbgl::Event event_, int64_t code_, std::string text_)
: severity(severity_),
event(event_),
code(code_),
text(std::move(text_)) {}
};
NodeLogObserver::NodeLogObserver(v8::Local<v8::Object> target)
: queue(new util::AsyncQueue<LogMessage>(uv_default_loop(), [this](LogMessage &message) {
Nan::HandleScope scope;
auto msg = Nan::New<v8::Object>();
Nan::Set(msg, Nan::New("class").ToLocalChecked(),
Nan::New(mbgl::Enum<mbgl::Event>::toString(message.event)).ToLocalChecked());
Nan::Set(msg, Nan::New("severity").ToLocalChecked(),
Nan::New(mbgl::Enum<mbgl::EventSeverity>::toString(message.severity)).ToLocalChecked());
if (message.code != -1) {
Nan::Set(msg, Nan::New("code").ToLocalChecked(),
Nan::New<v8::Number>(message.code));
}
if (!message.text.empty()) {
Nan::Set(msg, Nan::New("text").ToLocalChecked(),
Nan::New(message.text).ToLocalChecked());
}
v8::Local<v8::Value> argv[] = { Nan::New("message").ToLocalChecked(), msg };
auto handle = Nan::New<v8::Object>(module);
auto emit = Nan::To<v8::Object>(Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked()).ToLocalChecked();
Nan::CallAsFunction(emit, handle, 2, argv);
})) {
Nan::HandleScope scope;
module.Reset(target);
// Don't keep the event loop alive.
queue->unref();
}
NodeLogObserver::~NodeLogObserver() {
queue->stop();
}
bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) {
queue->send({ severity, event, code, text });
return true;
}
} // namespace node_mbgl

View File

@@ -0,0 +1,32 @@
#pragma once
#include "util/async_queue.hpp"
#include <mbgl/util/logging.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace node_mbgl {
namespace util { template <typename T> class AsyncQueue; }
class NodeLogObserver : public mbgl::Log::Observer {
public:
NodeLogObserver(v8::Local<v8::Object> target);
~NodeLogObserver() override;
// Log::Observer implementation
bool onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string& text) override;
private:
Nan::Persistent<v8::Object> module;
struct LogMessage;
util::AsyncQueue<LogMessage>* queue;
};
} // namespace node_mbgl

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,106 @@
#pragma once
#include <mbgl/map/map.hpp>
#include <mbgl/storage/file_source.hpp>
#include <mbgl/util/async_request.hpp>
#include <mbgl/util/image.hpp>
#include <exception>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
namespace mbgl {
class HeadlessFrontend;
} // namespace mbgl
namespace node_mbgl {
struct NodeMapObserver : public mbgl::MapObserver {
void onDidFailLoadingMap(mbgl::MapLoadError, const std::string&) final;
};
class RenderRequest;
class NodeMap : public Nan::ObjectWrap {
public:
struct RenderOptions;
class RenderWorker;
NodeMap(v8::Local<v8::Object>);
~NodeMap() override;
static Nan::Persistent<v8::Function> constructor;
static Nan::Persistent<v8::Object> parseError;
static void Init(v8::Local<v8::Object>);
static void New(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Load(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Loaded(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Render(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Release(const Nan::FunctionCallbackInfo<v8::Value>&);
static void Cancel(const Nan::FunctionCallbackInfo<v8::Value>&);
static void AddSource(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveSource(const Nan::FunctionCallbackInfo<v8::Value>&);
static void AddLayer(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveLayer(const Nan::FunctionCallbackInfo<v8::Value>&);
static void AddImage(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveImage(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetLayerZoomRange(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetLayerProperty(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetFilter(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetCenter(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetZoom(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetBearing(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetPitch(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetLight(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetAxonometric(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetXSkew(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetYSkew(const Nan::FunctionCallbackInfo<v8::Value>&);
static void DumpDebugLogs(const Nan::FunctionCallbackInfo<v8::Value>&);
static void QueryRenderedFeatures(const Nan::FunctionCallbackInfo<v8::Value>&);
static void SetFeatureState(const Nan::FunctionCallbackInfo<v8::Value>&);
static void GetFeatureState(const Nan::FunctionCallbackInfo<v8::Value>&);
static void RemoveFeatureState(const Nan::FunctionCallbackInfo<v8::Value>&);
static v8::Local<v8::Value> ParseError(const char* msg);
void startRender(const RenderOptions& options);
void renderFinished();
void release();
void cancel();
static RenderOptions ParseOptions(v8::Local<v8::Object>);
const float pixelRatio;
mbgl::MapMode mode;
bool crossSourceCollisions;
NodeMapObserver mapObserver;
std::unique_ptr<mbgl::HeadlessFrontend> frontend;
std::unique_ptr<mbgl::Map> map;
std::exception_ptr error;
mbgl::PremultipliedImage image;
std::unique_ptr<RenderRequest> req;
// Async for delivering the notifications of render completion.
uv_async_t *async;
bool loaded = false;
};
struct NodeFileSource : public mbgl::FileSource {
NodeFileSource(NodeMap* nodeMap_) : nodeMap(nodeMap_) {}
~NodeFileSource() override = default;
std::unique_ptr<mbgl::AsyncRequest> request(const mbgl::Resource&, mbgl::FileSource::Callback) final;
bool canRequest(const mbgl::Resource&) const override;
NodeMap* nodeMap;
};
} // namespace node_mbgl

View File

@@ -0,0 +1,95 @@
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <node.h>
#include <nan.h>
#pragma GCC diagnostic pop
#include <mbgl/util/run_loop.hpp>
#include <mbgl/gfx/backend.hpp>
#include "node_map.hpp"
#include "node_logging.hpp"
#include "node_request.hpp"
#include "node_expression.hpp"
void SetBackendType(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 1 || info[0]->IsUndefined()) {
return Nan::ThrowTypeError("Requires a render backend name");
}
const std::string backendName { *Nan::Utf8String(info[0]) };
(void)backendName;
}
void RegisterModule(v8::Local<v8::Object> target, v8::Local<v8::Object> 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.
static mbgl::util::RunLoop nodeRunLoop;
nodeRunLoop.stop();
Nan::SetMethod(target, "setBackendType", SetBackendType);
node_mbgl::NodeMap::Init(target);
node_mbgl::NodeRequest::Init();
node_mbgl::NodeExpression::Init(target);
// Exports Resource constants.
v8::Local<v8::Object> resource = Nan::New<v8::Object>();
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("Source").ToLocalChecked(),
Nan::New(mbgl::Resource::Source));
Nan::Set(resource,
Nan::New("Tile").ToLocalChecked(),
Nan::New(mbgl::Resource::Tile));
Nan::Set(resource,
Nan::New("Glyphs").ToLocalChecked(),
Nan::New(mbgl::Resource::Glyphs));
Nan::Set(resource,
Nan::New("SpriteImage").ToLocalChecked(),
Nan::New(mbgl::Resource::SpriteImage));
Nan::Set(resource,
Nan::New("SpriteJSON").ToLocalChecked(),
Nan::New(mbgl::Resource::SpriteJSON));
Nan::Set(target,
Nan::New("Resource").ToLocalChecked(),
resource);
// Make the exported object inherit from EventEmitter
v8::Local<v8::Function> require = Nan::Get(module,
Nan::New("require").ToLocalChecked()).ToLocalChecked().As<v8::Function>();
v8::Local<v8::Value> eventsString = Nan::New("events").ToLocalChecked();
v8::Local<v8::Object> events = Nan::To<v8::Object>(Nan::Call(require, module, 1, &eventsString).ToLocalChecked()).ToLocalChecked();
v8::Local<v8::Object> EventEmitter = Nan::To<v8::Object>(
Nan::Get(
events,
Nan::New("EventEmitter").ToLocalChecked()
).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<node_mbgl::NodeLogObserver>(target));
}
NODE_MODULE(mapbox_gl_native, RegisterModule)

View File

@@ -0,0 +1,153 @@
#include "node_request.hpp"
#include "node_map.hpp"
#include <mbgl/storage/response.hpp>
#include <mbgl/util/chrono.hpp>
#include <cmath>
namespace node_mbgl {
NodeRequest::NodeRequest(
mbgl::FileSource::Callback callback_,
NodeAsyncRequest* asyncRequest_)
: callback(std::move(callback_)),
asyncRequest(asyncRequest_) {
asyncRequest->request = this;
}
NodeRequest::~NodeRequest() {
// When this object gets garbage collected, make sure that the
// AsyncRequest can no longer attempt to remove the callback function
// this object was holding (it can't be fired anymore).
if (asyncRequest) {
asyncRequest->request = nullptr;
}
}
Nan::Persistent<v8::Function> NodeRequest::constructor;
void NodeRequest::Init() {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(Nan::New("Request").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "respond", HandleCallback);
constructor.Reset(tpl->GetFunction());
}
void NodeRequest::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto target = reinterpret_cast<NodeMap*>(info[0].As<v8::External>()->Value());
auto callback = reinterpret_cast<mbgl::FileSource::Callback*>(info[1].As<v8::External>()->Value());
auto asyncRequest = reinterpret_cast<NodeAsyncRequest*>(info[2].As<v8::External>()->Value());
auto request = new NodeRequest(*callback, asyncRequest);
request->Wrap(info.This());
request->Ref();
Nan::Set(info.This(), Nan::New("url").ToLocalChecked(), info[3]);
Nan::Set(info.This(), Nan::New("kind").ToLocalChecked(), info[4]);
v8::Local<v8::Value> argv[] = { info.This() };
request->asyncResource->runInAsyncScope(Nan::To<v8::Object>(target->handle()->GetInternalField(1)).ToLocalChecked(), "request", 1, argv);
info.GetReturnValue().Set(info.This());
}
void NodeRequest::HandleCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {
auto request = Nan::ObjectWrap::Unwrap<NodeRequest>(info.Holder());
// Move out of the object so callback() can only be fired once.
auto callback = std::move(request->callback);
request->callback = {};
if (!callback) {
request->unrefRequest();
return info.GetReturnValue().SetUndefined();
}
mbgl::Response response;
if (info.Length() < 1) {
response.noContent = true;
} else if (info[0]->IsObject()) {
auto err = Nan::To<v8::Object>(info[0]).ToLocalChecked();
auto msg = Nan::New("message").ToLocalChecked();
if (Nan::Has(err, msg).FromJust()) {
response.error = std::make_unique<mbgl::Response::Error>(
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>(
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");
} else {
auto res = Nan::To<v8::Object>(info[1]).ToLocalChecked();
if (Nan::Has(res, Nan::New("modified").ToLocalChecked()).FromJust()) {
const double modified = Nan::To<double>(Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()).FromJust();
if (!std::isnan(modified)) {
response.modified = mbgl::Timestamp{ mbgl::Seconds(
static_cast<mbgl::Seconds::rep>(modified / 1000)) };
}
}
if (Nan::Has(res, Nan::New("expires").ToLocalChecked()).FromJust()) {
const double expires = Nan::To<double>(Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()).FromJust();
if (!std::isnan(expires)) {
response.expires = mbgl::Timestamp{ mbgl::Seconds(
static_cast<mbgl::Seconds::rep>(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()) };
}
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<std::string>(
node::Buffer::Data(data),
node::Buffer::Length(data)
);
} else {
request->unrefRequest();
return Nan::ThrowTypeError("Response data must be a Buffer");
}
}
}
// Send the response object to the NodeFileSource object
callback(response);
request->unrefRequest();
info.GetReturnValue().SetUndefined();
}
void NodeRequest::unrefRequest() {
Nan::HandleScope scope;
delete asyncResource;
asyncResource = nullptr;
Unref();
}
NodeAsyncRequest::NodeAsyncRequest() = default;
NodeAsyncRequest::~NodeAsyncRequest() {
if (request) {
// Remove the callback function because the AsyncRequest was
// canceled and we are no longer interested in the result.
if (request->callback) {
request->callback = {};
}
request->asyncRequest = nullptr;
}
}
} // namespace node_mbgl

View File

@@ -0,0 +1,44 @@
#pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wshadow"
#include <nan.h>
#pragma GCC diagnostic pop
#include <mbgl/storage/file_source.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/util/async_request.hpp>
namespace node_mbgl {
class NodeRequest;
struct NodeAsyncRequest : public mbgl::AsyncRequest {
NodeAsyncRequest();
~NodeAsyncRequest() override;
NodeRequest* request = nullptr;
};
class NodeRequest : public Nan::ObjectWrap {
public:
NodeRequest(mbgl::FileSource::Callback, NodeAsyncRequest*);
~NodeRequest() override;
static Nan::Persistent<v8::Function> constructor;
static void Init();
static void New(const Nan::FunctionCallbackInfo<v8::Value>&);
static void HandleCallback(const Nan::FunctionCallbackInfo<v8::Value>&);
void unrefRequest();
mbgl::FileSource::Callback callback;
NodeAsyncRequest* asyncRequest;
Nan::AsyncResource* asyncResource = new Nan::AsyncResource("mbgl:execute");
};
} // namespace node_mbgl

View File

@@ -0,0 +1,76 @@
#pragma once
#include <uv.h>
#include <functional>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <utility>
namespace node_mbgl {
namespace util {
template <typename T>
class AsyncQueue {
public:
AsyncQueue(uv_loop_t *loop, std::function<void(T &)> fn) : callback(std::move(fn)) {
async.data = this;
uv_async_init(loop, &async, [](uv_async_t* handle) {
auto q = reinterpret_cast<AsyncQueue *>(handle->data);
q->process();
});
}
~AsyncQueue() = default;
void send(T &&data) {
{
std::lock_guard<std::mutex> lock(mutex);
queue.push(std::make_unique<T>(std::move(data)));
}
uv_async_send(&async);
}
void send(std::unique_ptr<T> data) {
{
std::lock_guard<std::mutex> lock(mutex);
queue.push(std::move(data));
}
uv_async_send(&async);
}
void stop() {
uv_close(reinterpret_cast<uv_handle_t *>(&async),
[](uv_handle_t *handle) { delete reinterpret_cast<AsyncQueue *>(handle->data); });
}
void ref() { uv_ref(reinterpret_cast<uv_handle_t *>(&async)); }
void unref() { uv_unref(reinterpret_cast<uv_handle_t *>(&async)); }
private:
void process() {
std::unique_ptr<T> item;
while (true) {
mutex.lock();
if (queue.empty()) {
mutex.unlock();
break;
}
item = std::move(queue.front());
queue.pop();
mutex.unlock();
callback(*item);
}
}
private:
std::mutex mutex;
uv_async_t async;
std::queue<std::unique_ptr<T>> queue;
std::function<void(T &)> callback;
};
} // namespace util
} // namespace node_mbgl

View File

View File

@@ -0,0 +1,104 @@
'use strict';
var mockfs = require('./mockfs');
var mbgl = require('../index');
var test = require('tape');
var firstRequest = "mapbox://sprites/mapbox/streets-v9@2x.json";
var params = {
mapPoolSize: 10,
numRenderings: 1000,
failurePercentage: 10,
timeoutPercentage: 10,
renderingTimeout: 5000,
ratio: 2
};
test('Benchmark', function(t) {
console.time('Time');
var renderCount = 0;
var failureCount = 0;
var cancelCount = 0;
var options = {
request: function(req, callback) {
setTimeout(function() {
var num = Math.floor(Math.random() * 100);
if (req.url == firstRequest && num < params.failurePercentage) {
callback(new Error('Failure'));
} else if (req.url == firstRequest && num > 99 - params.timeoutPercentage) {
setTimeout(function() { callback(new Error('Timeout')); }, params.renderingTimeout * 5);
} else {
var data = mockfs.dataForRequest(req);
callback(null, { data: mockfs.dataForRequest(req) });
}
}, 0);
},
ratio: params.ratio,
};
var mapPool = []
for (var i = 0; i < params.mapPoolSize; ++i) {
var map = new mbgl.Map(options);
mapPool.push(map);
}
var interval = setInterval(function () {
if (mapPool.length == 0 || renderCount == params.numRenderings) {
return;
}
var map = mapPool.shift();
map.load('{ "version": 8, "sources": {}, "layers": [] }');
map.load(mockfs.style_vector);
renderCount += 1;
if (renderCount % (params.numRenderings / 100) == 0) {
// Print some progress, so slow build bots don't timeout.
t.comment('Rendering (' + renderCount.toString() +
'/' + params.numRenderings.toString() + ')');
}
if (renderCount == params.numRenderings) {
clearInterval(interval);
t.end();
console.timeEnd('Time');
console.log('Failures: ' + failureCount);
console.log('Canceled: ' + cancelCount);
return;
}
var mapTimeout = setTimeout(function() {
map.cancel();
}, params.renderingTimeout);
map.render({ zoom: 16 }, function(err, pixels) {
clearTimeout(mapTimeout);
if (err) {
if (err.message == 'Failure') {
failureCount += 1;
}
if (err.message == 'Canceled') {
cancelCount += 1;
}
// We cancel the request before it gets a
// timeout error from the file source.
if (err.message == 'Timeout') {
t.fail('should never happen');
}
}
mapPool.push(map);
});
}, 1);
});

View File

@@ -0,0 +1,83 @@
const {run} = require('../../../mapbox-gl-js/test/integration/lib/expression');
const mbgl = require('../index');
const ignores = require('./ignores.json');
let tests;
if (process.argv[1] === __filename && process.argv.length > 2) {
tests = process.argv.slice(2);
}
function getExpectedType(spec) {
if (spec.type === 'array') {
const itemType = getExpectedType({ type: spec.value });
const array = {
kind: 'array',
itemType: itemType || { kind: 'value' },
};
if (typeof spec.length === 'number') {
array.N = spec.length;
}
return array;
}
if (spec.type === 'enum') {
return { kind: 'string' };
}
return typeof spec.type === 'string' ? {kind: spec.type} : null;
}
run('native', {ignores, tests}, (fixture) => {
const compiled = {};
const recompiled = {};
const result = {
compiled,
recompiled
};
const spec = fixture.propertySpec || {};
const expression = mbgl.Expression.parse(fixture.expression, getExpectedType(spec));
const evaluateExpression = (expression, compilationResult) => {
if (expression instanceof mbgl.Expression) {
compilationResult.result = 'success';
compilationResult.isFeatureConstant = expression.isFeatureConstant();
compilationResult.isZoomConstant = expression.isZoomConstant();
compilationResult.type = expression.getType();
const evaluate = fixture.inputs || [];
const evaluateResults = [];
for (const input of evaluate) {
const feature = Object.assign({
type: 'Feature',
properties: {},
geometry: { type: 'Point', coordinates: [0, 0] }
}, input[1]);
const output = expression.evaluate(input[0], feature);
evaluateResults.push(output);
}
if (fixture.inputs) {
return evaluateResults;
}
} else {
compilationResult.result = 'error';
compilationResult.errors = expression;
}
};
result.outputs = evaluateExpression(expression, compiled);
if (expression instanceof mbgl.Expression) {
result.serialized = expression.serialize();
const recompiledExpression = mbgl.Expression.parse(result.serialized, getExpectedType(spec));
result.roundTripOutputs = evaluateExpression(recompiledExpression, recompiled);
// Type is allowed to change through serialization
// (eg "array" -> "array<number, 3>")
// Override the round-tripped type here so that the equality check passes
recompiled.type = compiled.type;
}
return result;
});

31
platform/node/test/fixtures/style.json vendored Normal file
View File

@@ -0,0 +1,31 @@
{
"version": 8,
"name": "Empty",
"sources": {
"mapbox": {
"type": "vector",
"maxzoom": 15,
"tiles": [
"./fixtures/tiles/{z}-{x}-{y}.vector.pbf"
]
}
},
"layers": [
{
"id": "background",
"type": "background",
"paint": {
"background-color": "white"
}
},
{
"id": "water",
"type": "fill",
"source": "mapbox",
"source-layer": "water",
"paint": {
"fill-color": "blue"
}
}
]
}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 882 B

View File

@@ -0,0 +1,116 @@
'use strict';
var mockfs = require('./../mockfs');
var mbgl = require('../../index');
var test = require('tape');
var options = {
request: function(req, callback) {
callback(null, { data: mockfs.dataForRequest(req) });
},
ratio: 1,
};
test('Cancel', function(t) {
t.test('sanity', function(t) {
var renderCount = 0;
var cancelCount = 0;
var map = new mbgl.Map(options);
var renderCallback = function(err, pixels) {
if (err) {
cancelCount++;
} else {
renderCount++;
}
};
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, renderCallback);
map.cancel();
map.render({ zoom: 16 }, renderCallback);
map.cancel();
map.render({ zoom: 16 }, renderCallback);
map.cancel();
t.equal(renderCount, 0);
t.equal(cancelCount, 3);
t.end();
});
t.test('render after cancel', function(t) {
var map = new mbgl.Map(options);
var renderCallback = function(err, pixels) { if (!err) t.end(); };
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, renderCallback);
map.cancel();
map.render({ zoom: 16 }, renderCallback);
});
t.test('cancel after cancel', function(t) {
var cancelCount = 0;
var map = new mbgl.Map(options);
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {
cancelCount++;
});
map.cancel();
t.throws(function() {
map.cancel();
}, 'already canceled');
t.equal(cancelCount, 1);
t.end();
});
t.test('cancel without rendering', function(t) {
var cancelCount = 0;
var map = new mbgl.Map(options);
map.load(mockfs.style_vector);
t.throws(function() {
map.cancel();
}, 'nothing to cancel');
t.end();
});
t.test('release after cancel', function(t) {
var map = new mbgl.Map(options);
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {});
map.cancel();
map.release();
t.end();
});
t.test('cancel after release', function(t) {
var map = new mbgl.Map(options);
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {});
map.release();
t.throws(function() {
map.cancel();
}, 'map resources already released');
t.end();
});
})

View File

@@ -0,0 +1,643 @@
'use strict';
var test = require('tape');
var mbgl = require('../../index');
var fs = require('fs');
var path = require('path');
var style = require('../fixtures/style.json');
test('Map', function(t) {
// This test is skipped because of the req.respond shim in index.js
// which will always call new mbgl.Map()
t.skip('must be constructed with new', function(t) {
t.throws(function() {
mbgl.Map();
}, /Use the new operator to create new Map objects/);
t.end();
});
t.test('must be constructed with options object', function(t) {
t.throws(function() {
new mbgl.Map();
}, /Requires an options object as first argument/);
t.throws(function() {
new mbgl.Map('options');
}, /Requires an options object as first argument/);
t.end();
});
t.test('requires request property', function(t) {
var options = {};
t.throws(function() {
new mbgl.Map(options);
}, /Options object must have a 'request' method/);
options.request = 'test';
t.throws(function() {
new mbgl.Map(options);
}, /Options object must have a 'request' method/);
options.request = function() {};
t.doesNotThrow(function() {
var map = new mbgl.Map(options);
map.release();
});
t.end();
});
t.test('optional cancel property must be a function', function(t) {
var options = {
request: function() {}
};
options.cancel = 'test';
t.throws(function() {
new mbgl.Map(options);
}, /Options object 'cancel' property must be a function/);
options.cancel = function() {};
t.doesNotThrow(function() {
var map = new mbgl.Map(options);
map.release();
});
t.end();
});
t.test('optional ratio property must be a number', function(t) {
var options = {
request: function() {}
};
options.ratio = 'test';
t.throws(function() {
new mbgl.Map(options);
}, /Options object 'ratio' property must be a number/);
options.ratio = 1.0;
t.doesNotThrow(function() {
var map = new mbgl.Map(options);
map.release();
});
t.end();
});
t.test('instanceof mbgl.Map', function(t) {
var options = {
request: function() {},
ratio: 1
};
var map = new mbgl.Map(options);
t.ok(map instanceof mbgl.Map);
t.equal(map.__proto__, mbgl.Map.prototype);
var keys = Object.keys(mbgl.Map.prototype);
t.deepEqual(keys, [
'load',
'loaded',
'render',
'release',
'cancel',
'addSource',
'removeSource',
'addLayer',
'removeLayer',
'addImage',
'removeImage',
'setLayerZoomRange',
'setLayoutProperty',
'setPaintProperty',
'setFilter',
'setCenter',
'setZoom',
'setBearing',
'setPitch',
'setLight',
'setAxonometric',
'setXSkew',
'setYSkew',
'setFeatureState',
'getFeatureState',
'removeFeatureState',
'dumpDebugLogs',
'queryRenderedFeatures'
]);
for (var key in keys) {
t.equal(map[key], mbgl.Map.prototype[key]);
}
t.end();
});
t.test('.addImage', function(t) {
var options = {
request: function() {},
ratio: 1
};
t.test('requires 3 arguments', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.addImage();
}, /Three arguments required/);
map.release();
t.end();
});
t.test('requires image argument to be an object', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.addImage('foo', '', {});
}, /Second argument must be an object/);
map.release();
t.end();
});
t.test('requires options argument to have a height param', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.addImage('foo', {}, {
width: 40,
pixelRatio: 2
});
}, /height parameter required/);
map.release();
t.end();
});
t.test('requires options argument to have a pixelRatio param', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.addImage('foo', {}, {
width: 40,
height: 40
});
}, /pixelRatio parameter required/);
map.release();
t.end();
});
t.test('requires specified height to be actual height of image', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.addImage('foo', new Buffer(''), {
width: 401,
height: 400,
pixelRatio: 1
}, 'Image size does not match buffer size');
});
map.release();
t.end();
});
t.test('requires height and width to be less than 1024', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.addImage('foo', new Buffer(''), {
width: 1025,
height: 1025,
pixelRatio: 1
}, 'Max height and width is 1024');
});
map.release();
t.end();
});
t.test('requires specified height to be actual height of image', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.addImage('foo', new Buffer(' '), {
width: 401,
height: 400,
pixelRatio: 1
}, 'Image size does not match buffer size');
});
map.release();
t.end();
});
t.test('No error', function(t) {
var map = new mbgl.Map(options);
t.doesNotThrow(function() {
map.addImage('foo', new Buffer(' '), {
width: 1,
height: 1,
pixelRatio: 1
});
});
map.release();
t.end();
});
});
t.test('.removeImage', function(t) {
var options = {
request: function() {},
ratio: 1
};
t.test('requires one argument', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.removeImage();
}, /One argument required/);
map.release();
t.end();
});
t.test('requires string as first argument', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.removeImage({});
}, /First argument must be a string/);
map.release();
t.end();
});
t.test('removes image', function(t) {
var map = new mbgl.Map(options);
t.doesNotThrow(function() {
map.removeImage('fooBar');
});
map.release();
t.end();
});
});
t.test('.load', function(t) {
var options = {
request: function() {},
ratio: 1
};
t.test('requires a map style as first argument', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.load();
}, /Requires a map style as first argument/);
map.release();
t.end();
});
t.test('requires a map style to be a valid style JSON', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.load('foo bar');
}, /Failed to parse style: Invalid value. at offset 1/);
t.throws(function() {
map.load('""');
}, /Failed to parse style: style must be an object/);
t.throws(function() {
map.load('""');
}, mbgl.ParseError);
map.release();
t.end();
});
t.test('expect either an object or array at root', { timeout: 1000 }, function(t) {
var map = new mbgl.Map(options);
mbgl.once('message', function(msg) {
t.equal(msg.severity, 'ERROR');
t.equal(msg.class, 'ParseStyle');
t.ok(msg.text.match(/Invalid value/));
map.release();
t.end();
});
t.throws(function() {
map.load('invalid');
}, mbgl.ParseError);
t.throws(function() {
map.load('invalid');
}, /Failed to parse style: Invalid value. at offset 0/);
});
t.test('accepts an empty stylesheet string', function(t) {
var map = new mbgl.Map(options);
t.doesNotThrow(function() {
map.load('{}');
});
map.release();
t.end();
});
t.test('accepts a JSON stylesheet', { timeout: 1000 }, function(t) {
var map = new mbgl.Map(options);
t.doesNotThrow(function() {
map.load(style);
});
map.release();
t.end();
});
t.test('accepts a stringified stylesheet', { timeout: 1000 }, function(t) {
var map = new mbgl.Map(options);
t.doesNotThrow(function() {
map.load(JSON.stringify(style));
});
map.release();
t.end();
});
t.test('does not immediately trigger any tile loads', function(t) {
var map = new mbgl.Map({
request: function(req) {
t.fail('unexpected request ' + req.url);
},
ratio: 1
});
map.load(style);
setTimeout(function() {
map.release();
t.end();
}, 100);
});
});
t.test('.render', function(t) {
var options = {
request: function(req, callback) {
fs.readFile(path.join(__dirname, '..', req.url), function(err, data) {
callback(err, { data: data });
});
},
ratio: 1
};
t.test('requires an object as the first parameter', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.render();
}, /First argument must be an options object/);
t.throws(function() {
map.render('invalid');
}, /First argument must be an options object/);
map.release();
t.end();
});
t.test('requires a callback as the second parameter', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.render({});
}, /Second argument must be a callback function/);
t.throws(function() {
map.render({}, 'invalid');
}, /Second argument must be a callback function/);
map.release();
t.end();
});
t.test('requires a style to be set', function(t) {
var map = new mbgl.Map(options);
t.throws(function() {
map.render({}, function() {});
}, /Style is not loaded/);
map.release();
t.end();
});
t.test('returns an error delayed', function(t) {
var delay = 0;
var map = new mbgl.Map({
request: function(req, callback) {
delay += 100;
setTimeout(function() {
callback(new Error('not found'));
}, delay);
},
ratio: 1
});
map.load(style);
map.render({ zoom: 1 }, function(err, data) {
map.release();
t.ok(err, 'returns error');
t.end();
});
});
t.test('returns an error', function(t) {
var map = new mbgl.Map(options);
map.load(style);
map.render({ zoom: 1 }, function(err, data) {
map.release();
t.ok(err, 'returns error');
t.end();
});
});
t.test('double release', function(t) {
var map = new mbgl.Map(options);
map.release();
t.throws(function() {
map.release();
}, /Map resources have already been released/);
t.end();
});
t.test('returns an image', function(t) {
var map = new mbgl.Map(options);
map.load(style);
map.render({}, function(err, pixels) {
t.error(err);
map.release();
t.ok(pixels);
t.ok(pixels instanceof Buffer);
t.equal(pixels.length, 512 * 512 * 4)
t.end();
});
});
t.test('can be called several times in serial', function(t) {
var completed = 0;
var remaining = 10;
var start = +new Date;
var map = new mbgl.Map(options);
map.load(style);
function render() {
map.render({}, function(err, data) {
t.error(err);
t.ok(true, 'render @ ' + ((+new Date) - start) + 'ms');
if (++completed === remaining) {
map.release();
t.end();
} else {
render();
}
});
}
render();
});
t.test('throws if called in parallel', function(t) {
var map = new mbgl.Map(options);
map.load(style);
t.throws(function() {
map.render({}, function() {});
map.render({}, function() {});
}, /Map is currently processing a RenderRequest/);
map.release();
t.end();
});
// This can't be tested with a test-suite render test because zoom and center
// are set via a different code path when included as style properties.
t.test('sets zoom before center', function(t) {
var map = new mbgl.Map(options);
map.load({
"version": 8,
"sources": {
"geojson": {
"type": "geojson",
"data": {
"type": "Point",
"coordinates": [
18.05489,
59.32744
]
}
}
},
"layers": [
{
"id": "circle",
"type": "circle",
"source": "geojson",
"paint": {
"circle-color": "red"
}
}
]
});
map.render({width: 400, height: 400, zoom: 5, center: [18.05489, 59.32744]}, function(err, actual) {
t.error(err);
var PNG = require('pngjs').PNG;
var pixelmatch = require('pixelmatch');
var expected = PNG.sync.read(
fs.readFileSync(path.join(__dirname, '../fixtures/zoom-center/expected.png'))).data;
var numPixels = pixelmatch(actual, expected, undefined, 400, 400, { threshold: 0.13 });
t.equal(numPixels, 0);
t.end();
});
})
});
t.test('request callback', function (t) {
t.test('returning an error', function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
setImmediate(function () {
callback(new Error('request error'));
});
},
});
map.load(style);
map.render({ zoom: 1 }, function(err, data) {
map.release();
t.ok(err, 'returns error');
t.equal(err.message, 'request error');
t.end();
});
});
t.test('returning no content for a tile', function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
callback();
},
});
map.load(style);
map.render({ zoom: 1 }, function(err, data) {
map.release();
t.ok(data, 'no error');
t.end();
});
});
t.test('not holding references', function(t) {
var options = {
request: function() {},
ratio: 1
};
// We explicitly don't call release. mbgl.Map should
// not hold any reference to the node's main loop and
// prevent the test from exit.
var map1 = new mbgl.Map(options);
var map2 = new mbgl.Map(options);
var map3 = new mbgl.Map(options);
t.end();
});
});
});

View File

@@ -0,0 +1,167 @@
'use strict';
var mockfs = require('../mockfs');
var mbgl = require('../../index');
var test = require('tape');
[ 'sprite_png', 'sprite_json', 'source_vector', 'glyph' ].forEach(function (resource) {
test(`render reports an error when the request function responds with an error (${resource})`, function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
var data = mockfs.dataForRequest(req);
if (mockfs[resource] === data) {
callback(new Error('message'));
} else {
callback(null, { data: data });
}
}
});
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {
t.assert(err);
t.assert(/message/.test(err.message));
t.assert(!pixels);
t.end();
});
});
});
[ 'vector', 'raster' ].forEach(function (type) {
test(`render does not report an error when the request function responds with no data for a tile (${type})`, function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
var data = mockfs.dataForRequest(req);
if (mockfs[`tile_${type}`] === data) {
callback();
} else {
callback(null, { data: data });
}
}
});
map.load(mockfs[`style_${type}`]);
map.render({ zoom: 16 }, function(err, pixels) {
t.error(err);
t.assert(pixels);
t.end();
});
});
test(`render reports an error when the request function responds with an error for a tile (${type})`, function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
var data = mockfs.dataForRequest(req);
if (mockfs[`tile_${type}`] === data) {
callback(new Error('message'));
} else {
callback(null, { data: data });
}
}
});
map.load(mockfs[`style_${type}`]);
map.render({ zoom: 16 }, function(err, pixels) {
t.assert(err);
t.assert(/message/.test(err.message));
t.assert(!pixels);
t.end();
});
});
});
test(`render reports an error if the request function throws an exception`, function(t) {
var map = new mbgl.Map({
request: function() {
throw new Error('message');
}
});
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {
t.assert(err);
t.assert(/message/.test(err.message));
t.assert(!pixels);
t.end();
});
});
test(`render ignores request functions throwing an exception after calling the callback`, function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
var data = mockfs.dataForRequest(req);
callback(null, { data: data });
throw new Error('message');
}
});
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {
t.error(err);
t.assert(pixels);
t.end();
});
});
test(`render ignores request functions calling the callback a second time`, function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
var data = mockfs.dataForRequest(req);
callback(null, { data: data });
callback(null, { data: data });
}
});
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {
t.error(err);
t.assert(pixels);
t.end();
});
});
test(`render reports an error from loading the current style`, function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
var data = mockfs.dataForRequest(req);
if (mockfs.source_vector === data) {
callback(new Error('message'));
} else {
callback(null, { data: data });
}
}
});
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {
t.assert(err);
t.assert(/message/.test(err.message));
t.assert(!pixels);
map.render({ zoom: 16 }, function(err, pixels) {
t.assert(err);
t.assert(/message/.test(err.message));
t.assert(!pixels);
t.end();
});
});
});
test(`render does not report an error from rendering a previous style`, function(t) {
var map = new mbgl.Map({
request: function(req, callback) {
var data = mockfs.dataForRequest(req);
if (mockfs.source_vector === data) {
callback(new Error('message'));
} else {
callback(null, { data: data });
}
}
});
map.load(mockfs.style_vector);
map.render({ zoom: 16 }, function(err, pixels) {
t.assert(err);
t.assert(/message/.test(err.message));
t.assert(!pixels);
map.load(mockfs.style_raster);
map.render({ zoom: 16 }, function(err, pixels) {
t.error(err);
t.assert(pixels);
t.end();
});
});
});

View File

@@ -0,0 +1 @@
var mbgl = require('../../../../lib/mapbox_gl_native');

View File

@@ -0,0 +1,75 @@
'use strict';
var mockfs = require('./mockfs');
var mbgl = require('../index');
var test = require('tape');
var testParams = {
mapPoolSize: 10,
numRenderings: 100,
heapGrowthThreshold: 0,
ratio: 2
};
test('Memory', function(t) {
// Trigger garbage collection before starting test, then initialize
// heap size
if (typeof gc === 'function') gc();
var lastHeapSize = process.memoryUsage()['heapUsed'];
var options = {
request: function(req, callback) {
callback(null, { data: mockfs.dataForRequest(req) });
},
ratio: testParams.ratio,
};
var mapPool = []
for (var i = 0; i < testParams.mapPoolSize; ++i) {
var map = new mbgl.Map(options);
mapPool.push(map);
}
var renderCount = 0;
var heapGrowth = 0;
var interval = setInterval(function () {
if (mapPool.length == 0) {
return;
}
var map = mapPool.shift();
if (Math.floor(Math.random() * 2)) {
map.load(mockfs.style_raster);
} else {
map.load(mockfs.style_vector);
}
map.render({ zoom: 16 }, function(err, pixels) {
mapPool.push(map);
if (renderCount % (testParams.numRenderings / 10) == 0) {
// Manually trigger garbage collection
if (typeof gc === 'function') gc();
var currentHeapSize = process.memoryUsage()['heapUsed'];
// Print some progress, so slow build bots don't timeout.
t.comment("Rendering (" + renderCount.toString() +
"/" + testParams.numRenderings.toString() + ")");
heapGrowth = heapGrowth + currentHeapSize - lastHeapSize;
lastHeapSize = currentHeapSize;
}
if (++renderCount == testParams.numRenderings) {
t.ok(heapGrowth < testParams.heapGrowthThreshold, heapGrowth);
t.end();
clearInterval(interval);
}
});
}, 1);
});

View File

@@ -0,0 +1,53 @@
"use strict";
var fs = require('fs');
var path = require('path');
function readFixture(file) {
return fs.readFileSync(path.join('test/fixtures/resources', file));
}
var style_raster = readFixture('style_raster.json').toString('utf8');
var style_vector = readFixture('style_vector.json').toString('utf8');
var sprite_json = readFixture('sprite.json');
var sprite_png = readFixture('sprite.png');
var glyph = readFixture('glyphs.pbf');
var source_raster = readFixture('source_raster.json');
var source_vector = readFixture('source_vector.json');
var tile_raster = readFixture('raster.tile');
var tile_vector = readFixture('vector.tile');
function dataForRequest(req) {
if (req.url === null) {
return null;
} else if (req.url.indexOf('sprite') > -1 && req.url.endsWith('json')) {
return sprite_json;
} else if (req.url.indexOf('sprite') > -1 && req.url.endsWith('png')) {
return sprite_png;
} else if (req.url.indexOf('fonts') > -1 && req.url.endsWith('pbf')) {
return glyph;
} else if (req.url.endsWith('mapbox.satellite')) {
return source_raster;
} else if (req.url.indexOf('satellite') > -1 && (req.url.endsWith('png') || req.url.endsWith('webp'))) {
return tile_raster;
} else if (req.url.endsWith('mapbox.mapbox-streets-v7')) {
return source_vector;
} else if (req.url.indexOf('streets') > -1 && req.url.endsWith('pbf')) {
return tile_vector;
} else {
return null;
}
}
module.exports = {
dataForRequest: dataForRequest,
style_raster: style_raster,
style_vector: style_vector,
sprite_json: sprite_json,
sprite_png: sprite_png,
glyph: glyph,
source_raster: source_raster,
source_vector: source_vector,
tile_raster: tile_raster,
tile_vector: tile_vector
};

View File

@@ -0,0 +1,11 @@
import {run} from '../../../mapbox-gl-js/test/integration/lib/query';
import implementation from './suite_implementation';
import ignores from './ignores.json';
let tests;
if (process.argv[1] === __filename && process.argv.length > 2) {
tests = process.argv.slice(2);
}
run('native', {tests, ignores}, implementation);

View File

@@ -0,0 +1,5 @@
import {run} from '../../../mapbox-gl-js/test/integration/lib/render';
import implementation from './suite_implementation';
import ignores from './ignores.json';
run('native', ignores, implementation);

View File

@@ -0,0 +1,154 @@
import mbgl from '../index';
import request from 'request';
import {PNG} from 'pngjs';
import * as fs from 'fs';
import * as path from 'path';
mbgl.on('message', function(msg) {
console.log('%s (%s): %s', msg.severity, msg.class, msg.text);
});
// Map of map objects by pixel ratio
const maps = new Map();
export default function (style, options, callback) {
const tileMode = options.mapMode === 'tile';
let map;
if (options.recycleMap) {
const key = options.pixelRatio + '/' + tileMode + '/' + options.crossSourceCollisions;
if (maps.has(key)) {
map = maps.get(key);
map.request = mapRequest;
} else {
maps.set(key, new mbgl.Map({
ratio: options.pixelRatio,
request: mapRequest,
mode: options.mapMode,
crossSourceCollisions: typeof options.crossSourceCollisions === "undefined" ? true : options.crossSourceCollisions
}));
map = maps.get(key);
}
} else {
map = new mbgl.Map({
ratio: options.pixelRatio,
request: mapRequest,
mode: options.mapMode,
crossSourceCollisions: typeof options.crossSourceCollisions === "undefined" ? true : options.crossSourceCollisions
});
}
let timedOut = false;
const watchdog = setTimeout(function () {
timedOut = true;
map.dumpDebugLogs();
callback(new Error('timed out after 20 seconds'));
}, 20000);
options.debug = {
tileBorders: options.debug,
collision: options.collisionDebug,
overdraw: options.showOverdrawInspector,
};
options.center = style.center || [0, 0];
options.zoom = style.zoom || 0;
options.bearing = style.bearing || 0;
options.pitch = style.pitch || 0;
options.light = style.light || {};
map.load(style, { defaultStyleCamera: true });
function mapRequest(req, callback) {
request(req.url, {encoding: null}, function (err, response, body) {
if (err) {
callback(err);
} else if (response.statusCode === 404) {
callback();
} else if (response.statusCode !== 200) {
callback(new Error(response.statusMessage));
} else {
callback(null, {data: body});
}
});
}
applyOperations(options.operations, function() {
map.render(options, function (err, pixels) {
const results = options.queryGeometry ?
map.queryRenderedFeatures(options.queryGeometry, options.queryOptions || {}) :
[];
if (!options.recycleMap) {
map.release();
}
if (timedOut) return;
clearTimeout(watchdog);
callback(err, pixels, results.map(prepareFeatures));
});
});
function applyOperations(operations, callback) {
const operation = operations && operations[0];
if (!operations || operations.length === 0) {
callback();
} else if (operation[0] === 'wait') {
map.render(options, function () {
applyOperations(operations.slice(1), callback);
});
} else if (operation[0] === 'sleep') {
// Prefer "wait", which renders until the map is loaded
// Use "sleep" when you need to test something that sidesteps the "loaded" logic
setTimeout(() => {
applyOperations(operations.slice(1), callback);
}, operation[1]);
} else if (operation[0] === 'addImage' || operation[0] === 'updateImage') {
const img = PNG.sync.read(fs.readFileSync(path.join(__dirname, '../../../mapbox-gl-js/test/integration', operation[2])));
const testOpts = (operation.length > 3) ? operation[3] : {};
const options = {
height: img.height,
width: img.width,
pixelRatio: testOpts.pixelRatio || 1,
sdf: testOpts.sdf || false
};
map.addImage(operation[1], img.data, options);
applyOperations(operations.slice(1), callback);
} else if (operation[0] === 'setStyle') {
map.load(operation[1]);
applyOperations(operations.slice(1), callback);
} else if (operation[0] ==='setFeatureState' || operation[0] ==='getFeatureState' || operation[0] ==='removeFeatureState') {
map.render(options, function () {
map[operation[0]].apply(map, operation.slice(1));
applyOperations(operations.slice(1), callback);
});
} else {
// Ensure that the next `map.render(options)` does not overwrite this change.
if (operation[0] === 'setCenter') {
options.center = operation[1];
} else if (operation[0] === 'setZoom') {
options.zoom = operation[1];
} else if (operation[0] === 'setBearing') {
options.bearing = operation[1];
} else if (operation[0] === 'setPitch') {
options.pitch = operation[1];
} else if (operation[0] === 'setLight') {
options.light = operation[1];
}
map[operation[0]].apply(map, operation.slice(1));
applyOperations(operations.slice(1), callback);
}
}
function prepareFeatures(r) {
delete r.layer;
return r;
}
};

View File

@@ -0,0 +1,3 @@
{
local: *;
};