apply new tangram
[platform/core/location/maps-plugin-mapzen.git] / src / mapzen / tangram / tangram.h
1 #pragma once
2
3 #include "data/properties.h"
4 #include "util/types.h"
5
6 #include <array>
7 #include <functional>
8 #include <memory>
9 #include <string>
10 #include <vector>
11
12 namespace Tangram {
13
14 class Platform;
15 class TileSource;
16
17 enum LabelType {
18     icon,
19     text,
20 };
21
22 struct FeaturePickResult {
23     FeaturePickResult(std::shared_ptr<Properties> _properties,
24                       std::array<float, 2> _position)
25         : properties(_properties), position(_position) {}
26
27     std::shared_ptr<Properties> properties;
28     std::array<float, 2> position;
29 };
30
31 // Returns a pointer to the selected feature pick result or null, only valid on the callback scope
32 using FeaturePickCallback = std::function<void(const FeaturePickResult*)>;
33
34 struct LabelPickResult {
35     LabelPickResult(LabelType _type, LngLat _coordinates, FeaturePickResult _touchItem)
36         : type(_type),
37           coordinates(_coordinates),
38           touchItem(_touchItem) {}
39
40     LabelType type;
41     LngLat coordinates;
42     FeaturePickResult touchItem;
43 };
44
45 // Returns a pointer to the selected label pick result or null, only valid on the callback scope
46 using LabelPickCallback = std::function<void(const LabelPickResult*)>;
47
48 struct MarkerPickResult {
49     MarkerPickResult(MarkerID _id, LngLat _coordinates, std::array<float, 2> _position)
50         : id(_id), coordinates(_coordinates), position(_position) {}
51
52     MarkerID id;
53     LngLat coordinates;
54     std::array<float, 2> position;
55 };
56
57 // Returns a pointer to the selected marker pick result or null, only valid on the callback scope
58 using MarkerPickCallback = std::function<void(const MarkerPickResult*)>;
59
60 struct SceneUpdate {
61     std::string path;
62     std::string value;
63     SceneUpdate(std::string p, std::string v) : path(p), value(v) {}
64     SceneUpdate() {}
65 };
66
67 enum Error {
68     scene_update_path_not_found,
69     scene_update_path_yaml_syntax_error,
70     scene_update_value_yaml_syntax_error,
71 };
72
73 struct SceneUpdateError {
74     SceneUpdate update;
75     Error error;
76 };
77
78 using SceneUpdateErrorCallback = std::function<void(const SceneUpdateError&)>;
79
80 // Function type for a mapReady callback
81 using MapReady = std::function<void(void*)>;
82
83 enum class EaseType : char {
84     linear = 0,
85     cubic,
86     quint,
87     sine,
88 };
89
90 class Map {
91
92 public:
93
94     // Create an empty map object. To display a map, call either loadScene() or loadSceneAsync().
95     Map(std::shared_ptr<Platform> _platform);
96     ~Map();
97
98     // Load the scene at the given absolute file path asynchronously
99     // Any pending scene update will be cleared
100     void loadSceneAsync(const char* _scenePath,
101                         bool _useScenePosition = false,
102                         MapReady _onMapReady = nullptr,
103                         void *_onMapReadyUserData = nullptr,
104                         const std::vector<SceneUpdate>& sceneUpdates = {},
105                         SceneUpdateErrorCallback _onSceneUpdateError = nullptr);
106
107     // Load the scene at the given absolute file path synchronously
108     // Any pending scene update will be cleared
109     void loadScene(const char* _scenePath,
110                    bool _useScenePosition = false,
111                    const std::vector<SceneUpdate>& sceneUpdates = {},
112                    SceneUpdateErrorCallback _onSceneUpdateError = nullptr);
113
114     // Request an update to the scene configuration; the path is a series of yaml keys
115     // separated by a '.' and the value is a string of yaml to replace the current value
116     // at the given path in the scene
117     void queueSceneUpdate(const char* _path, const char* _value);
118     void queueSceneUpdate(const std::vector<SceneUpdate>& sceneUpdates);
119
120     // Apply all previously requested scene updates
121     void applySceneUpdates(SceneUpdateErrorCallback _onSceneUpdateError = nullptr);
122
123     // Set an MBTiles SQLite database file for a DataSource in the scene.
124     void setMBTiles(const char* _dataSourceName, const char* _mbtilesFilePath);
125
126     // Initialize graphics resources; OpenGL context must be created prior to calling this
127     void setupGL();
128
129     // Resize the map view to a new width and height (in pixels)
130     void resize(int _newWidth, int _newHeight);
131
132     // Update the map state with the time interval since the last update, returns
133     // true when the current view is completely loaded (all tiles are available and
134     // no animation in progress)
135     bool update(float _dt);
136
137     // Render a new frame of the map view (if needed)
138     void render();
139
140     // Gets the viewport height in physical pixels (framebuffer size)
141     int getViewportHeight();
142
143     // Gets the viewport width in physical pixels (framebuffer size)
144     int getViewportWidth();
145
146     // Set the ratio of hardware pixels to logical pixels (defaults to 1.0);
147     // this operation can be slow, so only perform this when necessary.
148     void setPixelScale(float _pixelsPerPoint);
149
150     // Gets the pixel scale
151     float getPixelScale();
152
153     // Capture a snapshot of the current frame and store it in the allocated _data
154     // _data is expected to be of size getViewportHeight() * getViewportWidth()
155     // Pixel data is stored starting from the lower left corner of the viewport
156     // Each pixel(x, y) would be located at _data[y * getViewportWidth() + x]
157     // Each unsigned int corresponds to an RGBA pixel value
158     void captureSnapshot(unsigned int* _data);
159
160     // Set the position of the map view in degrees longitude and latitude; if duration
161     // (in seconds) is provided, position eases to the set value over the duration;
162     // calling either version of the setter overrides all previous calls
163     void setPosition(double _lon, double _lat);
164     void setPositionEased(double _lon, double _lat, float _duration, EaseType _e = EaseType::quint);
165
166     // Set the values of the arguments to the position of the map view in degrees
167     // longitude and latitude
168     void getPosition(double& _lon, double& _lat);
169
170     // Set the fractional zoom level of the view; if duration (in seconds) is provided,
171     // zoom eases to the set value over the duration; calling either version of the setter
172     // overrides all previous calls
173     void setZoom(float _z);
174     void setZoomEased(float _z, float _duration, EaseType _e = EaseType::quint);
175
176     // Get the fractional zoom level of the view
177     float getZoom();
178
179     // Set the counter-clockwise rotation of the view in radians; 0 corresponds to
180     // North pointing up; if duration (in seconds) is provided, rotation eases to the
181     // the set value over the duration; calling either version of the setter overrides
182     // all previous calls
183     void setRotation(float _radians);
184     void setRotationEased(float _radians, float _duration, EaseType _e = EaseType::quint);
185
186     // Get the counter-clockwise rotation of the view in radians; 0 corresponds to
187     // North pointing up
188     float getRotation();
189
190     // Set the tilt angle of the view in radians; 0 corresponds to straight down;
191     // if duration (in seconds) is provided, tilt eases to the set value over the
192     // duration; calling either version of the setter overrides all previous calls
193     void setTilt(float _radians);
194     void setTiltEased(float _radians, float _duration, EaseType _e = EaseType::quint);
195
196     // Get the tilt angle of the view in radians; 0 corresponds to straight down
197     float getTilt();
198
199     // Set the camera type (0 = perspective, 1 = isometric, 2 = flat)
200     void setCameraType(int _type);
201
202     // Get the camera type (0 = perspective, 1 = isometric, 2 = flat)
203     int getCameraType();
204
205     // Given coordinates in screen space (x right, y down), set the output longitude and
206     // latitude to the geographic location corresponding to that point; returns false if
207     // no geographic position corresponds to the screen location, otherwise returns true
208     bool screenPositionToLngLat(double _x, double _y, double* _lng, double* _lat);
209
210     // Given longitude and latitude coordinates, set the output coordinates to the
211     // corresponding point in screen space (x right, y down); returns false if the
212     // point is not visible on the screen, otherwise returns true
213     bool lngLatToScreenPosition(double _lng, double _lat, double* _x, double* _y);
214
215     // Add a tile source for adding drawable map data, which will be styled
216     // according to the scene file using the provided data source name;
217     void addTileSource(std::shared_ptr<TileSource> _source);
218
219     // Remove a tile source from the map; returns true if the source was found
220     // and removed, otherwise returns false.
221     bool removeTileSource(TileSource& _source);
222
223     void clearTileSource(TileSource& _source, bool _data, bool _tiles);
224
225     // Add a marker object to the map and return an ID for it; an ID of 0 indicates an invalid marker;
226     // the marker will not be drawn until both styling and geometry are set using the functions below.
227     MarkerID markerAdd();
228
229     // Remove a marker object from the map; returns true if the marker ID was found and successfully
230     // removed, otherwise returns false.
231     bool markerRemove(MarkerID _marker);
232
233     // Set the styling for a marker object; _styling is a string of YAML that specifies a 'draw rule'
234     // according to the scene file syntax; returns true if the marker ID was found and successfully
235     // updated, otherwise returns false.
236     bool markerSetStylingFromString(MarkerID _marker, const char* _styling);
237
238     // Set an explicit draw group for a marker object; _path is a '.' delimited path to a draw rule
239     // in the current scene. The Marker will be styled using the draw rule specified at this path;
240     // returns true if the marker ID was found and successfully updated, otherwise returns false.
241     bool markerSetStylingFromPath(MarkerID _marker, const char* _path);
242
243     // Set a bitmap to use as the image for a point marker; _data is a buffer of RGBA pixel data with
244     // length of _width * _height; pixels are in row-major order beginning from the bottom-left of the
245     // image; returns true if the marker ID was found and successfully updated, otherwise returns false.
246     bool markerSetBitmap(MarkerID _marker, int _width, int _height, const unsigned int* _data);
247
248     // Set the geometry of a marker to a point at the given coordinates; markers can have their
249     // geometry set multiple times with possibly different geometry types; returns true if the
250     // marker ID was found and successfully updated, otherwise returns false.
251     bool markerSetPoint(MarkerID _marker, LngLat _lngLat);
252
253     // Set the geometry of a marker to a point at the given coordinates; if the marker was previously
254     // set to a point, this eases the position over the given duration in seconds with the given EaseType;
255     // returns true if the marker ID was found and successfully updated, otherwise returns false.
256     bool markerSetPointEased(MarkerID _marker, LngLat _lngLat, float _duration, EaseType _ease);
257
258     // Set the geometry of a marker to a polyline along the given coordinates; _coordinates is a
259     // pointer to a sequence of _count LngLats; markers can have their geometry set multiple times
260     // with possibly different geometry types; returns true if the marker ID was found and
261     // successfully updated, otherwise returns false.
262     bool markerSetPolyline(MarkerID _marker, LngLat* _coordinates, int _count);
263
264     // Set the geometry of a marker to a polygon with the given coordinates; _counts is a pointer
265     // to a sequence of _rings integers and _coordinates is a pointer to a sequence of LngLats with
266     // a total length equal to the sum of _counts; for each integer n in _counts, a polygon is created
267     // by taking the next n LngLats from _coordinates, with winding order and internal polygons
268     // behaving according to the GeoJSON specification; markers can have their geometry set multiple
269     // times with possibly different geometry types; returns true if the marker ID was found and
270     // successfully updated, otherwise returns false.
271     bool markerSetPolygon(MarkerID _marker, LngLat* _coordinates, int* _counts, int _rings);
272
273     // Set the visibility of a marker object; returns true if the marker ID was found and successfully
274     // updated, otherwise returns false.
275     bool markerSetVisible(MarkerID _marker, bool _visible);
276
277     // Set the ordering of point marker object relative to other markers; higher values are drawn 'above';
278     // returns true if the marker ID was found and successfully updated, otherwise returns false.
279     bool markerSetDrawOrder(MarkerID _marker, int _drawOrder);
280
281     // Remove all marker objects from the map; Any marker IDs previously returned from 'markerAdd'
282     // are invalidated after this.
283     void markerRemoveAll();
284
285     // Respond to a tap at the given screen coordinates (x right, y down)
286     void handleTapGesture(float _posX, float _posY);
287
288     // Respond to a double tap at the given screen coordinates (x right, y down)
289     void handleDoubleTapGesture(float _posX, float _posY);
290
291     // Respond to a drag with the given displacement in screen coordinates (x right, y down)
292     void handlePanGesture(float _startX, float _startY, float _endX, float _endY);
293
294     // Respond to a fling from the given position with the given velocity in screen coordinates
295     void handleFlingGesture(float _posX, float _posY, float _velocityX, float _velocityY);
296
297     // Respond to a pinch at the given position in screen coordinates with the given
298     // incremental scale
299     void handlePinchGesture(float _posX, float _posY, float _scale, float _velocity);
300
301     // Respond to a rotation gesture with the given incremental rotation in radians
302     void handleRotateGesture(float _posX, float _posY, float _rotation);
303
304     // Respond to a two-finger shove with the given distance in screen coordinates
305     void handleShoveGesture(float _distance);
306
307     // Set whether the OpenGL state will be cached between subsequent frames; this improves rendering
308     // efficiency, but can cause errors if your application code makes OpenGL calls (false by default)
309     void useCachedGlState(bool _use);
310
311     // Set the radius in logical pixels to use when picking features on the map (default is 0.5).
312     void setPickRadius(float _radius);
313
314     // Create a query to select a feature marked as 'interactive'. The query runs on the next frame.
315     // Calls _onFeaturePickCallback once the query has completed, and returns the FeaturePickResult
316     // with its associated properties or null if no feature was found.
317     void pickFeatureAt(float _x, float _y, FeaturePickCallback _onFeaturePickCallback);
318
319     // Create a query to select a label created for a feature marked as 'interactive'. The query runs
320     // on the next frame.
321     // Calls _onLabelPickCallback once the query has completed, and returns the LabelPickResult
322     // with its associated properties or null if no label was found.
323     void pickLabelAt(float _x, float _y, LabelPickCallback _onLabelPickCallback);
324
325     // Create a query to select a marker that is 'interactive'. The query runs on the next frame.
326     // Calls _onLMarkerPickCallback once the query has completed, and returns the MarkerPickResult
327     // with its associated properties or null if no marker was found.
328     void pickMarkerAt(float _x, float _y, MarkerPickCallback _onMarkerPickCallback);
329
330     // Run this task asynchronously to Tangram's main update loop.
331     void runAsyncTask(std::function<void()> _task);
332
333     // Send a signal to Tangram that the platform received a memory warning
334     void onMemoryWarning();
335
336     std::shared_ptr<Platform>& getPlatform();
337
338 private:
339
340     class Impl;
341     std::unique_ptr<Impl> impl;
342
343 protected:
344
345     std::shared_ptr<Platform> platform;
346
347 };
348
349 enum DebugFlags {
350     freeze_tiles = 0,   // While on, the set of tiles currently being drawn will not update to match the view
351     proxy_colors,       // Applies a color change to every other zoom level of tiles to visualize proxy tile behavior
352     tile_bounds,        // Draws tile boundaries
353     tile_infos,         // Debug tile infos
354     labels,             // Debug label bounding boxes
355     tangram_infos,      // Various text tangram debug info printed on the screen
356     draw_all_labels,    // Draw all labels
357     tangram_stats,      // Tangram frame graph stats
358     selection_buffer,   // Render selection framebuffer
359 };
360
361 // Set debug features on or off using a boolean (see debug.h)
362 void setDebugFlag(DebugFlags _flag, bool _on);
363
364 // Get the boolean state of a debug feature (see debug.h)
365 bool getDebugFlag(DebugFlags _flag);
366
367 // Toggle the boolean state of a debug feature (see debug.h)
368 void toggleDebugFlag(DebugFlags _flag);
369
370 }