forked from maplibre/maplibre-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glfw_view.cpp
1189 lines (1039 loc) · 46.8 KB
/
glfw_view.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "glfw_view.hpp"
#include "glfw_backend.hpp"
#include "glfw_renderer_frontend.hpp"
#include "ny_route.hpp"
#include "test_writer.hpp"
#include <mbgl/annotation/annotation.hpp>
#include <mbgl/gfx/backend.hpp>
#include <mbgl/gfx/backend_scope.hpp>
#include <mbgl/map/camera.hpp>
#include <mbgl/math/angles.hpp>
#include <mbgl/renderer/renderer.hpp>
#include <mbgl/style/expression/dsl.hpp>
#include <mbgl/style/image.hpp>
#include <mbgl/style/layers/fill_extrusion_layer.hpp>
#include <mbgl/style/layers/fill_layer.hpp>
#include <mbgl/style/layers/line_layer.hpp>
#include <mbgl/style/sources/custom_geometry_source.hpp>
#include <mbgl/style/sources/geojson_source.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/transition_options.hpp>
#include <mbgl/util/chrono.hpp>
#include <mbgl/util/geo.hpp>
#include <mbgl/util/interpolate.hpp>
#include <mbgl/util/io.hpp>
#include <mbgl/util/logging.hpp>
#include <mbgl/util/platform.hpp>
#include <mbgl/util/string.hpp>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4267)
#endif
#include <mapbox/cheap_ruler.hpp>
#include <mapbox/geometry.hpp>
#include <mapbox/geojson.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#if !defined(__APPLE__)
#define GLFW_INCLUDE_ES3
#endif
#define GL_GLEXT_PROTOTYPES
#include <GLFW/glfw3.h>
#include <cassert>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <utility>
#include <sstream>
#if defined(MLN_RENDER_BACKEND_OPENGL) && !defined(MBGL_LAYER_LOCATION_INDICATOR_DISABLE_ALL)
#include <mbgl/style/layers/location_indicator_layer.hpp>
namespace {
const std::string mbglPuckAssetsPath{MAPBOX_PUCK_ASSETS_PATH};
mbgl::Color premultiply(mbgl::Color c) {
c.r *= c.a;
c.g *= c.a;
c.b *= c.a;
return c;
}
std::array<double, 3> toArray(const mbgl::LatLng &crd) {
return {crd.latitude(), crd.longitude(), 0};
}
} // namespace
#endif
class SnapshotObserver final : public mbgl::MapSnapshotterObserver {
public:
~SnapshotObserver() override = default;
void onDidFinishLoadingStyle() override {
if (didFinishLoadingStyleCallback) {
didFinishLoadingStyleCallback();
}
}
std::function<void()> didFinishLoadingStyleCallback;
};
namespace {
void addFillExtrusionLayer(mbgl::style::Style &style, bool visible) {
using namespace mbgl::style;
using namespace mbgl::style::expression::dsl;
// Satellite-only style does not contain building extrusions data.
if (!style.getSource("composite")) {
return;
}
if (auto layer = style.getLayer("3d-buildings")) {
layer->setVisibility(VisibilityType(!visible));
return;
}
auto extrusionLayer = std::make_unique<FillExtrusionLayer>("3d-buildings", "composite");
extrusionLayer->setSourceLayer("building");
extrusionLayer->setMinZoom(15.0f);
extrusionLayer->setFilter(Filter(eq(get("extrude"), literal("true"))));
extrusionLayer->setFillExtrusionColor(PropertyExpression<mbgl::Color>(interpolate(linear(),
number(get("height")),
0.f,
toColor(literal("#160e23")),
50.f,
toColor(literal("#00615f")),
100.f,
toColor(literal("#55e9ff")))));
extrusionLayer->setFillExtrusionOpacity(0.6f);
extrusionLayer->setFillExtrusionHeight(PropertyExpression<float>(get("height")));
extrusionLayer->setFillExtrusionBase(PropertyExpression<float>(get("min_height")));
style.addLayer(std::move(extrusionLayer));
}
} // namespace
void glfwError(int error, const char *description) {
mbgl::Log::Error(mbgl::Event::OpenGL, std::string("GLFW error (") + std::to_string(error) + "): " + description);
}
GLFWView::GLFWView(bool fullscreen_,
bool benchmark_,
const mbgl::ResourceOptions &resourceOptions,
const mbgl::ClientOptions &clientOptions)
: fullscreen(fullscreen_),
benchmark(benchmark_),
snapshotterObserver(std::make_unique<SnapshotObserver>()),
mapResourceOptions(resourceOptions.clone()),
mapClientOptions(clientOptions.clone()) {
glfwSetErrorCallback(glfwError);
std::srand(static_cast<unsigned int>(std::time(nullptr)));
if (!glfwInit()) {
mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize glfw");
exit(1);
}
GLFWmonitor *monitor = nullptr;
if (fullscreen) {
monitor = glfwGetPrimaryMonitor();
auto videoMode = glfwGetVideoMode(monitor);
width = videoMode->width;
height = videoMode->height;
}
#if __APPLE__
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GL_TRUE);
#endif
if (mbgl::gfx::Backend::GetType() != mbgl::gfx::Backend::Type::OpenGL) {
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
} else {
#if __APPLE__
glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, GL_TRUE);
#endif
#if MBGL_WITH_EGL
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
#endif
#ifdef DEBUG
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
glfwWindowHint(GLFW_ALPHA_BITS, 8);
glfwWindowHint(GLFW_STENCIL_BITS, 8);
glfwWindowHint(GLFW_DEPTH_BITS, 16);
}
window = glfwCreateWindow(width, height, "MapLibre Native", monitor, nullptr);
if (!window) {
glfwTerminate();
mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize window");
exit(1);
}
glfwSetWindowUserPointer(window, this);
glfwSetCursorPosCallback(window, onMouseMove);
glfwSetMouseButtonCallback(window, onMouseClick);
glfwSetWindowSizeCallback(window, onWindowResize);
glfwSetFramebufferSizeCallback(window, onFramebufferResize);
glfwSetScrollCallback(window, onScroll);
glfwSetKeyCallback(window, onKey);
glfwSetWindowFocusCallback(window, onWindowFocus);
glfwGetWindowSize(window, &width, &height);
backend = GLFWBackend::Create(window, benchmark);
#ifdef __APPLE__
int fbW, fbH;
glfwGetFramebufferSize(window, &fbW, &fbH);
backend->setSize({fbW, fbH});
#endif
pixelRatio = static_cast<float>(backend->getSize().width) / width;
glfwMakeContextCurrent(nullptr);
printf("\n");
printf(
"======================================================================"
"==========\n");
printf("\n");
printf("- Press `S` to cycle through bundled styles\n");
printf("- Press `X` to reset the transform\n");
printf("- Press `N` to reset north\n");
printf("- Press `R` to enable the route demo\n");
printf("- Press `E` to insert an example building extrusion layer\n");
printf("- Press `O` to toggle online connectivity\n");
printf("- Press `Z` to cycle through north orientations\n");
printf("- Press `X` to cycle through the viewport modes\n");
printf("- Press `I` to delete existing database and re-initialize\n");
printf(
"- Press `A` to cycle through Mapbox offices in the world + dateline "
"monument\n");
printf("- Press `B` to cycle through the color, stencil, and depth buffer\n");
printf(
"- Press `D` to cycle through camera bounds: inside, crossing IDL at "
"left, crossing IDL at right, and "
"disabled\n");
printf("- Press `T` to add custom geometry source\n");
printf("- Press `F` to enable feature-state demo\n");
printf("- Press `U` to toggle pitch bounds\n");
printf("- Press `H` to take a snapshot of a current map.\n");
printf(
"- Press `J` to take a snapshot of a current map with an extrusions "
"overlay.\n");
printf("- Press `Y` to start a camera fly-by demo\n");
printf("\n");
printf(
"- Press `1` through `6` to add increasing numbers of point "
"annotations for testing\n");
printf(
"- Press `7` through `0` to add increasing numbers of shape "
"annotations for testing\n");
printf("\n");
printf("- Press `Q` to query annotations\n");
printf("- Press `C` to remove annotations\n");
printf("- Press `K` to add a random custom runtime imagery annotation\n");
printf("- Press `L` to add a random line annotation\n");
printf("- Press `W` to pop the last-added annotation off\n");
printf("- Press `P` to pause tile requests\n");
printf("\n");
printf("- Hold `Control` + mouse drag to rotate\n");
printf("- Hold `Shift` + mouse drag to tilt\n");
printf("\n");
printf("- Press `F1` to generate a render test for the current view\n");
printf("\n");
printf("- Press `Tab` to cycle through the map debug options\n");
printf("- Press `Esc` to quit\n");
printf("\n");
printf(
"======================================================================"
"==========\n");
printf("\n");
}
GLFWView::~GLFWView() {
glfwDestroyWindow(window);
glfwTerminate();
}
void GLFWView::setMap(mbgl::Map *map_) {
map = map_;
map->addAnnotationImage(makeImage("default_marker", 22, 22, 1));
}
void GLFWView::setRenderFrontend(GLFWRendererFrontend *rendererFrontend_) {
rendererFrontend = rendererFrontend_;
}
mbgl::gfx::RendererBackend &GLFWView::getRendererBackend() {
return backend->getRendererBackend();
}
void GLFWView::onKey(GLFWwindow *window, int key, int /*scancode*/, int action, int mods) {
auto *view = reinterpret_cast<GLFWView *>(glfwGetWindowUserPointer(window));
if (action == GLFW_RELEASE) {
if (key != GLFW_KEY_R || key != GLFW_KEY_S) view->animateRouteCallback = nullptr;
switch (key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, true);
break;
case GLFW_KEY_TAB:
view->cycleDebugOptions();
break;
case GLFW_KEY_X:
if (!mods)
view->map->jumpTo(
mbgl::CameraOptions().withCenter(mbgl::LatLng{}).withZoom(0.0).withBearing(0.0).withPitch(0.0));
break;
case GLFW_KEY_O:
view->onlineStatusCallback();
break;
case GLFW_KEY_S:
if (view->changeStyleCallback) view->changeStyleCallback();
break;
case GLFW_KEY_N:
if (!mods)
view->map->easeTo(mbgl::CameraOptions().withBearing(0.0),
mbgl::AnimationOptions{{mbgl::Milliseconds(500)}});
break;
case GLFW_KEY_Z:
view->nextOrientation();
break;
case GLFW_KEY_Q: {
auto result = view->rendererFrontend->getRenderer()->queryPointAnnotations(
{{}, {static_cast<double>(view->getSize().width), static_cast<double>(view->getSize().height)}});
printf("visible point annotations: %zu\n", result.size());
auto features = view->rendererFrontend->getRenderer()->queryRenderedFeatures(
mbgl::ScreenBox{{view->getSize().width * 0.5, view->getSize().height * 0.5},
{view->getSize().width * 0.5 + 1.0, view->getSize().height * 0.5 + 1}},
{});
printf("Rendered features at the center of the screen: %zu\n", features.size());
} break;
case GLFW_KEY_P:
view->pauseResumeCallback();
break;
case GLFW_KEY_C:
view->clearAnnotations();
break;
case GLFW_KEY_I:
view->resetDatabaseCallback();
break;
case GLFW_KEY_K:
view->addRandomCustomPointAnnotations(1);
break;
case GLFW_KEY_L:
view->addRandomLineAnnotations(1);
break;
case GLFW_KEY_A: {
// XXX Fix precision loss in flyTo:
// https://github.com/mapbox/mapbox-gl-native/issues/4298
static const std::vector<mbgl::LatLng> places = {
mbgl::LatLng{-16.796665, -179.999983}, // Dateline monument
mbgl::LatLng{12.9810542, 77.6345551}, // Mapbox Bengaluru, India
mbgl::LatLng{-13.15607, -74.21773}, // Mapbox Peru
mbgl::LatLng{37.77572, -122.4158818}, // Mapbox SF, USA
mbgl::LatLng{38.91318, -77.03255}, // Mapbox DC, USA
};
static size_t nextPlace = 0;
mbgl::CameraOptions cameraOptions;
cameraOptions.center = places[nextPlace++];
cameraOptions.zoom = 20;
cameraOptions.pitch = 30;
mbgl::AnimationOptions animationOptions(mbgl::Seconds(10));
view->map->flyTo(cameraOptions, animationOptions);
nextPlace = nextPlace % places.size();
} break;
case GLFW_KEY_R: {
view->show3DExtrusions = true;
view->toggle3DExtrusions(view->show3DExtrusions);
if (view->animateRouteCallback) break;
view->animateRouteCallback = [](mbgl::Map *routeMap) {
static mapbox::cheap_ruler::CheapRuler ruler{40.7}; // New York
static mapbox::geojson::geojson route{mapbox::geojson::parse(mbgl::platform::glfw::route)};
const auto &geometry = route.get<mapbox::geometry::geometry<double>>();
const auto &lineString = geometry.get<mapbox::geometry::line_string<double>>();
static double routeDistance = ruler.lineDistance(lineString);
static double routeProgress = 0;
routeProgress += 0.0005;
if (routeProgress > 1.0) {
routeProgress = 0.0;
}
auto camera = routeMap->getCameraOptions();
auto point = ruler.along(lineString, routeProgress * routeDistance);
const mbgl::LatLng center{point.y, point.x};
auto latLng = *camera.center;
double bearing = ruler.bearing({latLng.longitude(), latLng.latitude()}, point);
double easing = bearing - *camera.bearing;
easing += easing > 180.0 ? -360.0 : easing < -180 ? 360.0 : 0;
bearing = *camera.bearing + (easing / 20);
routeMap->jumpTo(
mbgl::CameraOptions().withCenter(center).withZoom(18.0).withBearing(bearing).withPitch(60.0));
};
view->animateRouteCallback(view->map);
} break;
case GLFW_KEY_E:
view->toggle3DExtrusions(!view->show3DExtrusions);
break;
case GLFW_KEY_D: {
static const std::vector<mbgl::LatLngBounds> bounds = {
mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -170.0}, mbgl::LatLng{45.0, 170.0}), // inside
mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, -200.0}, mbgl::LatLng{45.0, -160.0}), // left IDL
mbgl::LatLngBounds::hull(mbgl::LatLng{-45.0, 160.0}, mbgl::LatLng{45.0, 200.0}), // right IDL
mbgl::LatLngBounds()};
static size_t nextBound = 0u;
static mbgl::AnnotationID boundAnnotationID = std::numeric_limits<mbgl::AnnotationID>::max();
mbgl::LatLngBounds bound = bounds[nextBound++];
nextBound = nextBound % bounds.size();
view->map->setBounds(mbgl::BoundOptions().withLatLngBounds(bound));
if (bound == mbgl::LatLngBounds()) {
view->map->removeAnnotation(boundAnnotationID);
boundAnnotationID = std::numeric_limits<mbgl::AnnotationID>::max();
} else {
mbgl::Polygon<double> rect;
rect.push_back({
mbgl::Point<double>{bound.west(), bound.north()},
mbgl::Point<double>{bound.east(), bound.north()},
mbgl::Point<double>{bound.east(), bound.south()},
mbgl::Point<double>{bound.west(), bound.south()},
});
auto boundAnnotation = mbgl::FillAnnotation{
rect, 0.5f, {view->makeRandomColor()}, {view->makeRandomColor()}};
if (boundAnnotationID == std::numeric_limits<mbgl::AnnotationID>::max()) {
boundAnnotationID = view->map->addAnnotation(boundAnnotation);
} else {
view->map->updateAnnotation(boundAnnotationID, boundAnnotation);
}
}
} break;
case GLFW_KEY_T:
view->toggleCustomSource();
break;
case GLFW_KEY_F: {
using namespace mbgl;
using namespace mbgl::style;
using namespace mbgl::style::expression::dsl;
auto &style = view->map->getStyle();
if (!style.getSource("states")) {
std::string url =
"https://maplibre.org/maplibre-gl-js-docs/assets/"
"us_states.geojson";
auto source = std::make_unique<GeoJSONSource>("states");
source->setURL(url);
style.addSource(std::move(source));
mbgl::CameraOptions cameraOptions;
cameraOptions.center = mbgl::LatLng{42.619626, -103.523181};
cameraOptions.zoom = 3;
cameraOptions.pitch = 0;
cameraOptions.bearing = 0;
view->map->jumpTo(cameraOptions);
}
auto layer = style.getLayer("state-fills");
if (!layer) {
auto fillLayer = std::make_unique<FillLayer>("state-fills", "states");
fillLayer->setFillColor(mbgl::Color{0.0, 0.0, 1.0, 0.5});
fillLayer->setFillOpacity(PropertyExpression<float>(
createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 1, 0.5])")));
style.addLayer(std::move(fillLayer));
} else {
layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible
? mbgl::style::VisibilityType::None
: mbgl::style::VisibilityType::Visible);
}
layer = style.getLayer("state-borders");
if (!layer) {
auto borderLayer = std::make_unique<LineLayer>("state-borders", "states");
borderLayer->setLineColor(mbgl::Color{0.0, 0.0, 1.0, 1.0});
borderLayer->setLineWidth(PropertyExpression<float>(
createExpression(R"(["case", ["boolean", ["feature-state", "hover"], false], 2, 1])")));
style.addLayer(std::move(borderLayer));
} else {
layer->setVisibility(layer->getVisibility() == mbgl::style::VisibilityType::Visible
? mbgl::style::VisibilityType::None
: mbgl::style::VisibilityType::Visible);
}
} break;
case GLFW_KEY_F1: {
bool success = TestWriter()
.withInitialSize(mbgl::Size(view->width, view->height))
.withStyle(view->map->getStyle())
.withCameraOptions(view->map->getCameraOptions())
.write(view->testDirectory);
if (success) {
mbgl::Log::Info(mbgl::Event::General, "Render test created!");
} else {
mbgl::Log::Error(mbgl::Event::General,
"Fail to create render test! Base directory does not "
"exist or permission denied.");
}
} break;
case GLFW_KEY_U: {
auto bounds = view->map->getBounds();
if (bounds.minPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MIN) &&
bounds.maxPitch == mbgl::util::rad2deg(mbgl::util::PITCH_MAX)) {
mbgl::Log::Info(mbgl::Event::General, "Limiting pitch bounds to [30, 40] degrees");
view->map->setBounds(mbgl::BoundOptions().withMinPitch(30).withMaxPitch(40));
} else {
mbgl::Log::Info(mbgl::Event::General, "Resetting pitch bounds to [0, 60] degrees");
view->map->setBounds(mbgl::BoundOptions().withMinPitch(0).withMaxPitch(60));
}
} break;
case GLFW_KEY_H: {
view->makeSnapshot();
} break;
case GLFW_KEY_J: {
// Snapshot with overlay
view->makeSnapshot(true);
} break;
case GLFW_KEY_G: {
view->toggleLocationIndicatorLayer();
} break;
case GLFW_KEY_Y: {
view->freeCameraDemoPhase = 0;
view->freeCameraDemoStartTime = mbgl::Clock::now();
view->invalidate();
} break;
}
}
if (action == GLFW_RELEASE || action == GLFW_REPEAT) {
switch (key) {
case GLFW_KEY_W:
view->popAnnotation();
break;
case GLFW_KEY_1:
view->addRandomPointAnnotations(1);
break;
case GLFW_KEY_2:
view->addRandomPointAnnotations(10);
break;
case GLFW_KEY_3:
view->addRandomPointAnnotations(100);
break;
case GLFW_KEY_4:
view->addRandomPointAnnotations(1000);
break;
case GLFW_KEY_5:
view->addRandomPointAnnotations(10000);
break;
case GLFW_KEY_6:
view->addRandomPointAnnotations(100000);
break;
case GLFW_KEY_7:
view->addRandomShapeAnnotations(1);
break;
case GLFW_KEY_8:
view->addRandomShapeAnnotations(10);
break;
case GLFW_KEY_9:
view->addRandomShapeAnnotations(100);
break;
case GLFW_KEY_0:
view->addRandomShapeAnnotations(1000);
break;
case GLFW_KEY_M:
view->addAnimatedAnnotation();
break;
}
}
}
namespace mbgl {
namespace util {
template <>
struct Interpolator<mbgl::LatLng> {
mbgl::LatLng operator()(const mbgl::LatLng &a, const mbgl::LatLng &b, const double t) {
return {
interpolate<double>(a.latitude(), b.latitude(), t),
interpolate<double>(a.longitude(), b.longitude(), t),
};
}
};
} // namespace util
} // namespace mbgl
void GLFWView::updateFreeCameraDemo() {
const mbgl::LatLng trainStartPos = {60.171367, 24.941359};
const mbgl::LatLng trainEndPos = {60.185147, 24.936668};
const mbgl::LatLng cameraStartPos = {60.167443, 24.927176};
const mbgl::LatLng cameraEndPos = {60.185107, 24.933366};
const double cameraStartAlt = 1000.0;
const double cameraEndAlt = 150.0;
const double duration = 8.0;
// Interpolate between starting and ending points
std::chrono::duration<double> deltaTime = mbgl::Clock::now() - freeCameraDemoStartTime;
freeCameraDemoPhase = deltaTime.count() / duration;
auto trainPos = mbgl::util::interpolate(trainStartPos, trainEndPos, freeCameraDemoPhase);
auto cameraPos = mbgl::util::interpolate(cameraStartPos, cameraEndPos, freeCameraDemoPhase);
auto cameraAlt = mbgl::util::interpolate(cameraStartAlt, cameraEndAlt, freeCameraDemoPhase);
mbgl::FreeCameraOptions camera;
// Update camera position and focus point on the map with interpolated values
camera.setLocation({cameraPos, cameraAlt});
camera.lookAtPoint(trainPos);
map->setFreeCameraOptions(camera);
if (freeCameraDemoPhase > 1.0) {
freeCameraDemoPhase = -1.0;
}
}
mbgl::Color GLFWView::makeRandomColor() const {
const auto r = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
const auto g = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
const auto b = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
return {r, g, b, 1.0f};
}
mbgl::Point<double> GLFWView::makeRandomPoint() const {
const double x = width * static_cast<double>(std::rand()) / RAND_MAX;
const double y = height * static_cast<double>(std::rand()) / RAND_MAX;
mbgl::LatLng latLng = map->latLngForPixel({x, y});
return {latLng.longitude(), latLng.latitude()};
}
std::unique_ptr<mbgl::style::Image> GLFWView::makeImage(const std::string &id,
int width,
int height,
float pixelRatio) {
const int r = static_cast<int>(255 * (static_cast<double>(std::rand()) / RAND_MAX));
const int g = static_cast<int>(255 * (static_cast<double>(std::rand()) / RAND_MAX));
const int b = static_cast<int>(255 * (static_cast<double>(std::rand()) / RAND_MAX));
const int w = static_cast<int>(std::ceil(pixelRatio * width));
const int h = static_cast<int>(std::ceil(pixelRatio * height));
mbgl::PremultipliedImage image({static_cast<uint32_t>(w), static_cast<uint32_t>(h)});
auto data = reinterpret_cast<uint32_t *>(image.data.get());
const int dist = (w / 2) * (w / 2);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
const int dx = x - w / 2;
const int dy = y - h / 2;
const int diff = dist - (dx * dx + dy * dy);
if (diff > 0) {
const int a = std::min(0xFF, diff) * 0xFF / dist;
// Premultiply the rgb values with alpha
data[w * y + x] = (a << 24) | ((a * r / 0xFF) << 16) | ((a * g / 0xFF) << 8) | (a * b / 0xFF);
}
}
}
return std::make_unique<mbgl::style::Image>(id, std::move(image), pixelRatio);
}
void GLFWView::nextOrientation() {
using NO = mbgl::NorthOrientation;
switch (map->getMapOptions().northOrientation()) {
case NO::Upwards:
map->setNorthOrientation(NO::Rightwards);
break;
case NO::Rightwards:
map->setNorthOrientation(NO::Downwards);
break;
case NO::Downwards:
map->setNorthOrientation(NO::Leftwards);
break;
default:
map->setNorthOrientation(NO::Upwards);
break;
}
}
void GLFWView::addRandomCustomPointAnnotations(int count) {
for (int i = 0; i < count; i++) {
static int spriteID = 1;
const auto name = std::string{"marker-"} + mbgl::util::toString(spriteID++);
map->addAnnotationImage(makeImage(name, 22, 22, 1));
spriteIDs.push_back(name);
annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{makeRandomPoint(), name}));
}
}
void GLFWView::addRandomPointAnnotations(int count) {
for (int i = 0; i < count; ++i) {
annotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{makeRandomPoint(), "default_marker"}));
}
}
void GLFWView::addRandomLineAnnotations(int count) {
for (int i = 0; i < count; ++i) {
mbgl::LineString<double> lineString;
for (int j = 0; j < 3; ++j) {
lineString.push_back(makeRandomPoint());
}
annotationIDs.push_back(map->addAnnotation(mbgl::LineAnnotation{lineString, 1.0f, 2.0f, {makeRandomColor()}}));
}
}
void GLFWView::addRandomShapeAnnotations(int count) {
for (int i = 0; i < count; ++i) {
mbgl::Polygon<double> triangle;
triangle.push_back({makeRandomPoint(), makeRandomPoint(), makeRandomPoint()});
annotationIDs.push_back(
map->addAnnotation(mbgl::FillAnnotation{triangle, 0.5f, {makeRandomColor()}, {makeRandomColor()}}));
}
}
void GLFWView::addAnimatedAnnotation() {
const double started = glfwGetTime();
animatedAnnotationIDs.push_back(map->addAnnotation(mbgl::SymbolAnnotation{{0, 0}, "default_marker"}));
animatedAnnotationAddedTimes.push_back(started);
}
void GLFWView::updateAnimatedAnnotations() {
const double time = glfwGetTime();
for (size_t i = 0; i < animatedAnnotationIDs.size(); i++) {
auto dt = time - animatedAnnotationAddedTimes[i];
const double period = 10;
const double x = dt / period * 360 - 180;
const double y = std::sin(dt / period * M_PI * 2.0) * 80;
map->updateAnnotation(animatedAnnotationIDs[i], mbgl::SymbolAnnotation{{x, y}, "default_marker"});
}
}
void GLFWView::cycleDebugOptions() {
auto debug = map->getDebug();
if (debug & mbgl::MapDebugOptions::Overdraw)
debug = mbgl::MapDebugOptions::NoDebug;
else if (debug & mbgl::MapDebugOptions::Collision)
debug = mbgl::MapDebugOptions::Overdraw;
else if (debug & mbgl::MapDebugOptions::Timestamps)
debug = debug | mbgl::MapDebugOptions::Collision;
else if (debug & mbgl::MapDebugOptions::ParseStatus)
debug = debug | mbgl::MapDebugOptions::Timestamps;
else if (debug & mbgl::MapDebugOptions::TileBorders)
debug = debug | mbgl::MapDebugOptions::ParseStatus;
else
debug = mbgl::MapDebugOptions::TileBorders;
map->setDebug(debug);
}
void GLFWView::clearAnnotations() {
for (const auto &id : annotationIDs) {
map->removeAnnotation(id);
}
annotationIDs.clear();
for (const auto &id : animatedAnnotationIDs) {
map->removeAnnotation(id);
}
animatedAnnotationIDs.clear();
}
void GLFWView::popAnnotation() {
if (annotationIDs.empty()) {
return;
}
map->removeAnnotation(annotationIDs.back());
annotationIDs.pop_back();
}
void GLFWView::makeSnapshot(bool withOverlay) {
if (!snapshotter || snapshotter->getStyleURL() != map->getStyle().getURL()) {
snapshotter = std::make_unique<mbgl::MapSnapshotter>(map->getMapOptions().size(),
map->getMapOptions().pixelRatio(),
mapResourceOptions,
mapClientOptions,
*snapshotterObserver);
snapshotter->setStyleURL(map->getStyle().getURL());
}
auto snapshot = [&] {
snapshotter->setCameraOptions(map->getCameraOptions());
snapshotter->snapshot([](const std::exception_ptr &ptr,
mbgl::PremultipliedImage image,
const mbgl::MapSnapshotter::Attributions &,
const mbgl::MapSnapshotter::PointForFn &,
const mbgl::MapSnapshotter::LatLngForFn &) {
if (!ptr) {
std::ostringstream oss;
oss << "Made snapshot './snapshot.png' with size w:" << image.size.width << "px h:" << image.size.height
<< "px";
mbgl::Log::Info(mbgl::Event::General, oss.str());
std::ofstream file("./snapshot.png");
file << mbgl::encodePNG(image);
} else {
mbgl::Log::Error(mbgl::Event::General, "Failed to make a snapshot!");
}
});
};
if (withOverlay) {
snapshotterObserver->didFinishLoadingStyleCallback = [&] {
addFillExtrusionLayer(snapshotter->getStyle(), withOverlay);
snapshot();
};
} else {
snapshot();
}
}
void GLFWView::onScroll(GLFWwindow *window, double /*xOffset*/, double yOffset) {
auto *view = reinterpret_cast<GLFWView *>(glfwGetWindowUserPointer(window));
double delta = yOffset * 40;
bool isWheel = delta != 0 && std::fmod(delta, 4.000244140625) == 0;
double absDelta = delta < 0 ? -delta : delta;
double scale = 2.0 / (1.0 + std::exp(-absDelta / 100.0));
// Make the scroll wheel a bit slower.
if (!isWheel) {
scale = (scale - 1.0) / 2.0 + 1.0;
}
// Zooming out.
if (delta < 0 && scale != 0) {
scale = 1.0 / scale;
}
view->map->scaleBy(scale, mbgl::ScreenCoordinate{view->lastX, view->lastY});
#if defined(MLN_RENDER_BACKEND_OPENGL) && !defined(MBGL_LAYER_CUSTOM_DISABLE_ALL)
if (view->puck && view->puckFollowsCameraCenter) {
mbgl::LatLng mapCenter = view->map->getCameraOptions().center.value();
view->puck->setLocation(toArray(mapCenter));
}
#endif
}
void GLFWView::onWindowResize(GLFWwindow *window, int width, int height) {
auto *view = reinterpret_cast<GLFWView *>(glfwGetWindowUserPointer(window));
view->width = width;
view->height = height;
view->map->setSize({static_cast<uint32_t>(view->width), static_cast<uint32_t>(view->height)});
#ifdef __APPLE__
int fbW, fbH;
glfwGetFramebufferSize(window, &fbW, &fbH);
view->backend->setSize({fbW, fbH});
#endif
}
void GLFWView::onFramebufferResize(GLFWwindow *window, int width, int height) {
auto *view = reinterpret_cast<GLFWView *>(glfwGetWindowUserPointer(window));
view->backend->setSize({static_cast<uint32_t>(width), static_cast<uint32_t>(height)});
// This is only triggered when the framebuffer is resized, but not the
// window. It can happen when you move the window between screens with a
// different pixel ratio. We are forcing a repaint my invalidating the view,
// which triggers a rerender with the new framebuffer dimensions.
view->invalidate();
}
void GLFWView::onMouseClick(GLFWwindow *window, int button, int action, int modifiers) {
auto *view = reinterpret_cast<GLFWView *>(glfwGetWindowUserPointer(window));
if (button == GLFW_MOUSE_BUTTON_RIGHT || (button == GLFW_MOUSE_BUTTON_LEFT && modifiers & GLFW_MOD_CONTROL)) {
view->rotating = action == GLFW_PRESS;
view->map->setGestureInProgress(view->rotating);
} else if (button == GLFW_MOUSE_BUTTON_LEFT && (modifiers & GLFW_MOD_SHIFT)) {
view->pitching = action == GLFW_PRESS;
view->map->setGestureInProgress(view->pitching);
} else if (button == GLFW_MOUSE_BUTTON_LEFT) {
view->tracking = action == GLFW_PRESS;
view->map->setGestureInProgress(view->tracking);
if (action == GLFW_RELEASE) {
double now = glfwGetTime();
if (now - view->lastClick < 0.4 /* ms */) {
if (modifiers & GLFW_MOD_SHIFT) {
view->map->scaleBy(0.5,
mbgl::ScreenCoordinate{view->lastX, view->lastY},
mbgl::AnimationOptions{{mbgl::Milliseconds(500)}});
} else {
view->map->scaleBy(2.0,
mbgl::ScreenCoordinate{view->lastX, view->lastY},
mbgl::AnimationOptions{{mbgl::Milliseconds(500)}});
}
}
view->lastClick = now;
}
}
}
void GLFWView::onMouseMove(GLFWwindow *window, double x, double y) {
auto *view = reinterpret_cast<GLFWView *>(glfwGetWindowUserPointer(window));
if (view->tracking) {
const double dx = x - view->lastX;
const double dy = y - view->lastY;
if (dx || dy) {
view->map->moveBy(mbgl::ScreenCoordinate{dx, dy});
}
} else if (view->rotating) {
view->map->rotateBy({view->lastX, view->lastY}, {x, y});
} else if (view->pitching) {
const double dy = y - view->lastY;
if (dy) {
view->map->pitchBy(dy / 2);
}
}
view->lastX = x;
view->lastY = y;
#if defined(MLN_RENDER_BACKEND_OPENGL) && !defined(MBGL_LAYER_CUSTOM_DISABLE_ALL)
if (view->puck && view->puckFollowsCameraCenter) {
mbgl::LatLng mapCenter = view->map->getCameraOptions().center.value();
view->puck->setLocation(toArray(mapCenter));
}
#endif
auto &style = view->map->getStyle();
if (style.getLayer("state-fills")) {
auto screenCoordinate = mbgl::ScreenCoordinate{view->lastX, view->lastY};
const mbgl::RenderedQueryOptions queryOptions({{{"state-fills"}}, {}});
auto result = view->rendererFrontend->getRenderer()->queryRenderedFeatures(screenCoordinate, queryOptions);
using namespace mbgl;
FeatureState newState;
if (!result.empty()) {
FeatureIdentifier id = result[0].id;
std::optional<std::string> idStr = featureIDtoString(id);
if (idStr) {
if (view->featureID && (*view->featureID != *idStr)) {
newState["hover"] = false;
view->rendererFrontend->getRenderer()->setFeatureState("states", {}, *view->featureID, newState);
view->featureID = std::nullopt;
}
if (!view->featureID) {
newState["hover"] = true;
view->featureID = featureIDtoString(id);
view->rendererFrontend->getRenderer()->setFeatureState("states", {}, *view->featureID, newState);
}
}
} else {
if (view->featureID) {
newState["hover"] = false;
view->rendererFrontend->getRenderer()->setFeatureState("states", {}, *view->featureID, newState);
view->featureID = std::nullopt;
}
}
view->invalidate();
}
}
void GLFWView::onWindowFocus(GLFWwindow *window, int focused) {
if (focused == GLFW_FALSE) { // Focus lost.
auto *view = reinterpret_cast<GLFWView *>(glfwGetWindowUserPointer(window));
view->rendererFrontend->getRenderer()->reduceMemoryUse();
}
}
void GLFWView::run() {
auto callback = [&] {
if (glfwWindowShouldClose(window)) {
runLoop.stop();
return;
}
glfwPollEvents();
if (dirty && rendererFrontend) {
dirty = false;
const double started = glfwGetTime();
if (animateRouteCallback) animateRouteCallback(map);
updateAnimatedAnnotations();
mbgl::gfx::BackendScope scope{backend->getRendererBackend()};
rendererFrontend->render();
if (freeCameraDemoPhase >= 0.0) {
updateFreeCameraDemo();
}
report(static_cast<float>(1000 * (glfwGetTime() - started)));
if (benchmark) {
invalidate();
}
}
};
frameTick.start(mbgl::Duration::zero(), mbgl::Milliseconds(1000 / 60), callback);
#if defined(__APPLE__)