From 0f4f303791b9f8278bb54d62665cb6719d6286f5 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Fri, 28 Oct 2016 16:39:50 -0700 Subject: [PATCH] [core] Add support for data-driven styling --- cmake/core-files.cmake | 23 +- cmake/test-files.cmake | 6 +- include/mbgl/annotation/annotation.hpp | 11 +- .../conversion/data_driven_property_value.hpp | 46 +++ include/mbgl/style/conversion/function.hpp | 338 ++++++++++++++++-- .../mbgl/style/conversion/property_setter.hpp | 7 +- .../mbgl/style/conversion/property_value.hpp | 2 +- .../mbgl/style/data_driven_property_value.hpp | 45 +++ include/mbgl/style/function.hpp | 40 --- .../mbgl/style/function/camera_function.hpp | 41 +++ .../mbgl/style/function/categorical_stops.hpp | 42 +++ .../style/function/composite_function.hpp | 109 ++++++ .../mbgl/style/function/exponential_stops.hpp | 54 +++ .../mbgl/style/function/identity_stops.hpp | 20 ++ .../mbgl/style/function/interval_stops.hpp | 49 +++ .../mbgl/style/function/source_function.hpp | 56 +++ .../mbgl/style/layers/background_layer.hpp | 1 + include/mbgl/style/layers/circle_layer.hpp | 43 +-- .../style/layers/fill_extrusion_layer.hpp | 19 +- include/mbgl/style/layers/fill_layer.hpp | 19 +- include/mbgl/style/layers/layer.hpp.ejs | 13 +- include/mbgl/style/layers/line_layer.hpp | 31 +- include/mbgl/style/layers/raster_layer.hpp | 1 + include/mbgl/style/layers/symbol_layer.hpp | 13 +- include/mbgl/style/property_value.hpp | 26 +- include/mbgl/style/undefined.hpp | 12 + include/mbgl/util/feature.hpp | 17 + mapbox-gl-js | 2 +- package.json | 4 +- scripts/build-shaders.js | 59 +-- scripts/generate-style-code.js | 45 ++- src/mbgl/gl/attribute.cpp | 227 +++++++++++- src/mbgl/gl/attribute.hpp | 185 +++++++--- src/mbgl/gl/context.cpp | 87 ++--- src/mbgl/gl/context.hpp | 35 +- src/mbgl/gl/draw_mode.hpp | 19 +- src/mbgl/gl/normalization.hpp | 35 ++ src/mbgl/gl/program.hpp | 42 ++- src/mbgl/gl/segment.cpp | 7 + src/mbgl/gl/segment.hpp | 33 +- src/mbgl/gl/types.hpp | 10 - src/mbgl/gl/uniform.hpp | 33 +- src/mbgl/layout/symbol_feature.hpp | 3 + src/mbgl/layout/symbol_layout.cpp | 88 +++-- src/mbgl/layout/symbol_layout.hpp | 21 +- src/mbgl/programs/attributes.hpp | 160 ++++++++- src/mbgl/programs/circle_program.cpp | 2 +- src/mbgl/programs/circle_program.hpp | 32 +- src/mbgl/programs/collision_box_program.cpp | 2 +- src/mbgl/programs/collision_box_program.hpp | 21 +- src/mbgl/programs/debug_program.hpp | 12 +- src/mbgl/programs/fill_program.cpp | 4 +- src/mbgl/programs/fill_program.hpp | 58 +-- src/mbgl/programs/line_program.cpp | 10 +- src/mbgl/programs/line_program.hpp | 76 ++-- src/mbgl/programs/program.hpp | 54 ++- src/mbgl/programs/raster_program.cpp | 2 +- src/mbgl/programs/raster_program.hpp | 27 +- src/mbgl/programs/symbol_program.cpp | 2 +- src/mbgl/programs/symbol_program.hpp | 36 +- src/mbgl/renderer/bucket.hpp | 7 +- src/mbgl/renderer/circle_bucket.cpp | 27 +- src/mbgl/renderer/circle_bucket.hpp | 20 +- src/mbgl/renderer/debug_bucket.cpp | 4 +- src/mbgl/renderer/debug_bucket.hpp | 2 +- src/mbgl/renderer/fill_bucket.cpp | 30 +- src/mbgl/renderer/fill_bucket.hpp | 20 +- src/mbgl/renderer/line_bucket.cpp | 39 +- src/mbgl/renderer/line_bucket.hpp | 25 +- src/mbgl/renderer/painter.cpp | 24 +- src/mbgl/renderer/painter.hpp | 4 +- src/mbgl/renderer/painter_background.cpp | 31 +- src/mbgl/renderer/painter_circle.cpp | 12 +- src/mbgl/renderer/painter_clipping.cpp | 10 +- src/mbgl/renderer/painter_debug.cpp | 10 +- src/mbgl/renderer/painter_fill.cpp | 36 +- src/mbgl/renderer/painter_line.cpp | 5 +- src/mbgl/renderer/painter_raster.cpp | 6 +- src/mbgl/renderer/painter_symbol.cpp | 13 +- src/mbgl/renderer/symbol_bucket.cpp | 18 +- src/mbgl/renderer/symbol_bucket.hpp | 16 +- src/mbgl/style/bucket_parameters.cpp | 14 - src/mbgl/style/bucket_parameters.hpp | 21 +- src/mbgl/style/conversion/stringify.hpp | 148 +++++++- .../style/cross_faded_property_evaluator.cpp | 19 +- .../style/cross_faded_property_evaluator.hpp | 2 +- .../style/data_driven_property_evaluator.hpp | 42 +++ src/mbgl/style/function.cpp | 81 ----- src/mbgl/style/function/categorical_stops.cpp | 35 ++ src/mbgl/style/function/identity_stops.cpp | 43 +++ src/mbgl/style/layer_impl.hpp | 2 +- .../style/layers/background_layer_impl.cpp | 3 +- .../style/layers/background_layer_impl.hpp | 2 +- .../layers/background_layer_properties.hpp | 1 + src/mbgl/style/layers/circle_layer.cpp | 42 +-- src/mbgl/style/layers/circle_layer_impl.cpp | 22 +- src/mbgl/style/layers/circle_layer_impl.hpp | 2 +- .../style/layers/circle_layer_properties.hpp | 15 +- src/mbgl/style/layers/custom_layer_impl.cpp | 3 +- src/mbgl/style/layers/custom_layer_impl.hpp | 2 +- .../style/layers/fill_extrusion_layer.cpp | 18 +- .../layers/fill_extrusion_layer_impl.cpp | 2 +- .../layers/fill_extrusion_layer_impl.hpp | 2 +- .../fill_extrusion_layer_properties.hpp | 7 +- src/mbgl/style/layers/fill_layer.cpp | 18 +- src/mbgl/style/layers/fill_layer_impl.cpp | 17 +- src/mbgl/style/layers/fill_layer_impl.hpp | 2 +- .../style/layers/fill_layer_properties.hpp | 7 +- src/mbgl/style/layers/layer.cpp.ejs | 12 +- .../style/layers/layer_properties.hpp.ejs | 11 +- src/mbgl/style/layers/line_layer.cpp | 30 +- src/mbgl/style/layers/line_layer_impl.cpp | 35 +- src/mbgl/style/layers/line_layer_impl.hpp | 2 +- .../style/layers/line_layer_properties.hpp | 11 +- src/mbgl/style/layers/raster_layer_impl.cpp | 3 +- src/mbgl/style/layers/raster_layer_impl.hpp | 2 +- .../style/layers/raster_layer_properties.hpp | 1 + src/mbgl/style/layers/symbol_layer.cpp | 12 +- src/mbgl/style/layers/symbol_layer_impl.cpp | 49 +-- src/mbgl/style/layers/symbol_layer_impl.hpp | 6 +- .../style/layers/symbol_layer_properties.hpp | 7 +- src/mbgl/style/layout_property.hpp | 13 +- src/mbgl/style/paint_property.hpp | 82 +++-- src/mbgl/style/paint_property_binder.hpp | 283 +++++++++++++++ src/mbgl/style/parser.cpp | 12 +- .../possibly_evaluated_property_value.hpp | 74 ++++ src/mbgl/style/property_evaluator.hpp | 2 +- src/mbgl/text/quads.cpp | 2 +- src/mbgl/text/shaping.cpp | 13 +- src/mbgl/text/shaping.hpp | 41 ++- src/mbgl/tile/geometry_tile_worker.cpp | 27 +- src/mbgl/util/ignore.hpp | 3 + src/mbgl/util/indexed_tuple.hpp | 13 +- src/mbgl/util/interpolate.cpp | 19 + src/mbgl/util/interpolate.hpp | 9 +- src/mbgl/util/type_list.hpp | 40 +++ test/api/annotations.test.cpp | 14 +- test/gl/bucket.test.cpp | 19 +- test/style/conversion/stringify.test.cpp | 33 +- .../camera_function.test.cpp} | 14 +- test/style/style_layer.test.cpp | 116 +++--- test/text/quads.test.cpp | 4 +- test/tile/vector_tile.test.cpp | 4 +- test/util/merge_lines.test.cpp | 48 +-- 144 files changed, 3299 insertions(+), 1215 deletions(-) create mode 100644 include/mbgl/style/conversion/data_driven_property_value.hpp create mode 100644 include/mbgl/style/data_driven_property_value.hpp delete mode 100644 include/mbgl/style/function.hpp create mode 100644 include/mbgl/style/function/camera_function.hpp create mode 100644 include/mbgl/style/function/categorical_stops.hpp create mode 100644 include/mbgl/style/function/composite_function.hpp create mode 100644 include/mbgl/style/function/exponential_stops.hpp create mode 100644 include/mbgl/style/function/identity_stops.hpp create mode 100644 include/mbgl/style/function/interval_stops.hpp create mode 100644 include/mbgl/style/function/source_function.hpp create mode 100644 include/mbgl/style/undefined.hpp create mode 100644 src/mbgl/gl/normalization.hpp create mode 100644 src/mbgl/gl/segment.cpp create mode 100644 src/mbgl/style/data_driven_property_evaluator.hpp delete mode 100644 src/mbgl/style/function.cpp create mode 100644 src/mbgl/style/function/categorical_stops.cpp create mode 100644 src/mbgl/style/function/identity_stops.cpp create mode 100644 src/mbgl/style/paint_property_binder.hpp create mode 100644 src/mbgl/style/possibly_evaluated_property_value.hpp create mode 100644 src/mbgl/util/interpolate.cpp create mode 100644 src/mbgl/util/type_list.hpp rename test/style/{functions.test.cpp => function/camera_function.test.cpp} (82%) diff --git a/cmake/core-files.cmake b/cmake/core-files.cmake index 6c44117cd8e..1059e972ce7 100644 --- a/cmake/core-files.cmake +++ b/cmake/core-files.cmake @@ -70,11 +70,13 @@ set(MBGL_CORE_FILES src/mbgl/gl/framebuffer.hpp src/mbgl/gl/gl.cpp src/mbgl/gl/index_buffer.hpp + src/mbgl/gl/normalization.hpp src/mbgl/gl/object.cpp src/mbgl/gl/object.hpp src/mbgl/gl/primitives.hpp src/mbgl/gl/program.hpp src/mbgl/gl/renderbuffer.hpp + src/mbgl/gl/segment.cpp src/mbgl/gl/segment.hpp src/mbgl/gl/state.hpp src/mbgl/gl/stencil_mode.cpp @@ -205,14 +207,15 @@ set(MBGL_CORE_FILES # style include/mbgl/style/conversion.hpp + include/mbgl/style/data_driven_property_value.hpp include/mbgl/style/filter.hpp include/mbgl/style/filter_evaluator.hpp - include/mbgl/style/function.hpp include/mbgl/style/layer.hpp include/mbgl/style/property_value.hpp include/mbgl/style/source.hpp include/mbgl/style/transition_options.hpp include/mbgl/style/types.hpp + include/mbgl/style/undefined.hpp src/mbgl/style/bucket_parameters.cpp src/mbgl/style/bucket_parameters.hpp src/mbgl/style/cascade_parameters.hpp @@ -220,7 +223,7 @@ set(MBGL_CORE_FILES src/mbgl/style/class_dictionary.hpp src/mbgl/style/cross_faded_property_evaluator.cpp src/mbgl/style/cross_faded_property_evaluator.hpp - src/mbgl/style/function.cpp + src/mbgl/style/data_driven_property_evaluator.hpp src/mbgl/style/group_by_layout.cpp src/mbgl/style/group_by_layout.hpp src/mbgl/style/layer.cpp @@ -230,8 +233,10 @@ set(MBGL_CORE_FILES src/mbgl/style/layout_property.hpp src/mbgl/style/observer.hpp src/mbgl/style/paint_property.hpp + src/mbgl/style/paint_property_binder.hpp src/mbgl/style/parser.cpp src/mbgl/style/parser.hpp + src/mbgl/style/possibly_evaluated_property_value.hpp src/mbgl/style/property_evaluation_parameters.hpp src/mbgl/style/property_evaluator.hpp src/mbgl/style/property_parsing.cpp @@ -252,6 +257,7 @@ set(MBGL_CORE_FILES # style/conversion include/mbgl/style/conversion/constant.hpp + include/mbgl/style/conversion/data_driven_property_value.hpp include/mbgl/style/conversion/filter.hpp include/mbgl/style/conversion/function.hpp include/mbgl/style/conversion/geojson.hpp @@ -264,6 +270,17 @@ set(MBGL_CORE_FILES include/mbgl/style/conversion/tileset.hpp src/mbgl/style/conversion/stringify.hpp + # style/function + include/mbgl/style/function/camera_function.hpp + include/mbgl/style/function/categorical_stops.hpp + include/mbgl/style/function/composite_function.hpp + include/mbgl/style/function/exponential_stops.hpp + include/mbgl/style/function/identity_stops.hpp + include/mbgl/style/function/interval_stops.hpp + include/mbgl/style/function/source_function.hpp + src/mbgl/style/function/categorical_stops.cpp + src/mbgl/style/function/identity_stops.cpp + # style/layers include/mbgl/style/layers/background_layer.hpp include/mbgl/style/layers/circle_layer.hpp @@ -437,6 +454,7 @@ set(MBGL_CORE_FILES src/mbgl/util/i18n.hpp src/mbgl/util/ignore.hpp src/mbgl/util/indexed_tuple.hpp + src/mbgl/util/interpolate.cpp src/mbgl/util/interpolate.hpp src/mbgl/util/intersection_tests.cpp src/mbgl/util/intersection_tests.hpp @@ -469,6 +487,7 @@ set(MBGL_CORE_FILES src/mbgl/util/tile_cover.cpp src/mbgl/util/tile_cover.hpp src/mbgl/util/token.hpp + src/mbgl/util/type_list.hpp src/mbgl/util/url.cpp src/mbgl/util/url.hpp src/mbgl/util/utf.hpp diff --git a/cmake/test-files.cmake b/cmake/test-files.cmake index cd40d177cb8..617f71be789 100644 --- a/cmake/test-files.cmake +++ b/cmake/test-files.cmake @@ -77,7 +77,11 @@ set(MBGL_TEST_FILES # style test/style/filter.test.cpp - test/style/functions.test.cpp + + # style/function + test/style/function/camera_function.test.cpp + + # style test/style/group_by_layout.test.cpp test/style/source.test.cpp test/style/style.test.cpp diff --git a/include/mbgl/annotation/annotation.hpp b/include/mbgl/annotation/annotation.hpp index a72c65b8c46..de83d247121 100644 --- a/include/mbgl/annotation/annotation.hpp +++ b/include/mbgl/annotation/annotation.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -29,17 +30,17 @@ using ShapeAnnotationGeometry = variant< class LineAnnotation { public: ShapeAnnotationGeometry geometry; - style::PropertyValue opacity { 1.0f }; + style::DataDrivenPropertyValue opacity { 1.0f }; style::PropertyValue width { 1.0f }; - style::PropertyValue color { Color::black() }; + style::DataDrivenPropertyValue color { Color::black() }; }; class FillAnnotation { public: ShapeAnnotationGeometry geometry; - style::PropertyValue opacity { 1.0f }; - style::PropertyValue color { Color::black() }; - style::PropertyValue outlineColor {}; + style::DataDrivenPropertyValue opacity { 1.0f }; + style::DataDrivenPropertyValue color { Color::black() }; + style::DataDrivenPropertyValue outlineColor {}; }; // An annotation whose type and properties are sourced from a style layer. diff --git a/include/mbgl/style/conversion/data_driven_property_value.hpp b/include/mbgl/style/conversion/data_driven_property_value.hpp new file mode 100644 index 00000000000..83f44fdb278 --- /dev/null +++ b/include/mbgl/style/conversion/data_driven_property_value.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include + +namespace mbgl { +namespace style { +namespace conversion { + +template +struct Converter> { + template + Result> operator()(const V& value) const { + if (isUndefined(value)) { + return {}; + } else if (!isObject(value)) { + Result constant = convert(value); + if (!constant) { + return constant.error(); + } + return DataDrivenPropertyValue(*constant); + } else if (!objectMember(value, "property")) { + Result> function = convert>(value); + if (!function) { + return function.error(); + } + return DataDrivenPropertyValue(*function); + } else { + Result> composite = convert>(value); + if (composite) { + return DataDrivenPropertyValue(*composite); + } + Result> source = convert>(value); + if (!source) { + return source.error(); + } + return DataDrivenPropertyValue(*source); + } + } +}; + +} // namespace conversion +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/conversion/function.hpp b/include/mbgl/style/conversion/function.hpp index 6a0b67618fd..90b4b95063a 100644 --- a/include/mbgl/style/conversion/function.hpp +++ b/include/mbgl/style/conversion/function.hpp @@ -1,70 +1,340 @@ #pragma once -#include +#include +#include +#include #include #include +#include namespace mbgl { namespace style { namespace conversion { +template +Result> convertStops(const V& value) { + auto stopsValue = objectMember(value, "stops"); + if (!stopsValue) { + return Error { "function value must specify stops" }; + } + + if (!isArray(*stopsValue)) { + return Error { "function stops must be an array" }; + } + + if (arrayLength(*stopsValue) == 0) { + return Error { "function must have at least one stop" }; + } + + std::map stops; + for (std::size_t i = 0; i < arrayLength(*stopsValue); ++i) { + const auto& stopValue = arrayMember(*stopsValue, i); + + if (!isArray(stopValue)) { + return Error { "function stop must be an array" }; + } + + if (arrayLength(stopValue) != 2) { + return Error { "function stop must have two elements" }; + } + + Result d = convert(arrayMember(stopValue, 0)); + if (!d) { + return d.error(); + } + + Result r = convert(arrayMember(stopValue, 1)); + if (!r) { + return r.error(); + } + + stops.emplace(*d, *r); + } + + return stops; +} + template -struct Converter> { +struct Converter> { + static constexpr const char * type = "exponential"; + template - Result> operator()(const V& value) const { + Result> operator()(const V& value) const { + auto stops = convertStops(value); + if (!stops) { + return stops.error(); + } + + auto baseValue = objectMember(value, "base"); + if (!baseValue) { + return ExponentialStops(*stops); + } + + optional base = toNumber(*baseValue); + if (!base) { + return Error { "function base must be a number"}; + } + + return ExponentialStops(*stops, *base); + } +}; + +template +struct Converter> { + static constexpr const char * type = "interval"; + + template + Result> operator()(const V& value) const { + auto stops = convertStops(value); + if (!stops) { + return stops.error(); + } + return IntervalStops(*stops); + } +}; + +template <> +struct Converter { + template + Result operator()(const V& value) const { + auto b = toBool(value); + if (b) { + return *b; + } + + auto n = toNumber(value); + if (n) { + return int64_t(*n); + } + + auto s = toString(value); + if (s) { + return *s; + } + + return Error { "stop domain value must be a number, string, or boolean" }; + } +}; + +template +struct Converter> { + static constexpr const char * type = "categorical"; + + template + Result> operator()(const V& value) const { + auto stops = convertStops(value); + if (!stops) { + return stops.error(); + } + return CategoricalStops( + std::map((*stops).begin(), (*stops).end())); + } +}; + +template +struct Converter> { + static constexpr const char * type = "identity"; + + template + Result> operator()(const V&) const { + return IdentityStops(); + } +}; + +template +struct StopsConverter; + +template +struct StopsConverter> { +public: + template + Result> operator()(const V& value) const { + std::string type = util::Interpolatable ? "exponential" : "interval"; + + auto typeValue = objectMember(value, "type"); + if (typeValue && toString(*typeValue)) { + type = *toString(*typeValue); + } + + optional>> result; + + // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47226 + auto tryConvert = [&] (auto* tp) { + using Stops = std::decay_t; + if (type == Converter::type) { + auto stops = convert(value); + result = stops + ? Result>(*stops) + : Result>(stops.error()); + } + }; + + util::ignore({ + (tryConvert((Ts*)nullptr), 0)... + }); + + if (!result) { + return Error { "unsupported function type" }; + } + + return *result; + } +}; + +template +struct Converter> { + template + Result> operator()(const V& value) const { + if (!isObject(value)) { + return Error { "function must be an object" }; + } + + auto stops = StopsConverter::Stops>()(value); + if (!stops) { + return stops.error(); + } + + return CameraFunction(*stops); + } +}; + +template +struct Converter> { + template + Result> operator()(const V& value) const { + if (!isObject(value)) { + return Error { "function must be an object" }; + } + + auto propertyValue = objectMember(value, "property"); + if (!propertyValue) { + return Error { "function must specify property" }; + } + + auto propertyString = toString(*propertyValue); + if (!propertyString) { + return Error { "function property must be a string" }; + } + + auto stops = StopsConverter::Stops>()(value); + if (!stops) { + return stops.error(); + } + + return SourceFunction(*propertyString, *stops); + } +}; + +template +struct CompositeValue : std::pair { + using std::pair::pair; +}; + +template +struct Converter> { + template + Result> operator()(const V& value) const { + if (!isObject(value)) { + return Error { "stop must be an object" }; + } + + auto zoomValue = objectMember(value, "zoom"); + if (!zoomValue) { + return Error { "stop must specify zoom" }; + } + + auto propertyValue = objectMember(value, "value"); + if (!propertyValue) { + return Error { "stop must specify value" }; + } + + Result z = convert(*zoomValue); + if (!z) { + return z.error(); + } + + Result s = convert(*propertyValue); + if (!s) { + return s.error(); + } + + return CompositeValue { *z, *s }; + } +}; + +template +struct Converter> { + template + Result> operator()(const V& value) const { if (!isObject(value)) { return Error { "function must be an object" }; } - auto stopsValue = objectMember(value, "stops"); - if (!stopsValue) { - return Error { "function value must specify stops" }; + auto propertyValue = objectMember(value, "property"); + if (!propertyValue) { + return Error { "function must specify property" }; } - if (!isArray(*stopsValue)) { - return Error { "function stops must be an array" }; + auto propertyString = toString(*propertyValue); + if (!propertyString) { + return Error { "function property must be a string" }; } - if (arrayLength(*stopsValue) == 0) { - return Error { "function must have at least one stop" }; + std::string type = "exponential"; + auto typeValue = objectMember(value, "type"); + if (typeValue && toString(*typeValue)) { + type = *toString(*typeValue); } - std::vector> stops; - for (std::size_t i = 0; i < arrayLength(*stopsValue); ++i) { - const auto& stopValue = arrayMember(*stopsValue, i); + if (type == "exponential") { + auto stops = convertStops, T>(value); + if (!stops) { + return stops.error(); + } - if (!isArray(stopValue)) { - return Error { "function stop must be an array" }; + auto base = 1.0f; + auto baseValue = objectMember(value, "base"); + if (baseValue && toNumber(*baseValue)) { + base = *toNumber(*baseValue); } - if (arrayLength(stopValue) != 2) { - return Error { "function stop must have two elements" }; + std::map> convertedStops; + for (const auto& stop : *stops) { + auto& inner = convertedStops[stop.first.first]; + inner.base = base; + inner.stops.emplace(stop.first.second, stop.second); } - optional z = toNumber(arrayMember(stopValue, 0)); - if (!z) { - return Error { "function stop zoom level must be a number" }; + return CompositeFunction(*propertyString, convertedStops); + } else if (type == "interval") { + auto stops = convertStops, T>(value); + if (!stops) { + return stops.error(); } - Result v = convert(arrayMember(stopValue, 1)); - if (!v) { - return v.error(); + std::map> convertedStops; + for (const auto& stop : *stops) { + auto& inner = convertedStops[stop.first.first]; + inner.stops.emplace(stop.first.second, stop.second); } - stops.emplace_back(*z, *v); - } + return CompositeFunction(*propertyString, convertedStops); + } else if (type == "categorical") { + auto stops = convertStops, T>(value); + if (!stops) { + return stops.error(); + } - auto baseValue = objectMember(value, "base"); - if (!baseValue) { - return Function(stops, 1.0f); - } + std::map> convertedStops; + for (const auto& stop : *stops) { + auto& inner = convertedStops[stop.first.first]; + inner.stops.emplace(stop.first.second, stop.second); + } - optional base = toNumber(*baseValue); - if (!base) { - return Error { "function base must be a number"}; + return CompositeFunction(*propertyString, convertedStops); + } else { + return Error { "unsupported function type" }; } - - return Function(stops, *base); } }; diff --git a/include/mbgl/style/conversion/property_setter.hpp b/include/mbgl/style/conversion/property_setter.hpp index 1a601c7c1ba..52fb160fded 100644 --- a/include/mbgl/style/conversion/property_setter.hpp +++ b/include/mbgl/style/conversion/property_setter.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -18,15 +19,15 @@ using LayoutPropertySetter = std::function (Layer&, const V&)>; template using PaintPropertySetter = std::function (Layer&, const V&, const optional&)>; -template -auto makePropertySetter(void (L::*setter)(PropertyValue, const Args&...args)) { +template +auto makePropertySetter(void (L::*setter)(PropertyValue, const Args&...args)) { return [setter] (Layer& layer, const V& value, const Args&...args) -> optional { L* typedLayer = layer.as(); if (!typedLayer) { return Error { "layer doesn't support this property" }; } - Result> typedValue = convert>(value); + Result typedValue = convert(value); if (!typedValue) { return typedValue.error(); } diff --git a/include/mbgl/style/conversion/property_value.hpp b/include/mbgl/style/conversion/property_value.hpp index de95b561557..d5e2a5c3c86 100644 --- a/include/mbgl/style/conversion/property_value.hpp +++ b/include/mbgl/style/conversion/property_value.hpp @@ -16,7 +16,7 @@ struct Converter> { if (isUndefined(value)) { return {}; } else if (isObject(value)) { - Result> function = convert>(value); + Result> function = convert>(value); if (!function) { return function.error(); } diff --git a/include/mbgl/style/data_driven_property_value.hpp b/include/mbgl/style/data_driven_property_value.hpp new file mode 100644 index 00000000000..566003ab0f4 --- /dev/null +++ b/include/mbgl/style/data_driven_property_value.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace mbgl { +namespace style { + +template +class DataDrivenPropertyValue { +private: + using Value = variant< + Undefined, + T, + CameraFunction, + SourceFunction, + CompositeFunction>; + + Value value; + + friend bool operator==(const DataDrivenPropertyValue& lhs, + const DataDrivenPropertyValue& rhs) { + return lhs.value == rhs.value; + } + +public: + DataDrivenPropertyValue() = default; + DataDrivenPropertyValue( T v) : value(std::move(v)) {} + DataDrivenPropertyValue( CameraFunction v) : value(std::move(v)) {} + DataDrivenPropertyValue( SourceFunction v) : value(std::move(v)) {} + DataDrivenPropertyValue(CompositeFunction v) : value(std::move(v)) {} + + bool isUndefined() const { return value.template is(); } + + template + auto evaluate(const Evaluator& evaluator) const { + return Value::visit(value, evaluator); + } +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/function.hpp b/include/mbgl/style/function.hpp deleted file mode 100644 index b023229e4f8..00000000000 --- a/include/mbgl/style/function.hpp +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace mbgl { -namespace style { - -template -class Function { -public: - using Stop = std::pair; - using Stops = std::vector; - - Function(Stops stops_, float base_) - : base(base_), stops(std::move(stops_)) { - assert(stops.size() > 0); - } - - float getBase() const { return base; } - const std::vector>& getStops() const { return stops; } - - T evaluate(float z) const; - - friend bool operator==(const Function& lhs, const Function& rhs) { - return lhs.base == rhs.base && lhs.stops == rhs.stops; - } - - friend bool operator!=(const Function& lhs, const Function& rhs) { - return !(lhs == rhs); - } - -private: - float base = 1; - std::vector> stops; -}; - -} // namespace style -} // namespace mbgl diff --git a/include/mbgl/style/function/camera_function.hpp b/include/mbgl/style/function/camera_function.hpp new file mode 100644 index 00000000000..a96978939d0 --- /dev/null +++ b/include/mbgl/style/function/camera_function.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include + +namespace mbgl { +namespace style { + +template +class CameraFunction { +public: + using Stops = std::conditional_t< + util::Interpolatable, + variant< + ExponentialStops, + IntervalStops>, + variant< + IntervalStops>>; + + CameraFunction(Stops stops_) + : stops(std::move(stops_)) { + } + + T evaluate(float zoom) const { + return stops.match([&] (const auto& s) { + return s.evaluate(Value(double(zoom))); + }); + } + + friend bool operator==(const CameraFunction& lhs, + const CameraFunction& rhs) { + return lhs.stops == rhs.stops; + } + + Stops stops; +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/function/categorical_stops.hpp b/include/mbgl/style/function/categorical_stops.hpp new file mode 100644 index 00000000000..11ec2a0e5a1 --- /dev/null +++ b/include/mbgl/style/function/categorical_stops.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace mbgl { +namespace style { + +class CategoricalValue : public variant { +public: + using variant::variant; +}; + +template +class CategoricalStops { +public: + using Stops = std::map; + + Stops stops; + T defaultValue; + + CategoricalStops() = default; + CategoricalStops(Stops stops_, T defaultValue_ = T()) + : stops(std::move(stops_)), + defaultValue(std::move(defaultValue_)) { + assert(stops.size() > 0); + } + + T evaluate(const Value&) const; + + friend bool operator==(const CategoricalStops& lhs, + const CategoricalStops& rhs) { + return lhs.stops == rhs.stops && lhs.defaultValue == rhs.defaultValue; + } +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/function/composite_function.hpp b/include/mbgl/style/function/composite_function.hpp new file mode 100644 index 00000000000..169a4554357 --- /dev/null +++ b/include/mbgl/style/function/composite_function.hpp @@ -0,0 +1,109 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace mbgl { + +class GeometryTileFeature; + +namespace style { + +// A CompositeFunction consists of an outer zoom function whose stop range values are +// "inner" source functions. It provides the GL Native implementation of +// "zoom-and-property" functions from the style spec. + +template +class CompositeFunction { +public: + using InnerStops = std::conditional_t< + util::Interpolatable, + variant< + ExponentialStops, + IntervalStops, + CategoricalStops>, + variant< + IntervalStops, + CategoricalStops>>; + + using Stops = std::conditional_t< + util::Interpolatable, + variant< + std::map>, + std::map>, + std::map>>, + variant< + std::map>, + std::map>>>; + + CompositeFunction(std::string property_, Stops stops_) + : property(std::move(property_)), + stops(std::move(stops_)) { + } + + std::tuple, Range> + coveringRanges(float zoom) const { + return stops.match( + [&] (const auto& s) { + assert(!s.empty()); + auto minIt = s.lower_bound(zoom); + auto maxIt = s.upper_bound(zoom); + if (minIt != s.begin()) { + minIt--; + } + return std::make_tuple( + Range { + minIt == s.end() ? s.rbegin()->first : minIt->first, + maxIt == s.end() ? s.rbegin()->first : maxIt->first + }, + Range { + minIt == s.end() ? s.rbegin()->second : minIt->second, + maxIt == s.end() ? s.rbegin()->second : maxIt->second + } + ); + } + ); + } + + Range evaluate(Range coveringStops, + const GeometryTileFeature& feature) const { + optional v = feature.getValue(property); + if (!v) { + return { T(), T() }; + } + auto eval = [&] (const auto& s) { + return s.evaluate(*v); + }; + return Range { + coveringStops.min.match(eval), + coveringStops.max.match(eval) + }; + } + + T evaluate(float zoom, const GeometryTileFeature& feature) const { + std::tuple, Range> ranges = coveringRanges(zoom); + Range resultRange = evaluate(std::get<1>(ranges), feature); + return util::interpolate( + resultRange.min, + resultRange.max, + util::interpolationFactor(1.0f, std::get<0>(ranges), zoom)); + } + + friend bool operator==(const CompositeFunction& lhs, + const CompositeFunction& rhs) { + return lhs.property == rhs.property && lhs.stops == rhs.stops; + } + + std::string property; + Stops stops; +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/function/exponential_stops.hpp b/include/mbgl/style/function/exponential_stops.hpp new file mode 100644 index 00000000000..7bd87836147 --- /dev/null +++ b/include/mbgl/style/function/exponential_stops.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include +#include + +#include + +namespace mbgl { +namespace style { + +template +class ExponentialStops { +public: + using Stops = std::map; + + Stops stops; + float base = 1.0f; + + ExponentialStops() = default; + ExponentialStops(Stops stops_, float base_ = 1.0f) + : stops(std::move(stops_)), + base(base_) { + } + + T evaluate(const Value& value) const { + if (stops.empty()) { + assert(false); + return T(); + } + + optional z = numericValue(value); + if (!z) { + return T(); + } + + auto it = stops.upper_bound(*z); + if (it == stops.end()) { + return stops.rbegin()->second; + } else if (it == stops.begin()) { + return stops.begin()->second; + } else { + return util::interpolate(std::prev(it)->second, it->second, + util::interpolationFactor(base, { std::prev(it)->first, it->first }, *z)); + } + } + + friend bool operator==(const ExponentialStops& lhs, + const ExponentialStops& rhs) { + return lhs.stops == rhs.stops && lhs.base == rhs.base; + } +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/function/identity_stops.hpp b/include/mbgl/style/function/identity_stops.hpp new file mode 100644 index 00000000000..4e199f2e154 --- /dev/null +++ b/include/mbgl/style/function/identity_stops.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace mbgl { +namespace style { + +template +class IdentityStops { +public: + T evaluate(const Value&) const; + + friend bool operator==(const IdentityStops&, + const IdentityStops&) { + return true; + } +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/function/interval_stops.hpp b/include/mbgl/style/function/interval_stops.hpp new file mode 100644 index 00000000000..cf879d730bd --- /dev/null +++ b/include/mbgl/style/function/interval_stops.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include + +#include + +namespace mbgl { +namespace style { + +template +class IntervalStops { +public: + using Stops = std::map; + Stops stops; + + IntervalStops() = default; + IntervalStops(Stops stops_) + : stops(std::move(stops_)) { + } + + T evaluate(const Value& value) const { + if (stops.empty()) { + assert(false); + return T(); + } + + optional z = numericValue(value); + if (!z) { + return T(); + } + + auto it = stops.upper_bound(*z); + if (it == stops.end()) { + return stops.rbegin()->second; + } else if (it == stops.begin()) { + return stops.begin()->second; + } else { + return std::prev(it)->second; + } + } + + friend bool operator==(const IntervalStops& lhs, + const IntervalStops& rhs) { + return lhs.stops == rhs.stops; + } +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/function/source_function.hpp b/include/mbgl/style/function/source_function.hpp new file mode 100644 index 00000000000..e998be082a8 --- /dev/null +++ b/include/mbgl/style/function/source_function.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace mbgl { +namespace style { + +template +class SourceFunction { +public: + using Stops = std::conditional_t< + util::Interpolatable, + variant< + ExponentialStops, + IntervalStops, + CategoricalStops, + IdentityStops>, + variant< + IntervalStops, + CategoricalStops, + IdentityStops>>; + + SourceFunction(std::string property_, Stops stops_) + : property(std::move(property_)), + stops(std::move(stops_)) { + } + + T evaluate(const GeometryTileFeature& feature) const { + optional v = feature.getValue(property); + if (!v) { + return T(); + } + return stops.match([&] (const auto& s) { + return s.evaluate(*v); + }); + } + + friend bool operator==(const SourceFunction& lhs, + const SourceFunction& rhs) { + return lhs.property == rhs.property && lhs.stops == rhs.stops; + } + + std::string property; + Stops stops; +}; + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/style/layers/background_layer.hpp b/include/mbgl/style/layers/background_layer.hpp index c120b7f4933..050cb67df6b 100644 --- a/include/mbgl/style/layers/background_layer.hpp +++ b/include/mbgl/style/layers/background_layer.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include diff --git a/include/mbgl/style/layers/circle_layer.hpp b/include/mbgl/style/layers/circle_layer.hpp index 5562126c2f7..8ffea9946f3 100644 --- a/include/mbgl/style/layers/circle_layer.hpp +++ b/include/mbgl/style/layers/circle_layer.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include @@ -26,21 +27,21 @@ class CircleLayer : public Layer { // Paint properties - static PropertyValue getDefaultCircleRadius(); - PropertyValue getCircleRadius(const optional& klass = {}) const; - void setCircleRadius(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultCircleRadius(); + DataDrivenPropertyValue getCircleRadius(const optional& klass = {}) const; + void setCircleRadius(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultCircleColor(); - PropertyValue getCircleColor(const optional& klass = {}) const; - void setCircleColor(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultCircleColor(); + DataDrivenPropertyValue getCircleColor(const optional& klass = {}) const; + void setCircleColor(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultCircleBlur(); - PropertyValue getCircleBlur(const optional& klass = {}) const; - void setCircleBlur(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultCircleBlur(); + DataDrivenPropertyValue getCircleBlur(const optional& klass = {}) const; + void setCircleBlur(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultCircleOpacity(); - PropertyValue getCircleOpacity(const optional& klass = {}) const; - void setCircleOpacity(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultCircleOpacity(); + DataDrivenPropertyValue getCircleOpacity(const optional& klass = {}) const; + void setCircleOpacity(DataDrivenPropertyValue, const optional& klass = {}); static PropertyValue> getDefaultCircleTranslate(); PropertyValue> getCircleTranslate(const optional& klass = {}) const; @@ -54,17 +55,17 @@ class CircleLayer : public Layer { PropertyValue getCirclePitchScale(const optional& klass = {}) const; void setCirclePitchScale(PropertyValue, const optional& klass = {}); - static PropertyValue getDefaultCircleStrokeWidth(); - PropertyValue getCircleStrokeWidth(const optional& klass = {}) const; - void setCircleStrokeWidth(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultCircleStrokeWidth(); + DataDrivenPropertyValue getCircleStrokeWidth(const optional& klass = {}) const; + void setCircleStrokeWidth(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultCircleStrokeColor(); - PropertyValue getCircleStrokeColor(const optional& klass = {}) const; - void setCircleStrokeColor(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultCircleStrokeColor(); + DataDrivenPropertyValue getCircleStrokeColor(const optional& klass = {}) const; + void setCircleStrokeColor(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultCircleStrokeOpacity(); - PropertyValue getCircleStrokeOpacity(const optional& klass = {}) const; - void setCircleStrokeOpacity(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultCircleStrokeOpacity(); + DataDrivenPropertyValue getCircleStrokeOpacity(const optional& klass = {}) const; + void setCircleStrokeOpacity(DataDrivenPropertyValue, const optional& klass = {}); // Private implementation diff --git a/include/mbgl/style/layers/fill_extrusion_layer.hpp b/include/mbgl/style/layers/fill_extrusion_layer.hpp index 08728af309d..09a0040ff39 100644 --- a/include/mbgl/style/layers/fill_extrusion_layer.hpp +++ b/include/mbgl/style/layers/fill_extrusion_layer.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include @@ -30,9 +31,9 @@ class FillExtrusionLayer : public Layer { PropertyValue getFillExtrusionOpacity(const optional& klass = {}) const; void setFillExtrusionOpacity(PropertyValue, const optional& klass = {}); - static PropertyValue getDefaultFillExtrusionColor(); - PropertyValue getFillExtrusionColor(const optional& klass = {}) const; - void setFillExtrusionColor(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultFillExtrusionColor(); + DataDrivenPropertyValue getFillExtrusionColor(const optional& klass = {}) const; + void setFillExtrusionColor(DataDrivenPropertyValue, const optional& klass = {}); static PropertyValue> getDefaultFillExtrusionTranslate(); PropertyValue> getFillExtrusionTranslate(const optional& klass = {}) const; @@ -46,13 +47,13 @@ class FillExtrusionLayer : public Layer { PropertyValue getFillExtrusionPattern(const optional& klass = {}) const; void setFillExtrusionPattern(PropertyValue, const optional& klass = {}); - static PropertyValue getDefaultFillExtrusionHeight(); - PropertyValue getFillExtrusionHeight(const optional& klass = {}) const; - void setFillExtrusionHeight(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultFillExtrusionHeight(); + DataDrivenPropertyValue getFillExtrusionHeight(const optional& klass = {}) const; + void setFillExtrusionHeight(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultFillExtrusionBase(); - PropertyValue getFillExtrusionBase(const optional& klass = {}) const; - void setFillExtrusionBase(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultFillExtrusionBase(); + DataDrivenPropertyValue getFillExtrusionBase(const optional& klass = {}) const; + void setFillExtrusionBase(DataDrivenPropertyValue, const optional& klass = {}); // Private implementation diff --git a/include/mbgl/style/layers/fill_layer.hpp b/include/mbgl/style/layers/fill_layer.hpp index 4b9201641d2..079541ec393 100644 --- a/include/mbgl/style/layers/fill_layer.hpp +++ b/include/mbgl/style/layers/fill_layer.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include @@ -30,17 +31,17 @@ class FillLayer : public Layer { PropertyValue getFillAntialias(const optional& klass = {}) const; void setFillAntialias(PropertyValue, const optional& klass = {}); - static PropertyValue getDefaultFillOpacity(); - PropertyValue getFillOpacity(const optional& klass = {}) const; - void setFillOpacity(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultFillOpacity(); + DataDrivenPropertyValue getFillOpacity(const optional& klass = {}) const; + void setFillOpacity(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultFillColor(); - PropertyValue getFillColor(const optional& klass = {}) const; - void setFillColor(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultFillColor(); + DataDrivenPropertyValue getFillColor(const optional& klass = {}) const; + void setFillColor(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultFillOutlineColor(); - PropertyValue getFillOutlineColor(const optional& klass = {}) const; - void setFillOutlineColor(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultFillOutlineColor(); + DataDrivenPropertyValue getFillOutlineColor(const optional& klass = {}) const; + void setFillOutlineColor(DataDrivenPropertyValue, const optional& klass = {}); static PropertyValue> getDefaultFillTranslate(); PropertyValue> getFillTranslate(const optional& klass = {}) const; diff --git a/include/mbgl/style/layers/layer.hpp.ejs b/include/mbgl/style/layers/layer.hpp.ejs index 15d0fcee616..0c902de5af4 100644 --- a/include/mbgl/style/layers/layer.hpp.ejs +++ b/include/mbgl/style/layers/layer.hpp.ejs @@ -10,6 +10,7 @@ #include #include #include +#include #include @@ -45,18 +46,18 @@ public: // Layout properties <% for (const property of layoutProperties) { -%> - static PropertyValue<<%- propertyType(property) %>> getDefault<%- camelize(property.name) %>(); - PropertyValue<<%- propertyType(property) %>> get<%- camelize(property.name) %>() const; - void set<%- camelize(property.name) %>(PropertyValue<<%- propertyType(property) %>>); + static <%- propertyValueType(property) %> getDefault<%- camelize(property.name) %>(); + <%- propertyValueType(property) %> get<%- camelize(property.name) %>() const; + void set<%- camelize(property.name) %>(<%- propertyValueType(property) %>); <% } -%> <% } -%> // Paint properties <% for (const property of paintProperties) { -%> - static PropertyValue<<%- propertyType(property) %>> getDefault<%- camelize(property.name) %>(); - PropertyValue<<%- propertyType(property) %>> get<%- camelize(property.name) %>(const optional& klass = {}) const; - void set<%- camelize(property.name) %>(PropertyValue<<%- propertyType(property) %>>, const optional& klass = {}); + static <%- propertyValueType(property) %> getDefault<%- camelize(property.name) %>(); + <%- propertyValueType(property) %> get<%- camelize(property.name) %>(const optional& klass = {}) const; + void set<%- camelize(property.name) %>(<%- propertyValueType(property) %>, const optional& klass = {}); <% } -%> // Private implementation diff --git a/include/mbgl/style/layers/line_layer.hpp b/include/mbgl/style/layers/line_layer.hpp index c3c1026bcdf..c9413f10968 100644 --- a/include/mbgl/style/layers/line_layer.hpp +++ b/include/mbgl/style/layers/line_layer.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include @@ -46,13 +47,13 @@ class LineLayer : public Layer { // Paint properties - static PropertyValue getDefaultLineOpacity(); - PropertyValue getLineOpacity(const optional& klass = {}) const; - void setLineOpacity(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultLineOpacity(); + DataDrivenPropertyValue getLineOpacity(const optional& klass = {}) const; + void setLineOpacity(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultLineColor(); - PropertyValue getLineColor(const optional& klass = {}) const; - void setLineColor(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultLineColor(); + DataDrivenPropertyValue getLineColor(const optional& klass = {}) const; + void setLineColor(DataDrivenPropertyValue, const optional& klass = {}); static PropertyValue> getDefaultLineTranslate(); PropertyValue> getLineTranslate(const optional& klass = {}) const; @@ -66,17 +67,17 @@ class LineLayer : public Layer { PropertyValue getLineWidth(const optional& klass = {}) const; void setLineWidth(PropertyValue, const optional& klass = {}); - static PropertyValue getDefaultLineGapWidth(); - PropertyValue getLineGapWidth(const optional& klass = {}) const; - void setLineGapWidth(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultLineGapWidth(); + DataDrivenPropertyValue getLineGapWidth(const optional& klass = {}) const; + void setLineGapWidth(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultLineOffset(); - PropertyValue getLineOffset(const optional& klass = {}) const; - void setLineOffset(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultLineOffset(); + DataDrivenPropertyValue getLineOffset(const optional& klass = {}) const; + void setLineOffset(DataDrivenPropertyValue, const optional& klass = {}); - static PropertyValue getDefaultLineBlur(); - PropertyValue getLineBlur(const optional& klass = {}) const; - void setLineBlur(PropertyValue, const optional& klass = {}); + static DataDrivenPropertyValue getDefaultLineBlur(); + DataDrivenPropertyValue getLineBlur(const optional& klass = {}) const; + void setLineBlur(DataDrivenPropertyValue, const optional& klass = {}); static PropertyValue> getDefaultLineDasharray(); PropertyValue> getLineDasharray(const optional& klass = {}) const; diff --git a/include/mbgl/style/layers/raster_layer.hpp b/include/mbgl/style/layers/raster_layer.hpp index ae6ec7f91c8..e998abf12a8 100644 --- a/include/mbgl/style/layers/raster_layer.hpp +++ b/include/mbgl/style/layers/raster_layer.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include diff --git a/include/mbgl/style/layers/symbol_layer.hpp b/include/mbgl/style/layers/symbol_layer.hpp index 1e2e6ac4549..8826408e810 100644 --- a/include/mbgl/style/layers/symbol_layer.hpp +++ b/include/mbgl/style/layers/symbol_layer.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include @@ -72,9 +73,9 @@ class SymbolLayer : public Layer { PropertyValue getIconImage() const; void setIconImage(PropertyValue); - static PropertyValue getDefaultIconRotate(); - PropertyValue getIconRotate() const; - void setIconRotate(PropertyValue); + static DataDrivenPropertyValue getDefaultIconRotate(); + DataDrivenPropertyValue getIconRotate() const; + void setIconRotate(DataDrivenPropertyValue); static PropertyValue getDefaultIconPadding(); PropertyValue getIconPadding() const; @@ -84,9 +85,9 @@ class SymbolLayer : public Layer { PropertyValue getIconKeepUpright() const; void setIconKeepUpright(PropertyValue); - static PropertyValue> getDefaultIconOffset(); - PropertyValue> getIconOffset() const; - void setIconOffset(PropertyValue>); + static DataDrivenPropertyValue> getDefaultIconOffset(); + DataDrivenPropertyValue> getIconOffset() const; + void setIconOffset(DataDrivenPropertyValue>); static PropertyValue getDefaultTextPitchAlignment(); PropertyValue getTextPitchAlignment() const; diff --git a/include/mbgl/style/property_value.hpp b/include/mbgl/style/property_value.hpp index 83c4b4cf1b3..e784633aa7c 100644 --- a/include/mbgl/style/property_value.hpp +++ b/include/mbgl/style/property_value.hpp @@ -1,20 +1,16 @@ #pragma once #include -#include +#include +#include namespace mbgl { namespace style { -class Undefined {}; - -inline bool operator==(const Undefined&, const Undefined&) { return true; } -inline bool operator!=(const Undefined&, const Undefined&) { return false; } - template class PropertyValue { private: - using Value = variant>; + using Value = variant>; Value value; friend bool operator==(const PropertyValue& lhs, const PropertyValue& rhs) { @@ -26,16 +22,16 @@ class PropertyValue { } public: - PropertyValue() : value() {} - PropertyValue( T constant) : value(constant) {} - PropertyValue(Function function) : value(function) {} + PropertyValue() : value() {} + PropertyValue( T constant) : value(constant) {} + PropertyValue(CameraFunction function) : value(function) {} - bool isUndefined() const { return value.which() == 0; } - bool isConstant() const { return value.which() == 1; } - bool isFunction() const { return value.which() == 2; } + bool isUndefined() const { return value.which() == 0; } + bool isConstant() const { return value.which() == 1; } + bool isCameraFunction() const { return value.which() == 2; } - const T & asConstant() const { return value.template get< T >(); } - const Function& asFunction() const { return value.template get>(); } + const T & asConstant() const { return value.template get< T >(); } + const CameraFunction& asCameraFunction() const { return value.template get>(); } explicit operator bool() const { return !isUndefined(); }; diff --git a/include/mbgl/style/undefined.hpp b/include/mbgl/style/undefined.hpp new file mode 100644 index 00000000000..e43f132a80e --- /dev/null +++ b/include/mbgl/style/undefined.hpp @@ -0,0 +1,12 @@ +#pragma once + +namespace mbgl { +namespace style { + +class Undefined {}; + +inline bool operator==(const Undefined&, const Undefined&) { return true; } +inline bool operator!=(const Undefined&, const Undefined&) { return false; } + +} // namespace style +} // namespace mbgl diff --git a/include/mbgl/util/feature.hpp b/include/mbgl/util/feature.hpp index b72aa15ddda..4eeceda944a 100644 --- a/include/mbgl/util/feature.hpp +++ b/include/mbgl/util/feature.hpp @@ -12,4 +12,21 @@ using PropertyMap = mapbox::geometry::property_map; using FeatureIdentifier = mapbox::geometry::identifier; using Feature = mapbox::geometry::feature; +template +optional numericValue(const Value& value) { + return value.match( + [] (uint64_t t) { + return optional(t); + }, + [] (int64_t t) { + return optional(t); + }, + [] (double t) { + return optional(t); + }, + [] (auto) { + return optional(); + }); +} + } // namespace mbgl diff --git a/mapbox-gl-js b/mapbox-gl-js index 87800889510..e9d4b75e40c 160000 --- a/mapbox-gl-js +++ b/mapbox-gl-js @@ -1 +1 @@ -Subproject commit 878008895104b67861ce73f65809f7f6f0ed7263 +Subproject commit e9d4b75e40ce6c29b58faa0f0d061be099f35bd6 diff --git a/package.json b/package.json index 5a9e159cc52..370f88439eb 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "ejs": "^2.4.1", "express": "^4.11.1", "lodash": "^4.16.4", - "mapbox-gl-style-spec": "mapbox/mapbox-gl-style-spec#49e8b407bdbbe6f7c92dbcb56d3d51f425fc2653", + "mapbox-gl-style-spec": "mapbox/mapbox-gl-style-spec#2119ebac2896febcfaf6eb9c8b70e1d64556c960", "mkdirp": "^0.5.1", "node-cmake": "^1.2.1", "pixelmatch": "^4.0.2", @@ -48,4 +48,4 @@ "remote_path": "./{name}/v{version}", "package_name": "{node_abi}-{platform}-{arch}.tar.gz" } -} \ No newline at end of file +} diff --git a/scripts/build-shaders.js b/scripts/build-shaders.js index d00762acf0e..00ced5f23bd 100755 --- a/scripts/build-shaders.js +++ b/scripts/build-shaders.js @@ -14,28 +14,43 @@ if (!shaderName || !inputPath || !outputPath) { process.exit(1); } -var pragmaMapboxRe = /(\s*)#pragma\s+mapbox\s*:\s+(define|initialize)\s+(low|medium|high)p\s+(float|vec(?:2|3|4))\s+(.*)/; - - -function applyPragmas(source) { - return '\n' + source.split('\n').map(function(line) { - var params = line.match(pragmaMapboxRe); - if (params) { - if (params[2] === 'define') { - return params[1] + 'uniform ' + params[3] + 'p ' + params[4] + ' u_' + params[5] + ';'; - } else { - return params[1] + params[3] + 'p ' + params[4] + ' ' + params[5] + ' = u_' + params[5] + ';'; - } - } else { - return line; - } - }).join('\n'); +function applyPragmas(source, pragmas) { + return source.replace(/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g, (match, operation, precision, type, name) => { + return pragmas[operation] + .join("\n") + .replace(/\{type\}/g, type) + .replace(/\{precision\}/g, precision) + .replace(/\{name\}/g, name); + }); } -var vertexPrelude = fs.readFileSync(path.join(inputPath, '_prelude.vertex.glsl')); -var fragmentPrelude = fs.readFileSync(path.join(inputPath, '_prelude.fragment.glsl')); -var vertexSource = vertexPrelude + fs.readFileSync(path.join(inputPath, shaderName + '.vertex.glsl'), 'utf8'); -var fragmentSource = fragmentPrelude + fs.readFileSync(path.join(inputPath, shaderName + '.fragment.glsl'), 'utf8'); +function vertexSource() { + var prelude = fs.readFileSync(path.join(inputPath, '_prelude.vertex.glsl')); + var source = fs.readFileSync(path.join(inputPath, shaderName + '.vertex.glsl'), 'utf8'); + return prelude + applyPragmas(source, { + define: [ + "uniform lowp float a_{name}_t;", + "attribute {precision} {type} a_{name}_min;", + "attribute {precision} {type} a_{name}_max;", + "varying {precision} {type} {name};" + ], + initialize: [ + "{name} = mix(a_{name}_min, a_{name}_max, a_{name}_t);" + ] + }); +} + +function fragmentSource() { + var prelude = fs.readFileSync(path.join(inputPath, '_prelude.fragment.glsl')); + var source = fs.readFileSync(path.join(inputPath, shaderName + '.fragment.glsl'), 'utf8'); + return prelude + applyPragmas(source, { + define: [ + "varying {precision} {type} {name};" + ], + initialize: [ + ] + }); +} var content = "#pragma once\n" + "\n" + @@ -49,8 +64,8 @@ var content = "#pragma once\n" + "class " + shaderName + " {\n" + "public:\n" + " static constexpr const char* name = \"" + shaderName + "\";\n" + -" static constexpr const char* vertexSource = R\"MBGL_SHADER(" + applyPragmas(vertexSource) + ")MBGL_SHADER\";\n" + -" static constexpr const char* fragmentSource = R\"MBGL_SHADER(" + applyPragmas(fragmentSource) + ")MBGL_SHADER\";\n" + +" static constexpr const char* vertexSource = R\"MBGL_SHADER(\n" + vertexSource() + ")MBGL_SHADER\";\n" + +" static constexpr const char* fragmentSource = R\"MBGL_SHADER(\n" + fragmentSource() + ")MBGL_SHADER\";\n" + "};\n" + "\n" + "} // namespace shaders\n" + diff --git a/scripts/generate-style-code.js b/scripts/generate-style-code.js index f2acb12a2a9..9eb68048f79 100644 --- a/scripts/generate-style-code.js +++ b/scripts/generate-style-code.js @@ -14,7 +14,11 @@ function parseCSSColor(str) { ]; } -global.propertyType = function (property) { +global.isDataDriven = function (property) { + return property['property-function'] === true; +}; + +global.evaluatedType = function (property) { if (/-translate-anchor$/.test(property.name)) { return 'TranslateAnchorType'; } @@ -34,14 +38,45 @@ global.propertyType = function (property) { return `Color`; case 'array': if (property.length) { - return `std::array<${propertyType({type: property.value})}, ${property.length}>`; + return `std::array<${evaluatedType({type: property.value})}, ${property.length}>`; } else { - return `std::vector<${propertyType({type: property.value})}>`; + return `std::vector<${evaluatedType({type: property.value})}>`; } default: throw new Error(`unknown type for ${property.name}`) } }; +function attributeType(property, type) { + const name = property.name.replace(type + '-', '').replace('-', '_'); + return `attributes::a_${name}${name === 'offset' ? '<1>' : ''}`; +} + +global.layoutPropertyType = function (property) { + if (isDataDriven(property)) { + return `DataDrivenLayoutProperty<${evaluatedType(property)}>`; + } else { + return `LayoutProperty<${evaluatedType(property)}>`; + } +}; + +global.paintPropertyType = function (property, type) { + if (isDataDriven(property)) { + return `DataDrivenPaintProperty<${evaluatedType(property)}, ${attributeType(property, type)}>`; + } else if (/-pattern$/.test(property.name) || property.name === 'line-dasharray') { + return `CrossFadedPaintProperty<${evaluatedType(property)}>`; + } else { + return `PaintProperty<${evaluatedType(property)}>`; + } +}; + +global.propertyValueType = function (property) { + if (isDataDriven(property)) { + return `DataDrivenPropertyValue<${evaluatedType(property)}>`; + } else { + return `PropertyValue<${evaluatedType(property)}>`; + } +}; + global.defaultValue = function (property) { // https://github.com/mapbox/mapbox-gl-native/issues/5258 if (property.name === 'line-round-limit') { @@ -59,9 +94,9 @@ global.defaultValue = function (property) { return JSON.stringify(property.default || ""); case 'enum': if (property.default === undefined) { - return `${propertyType(property)}::Undefined`; + return `${evaluatedType(property)}::Undefined`; } else { - return `${propertyType(property)}::${camelize(property.default)}`; + return `${evaluatedType(property)}::${camelize(property.default)}`; } case 'color': const color = parseCSSColor(property.default).join(', '); diff --git a/src/mbgl/gl/attribute.cpp b/src/mbgl/gl/attribute.cpp index 7432fff590d..2c16dac3fc9 100644 --- a/src/mbgl/gl/attribute.cpp +++ b/src/mbgl/gl/attribute.cpp @@ -1,29 +1,238 @@ #include +#include #include +#include namespace mbgl { namespace gl { +static_assert(offsetof(Normalized, value) == 0, "unexpected normalized offset"); + AttributeLocation bindAttributeLocation(ProgramID id, AttributeLocation location, const char* name) { MBGL_CHECK_ERROR(glBindAttribLocation(id, location, name)); return location; } -void bindAttribute(AttributeLocation location, - std::size_t count, - DataType type, - std::size_t vertexSize, - std::size_t vertexOffset, - std::size_t attributeOffset) { +template DataType DataTypeOf = static_cast(0); +template <> DataType DataTypeOf< int8_t> = DataType::Byte; +template <> DataType DataTypeOf = DataType::UnsignedByte; +template <> DataType DataTypeOf< int16_t> = DataType::Short; +template <> DataType DataTypeOf = DataType::UnsignedShort; +template <> DataType DataTypeOf< int32_t> = DataType::Integer; +template <> DataType DataTypeOf = DataType::UnsignedInteger; +template <> DataType DataTypeOf = DataType::Float; + +template bool IsNormalized = false; +template bool IsNormalized> = true; +template DataType DataTypeOf> = DataTypeOf; + +template +void VariableAttributeBinding::bind(Context& context, + AttributeLocation location, + optional>& oldBinding, + std::size_t vertexOffset) const { + if (oldBinding == *this) { + return; + } + context.vertexBuffer = vertexBuffer; MBGL_CHECK_ERROR(glEnableVertexAttribArray(location)); MBGL_CHECK_ERROR(glVertexAttribPointer( location, - static_cast(count), - static_cast(type), - GL_FALSE, + static_cast(N), + static_cast(DataTypeOf), + static_cast(IsNormalized), static_cast(vertexSize), reinterpret_cast(attributeOffset + (vertexSize * vertexOffset)))); } +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; + +template class VariableAttributeBinding, 1>; +template class VariableAttributeBinding, 2>; +template class VariableAttributeBinding, 3>; +template class VariableAttributeBinding, 4>; + +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; + +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; + +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; +template class VariableAttributeBinding; + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3])); +} + + +template <> +void ConstantAttributeBinding, 1>::bind(Context&, AttributeLocation location, optional, 1>>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0].denormalized())); +} + +template <> +void ConstantAttributeBinding, 2>::bind(Context&, AttributeLocation location, optional, 2>>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0].denormalized(), value[1].denormalized())); +} + +template <> +void ConstantAttributeBinding, 3>::bind(Context&, AttributeLocation location, optional, 3>>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0].denormalized(), value[1].denormalized(), value[2].denormalized())); +} + +template <> +void ConstantAttributeBinding, 4>::bind(Context&, AttributeLocation location, optional, 4>>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0].denormalized(), value[1].denormalized(), value[2].denormalized(), value[3].denormalized())); +} + + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3])); +} + + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3])); +} + + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2])); +} + +template <> +void ConstantAttributeBinding::bind(Context&, AttributeLocation location, optional>& oldBinding, std::size_t) const { + assert(location != 0); + oldBinding = {}; + MBGL_CHECK_ERROR(glDisableVertexAttribArray(location)); + MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3])); +} + } // namespace gl } // namespace mbgl diff --git a/src/mbgl/gl/attribute.hpp b/src/mbgl/gl/attribute.hpp index e45014127bc..6300ebb56bf 100644 --- a/src/mbgl/gl/attribute.hpp +++ b/src/mbgl/gl/attribute.hpp @@ -1,8 +1,10 @@ #pragma once #include +#include #include #include +#include #include #include @@ -10,24 +12,79 @@ namespace mbgl { namespace gl { -template +template +class VariableAttributeBinding { +public: + VariableAttributeBinding(BufferID vertexBuffer_, + std::size_t vertexSize_, + std::size_t attributeOffset_) + : vertexBuffer(vertexBuffer_), + vertexSize(vertexSize_), + attributeOffset(attributeOffset_) + {} + + void bind(Context&, AttributeLocation, optional>&, std::size_t vertexOffset) const; + + friend bool operator==(const VariableAttributeBinding& lhs, + const VariableAttributeBinding& rhs) { + return lhs.vertexBuffer == rhs.vertexBuffer + && lhs.vertexSize == rhs.vertexSize + && lhs.attributeOffset == rhs.attributeOffset; + } + +private: + BufferID vertexBuffer; + std::size_t vertexSize; + std::size_t attributeOffset; +}; + +template +class ConstantAttributeBinding { +public: + ConstantAttributeBinding() { value.fill(T()); } + + explicit ConstantAttributeBinding(std::array value_) + : value(std::move(value_)) + {} + + void bind(Context&, AttributeLocation, optional>&, std::size_t) const; + + friend bool operator==(const ConstantAttributeBinding& lhs, + const ConstantAttributeBinding& rhs) { + return lhs.value == rhs.value; + } + +private: + std::array value; +}; + +template class Attribute { public: - using Type = T[N]; + using Value = std::array; + + using VariableBinding = VariableAttributeBinding; + using ConstantBinding = ConstantAttributeBinding; - class State { - public: - explicit State(AttributeLocation location_) - : location(location_) {} + using Location = AttributeLocation; - AttributeLocation location; - static constexpr std::size_t count = N; - static constexpr DataType type = DataTypeOf::value; - }; + using Binding = variant< + ConstantBinding, + VariableBinding>; + + static void bind(Context& context, + const Location& location, + optional& oldBinding, + const Binding& newBinding, + std::size_t vertexOffset) { + Binding::visit(newBinding, [&] (const auto& binding) { + binding.bind(context, location, oldBinding, vertexOffset); + }); + } }; #define MBGL_DEFINE_ATTRIBUTE(type_, n_, name_) \ - struct name_ : ::mbgl::gl::Attribute { static constexpr auto name = #name_; } + struct name_ : ::mbgl::gl::Attribute { static auto name() { return #name_; } } namespace detail { @@ -41,10 +98,16 @@ namespace detail { template class Vertex; +template <> +class Vertex<> { +public: + using VertexType = Vertex<>; +}; + template class Vertex { public: - typename A1::Type a1; + typename A1::Value a1; using VertexType = Vertex; static const std::size_t attributeOffsets[1]; @@ -53,8 +116,8 @@ class Vertex { template class Vertex { public: - typename A1::Type a1; - typename A2::Type a2; + typename A1::Value a1; + typename A2::Value a2; using VertexType = Vertex; static const std::size_t attributeOffsets[2]; @@ -63,9 +126,9 @@ class Vertex { template class Vertex { public: - typename A1::Type a1; - typename A2::Type a2; - typename A3::Type a3; + typename A1::Value a1; + typename A2::Value a2; + typename A3::Value a3; using VertexType = Vertex; static const std::size_t attributeOffsets[3]; @@ -74,10 +137,10 @@ class Vertex { template class Vertex { public: - typename A1::Type a1; - typename A2::Type a2; - typename A3::Type a3; - typename A4::Type a4; + typename A1::Value a1; + typename A2::Value a2; + typename A3::Value a3; + typename A4::Value a4; using VertexType = Vertex; static const std::size_t attributeOffsets[4]; @@ -86,11 +149,11 @@ class Vertex { template class Vertex { public: - typename A1::Type a1; - typename A2::Type a2; - typename A3::Type a3; - typename A4::Type a4; - typename A5::Type a5; + typename A1::Value a1; + typename A2::Value a2; + typename A3::Value a3; + typename A4::Value a4; + typename A5::Value a5; using VertexType = Vertex; static const std::size_t attributeOffsets[5]; @@ -135,37 +198,71 @@ const std::size_t Vertex::attributeOffsets[5] = { AttributeLocation bindAttributeLocation(ProgramID, AttributeLocation, const char * name); -void bindAttribute(AttributeLocation location, - std::size_t count, - DataType type, - std::size_t vertexSize, - std::size_t vertexOffset, - std::size_t attributeOffset); - template class Attributes { public: - using State = IndexedTuple, TypeList>; + using Types = TypeList; + using Locations = IndexedTuple< + TypeList, + TypeList>; + using Bindings = IndexedTuple< + TypeList, + TypeList>; + using VariableBindings = IndexedTuple< + TypeList, + TypeList...>>; + using Vertex = detail::Vertex; template static constexpr std::size_t Index = TypeIndex::value; - static State state(const ProgramID& id) { - return State { typename As::State(bindAttributeLocation(id, Index, As::name))... }; + static Locations locations(const ProgramID& id) { + return Locations { bindAttributeLocation(id, Index, As::name())... }; } - static std::function binder(const State& state) { - return [&state] (std::size_t vertexOffset) { - util::ignore({ (bindAttribute(state.template get().location, - state.template get().count, - state.template get().type, - sizeof(Vertex), - vertexOffset, - Vertex::attributeOffsets[Index]), 0)... }); + template + static Bindings allVariableBindings(const VertexBuffer& buffer) { + static_assert(std::is_standard_layout::value, "vertex type must use standard layout"); + + return Bindings { + typename As::VariableBinding { + buffer.buffer, + sizeof(Vertex), + Vertex::attributeOffsets[Index] + }... }; } + + static void bind(Context& context, + const Locations& locations, + VariableBindings& oldBindings, + const Bindings& newBindings, + std::size_t vertexOffset) { + util::ignore({ (As::bind(context, + locations.template get(), + oldBindings.template get(), + newBindings.template get(), + vertexOffset), 0)... }); + } }; +namespace detail { + +template +struct ConcatenateAttributes; + +template +struct ConcatenateAttributes, TypeList> { + using Type = Attributes; +}; + +} // namespace detail + +template +using ConcatenateAttributes = typename detail::ConcatenateAttributes< + typename A::Types, + typename B::Types>::Type; + } // namespace gl } // namespace mbgl diff --git a/src/mbgl/gl/context.cpp b/src/mbgl/gl/context.cpp index 5048ffcd660..a74e941bc67 100644 --- a/src/mbgl/gl/context.cpp +++ b/src/mbgl/gl/context.cpp @@ -122,6 +122,16 @@ UniqueTexture Context::createTexture() { return UniqueTexture{ std::move(id), { this } }; } +UniqueVertexArray Context::createVertexArray() { + if (!gl::GenVertexArrays) { + throw std::runtime_error("GL_ARB_vertex_array_object extension is required"); + } + + VertexArrayID id = 0; + MBGL_CHECK_ERROR(gl::GenVertexArrays(1, &id)); + return UniqueVertexArray(std::move(id), { this }); +} + UniqueFramebuffer Context::createFramebuffer() { FramebufferID id = 0; MBGL_CHECK_ERROR(glGenFramebuffers(1, &id)); @@ -407,32 +417,26 @@ void Context::clear(optional color, } #if not MBGL_USE_GLES2 -PrimitiveType Context::operator()(const Points& points) { +void Context::setDrawMode(const Points& points) { pointSize = points.pointSize; - return PrimitiveType::Points; } #else -PrimitiveType Context::operator()(const Points&) { - return PrimitiveType::Points; +void Context::setDrawMode(const Points&) { } #endif // MBGL_USE_GLES2 -PrimitiveType Context::operator()(const Lines& lines) { +void Context::setDrawMode(const Lines& lines) { lineWidth = lines.lineWidth; - return PrimitiveType::Lines; } -PrimitiveType Context::operator()(const LineStrip& lineStrip) { +void Context::setDrawMode(const LineStrip& lineStrip) { lineWidth = lineStrip.lineWidth; - return PrimitiveType::LineStrip; } -PrimitiveType Context::operator()(const Triangles&) { - return PrimitiveType::Triangles; +void Context::setDrawMode(const Triangles&) { } -PrimitiveType Context::operator()(const TriangleStrip&) { - return PrimitiveType::TriangleStrip; +void Context::setDrawMode(const TriangleStrip&) { } void Context::setDepthMode(const DepthMode& depth) { @@ -474,57 +478,14 @@ void Context::setColorMode(const ColorMode& color) { colorMask = color.mask; } -void Context::draw(const Drawable& drawable) { - if (drawable.segments.empty()) { - return; - } - - PrimitiveType primitiveType = apply_visitor([&] (auto m) { return (*this)(m); }, drawable.drawMode); - - setDepthMode(drawable.depthMode); - setStencilMode(drawable.stencilMode); - setColorMode(drawable.colorMode); - - program = drawable.program; - - drawable.bindUniforms(); - - for (const auto& segment : drawable.segments) { - auto needAttributeBindings = [&] () { - if (!gl::GenVertexArrays || !gl::BindVertexArray) { - return true; - } - - if (segment.vao) { - vertexArrayObject = *segment.vao; - return false; - } - - VertexArrayID id = 0; - MBGL_CHECK_ERROR(gl::GenVertexArrays(1, &id)); - vertexArrayObject = id; - segment.vao = UniqueVertexArray(std::move(id), { this }); - - // If we are initializing a new VAO, we need to force the buffers - // to be rebound. VAOs don't inherit the existing buffer bindings. - vertexBuffer.setDirty(); - elementBuffer.setDirty(); - - return true; - }; - - if (needAttributeBindings()) { - vertexBuffer = drawable.vertexBuffer; - elementBuffer = drawable.indexBuffer; - drawable.bindAttributes(segment.vertexOffset); - } - - MBGL_CHECK_ERROR(glDrawElements( - static_cast(primitiveType), - static_cast(segment.indexLength), - GL_UNSIGNED_SHORT, - reinterpret_cast(sizeof(uint16_t) * segment.indexOffset))); - } +void Context::draw(PrimitiveType primitiveType, + std::size_t indexOffset, + std::size_t indexLength) { + MBGL_CHECK_ERROR(glDrawElements( + static_cast(primitiveType), + static_cast(indexLength), + GL_UNSIGNED_SHORT, + reinterpret_cast(sizeof(uint16_t) * indexOffset))); } void Context::performCleanup() { diff --git a/src/mbgl/gl/context.hpp b/src/mbgl/gl/context.hpp index 093afa20ed4..636dfc9eac5 100644 --- a/src/mbgl/gl/context.hpp +++ b/src/mbgl/gl/context.hpp @@ -13,7 +13,6 @@ #include #include #include -#include #include @@ -40,6 +39,7 @@ class Context : private util::noncopyable { UniqueProgram createProgram(ShaderID vertexShader, ShaderID fragmentShader); void linkProgram(ProgramID); UniqueTexture createTexture(); + UniqueVertexArray createVertexArray(); template VertexBuffer createVertexBuffer(VertexVector&& v) { @@ -119,25 +119,20 @@ class Context : private util::noncopyable { optional depth, optional stencil); - struct Drawable { - DrawMode drawMode; - DepthMode depthMode; - StencilMode stencilMode; - ColorMode colorMode; - gl::ProgramID program; - gl::BufferID vertexBuffer; - gl::BufferID indexBuffer; - const std::vector& segments; - std::function bindUniforms; - std::function bindAttributes; - }; - - void draw(const Drawable&); + void setDrawMode(const Points&); + void setDrawMode(const Lines&); + void setDrawMode(const LineStrip&); + void setDrawMode(const Triangles&); + void setDrawMode(const TriangleStrip&); void setDepthMode(const DepthMode&); void setStencilMode(const StencilMode&); void setColorMode(const ColorMode&); + void draw(PrimitiveType, + std::size_t indexOffset, + std::size_t indexLength); + // Actually remove the objects we marked as abandoned with the above methods. // Only call this while the OpenGL context is exclusive to this thread. void performCleanup(); @@ -164,6 +159,8 @@ class Context : private util::noncopyable { std::array, 2> texture; State vertexArrayObject; State program; + State vertexBuffer; + State elementBuffer; #if not MBGL_USE_GLES2 State pixelZoom; @@ -196,8 +193,6 @@ class Context : private util::noncopyable { #if not MBGL_USE_GLES2 State pointSize; #endif // MBGL_USE_GLES2 - State vertexBuffer; - State elementBuffer; UniqueBuffer createVertexBuffer(const void* data, std::size_t size); UniqueBuffer createIndexBuffer(const void* data, std::size_t size); @@ -210,12 +205,6 @@ class Context : private util::noncopyable { void drawPixels(Size size, const void* data, TextureFormat); #endif // MBGL_USE_GLES2 - PrimitiveType operator()(const Points&); - PrimitiveType operator()(const Lines&); - PrimitiveType operator()(const LineStrip&); - PrimitiveType operator()(const Triangles&); - PrimitiveType operator()(const TriangleStrip&); - friend detail::ProgramDeleter; friend detail::ShaderDeleter; friend detail::BufferDeleter; diff --git a/src/mbgl/gl/draw_mode.hpp b/src/mbgl/gl/draw_mode.hpp index ab86d5e4690..275eb25b89f 100644 --- a/src/mbgl/gl/draw_mode.hpp +++ b/src/mbgl/gl/draw_mode.hpp @@ -1,7 +1,7 @@ #pragma once +#include #include -#include #include @@ -11,7 +11,9 @@ namespace gl { class Points { public: using Primitive = Point; + static constexpr std::size_t bufferGroupSize = 1; + static constexpr PrimitiveType primitiveType = PrimitiveType::Points; explicit Points(float pointSize_) : pointSize(pointSize_) {} @@ -21,7 +23,9 @@ class Points { class Lines { public: using Primitive = Line; + static constexpr std::size_t bufferGroupSize = 2; + static constexpr PrimitiveType primitiveType = PrimitiveType::Lines; explicit Lines(float lineWidth_) : lineWidth(lineWidth_) { assert(lineWidth > 0); @@ -35,7 +39,9 @@ class LineStrip { // LineStrip is a form of "Line" rendering, but the element buffer // cannot be grouped into logical elements beyond a single Point. using Primitive = Line; + static constexpr std::size_t bufferGroupSize = 1; + static constexpr PrimitiveType primitiveType = PrimitiveType::LineStrip; explicit LineStrip(float lineWidth_) : lineWidth(lineWidth_) { assert(lineWidth > 0); @@ -47,7 +53,9 @@ class LineStrip { class Triangles { public: using Primitive = Triangle; + static constexpr std::size_t bufferGroupSize = 3; + static constexpr PrimitiveType primitiveType = PrimitiveType::Triangles; }; class TriangleStrip { @@ -55,7 +63,9 @@ class TriangleStrip { // TriangleStrip is a form of "Triangle" rendering, but the element buffer // cannot be grouped into logical elements beyond a single Point. using Primitive = Triangle; + static constexpr std::size_t bufferGroupSize = 1; + static constexpr PrimitiveType primitiveType = PrimitiveType::TriangleStrip; }; // Special draw mode for use with VertexVector, in which @@ -65,12 +75,5 @@ class Indexed { static constexpr std::size_t bufferGroupSize = 1; }; -using DrawMode = variant< - Points, - Lines, - LineStrip, - Triangles, - TriangleStrip>; - } // namespace gl } // namespace mbgl diff --git a/src/mbgl/gl/normalization.hpp b/src/mbgl/gl/normalization.hpp new file mode 100644 index 00000000000..83fa67a3ec2 --- /dev/null +++ b/src/mbgl/gl/normalization.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include + +#include +#include + +namespace mbgl { +namespace gl { + +template +class Normalized { +public: + T value; + + Normalized() : value(0) {} + + explicit Normalized(float f) + : value(static_cast(std::numeric_limits::max() * util::clamp(f, 0.0f, 1.0f))) { + assert(f >= 0.0f); + assert(f <= 1.0f); + } + + float denormalized() const { + return float(value) / std::numeric_limits::max(); + } +}; + +template +bool operator==(const Normalized& lhs, const Normalized& rhs) { + return lhs.value == rhs.value; +} + +} // namespace gl +} // namespace mbgl diff --git a/src/mbgl/gl/program.hpp b/src/mbgl/gl/program.hpp index 33387e9d4ef..fa0470796e7 100644 --- a/src/mbgl/gl/program.hpp +++ b/src/mbgl/gl/program.hpp @@ -20,16 +20,14 @@ class Program { using Attributes = As; using Uniforms = Us; - using Vertex = typename Attributes::Vertex; using UniformValues = typename Uniforms::Values; - - static_assert(std::is_standard_layout::value, "vertex type must use standard layout"); + using AttributeBindings = typename Attributes::Bindings; Program(Context& context, const std::string& vertexSource, const std::string& fragmentSource) : vertexShader(context.createShader(ShaderType::Vertex, vertexSource)), fragmentShader(context.createShader(ShaderType::Fragment, fragmentSource)), program(context.createProgram(vertexShader, fragmentShader)), - attributesState(Attributes::state(program)), + attributeLocations(Attributes::locations(program)), uniformsState((context.linkProgram(program), Uniforms::state(program))) {} template @@ -39,22 +37,30 @@ class Program { StencilMode stencilMode, ColorMode colorMode, UniformValues&& uniformValues, - const VertexBuffer& vertexBuffer, + AttributeBindings&& attributeBindings, const IndexBuffer& indexBuffer, const SegmentVector& segments) { static_assert(std::is_same::value, "incompatible draw mode"); - context.draw({ - std::move(drawMode), - std::move(depthMode), - std::move(stencilMode), - std::move(colorMode), - program, - vertexBuffer.buffer, - indexBuffer.buffer, - segments, - Uniforms::binder(uniformsState, std::move(uniformValues)), - Attributes::binder(attributesState) - }); + + context.setDrawMode(drawMode); + context.setDepthMode(depthMode); + context.setStencilMode(stencilMode); + context.setColorMode(colorMode); + + context.program = program; + + Uniforms::bind(uniformsState, std::move(uniformValues)); + + for (const auto& segment : segments) { + segment.bind(context, + indexBuffer.buffer, + attributeLocations, + attributeBindings); + + context.draw(drawMode.primitiveType, + segment.indexOffset, + segment.indexLength); + } } private: @@ -62,7 +68,7 @@ class Program { UniqueShader fragmentShader; UniqueProgram program; - typename Attributes::State attributesState; + typename Attributes::Locations attributeLocations; typename Uniforms::State uniformsState; }; diff --git a/src/mbgl/gl/segment.cpp b/src/mbgl/gl/segment.cpp new file mode 100644 index 00000000000..aabdc83cd41 --- /dev/null +++ b/src/mbgl/gl/segment.cpp @@ -0,0 +1,7 @@ +#include + +namespace mbgl { +namespace gl { + +} // namespace gl +} // namespace mbgl diff --git a/src/mbgl/gl/segment.hpp b/src/mbgl/gl/segment.hpp index 8f74afd237c..bb9f2f1ee85 100644 --- a/src/mbgl/gl/segment.hpp +++ b/src/mbgl/gl/segment.hpp @@ -1,12 +1,16 @@ #pragma once +#include +#include #include #include +#include namespace mbgl { namespace gl { +template class Segment { public: Segment(std::size_t vertexOffset_, @@ -24,13 +28,38 @@ class Segment { std::size_t vertexLength; std::size_t indexLength; + void bind(Context& context, + BufferID indexBuffer_, + const typename Attributes::Locations& attributeLocations, + const typename Attributes::Bindings& attributeBindings_) const { + if (!vao) { + vao = context.createVertexArray(); + context.vertexBuffer.setDirty(); + } + + context.vertexArrayObject = *vao; + + if (indexBuffer != indexBuffer_) { + indexBuffer = indexBuffer_; + context.elementBuffer.setDirty(); + context.elementBuffer = indexBuffer_; + } + + Attributes::bind(context, + attributeLocations, + variableBindings, + attributeBindings_, + vertexOffset); + } + private: - friend class Context; mutable optional vao; + mutable optional indexBuffer; + mutable typename Attributes::VariableBindings variableBindings; }; template -class SegmentVector : public std::vector { +class SegmentVector : public std::vector> { public: SegmentVector() = default; }; diff --git a/src/mbgl/gl/types.hpp b/src/mbgl/gl/types.hpp index 577629d5d36..565ca5754f3 100644 --- a/src/mbgl/gl/types.hpp +++ b/src/mbgl/gl/types.hpp @@ -34,16 +34,6 @@ enum class DataType : uint32_t { Float = 0x1406 }; -template struct DataTypeOf; - -template <> struct DataTypeOf : std::integral_constant {}; -template <> struct DataTypeOf : std::integral_constant {}; -template <> struct DataTypeOf : std::integral_constant {}; -template <> struct DataTypeOf : std::integral_constant {}; -template <> struct DataTypeOf : std::integral_constant {}; -template <> struct DataTypeOf : std::integral_constant {}; -template <> struct DataTypeOf : std::integral_constant {}; - enum class RenderbufferType : uint32_t { RGBA = 0x8058, DepthStencil = 0x88F0, diff --git a/src/mbgl/gl/uniform.hpp b/src/mbgl/gl/uniform.hpp index 726cd4fe107..92136b61c20 100644 --- a/src/mbgl/gl/uniform.hpp +++ b/src/mbgl/gl/uniform.hpp @@ -50,32 +50,49 @@ template using UniformMatrix = Uniform>; #define MBGL_DEFINE_UNIFORM_SCALAR(type_, name_) \ - struct name_ : ::mbgl::gl::UniformScalar { static constexpr auto name = #name_; } + struct name_ : ::mbgl::gl::UniformScalar { static auto name() { return #name_; } } #define MBGL_DEFINE_UNIFORM_VECTOR(type_, n_, name_) \ - struct name_ : ::mbgl::gl::UniformVector { static constexpr auto name = #name_; } + struct name_ : ::mbgl::gl::UniformVector { static auto name() { return #name_; } } #define MBGL_DEFINE_UNIFORM_MATRIX(type_, n_, name_) \ - struct name_ : ::mbgl::gl::UniformMatrix { static constexpr auto name = #name_; } + struct name_ : ::mbgl::gl::UniformMatrix { static auto name() { return #name_; } } UniformLocation uniformLocation(ProgramID, const char * name); template class Uniforms { public: + using Types = TypeList; using State = IndexedTuple, TypeList>; using Values = IndexedTuple, TypeList>; static State state(const ProgramID& id) { - return State { { uniformLocation(id, Us::name) }... }; + return State { { uniformLocation(id, Us::name()) }... }; } - static std::function binder(State& state, Values&& values_) { - return [&state, values = std::move(values_)] () mutable { - util::ignore({ (state.template get() = values.template get(), 0)... }); - }; + static void bind(State& state, Values&& values) { + util::ignore({ (state.template get() = values.template get(), 0)... }); } }; + +namespace detail { + +template +struct ConcatenateUniforms; + +template +struct ConcatenateUniforms, TypeList> { + using Type = Uniforms; +}; + +} // namespace detail + +template +using ConcatenateUniforms = typename detail::ConcatenateUniforms< + typename A::Types, + typename B::Types>::Type; + } // namespace gl } // namespace mbgl diff --git a/src/mbgl/layout/symbol_feature.hpp b/src/mbgl/layout/symbol_feature.hpp index 5dd61d91564..e55995f9528 100644 --- a/src/mbgl/layout/symbol_feature.hpp +++ b/src/mbgl/layout/symbol_feature.hpp @@ -3,6 +3,7 @@ #include #include +#include #include namespace mbgl { @@ -13,6 +14,8 @@ class SymbolFeature { GeometryCollection geometry; optional text; optional icon; + std::array iconOffset; + float iconRotation; std::size_t index; }; diff --git a/src/mbgl/layout/symbol_layout.cpp b/src/mbgl/layout/symbol_layout.cpp index eaa03329952..5dd36c41bdb 100644 --- a/src/mbgl/layout/symbol_layout.cpp +++ b/src/mbgl/layout/symbol_layout.cpp @@ -3,7 +3,9 @@ #include #include #include -#include +#include +#include +#include #include #include #include @@ -27,27 +29,49 @@ namespace mbgl { using namespace style; -SymbolLayout::SymbolLayout(std::vector layerIDs_, - std::string sourceLayerName_, - uint32_t overscaling_, - float zoom_, - const MapMode mode_, - const GeometryTileLayer& layer, - const style::Filter& filter, - style::SymbolLayoutProperties::Evaluated layout_, - float textMaxSize_, +SymbolLayout::SymbolLayout(const BucketParameters& parameters, + const std::vector& layers, + const GeometryTileLayer& sourceLayer, SpriteAtlas& spriteAtlas_) - : layerIDs(std::move(layerIDs_)), - sourceLayerName(std::move(sourceLayerName_)), - overscaling(overscaling_), - zoom(zoom_), - mode(mode_), - layout(std::move(layout_)), - textMaxSize(textMaxSize_), + : sourceLayerName(sourceLayer.getName()), + bucketName(layers.at(0)->getID()), + overscaling(parameters.tileID.overscaleFactor()), + zoom(parameters.tileID.overscaledZ), + mode(parameters.mode), spriteAtlas(spriteAtlas_), - tileSize(util::tileSize * overscaling_), + tileSize(util::tileSize * overscaling), tilePixelRatio(float(util::EXTENT) / tileSize) { + const SymbolLayer::Impl& leader = *layers.at(0)->as()->impl; + + layout = leader.layout.evaluate(PropertyEvaluationParameters(zoom)); + + if (layout.get() == AlignmentType::Auto) { + if (layout.get() == SymbolPlacementType::Line) { + layout.get() = AlignmentType::Map; + } else { + layout.get() = AlignmentType::Viewport; + } + } + + if (layout.get() == AlignmentType::Auto) { + if (layout.get() == SymbolPlacementType::Line) { + layout.get() = AlignmentType::Map; + } else { + layout.get() = AlignmentType::Viewport; + } + } + + // If unspecified `text-pitch-alignment` inherits `text-rotation-alignment` + if (layout.get() == AlignmentType::Auto) { + layout.get() = layout.get(); + } + + textMaxSize = leader.layout.evaluate(PropertyEvaluationParameters(18)); + + layout.get() = leader.layout.evaluate(PropertyEvaluationParameters(zoom + 1)); + layout.get() = leader.layout.evaluate(PropertyEvaluationParameters(zoom + 1)); + const bool hasText = !layout.get().empty() && !layout.get().empty(); const bool hasIcon = !layout.get().empty(); @@ -55,13 +79,15 @@ SymbolLayout::SymbolLayout(std::vector layerIDs_, return; } - auto layerName = layer.getName(); + for (const auto& layer : layers) { + layerPaintProperties.emplace(layer->getID(), layer->as()->impl->paint.evaluated); + } // Determine and load glyph ranges - const size_t featureCount = layer.featureCount(); + const size_t featureCount = sourceLayer.featureCount(); for (size_t i = 0; i < featureCount; ++i) { - auto feature = layer.getFeature(i); - if (!filter(feature->getType(), feature->getID(), [&] (const auto& key) { return feature->getValue(key); })) + auto feature = sourceLayer.getFeature(i); + if (!leader.filter(feature->getType(), feature->getID(), [&] (const auto& key) { return feature->getValue(key); })) continue; SymbolFeature ft; @@ -103,6 +129,8 @@ SymbolLayout::SymbolLayout(std::vector layerIDs_, if (hasIcon) { ft.icon = util::replaceTokens(layout.get(), getValue); + ft.iconOffset = layout.get().evaluate(zoom, *feature); + ft.iconRotation = layout.get().evaluate(zoom, *feature) * util::DEG2RAD; } if (ft.text || ft.icon) { @@ -209,14 +237,14 @@ void SymbolLayout::prepare(uintptr_t tileUID, if (feature.icon) { auto image = spriteAtlas.getImage(*feature.icon, SpritePatternMode::Single); if (image) { - shapedIcon = shapeIcon(*image, layout); + shapedIcon = shapeIcon(*image, feature); assert((*image).spriteImage); if ((*image).spriteImage->sdf) { sdfIcons = true; } if ((*image).relativePixelRatio != 1.0f) { iconsNeedLinear = true; - } else if (layout.get() != 0) { + } else if (layout.get().constantOr(1) != 0) { iconsNeedLinear = true; } } @@ -254,7 +282,7 @@ void SymbolLayout::addFeature(const SymbolFeature& feature, ? SymbolPlacementType::Point : layout.get(); const float textRepeatDistance = symbolSpacing / 2; - IndexedSubfeature indexedFeature = {feature.index, sourceLayerName, layerIDs.at(0), symbolInstances.size()}; + IndexedSubfeature indexedFeature = {feature.index, sourceLayerName, bucketName, symbolInstances.size()}; auto addSymbolInstance = [&] (const GeometryCoordinates& line, Anchor& anchor) { // https://github.com/mapbox/vector-tile-spec/tree/master/2.1#41-layers @@ -350,7 +378,7 @@ bool SymbolLayout::anchorIsTooClose(const std::u16string& text, const float repe } std::unique_ptr SymbolLayout::place(CollisionTile& collisionTile) { - auto bucket = std::make_unique(mode, layout, sdfIcons, iconsNeedLinear); + auto bucket = std::make_unique(layout, layerPaintProperties, zoom, sdfIcons, iconsNeedLinear); // Calculate which labels can be shown and when they can be shown and // create the bufers used for rendering. @@ -487,13 +515,13 @@ void SymbolLayout::addSymbols(Buffer &buffer, const SymbolQuads &symbols, float uint8_t glyphAngle = std::round((symbol.glyphAngle / (M_PI * 2)) * 256); // coordinates (2 triangles) - buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, tl, tex.x, tex.y, + buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, tl, tex.x, tex.y, minZoom, maxZoom, placementZoom, glyphAngle)); - buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, tr, tex.x + tex.w, tex.y, + buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, tr, tex.x + tex.w, tex.y, minZoom, maxZoom, placementZoom, glyphAngle)); - buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, bl, tex.x, tex.y + tex.h, + buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, bl, tex.x, tex.y + tex.h, minZoom, maxZoom, placementZoom, glyphAngle)); - buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, br, tex.x + tex.w, tex.y + tex.h, + buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, br, tex.x + tex.w, tex.y + tex.h, minZoom, maxZoom, placementZoom, glyphAngle)); // add the two triangles, referencing the four coordinates we just inserted. diff --git a/src/mbgl/layout/symbol_layout.hpp b/src/mbgl/layout/symbol_layout.hpp index c89b791ccc4..ba5dc74e13a 100644 --- a/src/mbgl/layout/symbol_layout.hpp +++ b/src/mbgl/layout/symbol_layout.hpp @@ -20,6 +20,7 @@ class GlyphAtlas; class SymbolBucket; namespace style { +class BucketParameters; class Filter; class Layer; } // namespace style @@ -28,15 +29,9 @@ struct Anchor; class SymbolLayout { public: - SymbolLayout(std::vector layerIDs_, - std::string sourceLayerName_, - uint32_t overscaling, - float zoom, - const MapMode, + SymbolLayout(const style::BucketParameters&, + const std::vector&, const GeometryTileLayer&, - const style::Filter&, - style::SymbolLayoutProperties::Evaluated, - float textMaxSize, SpriteAtlas&); bool canPrepare(GlyphAtlas&); @@ -56,8 +51,7 @@ class SymbolLayout { State state = Pending; - const std::vector layerIDs; - const std::string sourceLayerName; + std::unordered_map layerPaintProperties; private: void addFeature(const SymbolFeature&, @@ -75,11 +69,14 @@ class SymbolLayout { void addSymbols(Buffer&, const SymbolQuads&, float scale, const bool keepUpright, const style::SymbolPlacementType, const float placementAngle); + const std::string sourceLayerName; + const std::string bucketName; const float overscaling; const float zoom; const MapMode mode; - const style::SymbolLayoutProperties::Evaluated layout; - const float textMaxSize; + + style::SymbolLayoutProperties::Evaluated layout; + float textMaxSize; SpriteAtlas& spriteAtlas; diff --git a/src/mbgl/programs/attributes.hpp b/src/mbgl/programs/attributes.hpp index 38bbe893776..c4cc5dea8ba 100644 --- a/src/mbgl/programs/attributes.hpp +++ b/src/mbgl/programs/attributes.hpp @@ -1,22 +1,174 @@ #pragma once #include +#include +#include #include namespace mbgl { namespace attributes { -// Attributes common to several shaders. +// Layout attributes MBGL_DEFINE_ATTRIBUTE(int16_t, 2, a_pos); -MBGL_DEFINE_ATTRIBUTE(int16_t, 2, a_offset); MBGL_DEFINE_ATTRIBUTE(int16_t, 2, a_extrude); MBGL_DEFINE_ATTRIBUTE(uint16_t, 2, a_texture_pos); template -struct a_data : gl::Attribute, uint8_t, N> { - static constexpr auto name = "a_data"; +struct a_data : gl::Attribute { + static auto name() { return "a_data"; } +}; + +template +struct a_offset : gl::Attribute { + static auto name() { return "a_offset"; } +}; + +// Paint attributes + +template +struct Min : Attr { + static auto name() { + static const std::string name = Attr::name() + std::string("_min"); + return name.c_str(); + } +}; + +template +struct Max : Attr { + static auto name() { + static const std::string name = Attr::name() + std::string("_max"); + return name.c_str(); + } +}; + +template +struct InterpolationUniform : gl::UniformScalar, float> { + static auto name() { + static const std::string name = Attr::name() + std::string("_t"); + return name.c_str(); + } +}; + +struct a_color : gl::Attribute, 4> { + static auto name() { return "a_color"; } + + static Value value(const Color& color) { + return {{ + gl::Normalized(color.r), + gl::Normalized(color.g), + gl::Normalized(color.b), + gl::Normalized(color.a) + }}; + } +}; + +struct a_stroke_color : gl::Attribute, 4> { + static auto name() { return "a_stroke_color"; } + + static Value value(const Color& color) { + return {{ + gl::Normalized(color.r), + gl::Normalized(color.g), + gl::Normalized(color.b), + gl::Normalized(color.a) + }}; + } +}; + +struct a_outline_color : gl::Attribute, 4> { + static auto name() { return "a_outline_color"; } + + static Value value(const Color& color) { + return {{ + gl::Normalized(color.r), + gl::Normalized(color.g), + gl::Normalized(color.b), + gl::Normalized(color.a) + }}; + } +}; + +struct a_opacity : gl::Attribute, 1> { + static auto name() { return "a_opacity"; } + + static Value value(float opacity) { + return {{ gl::Normalized(opacity) }}; + } +}; + +struct a_stroke_opacity : gl::Attribute, 1> { + static auto name() { return "a_stroke_opacity"; } + + static Value value(float opacity) { + return {{ gl::Normalized(opacity) }}; + } +}; + +struct a_blur : gl::Attribute { + static auto name() { return "a_blur"; } + + static Value value(float blur) { + return {{ blur }}; + } +}; + +struct a_radius : gl::Attribute { + static auto name() { return "a_radius"; } + + static Value value(float radius) { + return {{ radius }}; + } +}; + +struct a_width : gl::Attribute { + static auto name() { return "a_width"; } + + static Value value(float width) { + return {{ width }}; + } +}; + +struct a_height : gl::Attribute { + static auto name() { return "a_height"; } + + static Value value(float width) { + return {{ width }}; + } +}; + +struct a_base : gl::Attribute { + static auto name() { return "a_base"; } + + static Value value(float width) { + return {{ width }}; + } +}; + +struct a_gap_width : gl::Attribute { + static auto name() { return "a_gapwidth"; } + + static Value value(float width) { + return {{ width }}; + } +}; + +struct a_stroke_width : gl::Attribute { + static auto name() { return "a_stroke_width"; } + + static Value value(float width) { + return {{ width }}; + } +}; + +template <> +struct a_offset<1> : gl::Attribute { + static auto name() { return "a_offset"; } + + static Value value(float offset) { + return {{ offset }}; + } }; } // namespace attributes diff --git a/src/mbgl/programs/circle_program.cpp b/src/mbgl/programs/circle_program.cpp index d6bc439feb7..99b47dd5c02 100644 --- a/src/mbgl/programs/circle_program.cpp +++ b/src/mbgl/programs/circle_program.cpp @@ -2,6 +2,6 @@ namespace mbgl { -static_assert(sizeof(CircleProgram::Vertex) == 4, "expected CircleVertex size"); +static_assert(sizeof(CircleLayoutVertex) == 4, "expected CircleLayoutVertex size"); } // namespace mbgl diff --git a/src/mbgl/programs/circle_program.hpp b/src/mbgl/programs/circle_program.hpp index c9aea1d137e..60a5faf649c 100644 --- a/src/mbgl/programs/circle_program.hpp +++ b/src/mbgl/programs/circle_program.hpp @@ -5,35 +5,24 @@ #include #include #include +#include namespace mbgl { namespace uniforms { -MBGL_DEFINE_UNIFORM_SCALAR(float, u_radius); -MBGL_DEFINE_UNIFORM_SCALAR(Color, u_stroke_color); -MBGL_DEFINE_UNIFORM_SCALAR(float, u_stroke_width); -MBGL_DEFINE_UNIFORM_SCALAR(float, u_stroke_opacity); MBGL_DEFINE_UNIFORM_SCALAR(bool, u_scale_with_map); } // namespace uniforms -using CircleAttributes = gl::Attributes< - attributes::a_pos>; - class CircleProgram : public Program< shaders::circle, gl::Triangle, - CircleAttributes, + gl::Attributes< + attributes::a_pos>, gl::Uniforms< uniforms::u_matrix, - uniforms::u_opacity, - uniforms::u_color, - uniforms::u_radius, - uniforms::u_blur, - uniforms::u_stroke_color, - uniforms::u_stroke_width, - uniforms::u_stroke_opacity, uniforms::u_scale_with_map, - uniforms::u_extrude_scale>> + uniforms::u_extrude_scale>, + style::CirclePaintProperties> { public: using Program::Program; @@ -44,16 +33,17 @@ class CircleProgram : public Program< * @param {number} ex extrude normal * @param {number} ey extrude normal */ - static Vertex vertex(Point p, float ex, float ey) { - return Vertex { - { + static LayoutVertex vertex(Point p, float ex, float ey) { + return LayoutVertex { + {{ static_cast((p.x * 2) + ((ex + 1) / 2)), static_cast((p.y * 2) + ((ey + 1) / 2)) - } + }} }; } }; -using CircleVertex = CircleProgram::Vertex; +using CircleLayoutVertex = CircleProgram::LayoutVertex; +using CircleAttributes = CircleProgram::Attributes; } // namespace mbgl diff --git a/src/mbgl/programs/collision_box_program.cpp b/src/mbgl/programs/collision_box_program.cpp index d6a36e54a17..a3dc01ebe4a 100644 --- a/src/mbgl/programs/collision_box_program.cpp +++ b/src/mbgl/programs/collision_box_program.cpp @@ -2,6 +2,6 @@ namespace mbgl { -static_assert(sizeof(CollisionBoxProgram::Vertex) == 10, "expected CollisionBoxVertex size"); +static_assert(sizeof(CollisionBoxProgram::LayoutVertex) == 10, "expected CollisionBoxVertex size"); } // namespace mbgl diff --git a/src/mbgl/programs/collision_box_program.hpp b/src/mbgl/programs/collision_box_program.hpp index 26e38419a47..e59aa5ac8b2 100644 --- a/src/mbgl/programs/collision_box_program.hpp +++ b/src/mbgl/programs/collision_box_program.hpp @@ -28,29 +28,30 @@ class CollisionBoxProgram : public Program< uniforms::u_matrix, uniforms::u_scale, uniforms::u_zoom, - uniforms::u_maxzoom>> + uniforms::u_maxzoom>, + style::PaintProperties<>> { public: using Program::Program; - static Vertex vertex(Point a, Point o, float maxzoom, float placementZoom) { - return Vertex { - { + static LayoutVertex vertex(Point a, Point o, float maxzoom, float placementZoom) { + return LayoutVertex { + {{ static_cast(a.x), static_cast(a.y) - }, - { + }}, + {{ static_cast(::round(o.x)), static_cast(::round(o.y)) - }, - { + }}, + {{ static_cast(maxzoom * 10), static_cast(placementZoom * 10) - } + }} }; } }; -using CollisionBoxVertex = CollisionBoxProgram::Vertex; +using CollisionBoxVertex = CollisionBoxProgram::LayoutVertex; } // namespace mbgl diff --git a/src/mbgl/programs/debug_program.hpp b/src/mbgl/programs/debug_program.hpp index cd4e08b1bce..6b3b479d242 100644 --- a/src/mbgl/programs/debug_program.hpp +++ b/src/mbgl/programs/debug_program.hpp @@ -7,21 +7,21 @@ namespace mbgl { -using DebugAttributes = gl::Attributes< - attributes::a_pos>; - class DebugProgram : public Program< shaders::debug, gl::Line, - DebugAttributes, + gl::Attributes< + attributes::a_pos>, gl::Uniforms< uniforms::u_matrix, - uniforms::u_color>> + uniforms::u_color>, + style::PaintProperties<>> { public: using Program::Program; }; -using DebugVertex = DebugProgram::Vertex; +using DebugLayoutVertex = DebugProgram::LayoutVertex; +using DebugAttributes = DebugProgram::Attributes; } // namespace mbgl diff --git a/src/mbgl/programs/fill_program.cpp b/src/mbgl/programs/fill_program.cpp index a8154d08f90..6998d56232c 100644 --- a/src/mbgl/programs/fill_program.cpp +++ b/src/mbgl/programs/fill_program.cpp @@ -8,11 +8,10 @@ namespace mbgl { using namespace style; -static_assert(sizeof(FillAttributes::Vertex) == 4, "expected FillVertex size"); +static_assert(sizeof(FillLayoutVertex) == 4, "expected FillLayoutVertex size"); FillPatternUniforms::Values FillPatternUniforms::values(mat4 matrix, - float opacity, Size framebufferSize, const SpriteAtlasPosition& a, const SpriteAtlasPosition& b, @@ -26,7 +25,6 @@ FillPatternUniforms::values(mat4 matrix, return FillPatternUniforms::Values { uniforms::u_matrix::Value{ matrix }, - uniforms::u_opacity::Value{ opacity }, uniforms::u_world::Value{ framebufferSize }, uniforms::u_pattern_tl_a::Value{ a.tl }, uniforms::u_pattern_br_a::Value{ a.br }, diff --git a/src/mbgl/programs/fill_program.hpp b/src/mbgl/programs/fill_program.hpp index d885215c596..600e25bb466 100644 --- a/src/mbgl/programs/fill_program.hpp +++ b/src/mbgl/programs/fill_program.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include @@ -25,7 +26,6 @@ template class Faded; namespace uniforms { MBGL_DEFINE_UNIFORM_SCALAR(Size, u_world); -MBGL_DEFINE_UNIFORM_SCALAR(Color, u_outline_color); MBGL_DEFINE_UNIFORM_SCALAR(float, u_scale_a); MBGL_DEFINE_UNIFORM_SCALAR(float, u_scale_b); MBGL_DEFINE_UNIFORM_SCALAR(float, u_tile_units_to_pixels); @@ -33,32 +33,17 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_pixel_coord_upper); MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_pixel_coord_lower); } // namespace uniforms -struct FillAttributes : gl::Attributes< +struct FillLayoutAttributes : gl::Attributes< attributes::a_pos> -{ - static Vertex vertex(Point p) { - return Vertex { - { - p.x, - p.y - } - }; - } -}; - -using FillVertex = FillAttributes::Vertex; +{}; struct FillUniforms : gl::Uniforms< uniforms::u_matrix, - uniforms::u_opacity, - uniforms::u_color, - uniforms::u_outline_color, uniforms::u_world> {}; struct FillPatternUniforms : gl::Uniforms< uniforms::u_matrix, - uniforms::u_opacity, uniforms::u_world, uniforms::u_pattern_tl_a, uniforms::u_pattern_br_a, @@ -75,7 +60,6 @@ struct FillPatternUniforms : gl::Uniforms< uniforms::u_tile_units_to_pixels> { static Values values(mat4 matrix, - float opacity, Size framebufferSize, const SpriteAtlasPosition&, const SpriteAtlasPosition&, @@ -87,37 +71,57 @@ struct FillPatternUniforms : gl::Uniforms< class FillProgram : public Program< shaders::fill, gl::Triangle, - FillAttributes, - FillUniforms> + FillLayoutAttributes, + FillUniforms, + style::FillPaintProperties> { +public: using Program::Program; + + static LayoutVertex layoutVertex(Point p) { + return LayoutVertex { + {{ + p.x, + p.y + }} + }; + } }; class FillPatternProgram : public Program< shaders::fill_pattern, gl::Triangle, - FillAttributes, - FillPatternUniforms> + FillLayoutAttributes, + FillPatternUniforms, + style::FillPaintProperties> { +public: using Program::Program; }; class FillOutlineProgram : public Program< shaders::fill_outline, gl::Line, - FillAttributes, - FillUniforms> + FillLayoutAttributes, + FillUniforms, + style::FillPaintProperties> { +public: using Program::Program; }; class FillOutlinePatternProgram : public Program< shaders::fill_outline_pattern, gl::Line, - FillAttributes, - FillPatternUniforms> + FillLayoutAttributes, + FillPatternUniforms, + style::FillPaintProperties> { +public: using Program::Program; }; +using FillLayoutVertex = FillProgram::LayoutVertex; +using FillAttributes = FillProgram::Attributes; + } // namespace mbgl diff --git a/src/mbgl/programs/line_program.cpp b/src/mbgl/programs/line_program.cpp index f7054d3398a..8a26c88aeaf 100644 --- a/src/mbgl/programs/line_program.cpp +++ b/src/mbgl/programs/line_program.cpp @@ -10,7 +10,7 @@ namespace mbgl { using namespace style; -static_assert(sizeof(LineAttributes::Vertex) == 8, "expected LineVertex size"); +static_assert(sizeof(LineLayoutVertex) == 8, "expected LineLayoutVertex size"); template Values makeValues(const LinePaintProperties::Evaluated& properties, @@ -25,11 +25,7 @@ Values makeValues(const LinePaintProperties::Evaluated& properties, properties.get(), state) }, - uniforms::u_opacity::Value{ properties.get() }, uniforms::u_width::Value{ properties.get() }, - uniforms::u_gapwidth::Value{ properties.get() }, - uniforms::u_blur::Value{ properties.get() }, - uniforms::u_offset::Value{ properties.get() }, uniforms::u_ratio::Value{ 1.0f / tile.id.pixelsToTileUnits(1.0, state.getZoom()) }, uniforms::u_gl_units_to_pixels::Value{{{ 1.0f / pixelsToGLUnits[0], 1.0f / pixelsToGLUnits[1] }}}, std::forward(args)... @@ -45,8 +41,7 @@ LineProgram::uniformValues(const LinePaintProperties::Evaluated& properties, properties, tile, state, - pixelsToGLUnits, - uniforms::u_color::Value{ properties.get() } + pixelsToGLUnits ); } @@ -78,7 +73,6 @@ LineSDFProgram::uniformValues(const LinePaintProperties::Evaluated& properties, tile, state, pixelsToGLUnits, - uniforms::u_color::Value{ properties.get() }, uniforms::u_patternscale_a::Value{ scaleA }, uniforms::u_patternscale_b::Value{ scaleB }, uniforms::u_tex_y_a::Value{ posA.y }, diff --git a/src/mbgl/programs/line_program.hpp b/src/mbgl/programs/line_program.hpp index 9b97cc47a92..4fc7a97e0f1 100644 --- a/src/mbgl/programs/line_program.hpp +++ b/src/mbgl/programs/line_program.hpp @@ -6,8 +6,8 @@ #include #include #include -#include #include +#include #include @@ -21,8 +21,6 @@ class SpriteAtlasPosition; namespace uniforms { MBGL_DEFINE_UNIFORM_SCALAR(float, u_ratio); MBGL_DEFINE_UNIFORM_SCALAR(float, u_width); -MBGL_DEFINE_UNIFORM_SCALAR(float, u_gapwidth); -MBGL_DEFINE_UNIFORM_SCALAR(float, u_offset); MBGL_DEFINE_UNIFORM_SCALAR(float, u_tex_y_a); MBGL_DEFINE_UNIFORM_SCALAR(float, u_tex_y_b); MBGL_DEFINE_UNIFORM_SCALAR(float, u_sdfgamma); @@ -32,23 +30,38 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_patternscale_b); MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_gl_units_to_pixels); } // namespace uniforms -struct LineAttributes : gl::Attributes< +struct LineLayoutAttributes : gl::Attributes< attributes::a_pos, attributes::a_data<4>> +{}; + +class LineProgram : public Program< + shaders::line, + gl::Triangle, + LineLayoutAttributes, + gl::Uniforms< + uniforms::u_matrix, + uniforms::u_width, + uniforms::u_ratio, + uniforms::u_gl_units_to_pixels>, + style::LinePaintProperties> { +public: + using Program::Program; + /* * @param p vertex position * @param e extrude normal * @param t texture normal * @param dir direction of the line cap (-1/0/1) */ - static Vertex vertex(Point p, Point e, Point t, int8_t dir, int32_t linesofar = 0) { - return Vertex { - { + static LayoutVertex layoutVertex(Point p, Point e, Point t, int8_t dir, int32_t linesofar = 0) { + return LayoutVertex { + {{ static_cast((p.x * 2) | t.x), static_cast((p.y * 2) | t.y) - }, - { + }}, + {{ // add 128 to store an byte in an unsigned byte static_cast(::round(extrudeScale * e.x) + 128), static_cast(::round(extrudeScale * e.y) + 128), @@ -65,7 +78,7 @@ struct LineAttributes : gl::Attributes< // so we need to shift the linesofar. static_cast(((dir == 0 ? 0 : (dir < 0 ? -1 : 1 )) + 1) | ((linesofar & 0x3F) << 2)), static_cast(linesofar >> 6) - } + }} }; } @@ -77,27 +90,6 @@ struct LineAttributes : gl::Attributes< * the acute/bevelled line join. */ static const int8_t extrudeScale = 63; -}; - -using LineVertex = LineAttributes::Vertex; - -class LineProgram : public Program< - shaders::line, - gl::Triangle, - LineAttributes, - gl::Uniforms< - uniforms::u_matrix, - uniforms::u_opacity, - uniforms::u_width, - uniforms::u_gapwidth, - uniforms::u_blur, - uniforms::u_offset, - uniforms::u_ratio, - uniforms::u_gl_units_to_pixels, - uniforms::u_color>> -{ -public: - using Program::Program; static UniformValues uniformValues(const style::LinePaintProperties::Evaluated&, const RenderTile&, @@ -108,14 +100,10 @@ class LineProgram : public Program< class LinePatternProgram : public Program< shaders::line_pattern, gl::Triangle, - LineAttributes, + LineLayoutAttributes, gl::Uniforms< uniforms::u_matrix, - uniforms::u_opacity, uniforms::u_width, - uniforms::u_gapwidth, - uniforms::u_blur, - uniforms::u_offset, uniforms::u_ratio, uniforms::u_gl_units_to_pixels, uniforms::u_pattern_tl_a, @@ -125,7 +113,8 @@ class LinePatternProgram : public Program< uniforms::u_pattern_size_a, uniforms::u_pattern_size_b, uniforms::u_fade, - uniforms::u_image>> + uniforms::u_image>, + style::LinePaintProperties> { public: using Program::Program; @@ -141,24 +130,20 @@ class LinePatternProgram : public Program< class LineSDFProgram : public Program< shaders::line_sdf, gl::Triangle, - LineAttributes, + LineLayoutAttributes, gl::Uniforms< uniforms::u_matrix, - uniforms::u_opacity, uniforms::u_width, - uniforms::u_gapwidth, - uniforms::u_blur, - uniforms::u_offset, uniforms::u_ratio, uniforms::u_gl_units_to_pixels, - uniforms::u_color, uniforms::u_patternscale_a, uniforms::u_patternscale_b, uniforms::u_tex_y_a, uniforms::u_tex_y_b, uniforms::u_mix, uniforms::u_sdfgamma, - uniforms::u_image>> + uniforms::u_image>, + style::LinePaintProperties> { public: using Program::Program; @@ -174,4 +159,7 @@ class LineSDFProgram : public Program< float atlasWidth); }; +using LineLayoutVertex = LineProgram::LayoutVertex; +using LineAttributes = LineProgram::Attributes; + } // namespace mbgl diff --git a/src/mbgl/programs/program.hpp b/src/mbgl/programs/program.hpp index e5aae249971..d48e6875470 100644 --- a/src/mbgl/programs/program.hpp +++ b/src/mbgl/programs/program.hpp @@ -2,19 +2,38 @@ #include #include +#include +#include #include #include namespace mbgl { -template -class Program : public gl::Program { +template +class Program { public: - using ParentType = gl::Program; + using LayoutAttributes = LayoutAttrs; + using LayoutVertex = typename LayoutAttributes::Vertex; + + using PaintPropertyBinders = typename PaintProperties::Binders; + using PaintAttributes = typename PaintPropertyBinders::Attributes; + using Attributes = gl::ConcatenateAttributes; + + using UniformValues = typename Uniforms::Values; + using PaintUniforms = typename PaintPropertyBinders::Uniforms; + using AllUniforms = gl::ConcatenateUniforms; + + using ProgramType = gl::Program; + + ProgramType program; Program(gl::Context& context, const ProgramParameters& programParameters) - : ParentType(context, vertexSource(programParameters), fragmentSource(programParameters)) + : program(context, vertexSource(programParameters), fragmentSource(programParameters)) {} static std::string pixelRatioDefine(const ProgramParameters& parameters) { @@ -38,6 +57,33 @@ class Program : public gl::Program { return pixelRatioDefine(parameters) + Shaders::vertexSource; } + template + void draw(gl::Context& context, + DrawMode drawMode, + gl::DepthMode depthMode, + gl::StencilMode stencilMode, + gl::ColorMode colorMode, + UniformValues&& uniformValues, + const gl::VertexBuffer& layoutVertexBuffer, + const gl::IndexBuffer& indexBuffer, + const gl::SegmentVector& segments, + const PaintPropertyBinders& paintPropertyBinders, + const typename PaintProperties::Evaluated& currentProperties, + float currentZoom) { + program.draw( + context, + std::move(drawMode), + std::move(depthMode), + std::move(stencilMode), + std::move(colorMode), + uniformValues + .concat(paintPropertyBinders.uniformValues(currentZoom)), + LayoutAttributes::allVariableBindings(layoutVertexBuffer) + .concat(paintPropertyBinders.attributeBindings(currentProperties)), + indexBuffer, + segments + ); + } }; } // namespace mbgl diff --git a/src/mbgl/programs/raster_program.cpp b/src/mbgl/programs/raster_program.cpp index ebec4c68ccc..6906903e6bd 100644 --- a/src/mbgl/programs/raster_program.cpp +++ b/src/mbgl/programs/raster_program.cpp @@ -2,6 +2,6 @@ namespace mbgl { -static_assert(sizeof(RasterProgram::Vertex) == 8, "expected RasterVertex size"); +static_assert(sizeof(RasterLayoutVertex) == 8, "expected RasterLayoutVertex size"); } // namespace mbgl diff --git a/src/mbgl/programs/raster_program.hpp b/src/mbgl/programs/raster_program.hpp index 9aa25cf90c4..7b4c3842bed 100644 --- a/src/mbgl/programs/raster_program.hpp +++ b/src/mbgl/programs/raster_program.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace mbgl { @@ -22,14 +23,12 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 3, u_spin_weights); MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_tl_parent); } // namespace uniforms -using RasterAttributes = gl::Attributes< - attributes::a_pos, - attributes::a_texture_pos>; - class RasterProgram : public Program< shaders::raster, gl::Triangle, - RasterAttributes, + gl::Attributes< + attributes::a_pos, + attributes::a_texture_pos>, gl::Uniforms< uniforms::u_matrix, uniforms::u_image0, @@ -43,25 +42,27 @@ class RasterProgram : public Program< uniforms::u_spin_weights, uniforms::u_buffer_scale, uniforms::u_scale_parent, - uniforms::u_tl_parent>> + uniforms::u_tl_parent>, + style::RasterPaintProperties> { public: using Program::Program; - static Vertex vertex(Point p, Point t) { - return Vertex { - { + static LayoutVertex layoutVertex(Point p, Point t) { + return LayoutVertex { + {{ p.x, p.y - }, - { + }}, + {{ t.x, t.y - } + }} }; } }; -using RasterVertex = RasterProgram::Vertex; +using RasterLayoutVertex = RasterProgram::LayoutVertex; +using RasterAttributes = RasterProgram::Attributes; } // namespace mbgl diff --git a/src/mbgl/programs/symbol_program.cpp b/src/mbgl/programs/symbol_program.cpp index d609dada8d0..3f59000b944 100644 --- a/src/mbgl/programs/symbol_program.cpp +++ b/src/mbgl/programs/symbol_program.cpp @@ -7,7 +7,7 @@ namespace mbgl { using namespace style; -static_assert(sizeof(SymbolAttributes::Vertex) == 16, "expected SymbolVertex size"); +static_assert(sizeof(SymbolLayoutVertex) == 16, "expected SymbolLayoutVertex size"); template Values makeValues(const style::SymbolPropertyValues& values, diff --git a/src/mbgl/programs/symbol_program.hpp b/src/mbgl/programs/symbol_program.hpp index be987551c0b..01302553560 100644 --- a/src/mbgl/programs/symbol_program.hpp +++ b/src/mbgl/programs/symbol_program.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -31,9 +32,9 @@ MBGL_DEFINE_UNIFORM_SCALAR(float, u_gamma); MBGL_DEFINE_UNIFORM_SCALAR(float, u_aspect_ratio); } // namespace uniforms -struct SymbolAttributes : gl::Attributes< +struct SymbolLayoutAttributes : gl::Attributes< attributes::a_pos, - attributes::a_offset, + attributes::a_offset<2>, attributes::a_texture_pos, attributes::a_data<4>> { @@ -46,34 +47,32 @@ struct SymbolAttributes : gl::Attributes< float labelminzoom, uint8_t labelangle) { return Vertex { - { + {{ static_cast(a.x), static_cast(a.y) - }, - { + }}, + {{ static_cast(::round(o.x * 64)), // use 1/64 pixels for placement static_cast(::round(o.y * 64)) - }, - { + }}, + {{ static_cast(tx / 4), static_cast(ty / 4) - }, - { + }}, + {{ static_cast(labelminzoom * 10), // 1/10 zoom levels: z16 == 160 static_cast(labelangle), static_cast(minzoom * 10), static_cast(::fmin(maxzoom, 25) * 10) - } + }} }; } }; -using SymbolVertex = SymbolAttributes::Vertex; - class SymbolIconProgram : public Program< shaders::symbol_icon, gl::Triangle, - SymbolAttributes, + SymbolLayoutAttributes, gl::Uniforms< uniforms::u_matrix, uniforms::u_opacity, @@ -82,7 +81,8 @@ class SymbolIconProgram : public Program< uniforms::u_zoom, uniforms::u_rotate_with_map, uniforms::u_texture, - uniforms::u_fadetexture>> + uniforms::u_fadetexture>, + style::SymbolPaintProperties> { public: using Program::Program; @@ -97,7 +97,7 @@ class SymbolIconProgram : public Program< class SymbolSDFProgram : public Program< shaders::symbol_sdf, gl::Triangle, - SymbolAttributes, + SymbolLayoutAttributes, gl::Uniforms< uniforms::u_matrix, uniforms::u_opacity, @@ -113,7 +113,8 @@ class SymbolSDFProgram : public Program< uniforms::u_pitch, uniforms::u_bearing, uniforms::u_aspect_ratio, - uniforms::u_pitch_with_map>> + uniforms::u_pitch_with_map>, + style::SymbolPaintProperties> { public: using Program::Program; @@ -133,4 +134,7 @@ class SymbolSDFProgram : public Program< float pixelRatio); }; +using SymbolLayoutVertex = SymbolLayoutAttributes::Vertex; +using SymbolAttributes = SymbolIconProgram::Attributes; + } // namespace mbgl diff --git a/src/mbgl/renderer/bucket.hpp b/src/mbgl/renderer/bucket.hpp index 49619c14f76..294e50dd8c8 100644 --- a/src/mbgl/renderer/bucket.hpp +++ b/src/mbgl/renderer/bucket.hpp @@ -2,6 +2,7 @@ #include #include +#include #include @@ -22,6 +23,10 @@ class Layer; class Bucket : private util::noncopyable { public: Bucket() = default; + virtual ~Bucket() = default; + + virtual void addFeature(const GeometryTileFeature&, + const GeometryCollection&) {}; // As long as this bucket has a Prepare render pass, this function is getting called. Typically, // this only happens once when the bucket is being rendered for the first time. @@ -31,8 +36,6 @@ class Bucket : private util::noncopyable { // once or twice (for Opaque and Transparent render passes). virtual void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) = 0; - virtual ~Bucket() = default; - virtual bool hasData() const = 0; bool needsUpload() const { diff --git a/src/mbgl/renderer/circle_bucket.cpp b/src/mbgl/renderer/circle_bucket.cpp index ba2285c4eb7..9b2785ac30b 100644 --- a/src/mbgl/renderer/circle_bucket.cpp +++ b/src/mbgl/renderer/circle_bucket.cpp @@ -1,21 +1,33 @@ #include #include -#include - #include +#include #include +#include #include namespace mbgl { using namespace style; -CircleBucket::CircleBucket(MapMode mode_) : mode(mode_) { +CircleBucket::CircleBucket(const BucketParameters& parameters, const std::vector& layers) + : mode(parameters.mode) { + for (const auto& layer : layers) { + paintPropertyBinders.emplace(layer->getID(), + CircleProgram::PaintPropertyBinders( + layer->as()->impl->paint.evaluated, + parameters.tileID.overscaledZ)); + } } void CircleBucket::upload(gl::Context& context) { vertexBuffer = context.createVertexBuffer(std::move(vertices)); indexBuffer = context.createIndexBuffer(std::move(triangles)); + + for (auto& pair : paintPropertyBinders) { + pair.second.upload(context); + } + uploaded = true; } @@ -30,10 +42,11 @@ bool CircleBucket::hasData() const { return !segments.empty(); } -void CircleBucket::addGeometry(const GeometryCollection& geometryCollection) { +void CircleBucket::addFeature(const GeometryTileFeature& feature, + const GeometryCollection& geometry) { constexpr const uint16_t vertexLength = 4; - for (auto& circle : geometryCollection) { + for (auto& circle : geometry) { for(auto& point : circle) { auto x = point.x; auto y = point.y; @@ -76,6 +89,10 @@ void CircleBucket::addGeometry(const GeometryCollection& geometryCollection) { segment.indexLength += 6; } } + + for (auto& pair : paintPropertyBinders) { + pair.second.populateVertexVectors(feature, vertices.vertexSize()); + } } } // namespace mbgl diff --git a/src/mbgl/renderer/circle_bucket.hpp b/src/mbgl/renderer/circle_bucket.hpp index af7041a2384..412db53f65a 100644 --- a/src/mbgl/renderer/circle_bucket.hpp +++ b/src/mbgl/renderer/circle_bucket.hpp @@ -7,26 +7,34 @@ #include #include #include +#include namespace mbgl { +namespace style { +class BucketParameters; +} // namespace style + class CircleBucket : public Bucket { public: - CircleBucket(const MapMode); + CircleBucket(const style::BucketParameters&, const std::vector&); + + void addFeature(const GeometryTileFeature&, + const GeometryCollection&) override; + bool hasData() const override; void upload(gl::Context&) override; void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override; - bool hasData() const override; - void addGeometry(const GeometryCollection&); - - gl::VertexVector vertices; + gl::VertexVector vertices; gl::IndexVector triangles; gl::SegmentVector segments; - optional> vertexBuffer; + optional> vertexBuffer; optional> indexBuffer; + std::unordered_map paintPropertyBinders; + const MapMode mode; }; diff --git a/src/mbgl/renderer/debug_bucket.cpp b/src/mbgl/renderer/debug_bucket.cpp index 167df4376f4..2a514989cfd 100644 --- a/src/mbgl/renderer/debug_bucket.cpp +++ b/src/mbgl/renderer/debug_bucket.cpp @@ -23,7 +23,7 @@ DebugBucket::DebugBucket(const OverscaledTileID& id, expires(std::move(expires_)), debugMode(debugMode_) { - gl::VertexVector vertices; + gl::VertexVector vertices; gl::IndexVector indices; auto addText = [&] (const std::string& text, double left, double baseline, double scale) { @@ -43,7 +43,7 @@ DebugBucket::DebugBucket(const OverscaledTileID& id, int16_t(::round(baseline - glyph.data[j + 1] * scale)) }; - vertices.emplace_back(FillAttributes::vertex(p)); + vertices.emplace_back(FillProgram::layoutVertex(p)); if (prev) { indices.emplace_back(vertices.vertexSize() - 2, diff --git a/src/mbgl/renderer/debug_bucket.hpp b/src/mbgl/renderer/debug_bucket.hpp index 4676381789f..756e58a6dec 100644 --- a/src/mbgl/renderer/debug_bucket.hpp +++ b/src/mbgl/renderer/debug_bucket.hpp @@ -34,7 +34,7 @@ class DebugBucket : private util::noncopyable { const MapDebugOptions debugMode; gl::SegmentVector segments; - optional> vertexBuffer; + optional> vertexBuffer; optional> indexBuffer; }; diff --git a/src/mbgl/renderer/fill_bucket.cpp b/src/mbgl/renderer/fill_bucket.cpp index b89e9820572..64efafb108d 100644 --- a/src/mbgl/renderer/fill_bucket.cpp +++ b/src/mbgl/renderer/fill_bucket.cpp @@ -1,8 +1,9 @@ #include -#include #include #include -#include +#include +#include +#include #include @@ -26,7 +27,17 @@ using namespace style; struct GeometryTooLongException : std::exception {}; -void FillBucket::addGeometry(const GeometryCollection& geometry) { +FillBucket::FillBucket(const BucketParameters& parameters, const std::vector& layers) { + for (const auto& layer : layers) { + paintPropertyBinders.emplace(layer->getID(), + FillProgram::PaintPropertyBinders( + layer->as()->impl->paint.evaluated, + parameters.tileID.overscaledZ)); + } +} + +void FillBucket::addFeature(const GeometryTileFeature& feature, + const GeometryCollection& geometry) { for (auto& polygon : classifyRings(geometry)) { // Optimize polygons with many interior rings for earcut tesselation. limitHoles(polygon, 500); @@ -55,11 +66,11 @@ void FillBucket::addGeometry(const GeometryCollection& geometry) { assert(lineSegment.vertexLength <= std::numeric_limits::max()); uint16_t lineIndex = lineSegment.vertexLength; - vertices.emplace_back(FillAttributes::vertex(ring[0])); + vertices.emplace_back(FillProgram::layoutVertex(ring[0])); lines.emplace_back(lineIndex + nVertices - 1, lineIndex); for (uint32_t i = 1; i < nVertices; i++) { - vertices.emplace_back(FillAttributes::vertex(ring[i])); + vertices.emplace_back(FillProgram::layoutVertex(ring[i])); lines.emplace_back(lineIndex + i - 1, lineIndex + i); } @@ -89,6 +100,10 @@ void FillBucket::addGeometry(const GeometryCollection& geometry) { triangleSegment.vertexLength += totalVertices; triangleSegment.indexLength += nIndicies; } + + for (auto& pair : paintPropertyBinders) { + pair.second.populateVertexVectors(feature, vertices.vertexSize()); + } } void FillBucket::upload(gl::Context& context) { @@ -96,7 +111,10 @@ void FillBucket::upload(gl::Context& context) { lineIndexBuffer = context.createIndexBuffer(std::move(lines)); triangleIndexBuffer = context.createIndexBuffer(std::move(triangles)); - // From now on, we're going to render during the opaque and translucent pass. + for (auto& pair : paintPropertyBinders) { + pair.second.upload(context); + } + uploaded = true; } diff --git a/src/mbgl/renderer/fill_bucket.hpp b/src/mbgl/renderer/fill_bucket.hpp index edb1521c1d2..b403e1053bd 100644 --- a/src/mbgl/renderer/fill_bucket.hpp +++ b/src/mbgl/renderer/fill_bucket.hpp @@ -6,28 +6,38 @@ #include #include #include +#include #include namespace mbgl { +namespace style { +class BucketParameters; +} // namespace style + class FillBucket : public Bucket { public: - void upload(gl::Context&) override; - void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override; + FillBucket(const style::BucketParameters&, const std::vector&); + + void addFeature(const GeometryTileFeature&, + const GeometryCollection&) override; bool hasData() const override; - void addGeometry(const GeometryCollection&); + void upload(gl::Context&) override; + void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override; - gl::VertexVector vertices; + gl::VertexVector vertices; gl::IndexVector lines; gl::IndexVector triangles; gl::SegmentVector lineSegments; gl::SegmentVector triangleSegments; - optional> vertexBuffer; + optional> vertexBuffer; optional> lineIndexBuffer; optional> triangleIndexBuffer; + + std::unordered_map paintPropertyBinders; }; } // namespace mbgl diff --git a/src/mbgl/renderer/line_bucket.cpp b/src/mbgl/renderer/line_bucket.cpp index 007060bd1bc..a83a0e6fdc7 100644 --- a/src/mbgl/renderer/line_bucket.cpp +++ b/src/mbgl/renderer/line_bucket.cpp @@ -1,6 +1,8 @@ #include -#include #include +#include +#include +#include #include #include @@ -10,19 +12,29 @@ namespace mbgl { using namespace style; -LineBucket::LineBucket(uint32_t overscaling_) : overscaling(overscaling_) { -} - -LineBucket::~LineBucket() { - // Do not remove. header file only contains forward definitions to unique pointers. +LineBucket::LineBucket(const BucketParameters& parameters, + const std::vector& layers, + const style::LineLayoutProperties& layout_) + : layout(layout_.evaluate(PropertyEvaluationParameters(parameters.tileID.overscaledZ))), + overscaling(parameters.tileID.overscaleFactor()) { + for (const auto& layer : layers) { + paintPropertyBinders.emplace(layer->getID(), + LineProgram::PaintPropertyBinders( + layer->as()->impl->paint.evaluated, + parameters.tileID.overscaledZ)); + } } -void LineBucket::addGeometry(const GeometryCollection& geometryCollection) { +void LineBucket::addFeature(const GeometryTileFeature& feature, + const GeometryCollection& geometryCollection) { for (auto& line : geometryCollection) { addGeometry(line); } -} + for (auto& pair : paintPropertyBinders) { + pair.second.populateVertexVectors(feature, vertices.vertexSize()); + } +} /* * Sharp corners cause dashed lines to tilt because the distance along the line @@ -375,7 +387,7 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, Point extrude = normal; if (endLeft) extrude = extrude - (util::perp(normal) * endLeft); - vertices.emplace_back(LineAttributes::vertex(currentCoordinate, extrude, { round, false }, endLeft, distance * LINE_DISTANCE_SCALE)); + vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, { round, false }, endLeft, distance * LINE_DISTANCE_SCALE)); e3 = vertices.vertexSize() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(e1, e2, e3); @@ -386,7 +398,7 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate, extrude = normal * -1.0; if (endRight) extrude = extrude - (util::perp(normal) * endRight); - vertices.emplace_back(LineAttributes::vertex(currentCoordinate, extrude, { round, true }, -endRight, distance * LINE_DISTANCE_SCALE)); + vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, { round, true }, -endRight, distance * LINE_DISTANCE_SCALE)); e3 = vertices.vertexSize() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(e1, e2, e3); @@ -411,7 +423,7 @@ void LineBucket::addPieSliceVertex(const GeometryCoordinate& currentVertex, std::size_t startVertex, std::vector& triangleStore) { Point flippedExtrude = extrude * (lineTurnsLeft ? -1.0 : 1.0); - vertices.emplace_back(LineAttributes::vertex(currentVertex, flippedExtrude, { false, lineTurnsLeft }, 0, distance * LINE_DISTANCE_SCALE)); + vertices.emplace_back(LineProgram::layoutVertex(currentVertex, flippedExtrude, { false, lineTurnsLeft }, 0, distance * LINE_DISTANCE_SCALE)); e3 = vertices.vertexSize() - 1 - startVertex; if (e1 >= 0 && e2 >= 0) { triangleStore.emplace_back(e1, e2, e3); @@ -428,7 +440,10 @@ void LineBucket::upload(gl::Context& context) { vertexBuffer = context.createVertexBuffer(std::move(vertices)); indexBuffer = context.createIndexBuffer(std::move(triangles)); - // From now on, we're only going to render during the translucent pass. + for (auto& pair : paintPropertyBinders) { + pair.second.upload(context); + } + uploaded = true; } diff --git a/src/mbgl/renderer/line_bucket.hpp b/src/mbgl/renderer/line_bucket.hpp index d11d78ff691..78293d75f92 100644 --- a/src/mbgl/renderer/line_bucket.hpp +++ b/src/mbgl/renderer/line_bucket.hpp @@ -12,28 +12,37 @@ namespace mbgl { +namespace style { +class BucketParameters; +} // namespace style + class LineBucket : public Bucket { public: - LineBucket(uint32_t overscaling); - ~LineBucket() override; + LineBucket(const style::BucketParameters&, + const std::vector&, + const style::LineLayoutProperties&); - void upload(gl::Context&) override; - void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override; + void addFeature(const GeometryTileFeature&, + const GeometryCollection&) override; bool hasData() const override; - void addGeometry(const GeometryCollection&); - void addGeometry(const GeometryCoordinates& line); + void upload(gl::Context&) override; + void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override; style::LineLayoutProperties::Evaluated layout; - gl::VertexVector vertices; + gl::VertexVector vertices; gl::IndexVector triangles; gl::SegmentVector segments; - optional> vertexBuffer; + optional> vertexBuffer; optional> indexBuffer; + std::unordered_map paintPropertyBinders; + private: + void addGeometry(const GeometryCoordinates& line); + struct TriangleElement { TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) : a(a_), b(b_), c(c_) {} uint16_t a, b, c; diff --git a/src/mbgl/renderer/painter.cpp b/src/mbgl/renderer/painter.cpp index 5894912ef34..910a53e981c 100644 --- a/src/mbgl/renderer/painter.cpp +++ b/src/mbgl/renderer/painter.cpp @@ -42,12 +42,12 @@ namespace mbgl { using namespace style; -static gl::VertexVector tileVertices() { - gl::VertexVector result; - result.emplace_back(FillAttributes::vertex({ 0, 0 })); - result.emplace_back(FillAttributes::vertex({ util::EXTENT, 0 })); - result.emplace_back(FillAttributes::vertex({ 0, util::EXTENT })); - result.emplace_back(FillAttributes::vertex({ util::EXTENT, util::EXTENT })); +static gl::VertexVector tileVertices() { + gl::VertexVector result; + result.emplace_back(FillProgram::layoutVertex({ 0, 0 })); + result.emplace_back(FillProgram::layoutVertex({ util::EXTENT, 0 })); + result.emplace_back(FillProgram::layoutVertex({ 0, util::EXTENT })); + result.emplace_back(FillProgram::layoutVertex({ util::EXTENT, util::EXTENT })); return result; } @@ -68,12 +68,12 @@ static gl::IndexVector tileLineStripIndices() { return result; } -static gl::VertexVector rasterVertices() { - gl::VertexVector result; - result.emplace_back(RasterProgram::vertex({ 0, 0 }, { 0, 0 })); - result.emplace_back(RasterProgram::vertex({ util::EXTENT, 0 }, { 32767, 0 })); - result.emplace_back(RasterProgram::vertex({ 0, util::EXTENT }, { 0, 32767 })); - result.emplace_back(RasterProgram::vertex({ util::EXTENT, util::EXTENT }, { 32767, 32767 })); +static gl::VertexVector rasterVertices() { + gl::VertexVector result; + result.emplace_back(RasterProgram::layoutVertex({ 0, 0 }, { 0, 0 })); + result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, 0 }, { 32767, 0 })); + result.emplace_back(RasterProgram::layoutVertex({ 0, util::EXTENT }, { 0, 32767 })); + result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, util::EXTENT }, { 32767, 32767 })); return result; } diff --git a/src/mbgl/renderer/painter.hpp b/src/mbgl/renderer/painter.hpp index dec7fa57fd3..91f329a6ebb 100644 --- a/src/mbgl/renderer/painter.hpp +++ b/src/mbgl/renderer/painter.hpp @@ -158,8 +158,8 @@ class Painter : private util::noncopyable { std::unique_ptr overdrawPrograms; #endif - gl::VertexBuffer tileVertexBuffer; - gl::VertexBuffer rasterVertexBuffer; + gl::VertexBuffer tileVertexBuffer; + gl::VertexBuffer rasterVertexBuffer; gl::IndexBuffer tileTriangleIndexBuffer; gl::IndexBuffer tileBorderIndexBuffer; diff --git a/src/mbgl/renderer/painter_background.cpp b/src/mbgl/renderer/painter_background.cpp index 4a3e41701dc..e8a5342f4ab 100644 --- a/src/mbgl/renderer/painter_background.cpp +++ b/src/mbgl/renderer/painter_background.cpp @@ -14,13 +14,20 @@ using namespace style; void Painter::renderBackground(PaintParameters& parameters, const BackgroundLayer& layer) { // Note that for bottommost layers without a pattern, the background color is drawn with // glClear rather than this method. - const BackgroundPaintProperties::Evaluated& properties = layer.impl->paint.evaluated; + const BackgroundPaintProperties::Evaluated& background = layer.impl->paint.evaluated; - if (!properties.get().to.empty()) { + style::FillPaintProperties::Evaluated properties; + properties.get() = background.get(); + properties.get() = { background.get() }; + properties.get() = { background.get() }; + + const FillProgram::PaintPropertyBinders paintAttibuteData(properties, 0); + + if (!background.get().to.empty()) { optional imagePosA = spriteAtlas->getPosition( - properties.get().from, SpritePatternMode::Repeating); + background.get().from, SpritePatternMode::Repeating); optional imagePosB = spriteAtlas->getPosition( - properties.get().to, SpritePatternMode::Repeating); + background.get().to, SpritePatternMode::Repeating); if (!imagePosA || !imagePosB) return; @@ -36,17 +43,19 @@ void Painter::renderBackground(PaintParameters& parameters, const BackgroundLaye colorModeForRenderPass(), FillPatternUniforms::values( matrixForTile(tileID), - properties.get(), context.viewport.getCurrentValue().size, *imagePosA, *imagePosB, - properties.get(), + background.get(), tileID, state ), tileVertexBuffer, tileTriangleIndexBuffer, - tileTriangleSegments + tileTriangleSegments, + paintAttibuteData, + properties, + state.getZoom() ); } } else { @@ -59,14 +68,14 @@ void Painter::renderBackground(PaintParameters& parameters, const BackgroundLaye colorModeForRenderPass(), FillProgram::UniformValues { uniforms::u_matrix::Value{ matrixForTile(tileID) }, - uniforms::u_opacity::Value{ properties.get() }, - uniforms::u_color::Value{ properties.get() }, - uniforms::u_outline_color::Value{ properties.get() }, uniforms::u_world::Value{ context.viewport.getCurrentValue().size }, }, tileVertexBuffer, tileTriangleIndexBuffer, - tileTriangleSegments + tileTriangleSegments, + paintAttibuteData, + properties, + state.getZoom() ); } } diff --git a/src/mbgl/renderer/painter_circle.cpp b/src/mbgl/renderer/painter_circle.cpp index 966d58b59be..8d47e75f71a 100644 --- a/src/mbgl/renderer/painter_circle.cpp +++ b/src/mbgl/renderer/painter_circle.cpp @@ -37,13 +37,6 @@ void Painter::renderCircle(PaintParameters& parameters, properties.get(), state) }, - uniforms::u_opacity::Value{ properties.get() }, - uniforms::u_color::Value{ properties.get() }, - uniforms::u_radius::Value{ properties.get() }, - uniforms::u_blur::Value{ properties.get() }, - uniforms::u_stroke_color::Value{ properties.get() }, - uniforms::u_stroke_width::Value{ properties.get() }, - uniforms::u_stroke_opacity::Value{ properties.get() }, uniforms::u_scale_with_map::Value{ scaleWithMap }, uniforms::u_extrude_scale::Value{ scaleWithMap ? std::array {{ @@ -54,7 +47,10 @@ void Painter::renderCircle(PaintParameters& parameters, }, *bucket.vertexBuffer, *bucket.indexBuffer, - bucket.segments + bucket.segments, + bucket.paintPropertyBinders.at(layer.getID()), + properties, + state.getZoom() ); } diff --git a/src/mbgl/renderer/painter_clipping.cpp b/src/mbgl/renderer/painter_clipping.cpp index a2529561fed..70df9837e88 100644 --- a/src/mbgl/renderer/painter_clipping.cpp +++ b/src/mbgl/renderer/painter_clipping.cpp @@ -6,6 +6,8 @@ namespace mbgl { void Painter::renderClippingMask(const UnwrappedTileID& tileID, const ClipID& clip) { + static const style::FillPaintProperties::Evaluated properties {}; + static const FillProgram::PaintPropertyBinders paintAttibuteData(properties, 0); programs->fill.draw( context, gl::Triangles(), @@ -21,14 +23,14 @@ void Painter::renderClippingMask(const UnwrappedTileID& tileID, const ClipID& cl gl::ColorMode::disabled(), FillProgram::UniformValues { uniforms::u_matrix::Value{ matrixForTile(tileID) }, - uniforms::u_opacity::Value{ 0.0f }, - uniforms::u_color::Value{ Color {} }, - uniforms::u_outline_color::Value{ Color {} }, uniforms::u_world::Value{ context.viewport.getCurrentValue().size }, }, tileVertexBuffer, tileTriangleIndexBuffer, - tileTriangleSegments + tileTriangleSegments, + paintAttibuteData, + properties, + state.getZoom() ); } diff --git a/src/mbgl/renderer/painter_debug.cpp b/src/mbgl/renderer/painter_debug.cpp index 2b838dec0ef..5b347884bf0 100644 --- a/src/mbgl/renderer/painter_debug.cpp +++ b/src/mbgl/renderer/painter_debug.cpp @@ -12,12 +12,17 @@ namespace mbgl { +using namespace style; + void Painter::renderTileDebug(const RenderTile& renderTile) { if (frame.debugOptions == MapDebugOptions::NoDebug) return; MBGL_DEBUG_GROUP(std::string { "debug " } + util::toString(renderTile.id)); + static const style::PaintProperties<>::Evaluated properties {}; + static const DebugProgram::PaintPropertyBinders paintAttibuteData(properties, 0); + auto draw = [&] (Color color, const auto& vertexBuffer, const auto& indexBuffer, const auto& segments, auto drawMode) { programs->debug.draw( context, @@ -31,7 +36,10 @@ void Painter::renderTileDebug(const RenderTile& renderTile) { }, vertexBuffer, indexBuffer, - segments + segments, + paintAttibuteData, + properties, + state.getZoom() ); }; diff --git a/src/mbgl/renderer/painter_fill.cpp b/src/mbgl/renderer/painter_fill.cpp index f4e73f94ac6..d98cb2b57ce 100644 --- a/src/mbgl/renderer/painter_fill.cpp +++ b/src/mbgl/renderer/painter_fill.cpp @@ -38,7 +38,6 @@ void Painter::renderFill(PaintParameters& parameters, auto draw = [&] (uint8_t sublayer, auto& program, const auto& drawMode, - const auto& vertexBuffer, const auto& indexBuffer, const auto& segments) { program.draw( @@ -51,7 +50,6 @@ void Painter::renderFill(PaintParameters& parameters, tile.translatedMatrix(properties.get(), properties.get(), state), - properties.get(), context.viewport.getCurrentValue().size, *imagePosA, *imagePosB, @@ -59,16 +57,18 @@ void Painter::renderFill(PaintParameters& parameters, tile.id, state ), - vertexBuffer, + *bucket.vertexBuffer, indexBuffer, - segments + segments, + bucket.paintPropertyBinders.at(layer.getID()), + properties, + state.getZoom() ); }; draw(0, parameters.programs.fillPattern, gl::Triangles(), - *bucket.vertexBuffer, *bucket.triangleIndexBuffer, bucket.triangleSegments); @@ -79,14 +79,12 @@ void Painter::renderFill(PaintParameters& parameters, draw(2, parameters.programs.fillOutlinePattern, gl::Lines { 2.0f }, - *bucket.vertexBuffer, *bucket.lineIndexBuffer, bucket.lineSegments); } else { auto draw = [&] (uint8_t sublayer, auto& program, const auto& drawMode, - const auto& vertexBuffer, const auto& indexBuffer, const auto& segments) { program.draw( @@ -96,17 +94,19 @@ void Painter::renderFill(PaintParameters& parameters, stencilModeForClipping(tile.clip), colorModeForRenderPass(), FillProgram::UniformValues { - uniforms::u_matrix::Value{ tile.translatedMatrix(properties.get(), - properties.get(), - state) }, - uniforms::u_opacity::Value{ properties.get() }, - uniforms::u_color::Value{ properties.get() }, - uniforms::u_outline_color::Value{ properties.get() }, + uniforms::u_matrix::Value{ + tile.translatedMatrix(properties.get(), + properties.get(), + state) + }, uniforms::u_world::Value{ context.viewport.getCurrentValue().size }, }, - vertexBuffer, + *bucket.vertexBuffer, indexBuffer, - segments + segments, + bucket.paintPropertyBinders.at(layer.getID()), + properties, + state.getZoom() ); }; @@ -114,18 +114,17 @@ void Painter::renderFill(PaintParameters& parameters, draw(2, parameters.programs.fillOutline, gl::Lines { 2.0f }, - *bucket.vertexBuffer, *bucket.lineIndexBuffer, bucket.lineSegments); } // Only draw the fill when it's opaque and we're drawing opaque fragments, // or when it's translucent and we're drawing translucent fragments. - if ((properties.get().a >= 1.0f && properties.get() >= 1.0f) == (pass == RenderPass::Opaque)) { + if ((properties.get().constantOr(Color()).a >= 1.0f + && properties.get().constantOr(0) >= 1.0f) == (pass == RenderPass::Opaque)) { draw(1, parameters.programs.fill, gl::Triangles(), - *bucket.vertexBuffer, *bucket.triangleIndexBuffer, bucket.triangleSegments); } @@ -134,7 +133,6 @@ void Painter::renderFill(PaintParameters& parameters, draw(2, parameters.programs.fillOutline, gl::Lines { 2.0f }, - *bucket.vertexBuffer, *bucket.lineIndexBuffer, bucket.lineSegments); } diff --git a/src/mbgl/renderer/painter_line.cpp b/src/mbgl/renderer/painter_line.cpp index 012746d2f2d..0fbff94ff7d 100644 --- a/src/mbgl/renderer/painter_line.cpp +++ b/src/mbgl/renderer/painter_line.cpp @@ -33,7 +33,10 @@ void Painter::renderLine(PaintParameters& parameters, std::move(uniformValues), *bucket.vertexBuffer, *bucket.indexBuffer, - bucket.segments + bucket.segments, + bucket.paintPropertyBinders.at(layer.getID()), + properties, + state.getZoom() ); }; diff --git a/src/mbgl/renderer/painter_raster.cpp b/src/mbgl/renderer/painter_raster.cpp index dcf2644140d..c216955db8d 100644 --- a/src/mbgl/renderer/painter_raster.cpp +++ b/src/mbgl/renderer/painter_raster.cpp @@ -49,6 +49,7 @@ void Painter::renderRaster(PaintParameters& parameters, return; const RasterPaintProperties::Evaluated& properties = layer.impl->paint.evaluated; + const RasterProgram::PaintPropertyBinders paintAttributeData(properties, 0); assert(bucket.texture); context.bindTexture(*bucket.texture, 0, gl::TextureFilter::Linear); @@ -77,7 +78,10 @@ void Painter::renderRaster(PaintParameters& parameters, }, rasterVertexBuffer, tileTriangleIndexBuffer, - rasterSegments + rasterSegments, + paintAttributeData, + properties, + state.getZoom() ); } diff --git a/src/mbgl/renderer/painter_symbol.cpp b/src/mbgl/renderer/painter_symbol.cpp index 39075976a0b..0113c15a087 100644 --- a/src/mbgl/renderer/painter_symbol.cpp +++ b/src/mbgl/renderer/painter_symbol.cpp @@ -51,7 +51,10 @@ void Painter::renderSymbol(PaintParameters& parameters, std::move(uniformValues), *buffers.vertexBuffer, *buffers.indexBuffer, - buffers.segments + buffers.segments, + bucket.paintPropertyBinders.at(layer.getID()), + layer.impl->paint.evaluated, + state.getZoom() ); }; @@ -110,6 +113,9 @@ void Painter::renderSymbol(PaintParameters& parameters, } if (bucket.hasCollisionBoxData()) { + static const style::PaintProperties<>::Evaluated properties {}; + static const CollisionBoxProgram::PaintPropertyBinders paintAttributeData(properties, 0); + programs->collisionBox.draw( context, gl::Lines { 1.0f }, @@ -124,7 +130,10 @@ void Painter::renderSymbol(PaintParameters& parameters, }, *bucket.collisionBox.vertexBuffer, *bucket.collisionBox.indexBuffer, - bucket.collisionBox.segments + bucket.collisionBox.segments, + paintAttributeData, + properties, + state.getZoom() ); } } diff --git a/src/mbgl/renderer/symbol_bucket.cpp b/src/mbgl/renderer/symbol_bucket.cpp index 0f2c89339fa..9d4bde9d071 100644 --- a/src/mbgl/renderer/symbol_bucket.cpp +++ b/src/mbgl/renderer/symbol_bucket.cpp @@ -1,19 +1,25 @@ #include #include +#include #include +#include namespace mbgl { using namespace style; -SymbolBucket::SymbolBucket(const MapMode mode_, - style::SymbolLayoutProperties::Evaluated layout_, +SymbolBucket::SymbolBucket(style::SymbolLayoutProperties::Evaluated layout_, + const std::unordered_map& layerPaintProperties, + float zoom, bool sdfIcons_, bool iconsNeedLinear_) - : mode(mode_), - layout(std::move(layout_)), + : layout(std::move(layout_)), sdfIcons(sdfIcons_), iconsNeedLinear(iconsNeedLinear_) { + for (const auto& pair : layerPaintProperties) { + paintPropertyBinders.emplace(pair.first, + SymbolIconProgram::PaintPropertyBinders(pair.second, zoom)); + } } void SymbolBucket::upload(gl::Context& context) { @@ -32,6 +38,10 @@ void SymbolBucket::upload(gl::Context& context) { collisionBox.indexBuffer = context.createIndexBuffer(std::move(collisionBox.lines)); } + for (auto& pair : paintPropertyBinders) { + pair.second.upload(context); + } + uploaded = true; } diff --git a/src/mbgl/renderer/symbol_bucket.hpp b/src/mbgl/renderer/symbol_bucket.hpp index d62a61aab76..0b40bb34ae5 100644 --- a/src/mbgl/renderer/symbol_bucket.hpp +++ b/src/mbgl/renderer/symbol_bucket.hpp @@ -16,8 +16,9 @@ namespace mbgl { class SymbolBucket : public Bucket { public: - SymbolBucket(const MapMode, - style::SymbolLayoutProperties::Evaluated, + SymbolBucket(style::SymbolLayoutProperties::Evaluated, + const std::unordered_map&, + float zoom, bool sdfIcons, bool iconsNeedLinear); @@ -28,26 +29,27 @@ class SymbolBucket : public Bucket { bool hasIconData() const; bool hasCollisionBoxData() const; - const MapMode mode; const style::SymbolLayoutProperties::Evaluated layout; const bool sdfIcons; const bool iconsNeedLinear; + std::unordered_map paintPropertyBinders; + struct TextBuffer { - gl::VertexVector vertices; + gl::VertexVector vertices; gl::IndexVector triangles; gl::SegmentVector segments; - optional> vertexBuffer; + optional> vertexBuffer; optional> indexBuffer; } text; struct IconBuffer { - gl::VertexVector vertices; + gl::VertexVector vertices; gl::IndexVector triangles; gl::SegmentVector segments; - optional> vertexBuffer; + optional> vertexBuffer; optional> indexBuffer; } icon; diff --git a/src/mbgl/style/bucket_parameters.cpp b/src/mbgl/style/bucket_parameters.cpp index e641120c5ea..2b02ac4a4a2 100644 --- a/src/mbgl/style/bucket_parameters.cpp +++ b/src/mbgl/style/bucket_parameters.cpp @@ -1,21 +1,7 @@ #include -#include -#include namespace mbgl { namespace style { -void BucketParameters::eachFilteredFeature(const Filter& filter, - const GeometryTileLayer& layer, - std::function function) { - auto name = layer.getName(); - for (std::size_t i = 0; !cancelled() && i < layer.featureCount(); i++) { - auto feature = layer.getFeature(i); - if (!filter(feature->getType(), feature->getID(), [&] (const auto& key) { return feature->getValue(key); })) - continue; - function(*feature, i, name); - } -} - } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/bucket_parameters.hpp b/src/mbgl/style/bucket_parameters.hpp index d5e05c5dd2d..d0edbcac303 100644 --- a/src/mbgl/style/bucket_parameters.hpp +++ b/src/mbgl/style/bucket_parameters.hpp @@ -2,33 +2,14 @@ #include #include -#include - -#include -#include namespace mbgl { - -class GeometryTileLayer; -class GeometryTileFeature; -class FeatureIndex; - namespace style { class BucketParameters { public: - const OverscaledTileID& tileID; - const std::atomic& obsolete; - FeatureIndex& featureIndex; + const OverscaledTileID tileID; const MapMode mode; - - bool cancelled() const { - return obsolete; - } - - void eachFilteredFeature(const Filter&, - const GeometryTileLayer&, - std::function); }; } // namespace style diff --git a/src/mbgl/style/conversion/stringify.hpp b/src/mbgl/style/conversion/stringify.hpp index d06b2f2814d..71755bd9d62 100644 --- a/src/mbgl/style/conversion/stringify.hpp +++ b/src/mbgl/style/conversion/stringify.hpp @@ -214,20 +214,131 @@ void stringify(Writer& writer, const Undefined&) { writer.Null(); } -template -void stringify(Writer& writer, const Function& f) { - writer.StartObject(); - writer.Key("base"); - writer.Double(f.getBase()); - writer.Key("stops"); - writer.StartArray(); - for (const auto& stop : f.getStops()) { +template +void stringify(Writer& writer, const CategoricalValue& v) { + CategoricalValue::visit(v, [&] (const auto& v_) { stringify(writer, v_); }); +} + +template +class StringifyStops { +public: + Writer& writer; + + template + void operator()(const ExponentialStops& f) { + writer.Key("type"); + writer.String("exponential"); + writer.Key("base"); + writer.Double(f.base); + writer.Key("stops"); + stringifyStops(f.stops); + } + + template + void operator()(const IntervalStops& f) { + writer.Key("type"); + writer.String("interval"); + writer.Key("stops"); + stringifyStops(f.stops); + } + + template + void operator()(const CategoricalStops& f) { + writer.Key("type"); + writer.String("categorical"); + writer.Key("stops"); + stringifyStops(f.stops); + } + + template + void operator()(const IdentityStops&) { + writer.Key("type"); + writer.String("identity"); + } + + template + void operator()(const std::map>& f) { + writer.Key("type"); + writer.String("exponential"); + if (!f.empty()) { + writer.Key("base"); + writer.Double(f.begin()->second.base); + } + writer.Key("stops"); + stringifyCompositeStops(f); + } + + template + void operator()(const std::map>& f) { + writer.Key("type"); + writer.String("interval"); + writer.Key("stops"); + stringifyCompositeStops(f); + } + + template + void operator()(const std::map>& f) { + writer.Key("type"); + writer.String("categorical"); + writer.Key("stops"); + stringifyCompositeStops(f); + } + +private: + template + void stringifyStops(const std::map& stops) { writer.StartArray(); - writer.Double(stop.first); - stringify(writer, stop.second); + for (const auto& stop : stops) { + writer.StartArray(); + stringify(writer, stop.first); + stringify(writer, stop.second); + writer.EndArray(); + } writer.EndArray(); } - writer.EndArray(); + + template + void stringifyCompositeStops(const std::map& stops) { + writer.StartArray(); + for (const auto& outer : stops) { + for (const auto& inner : outer.second.stops) { + writer.StartArray(); + writer.StartObject(); + writer.Key("zoom"); + writer.Double(outer.first); + writer.Key("value"); + stringify(writer, inner.first); + writer.EndObject(); + stringify(writer, inner.second); + writer.EndArray(); + } + } + writer.EndArray(); + } +}; + +template +void stringify(Writer& writer, const CameraFunction& f) { + writer.StartObject(); + CameraFunction::Stops::visit(f.stops, StringifyStops { writer }); + writer.EndObject(); +} + +template +void stringify(Writer& writer, const SourceFunction& f) { + writer.StartObject(); + writer.Key("property"); + writer.String(f.property); + SourceFunction::Stops::visit(f.stops, StringifyStops { writer }); + writer.EndObject(); +} + +template +void stringify(Writer& writer, const CompositeFunction& f) { + writer.StartObject(); + writer.Key("property"); + writer.String(f.property); + CompositeFunction::Stops::visit(f.stops, StringifyStops { writer }); writer.EndObject(); } @@ -238,7 +349,20 @@ void stringify(Writer& writer, const PropertyValue& v) { template void stringify(Writer& writer, const PropertyValue& value) { - if (value) { + if (!value.isUndefined()) { + writer.Key(Property::key); + stringify(writer, value); + } +} + +template +void stringify(Writer& writer, const DataDrivenPropertyValue& v) { + v.evaluate([&] (const auto& v_) { stringify(writer, v_); }); +} + +template +void stringify(Writer& writer, const DataDrivenPropertyValue& value) { + if (!value.isUndefined()) { writer.Key(Property::key); stringify(writer, value); } diff --git a/src/mbgl/style/cross_faded_property_evaluator.cpp b/src/mbgl/style/cross_faded_property_evaluator.cpp index 4de939576e1..796ca00bbfc 100644 --- a/src/mbgl/style/cross_faded_property_evaluator.cpp +++ b/src/mbgl/style/cross_faded_property_evaluator.cpp @@ -17,21 +17,10 @@ Faded CrossFadedPropertyEvaluator::operator()(const T& constant) const { } template -T getBiggestStopLessThan(const Function& function, float z) { - const auto& stops = function.getStops(); - for (uint32_t i = 0; i < stops.size(); i++) { - if (stops[i].first > z) { - return stops[i == 0 ? i : i - 1].second; - } - } - return stops.at(stops.size() - 1).second; -} - -template -Faded CrossFadedPropertyEvaluator::operator()(const Function& function) const { - return calculate(getBiggestStopLessThan(function, parameters.z - 1.0f), - getBiggestStopLessThan(function, parameters.z), - getBiggestStopLessThan(function, parameters.z + 1.0f)); +Faded CrossFadedPropertyEvaluator::operator()(const CameraFunction& function) const { + return calculate(function.evaluate(parameters.z - 1.0f), + function.evaluate(parameters.z), + function.evaluate(parameters.z + 1.0f)); } template diff --git a/src/mbgl/style/cross_faded_property_evaluator.hpp b/src/mbgl/style/cross_faded_property_evaluator.hpp index 70c8c0c978d..c5642f5cfb9 100644 --- a/src/mbgl/style/cross_faded_property_evaluator.hpp +++ b/src/mbgl/style/cross_faded_property_evaluator.hpp @@ -28,7 +28,7 @@ class CrossFadedPropertyEvaluator { Faded operator()(const Undefined&) const; Faded operator()(const T& constant) const; - Faded operator()(const Function&) const; + Faded operator()(const CameraFunction&) const; private: Faded calculate(const T& min, const T& mid, const T& max) const; diff --git a/src/mbgl/style/data_driven_property_evaluator.hpp b/src/mbgl/style/data_driven_property_evaluator.hpp new file mode 100644 index 00000000000..7a0ff9a0944 --- /dev/null +++ b/src/mbgl/style/data_driven_property_evaluator.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include + +namespace mbgl { +namespace style { + +template +class DataDrivenPropertyEvaluator { +public: + using ResultType = PossiblyEvaluatedPropertyValue; + + DataDrivenPropertyEvaluator(const PropertyEvaluationParameters& parameters_, T defaultValue_) + : parameters(parameters_), + defaultValue(std::move(defaultValue_)) {} + + ResultType operator()(const Undefined&) const { + return ResultType(defaultValue); + } + + ResultType operator()(const T& constant) const { + return ResultType(constant); + } + + ResultType operator()(const CameraFunction& function) const { + return ResultType(function.evaluate(parameters.z)); + } + + template + ResultType operator()(const Function& function) const { + return ResultType(function); + } + +private: + const PropertyEvaluationParameters& parameters; + T defaultValue; +}; + +} // namespace style +} // namespace mbgl diff --git a/src/mbgl/style/function.cpp b/src/mbgl/style/function.cpp deleted file mode 100644 index 02750c7d2e6..00000000000 --- a/src/mbgl/style/function.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include -#include -#include -#include - -#include - -namespace mbgl { -namespace style { - -template -T Function::evaluate(float z) const { - bool smaller = false; - float smaller_z = 0.0f; - T smaller_val = T(); - bool larger = false; - float larger_z = 0.0f; - T larger_val = T(); - - for (uint32_t i = 0; i < stops.size(); i++) { - float stop_z = stops[i].first; - T stop_val = stops[i].second; - if (stop_z <= z && (!smaller || smaller_z < stop_z)) { - smaller = true; - smaller_z = stop_z; - smaller_val = stop_val; - } - if (stop_z >= z && (!larger || larger_z > stop_z)) { - larger = true; - larger_z = stop_z; - larger_val = stop_val; - } - } - - if (smaller && larger) { - if (larger_z == smaller_z || larger_val == smaller_val) { - return smaller_val; - } - const float zoomDiff = larger_z - smaller_z; - const float zoomProgress = z - smaller_z; - if (base == 1.0f) { - const float t = zoomProgress / zoomDiff; - return util::interpolate(smaller_val, larger_val, t); - } else { - const float t = (std::pow(base, zoomProgress) - 1) / (std::pow(base, zoomDiff) - 1); - return util::interpolate(smaller_val, larger_val, t); - } - } else if (larger) { - return larger_val; - } else if (smaller) { - return smaller_val; - } else { - // No stop defined. - assert(false); - return T(); - } -} - -template class Function; -template class Function; -template class Function; -template class Function>; -template class Function>; -template class Function>; -template class Function>; - -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; -template class Function; - -} // namespace style -} // namespace mbgl diff --git a/src/mbgl/style/function/categorical_stops.cpp b/src/mbgl/style/function/categorical_stops.cpp new file mode 100644 index 00000000000..bcdf170f177 --- /dev/null +++ b/src/mbgl/style/function/categorical_stops.cpp @@ -0,0 +1,35 @@ +#include +#include + +#include + +namespace mbgl { +namespace style { + +optional categoricalValue(const Value& value) { + return value.match( + [] (bool t) { return optional(t); }, + [] (uint64_t t) { return optional(int64_t(t)); }, + [] (int64_t t) { return optional(t); }, + [] (double t) { return optional(int64_t(t)); }, + [] (const std::string& t) { return optional(t); }, + [] (const auto&) { return optional(); } + ); +} + +template +T CategoricalStops::evaluate(const Value& value) const { + auto v = categoricalValue(value); + if (!v) { + return defaultValue; + } + auto it = stops.find(*v); + return it == stops.end() ? defaultValue : it->second; +} + +template class CategoricalStops; +template class CategoricalStops; +template class CategoricalStops>; + +} // namespace style +} // namespace mbgl diff --git a/src/mbgl/style/function/identity_stops.cpp b/src/mbgl/style/function/identity_stops.cpp new file mode 100644 index 00000000000..e210b4d7739 --- /dev/null +++ b/src/mbgl/style/function/identity_stops.cpp @@ -0,0 +1,43 @@ +#include +#include + +#include + +namespace mbgl { +namespace style { + +template <> +float IdentityStops::evaluate(const Value& value) const { + return numericValue(value) + .value_or(0.0f); +} + +template <> +Color IdentityStops::evaluate(const Value& value) const { + if (!value.is()) { + return Color::black(); + } + + return Color::parse(value.get()) + .value_or(Color::black()); +} + +template <> +std::array IdentityStops>::evaluate(const Value& value) const { + if (!value.is>()) { + return {{ 0, 0 }}; + } + + const std::vector& vector = value.get>(); + if (vector.size() != 2 || !numericValue(vector[0]) || !numericValue(vector[1])) { + return {{ 0, 0 }}; + } + + return {{ + *numericValue(vector[0]), + *numericValue(vector[1]) + }}; +} + +} // namespace style +} // namespace mbgl diff --git a/src/mbgl/style/layer_impl.hpp b/src/mbgl/style/layer_impl.hpp index 0fea70c10b9..9b2bfe4d2ca 100644 --- a/src/mbgl/style/layer_impl.hpp +++ b/src/mbgl/style/layer_impl.hpp @@ -61,7 +61,7 @@ class Layer::Impl { // Returns true if any paint properties have active transitions. virtual bool evaluate(const PropertyEvaluationParameters&) = 0; - virtual std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const = 0; + virtual std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const = 0; // Checks whether this layer needs to be rendered in the given render pass. bool hasRenderPass(RenderPass) const; diff --git a/src/mbgl/style/layers/background_layer_impl.cpp b/src/mbgl/style/layers/background_layer_impl.cpp index 4a8fe39c9a1..f25ba9cfb49 100644 --- a/src/mbgl/style/layers/background_layer_impl.cpp +++ b/src/mbgl/style/layers/background_layer_impl.cpp @@ -16,7 +16,8 @@ bool BackgroundLayer::Impl::evaluate(const PropertyEvaluationParameters& paramet return paint.hasTransition(); } -std::unique_ptr BackgroundLayer::Impl::createBucket(BucketParameters&, const GeometryTileLayer&) const { +std::unique_ptr BackgroundLayer::Impl::createBucket(const BucketParameters&, const std::vector&) const { + assert(false); return nullptr; } diff --git a/src/mbgl/style/layers/background_layer_impl.hpp b/src/mbgl/style/layers/background_layer_impl.hpp index 4629217e6d3..02a8c423d66 100644 --- a/src/mbgl/style/layers/background_layer_impl.hpp +++ b/src/mbgl/style/layers/background_layer_impl.hpp @@ -16,7 +16,7 @@ class BackgroundLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) override; bool evaluate(const PropertyEvaluationParameters&) override; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const override; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const override; BackgroundPaintProperties paint; }; diff --git a/src/mbgl/style/layers/background_layer_properties.hpp b/src/mbgl/style/layers/background_layer_properties.hpp index 792bf3de949..fae6c26a4b0 100644 --- a/src/mbgl/style/layers/background_layer_properties.hpp +++ b/src/mbgl/style/layers/background_layer_properties.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace mbgl { namespace style { diff --git a/src/mbgl/style/layers/circle_layer.cpp b/src/mbgl/style/layers/circle_layer.cpp index 389ab934032..616da313cd9 100644 --- a/src/mbgl/style/layers/circle_layer.cpp +++ b/src/mbgl/style/layers/circle_layer.cpp @@ -65,60 +65,60 @@ const Filter& CircleLayer::getFilter() const { // Paint properties -PropertyValue CircleLayer::getDefaultCircleRadius() { +DataDrivenPropertyValue CircleLayer::getDefaultCircleRadius() { return { 5 }; } -PropertyValue CircleLayer::getCircleRadius(const optional& klass) const { +DataDrivenPropertyValue CircleLayer::getCircleRadius(const optional& klass) const { return impl->paint.get(klass); } -void CircleLayer::setCircleRadius(PropertyValue value, const optional& klass) { +void CircleLayer::setCircleRadius(DataDrivenPropertyValue value, const optional& klass) { if (value == getCircleRadius(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue CircleLayer::getDefaultCircleColor() { +DataDrivenPropertyValue CircleLayer::getDefaultCircleColor() { return { Color::black() }; } -PropertyValue CircleLayer::getCircleColor(const optional& klass) const { +DataDrivenPropertyValue CircleLayer::getCircleColor(const optional& klass) const { return impl->paint.get(klass); } -void CircleLayer::setCircleColor(PropertyValue value, const optional& klass) { +void CircleLayer::setCircleColor(DataDrivenPropertyValue value, const optional& klass) { if (value == getCircleColor(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue CircleLayer::getDefaultCircleBlur() { +DataDrivenPropertyValue CircleLayer::getDefaultCircleBlur() { return { 0 }; } -PropertyValue CircleLayer::getCircleBlur(const optional& klass) const { +DataDrivenPropertyValue CircleLayer::getCircleBlur(const optional& klass) const { return impl->paint.get(klass); } -void CircleLayer::setCircleBlur(PropertyValue value, const optional& klass) { +void CircleLayer::setCircleBlur(DataDrivenPropertyValue value, const optional& klass) { if (value == getCircleBlur(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue CircleLayer::getDefaultCircleOpacity() { +DataDrivenPropertyValue CircleLayer::getDefaultCircleOpacity() { return { 1 }; } -PropertyValue CircleLayer::getCircleOpacity(const optional& klass) const { +DataDrivenPropertyValue CircleLayer::getCircleOpacity(const optional& klass) const { return impl->paint.get(klass); } -void CircleLayer::setCircleOpacity(PropertyValue value, const optional& klass) { +void CircleLayer::setCircleOpacity(DataDrivenPropertyValue value, const optional& klass) { if (value == getCircleOpacity(klass)) return; impl->paint.set(value, klass); @@ -170,45 +170,45 @@ void CircleLayer::setCirclePitchScale(PropertyValue value, impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue CircleLayer::getDefaultCircleStrokeWidth() { +DataDrivenPropertyValue CircleLayer::getDefaultCircleStrokeWidth() { return { 0 }; } -PropertyValue CircleLayer::getCircleStrokeWidth(const optional& klass) const { +DataDrivenPropertyValue CircleLayer::getCircleStrokeWidth(const optional& klass) const { return impl->paint.get(klass); } -void CircleLayer::setCircleStrokeWidth(PropertyValue value, const optional& klass) { +void CircleLayer::setCircleStrokeWidth(DataDrivenPropertyValue value, const optional& klass) { if (value == getCircleStrokeWidth(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue CircleLayer::getDefaultCircleStrokeColor() { +DataDrivenPropertyValue CircleLayer::getDefaultCircleStrokeColor() { return { Color::black() }; } -PropertyValue CircleLayer::getCircleStrokeColor(const optional& klass) const { +DataDrivenPropertyValue CircleLayer::getCircleStrokeColor(const optional& klass) const { return impl->paint.get(klass); } -void CircleLayer::setCircleStrokeColor(PropertyValue value, const optional& klass) { +void CircleLayer::setCircleStrokeColor(DataDrivenPropertyValue value, const optional& klass) { if (value == getCircleStrokeColor(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue CircleLayer::getDefaultCircleStrokeOpacity() { +DataDrivenPropertyValue CircleLayer::getDefaultCircleStrokeOpacity() { return { 1 }; } -PropertyValue CircleLayer::getCircleStrokeOpacity(const optional& klass) const { +DataDrivenPropertyValue CircleLayer::getCircleStrokeOpacity(const optional& klass) const { return impl->paint.get(klass); } -void CircleLayer::setCircleStrokeOpacity(PropertyValue value, const optional& klass) { +void CircleLayer::setCircleStrokeOpacity(DataDrivenPropertyValue value, const optional& klass) { if (value == getCircleStrokeOpacity(klass)) return; impl->paint.set(value, klass); diff --git a/src/mbgl/style/layers/circle_layer_impl.cpp b/src/mbgl/style/layers/circle_layer_impl.cpp index 136522e41c4..655ad9b5b9b 100644 --- a/src/mbgl/style/layers/circle_layer_impl.cpp +++ b/src/mbgl/style/layers/circle_layer_impl.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -15,27 +14,22 @@ void CircleLayer::Impl::cascade(const CascadeParameters& parameters) { bool CircleLayer::Impl::evaluate(const PropertyEvaluationParameters& parameters) { paint.evaluate(parameters); - passes = (paint.evaluated.get() > 0 && paint.evaluated.get().a > 0 && paint.evaluated.get() > 0) + passes = (paint.evaluated.get().constantOr(1) > 0 + && paint.evaluated.get().constantOr(Color::black()).a > 0 + && paint.evaluated.get().constantOr(1) > 0) ? RenderPass::Translucent : RenderPass::None; return paint.hasTransition(); } -std::unique_ptr CircleLayer::Impl::createBucket(BucketParameters& parameters, const GeometryTileLayer& layer) const { - auto bucket = std::make_unique(parameters.mode); - - parameters.eachFilteredFeature(filter, layer, [&] (const auto& feature, std::size_t index, const std::string& layerName) { - auto geometries = feature.getGeometries(); - bucket->addGeometry(geometries); - parameters.featureIndex.insert(geometries, index, layerName, id); - }); - - return std::move(bucket); +std::unique_ptr CircleLayer::Impl::createBucket(const BucketParameters& parameters, const std::vector& layers) const { + return std::make_unique(parameters, layers); } float CircleLayer::Impl::getQueryRadius() const { const std::array& translate = paint.evaluated.get(); - return paint.evaluated.get() + util::length(translate[0], translate[1]); + return paint.evaluated.get().constantOr(CircleRadius::defaultValue()) + + util::length(translate[0], translate[1]); } bool CircleLayer::Impl::queryIntersectsGeometry( @@ -47,7 +41,7 @@ bool CircleLayer::Impl::queryIntersectsGeometry( auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( queryGeometry, paint.evaluated.get(), paint.evaluated.get(), bearing, pixelsToTileUnits); - auto circleRadius = paint.evaluated.get() * pixelsToTileUnits; + auto circleRadius = paint.evaluated.get().constantOr(CircleRadius::defaultValue()) * pixelsToTileUnits; return util::polygonIntersectsBufferedMultiPoint( translatedQueryGeometry.value_or(queryGeometry), geometry, circleRadius); diff --git a/src/mbgl/style/layers/circle_layer_impl.hpp b/src/mbgl/style/layers/circle_layer_impl.hpp index 744a56898ce..0f9611d589b 100644 --- a/src/mbgl/style/layers/circle_layer_impl.hpp +++ b/src/mbgl/style/layers/circle_layer_impl.hpp @@ -16,7 +16,7 @@ class CircleLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) override; bool evaluate(const PropertyEvaluationParameters&) override; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const override; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const override; float getQueryRadius() const override; bool queryIntersectsGeometry( diff --git a/src/mbgl/style/layers/circle_layer_properties.hpp b/src/mbgl/style/layers/circle_layer_properties.hpp index ea36b31949b..1cb4f5a635a 100644 --- a/src/mbgl/style/layers/circle_layer_properties.hpp +++ b/src/mbgl/style/layers/circle_layer_properties.hpp @@ -5,23 +5,24 @@ #include #include #include +#include namespace mbgl { namespace style { -struct CircleRadius : PaintProperty { +struct CircleRadius : DataDrivenPaintProperty { static float defaultValue() { return 5; } }; -struct CircleColor : PaintProperty { +struct CircleColor : DataDrivenPaintProperty { static Color defaultValue() { return Color::black(); } }; -struct CircleBlur : PaintProperty { +struct CircleBlur : DataDrivenPaintProperty { static float defaultValue() { return 0; } }; -struct CircleOpacity : PaintProperty { +struct CircleOpacity : DataDrivenPaintProperty { static float defaultValue() { return 1; } }; @@ -37,15 +38,15 @@ struct CirclePitchScale : PaintProperty { static CirclePitchScaleType defaultValue() { return CirclePitchScaleType::Map; } }; -struct CircleStrokeWidth : PaintProperty { +struct CircleStrokeWidth : DataDrivenPaintProperty { static float defaultValue() { return 0; } }; -struct CircleStrokeColor : PaintProperty { +struct CircleStrokeColor : DataDrivenPaintProperty { static Color defaultValue() { return Color::black(); } }; -struct CircleStrokeOpacity : PaintProperty { +struct CircleStrokeOpacity : DataDrivenPaintProperty { static float defaultValue() { return 1; } }; diff --git a/src/mbgl/style/layers/custom_layer_impl.cpp b/src/mbgl/style/layers/custom_layer_impl.cpp index cecd60a296d..379de25e8fe 100644 --- a/src/mbgl/style/layers/custom_layer_impl.cpp +++ b/src/mbgl/style/layers/custom_layer_impl.cpp @@ -70,7 +70,8 @@ bool CustomLayer::Impl::evaluate(const PropertyEvaluationParameters&) { return false; } -std::unique_ptr CustomLayer::Impl::createBucket(BucketParameters&, const GeometryTileLayer&) const { +std::unique_ptr CustomLayer::Impl::createBucket(const BucketParameters&, const std::vector&) const { + assert(false); return nullptr; } diff --git a/src/mbgl/style/layers/custom_layer_impl.hpp b/src/mbgl/style/layers/custom_layer_impl.hpp index 71fb46d0d91..33eb86828c0 100644 --- a/src/mbgl/style/layers/custom_layer_impl.hpp +++ b/src/mbgl/style/layers/custom_layer_impl.hpp @@ -32,7 +32,7 @@ class CustomLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) final {} bool evaluate(const PropertyEvaluationParameters&) final; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const final; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const final; CustomLayerInitializeFunction initializeFn = nullptr; CustomLayerRenderFunction renderFn = nullptr; diff --git a/src/mbgl/style/layers/fill_extrusion_layer.cpp b/src/mbgl/style/layers/fill_extrusion_layer.cpp index 34f0267d166..45f5cdb5ee7 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer.cpp +++ b/src/mbgl/style/layers/fill_extrusion_layer.cpp @@ -80,15 +80,15 @@ void FillExtrusionLayer::setFillExtrusionOpacity(PropertyValue value, con impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue FillExtrusionLayer::getDefaultFillExtrusionColor() { +DataDrivenPropertyValue FillExtrusionLayer::getDefaultFillExtrusionColor() { return { Color::black() }; } -PropertyValue FillExtrusionLayer::getFillExtrusionColor(const optional& klass) const { +DataDrivenPropertyValue FillExtrusionLayer::getFillExtrusionColor(const optional& klass) const { return impl->paint.get(klass); } -void FillExtrusionLayer::setFillExtrusionColor(PropertyValue value, const optional& klass) { +void FillExtrusionLayer::setFillExtrusionColor(DataDrivenPropertyValue value, const optional& klass) { if (value == getFillExtrusionColor(klass)) return; impl->paint.set(value, klass); @@ -140,30 +140,30 @@ void FillExtrusionLayer::setFillExtrusionPattern(PropertyValue valu impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue FillExtrusionLayer::getDefaultFillExtrusionHeight() { +DataDrivenPropertyValue FillExtrusionLayer::getDefaultFillExtrusionHeight() { return { 0 }; } -PropertyValue FillExtrusionLayer::getFillExtrusionHeight(const optional& klass) const { +DataDrivenPropertyValue FillExtrusionLayer::getFillExtrusionHeight(const optional& klass) const { return impl->paint.get(klass); } -void FillExtrusionLayer::setFillExtrusionHeight(PropertyValue value, const optional& klass) { +void FillExtrusionLayer::setFillExtrusionHeight(DataDrivenPropertyValue value, const optional& klass) { if (value == getFillExtrusionHeight(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue FillExtrusionLayer::getDefaultFillExtrusionBase() { +DataDrivenPropertyValue FillExtrusionLayer::getDefaultFillExtrusionBase() { return { 0 }; } -PropertyValue FillExtrusionLayer::getFillExtrusionBase(const optional& klass) const { +DataDrivenPropertyValue FillExtrusionLayer::getFillExtrusionBase(const optional& klass) const { return impl->paint.get(klass); } -void FillExtrusionLayer::setFillExtrusionBase(PropertyValue value, const optional& klass) { +void FillExtrusionLayer::setFillExtrusionBase(DataDrivenPropertyValue value, const optional& klass) { if (value == getFillExtrusionBase(klass)) return; impl->paint.set(value, klass); diff --git a/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp b/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp index ebe9009312a..a8098206440 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp +++ b/src/mbgl/style/layers/fill_extrusion_layer_impl.cpp @@ -11,7 +11,7 @@ bool FillExtrusionLayer::Impl::evaluate(const PropertyEvaluationParameters&) { return false; } -std::unique_ptr FillExtrusionLayer::Impl::createBucket(BucketParameters&, const GeometryTileLayer&) const { +std::unique_ptr FillExtrusionLayer::Impl::createBucket(const BucketParameters&, const std::vector&) const { return nullptr; } diff --git a/src/mbgl/style/layers/fill_extrusion_layer_impl.hpp b/src/mbgl/style/layers/fill_extrusion_layer_impl.hpp index 3dd8bb270a4..ed7ef747fb3 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer_impl.hpp +++ b/src/mbgl/style/layers/fill_extrusion_layer_impl.hpp @@ -16,7 +16,7 @@ class FillExtrusionLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) override; bool evaluate(const PropertyEvaluationParameters&) override; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const override; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const override; FillExtrusionPaintProperties paint; }; diff --git a/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp b/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp index a2d01199a56..c1dd3b079de 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp +++ b/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace mbgl { namespace style { @@ -13,7 +14,7 @@ struct FillExtrusionOpacity : PaintProperty { static float defaultValue() { return 1; } }; -struct FillExtrusionColor : PaintProperty { +struct FillExtrusionColor : DataDrivenPaintProperty { static Color defaultValue() { return Color::black(); } }; @@ -29,11 +30,11 @@ struct FillExtrusionPattern : CrossFadedPaintProperty { static std::string defaultValue() { return ""; } }; -struct FillExtrusionHeight : PaintProperty { +struct FillExtrusionHeight : DataDrivenPaintProperty { static float defaultValue() { return 0; } }; -struct FillExtrusionBase : PaintProperty { +struct FillExtrusionBase : DataDrivenPaintProperty { static float defaultValue() { return 0; } }; diff --git a/src/mbgl/style/layers/fill_layer.cpp b/src/mbgl/style/layers/fill_layer.cpp index b8fa8cad8b7..5c56ce7f8d1 100644 --- a/src/mbgl/style/layers/fill_layer.cpp +++ b/src/mbgl/style/layers/fill_layer.cpp @@ -80,45 +80,45 @@ void FillLayer::setFillAntialias(PropertyValue value, const optionalobserver->onLayerPaintPropertyChanged(*this); } -PropertyValue FillLayer::getDefaultFillOpacity() { +DataDrivenPropertyValue FillLayer::getDefaultFillOpacity() { return { 1 }; } -PropertyValue FillLayer::getFillOpacity(const optional& klass) const { +DataDrivenPropertyValue FillLayer::getFillOpacity(const optional& klass) const { return impl->paint.get(klass); } -void FillLayer::setFillOpacity(PropertyValue value, const optional& klass) { +void FillLayer::setFillOpacity(DataDrivenPropertyValue value, const optional& klass) { if (value == getFillOpacity(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue FillLayer::getDefaultFillColor() { +DataDrivenPropertyValue FillLayer::getDefaultFillColor() { return { Color::black() }; } -PropertyValue FillLayer::getFillColor(const optional& klass) const { +DataDrivenPropertyValue FillLayer::getFillColor(const optional& klass) const { return impl->paint.get(klass); } -void FillLayer::setFillColor(PropertyValue value, const optional& klass) { +void FillLayer::setFillColor(DataDrivenPropertyValue value, const optional& klass) { if (value == getFillColor(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue FillLayer::getDefaultFillOutlineColor() { +DataDrivenPropertyValue FillLayer::getDefaultFillOutlineColor() { return { {} }; } -PropertyValue FillLayer::getFillOutlineColor(const optional& klass) const { +DataDrivenPropertyValue FillLayer::getFillOutlineColor(const optional& klass) const { return impl->paint.get(klass); } -void FillLayer::setFillOutlineColor(PropertyValue value, const optional& klass) { +void FillLayer::setFillOutlineColor(DataDrivenPropertyValue value, const optional& klass) { if (value == getFillOutlineColor(klass)) return; impl->paint.set(value, klass); diff --git a/src/mbgl/style/layers/fill_layer_impl.cpp b/src/mbgl/style/layers/fill_layer_impl.cpp index 1ff26aa003c..c7c89f8c20d 100644 --- a/src/mbgl/style/layers/fill_layer_impl.cpp +++ b/src/mbgl/style/layers/fill_layer_impl.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -25,7 +24,9 @@ bool FillLayer::Impl::evaluate(const PropertyEvaluationParameters& parameters) { passes |= RenderPass::Translucent; } - if (!paint.evaluated.get().from.empty() || (paint.evaluated.get().a * paint.evaluated.get()) < 1.0f) { + if (!paint.unevaluated.get().isUndefined() + || paint.evaluated.get().constantOr(Color()).a < 1.0f + || paint.evaluated.get().constantOr(0) < 1.0f) { passes |= RenderPass::Translucent; } else { passes |= RenderPass::Opaque; @@ -34,16 +35,8 @@ bool FillLayer::Impl::evaluate(const PropertyEvaluationParameters& parameters) { return paint.hasTransition(); } -std::unique_ptr FillLayer::Impl::createBucket(BucketParameters& parameters, const GeometryTileLayer& layer) const { - auto bucket = std::make_unique(); - - parameters.eachFilteredFeature(filter, layer, [&] (const auto& feature, std::size_t index, const std::string& layerName) { - auto geometries = feature.getGeometries(); - bucket->addGeometry(geometries); - parameters.featureIndex.insert(geometries, index, layerName, id); - }); - - return std::move(bucket); +std::unique_ptr FillLayer::Impl::createBucket(const BucketParameters& parameters, const std::vector& layers) const { + return std::make_unique(parameters, layers); } float FillLayer::Impl::getQueryRadius() const { diff --git a/src/mbgl/style/layers/fill_layer_impl.hpp b/src/mbgl/style/layers/fill_layer_impl.hpp index 28e2fa7edc8..bd25a8bebf1 100644 --- a/src/mbgl/style/layers/fill_layer_impl.hpp +++ b/src/mbgl/style/layers/fill_layer_impl.hpp @@ -16,7 +16,7 @@ class FillLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) override; bool evaluate(const PropertyEvaluationParameters&) override; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const override; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const override; float getQueryRadius() const override; bool queryIntersectsGeometry( diff --git a/src/mbgl/style/layers/fill_layer_properties.hpp b/src/mbgl/style/layers/fill_layer_properties.hpp index b2d926c31e9..f44a18d0e03 100644 --- a/src/mbgl/style/layers/fill_layer_properties.hpp +++ b/src/mbgl/style/layers/fill_layer_properties.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace mbgl { namespace style { @@ -13,15 +14,15 @@ struct FillAntialias : PaintProperty { static bool defaultValue() { return true; } }; -struct FillOpacity : PaintProperty { +struct FillOpacity : DataDrivenPaintProperty { static float defaultValue() { return 1; } }; -struct FillColor : PaintProperty { +struct FillColor : DataDrivenPaintProperty { static Color defaultValue() { return Color::black(); } }; -struct FillOutlineColor : PaintProperty { +struct FillOutlineColor : DataDrivenPaintProperty { static Color defaultValue() { return {}; } }; diff --git a/src/mbgl/style/layers/layer.cpp.ejs b/src/mbgl/style/layers/layer.cpp.ejs index e730e3a29b9..4ffc275b1f1 100644 --- a/src/mbgl/style/layers/layer.cpp.ejs +++ b/src/mbgl/style/layers/layer.cpp.ejs @@ -86,15 +86,15 @@ const Filter& <%- camelize(type) %>Layer::getFilter() const { // Layout properties <% for (const property of layoutProperties) { -%> -PropertyValue<<%- propertyType(property) %>> <%- camelize(type) %>Layer::getDefault<%- camelize(property.name) %>() { +<%- propertyValueType(property) %> <%- camelize(type) %>Layer::getDefault<%- camelize(property.name) %>() { return <%- camelize(property.name) %>::defaultValue(); } -PropertyValue<<%- propertyType(property) %>> <%- camelize(type) %>Layer::get<%- camelize(property.name) %>() const { +<%- propertyValueType(property) %> <%- camelize(type) %>Layer::get<%- camelize(property.name) %>() const { return impl->layout.unevaluated.get<<%- camelize(property.name) %>>(); } -void <%- camelize(type) %>Layer::set<%- camelize(property.name) %>(PropertyValue<<%- propertyType(property) %>> value) { +void <%- camelize(type) %>Layer::set<%- camelize(property.name) %>(<%- propertyValueType(property) %> value) { if (value == get<%- camelize(property.name) %>()) return; impl->layout.unevaluated.get<<%- camelize(property.name) %>>() = value; @@ -104,15 +104,15 @@ void <%- camelize(type) %>Layer::set<%- camelize(property.name) %>(PropertyValue // Paint properties <% for (const property of paintProperties) { %> -PropertyValue<<%- propertyType(property) %>> <%- camelize(type) %>Layer::getDefault<%- camelize(property.name) %>() { +<%- propertyValueType(property) %> <%- camelize(type) %>Layer::getDefault<%- camelize(property.name) %>() { return { <%- defaultValue(property) %> }; } -PropertyValue<<%- propertyType(property) %>> <%- camelize(type) %>Layer::get<%- camelize(property.name) %>(const optional& klass) const { +<%- propertyValueType(property) %> <%- camelize(type) %>Layer::get<%- camelize(property.name) %>(const optional& klass) const { return impl->paint.get<<%- camelize(property.name) %>>(klass); } -void <%- camelize(type) %>Layer::set<%- camelize(property.name) %>(PropertyValue<<%- propertyType(property) %>> value, const optional& klass) { +void <%- camelize(type) %>Layer::set<%- camelize(property.name) %>(<%- propertyValueType(property) %> value, const optional& klass) { if (value == get<%- camelize(property.name) %>(klass)) return; impl->paint.set<<%- camelize(property.name) %>>(value, klass); diff --git a/src/mbgl/style/layers/layer_properties.hpp.ejs b/src/mbgl/style/layers/layer_properties.hpp.ejs index d18ad44efd8..2a736ca3889 100644 --- a/src/mbgl/style/layers/layer_properties.hpp.ejs +++ b/src/mbgl/style/layers/layer_properties.hpp.ejs @@ -10,22 +10,21 @@ #include #include #include +#include namespace mbgl { namespace style { <% for (const property of layoutProperties) { -%> -struct <%- camelize(property.name) %> : LayoutProperty<<%- propertyType(property) %>> { +struct <%- camelize(property.name) %> : <%- layoutPropertyType(property, type) %> { static constexpr const char * key = "<%- property.name %>"; - static <%- propertyType(property) %> defaultValue() { return <%- defaultValue(property) %>; } + static <%- evaluatedType(property) %> defaultValue() { return <%- defaultValue(property) %>; } }; <% } -%> <% for (const property of paintProperties) { -%> -struct <%- camelize(property.name) %> : <% -if (/-pattern$/.test(property.name) || property.name === 'line-dasharray') { -%>CrossFaded<% } -%>PaintProperty<<%- propertyType(property) %>> { - static <%- propertyType(property) %> defaultValue() { return <%- defaultValue(property) %>; } +struct <%- camelize(property.name) %> : <%- paintPropertyType(property, type) %> { + static <%- evaluatedType(property) %> defaultValue() { return <%- defaultValue(property) %>; } }; <% } -%> diff --git a/src/mbgl/style/layers/line_layer.cpp b/src/mbgl/style/layers/line_layer.cpp index 7f6c148cd19..2c039d690b2 100644 --- a/src/mbgl/style/layers/line_layer.cpp +++ b/src/mbgl/style/layers/line_layer.cpp @@ -122,30 +122,30 @@ void LineLayer::setLineRoundLimit(PropertyValue value) { // Paint properties -PropertyValue LineLayer::getDefaultLineOpacity() { +DataDrivenPropertyValue LineLayer::getDefaultLineOpacity() { return { 1 }; } -PropertyValue LineLayer::getLineOpacity(const optional& klass) const { +DataDrivenPropertyValue LineLayer::getLineOpacity(const optional& klass) const { return impl->paint.get(klass); } -void LineLayer::setLineOpacity(PropertyValue value, const optional& klass) { +void LineLayer::setLineOpacity(DataDrivenPropertyValue value, const optional& klass) { if (value == getLineOpacity(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue LineLayer::getDefaultLineColor() { +DataDrivenPropertyValue LineLayer::getDefaultLineColor() { return { Color::black() }; } -PropertyValue LineLayer::getLineColor(const optional& klass) const { +DataDrivenPropertyValue LineLayer::getLineColor(const optional& klass) const { return impl->paint.get(klass); } -void LineLayer::setLineColor(PropertyValue value, const optional& klass) { +void LineLayer::setLineColor(DataDrivenPropertyValue value, const optional& klass) { if (value == getLineColor(klass)) return; impl->paint.set(value, klass); @@ -197,45 +197,45 @@ void LineLayer::setLineWidth(PropertyValue value, const optionalobserver->onLayerPaintPropertyChanged(*this); } -PropertyValue LineLayer::getDefaultLineGapWidth() { +DataDrivenPropertyValue LineLayer::getDefaultLineGapWidth() { return { 0 }; } -PropertyValue LineLayer::getLineGapWidth(const optional& klass) const { +DataDrivenPropertyValue LineLayer::getLineGapWidth(const optional& klass) const { return impl->paint.get(klass); } -void LineLayer::setLineGapWidth(PropertyValue value, const optional& klass) { +void LineLayer::setLineGapWidth(DataDrivenPropertyValue value, const optional& klass) { if (value == getLineGapWidth(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue LineLayer::getDefaultLineOffset() { +DataDrivenPropertyValue LineLayer::getDefaultLineOffset() { return { 0 }; } -PropertyValue LineLayer::getLineOffset(const optional& klass) const { +DataDrivenPropertyValue LineLayer::getLineOffset(const optional& klass) const { return impl->paint.get(klass); } -void LineLayer::setLineOffset(PropertyValue value, const optional& klass) { +void LineLayer::setLineOffset(DataDrivenPropertyValue value, const optional& klass) { if (value == getLineOffset(klass)) return; impl->paint.set(value, klass); impl->observer->onLayerPaintPropertyChanged(*this); } -PropertyValue LineLayer::getDefaultLineBlur() { +DataDrivenPropertyValue LineLayer::getDefaultLineBlur() { return { 0 }; } -PropertyValue LineLayer::getLineBlur(const optional& klass) const { +DataDrivenPropertyValue LineLayer::getLineBlur(const optional& klass) const { return impl->paint.get(klass); } -void LineLayer::setLineBlur(PropertyValue value, const optional& klass) { +void LineLayer::setLineBlur(DataDrivenPropertyValue value, const optional& klass) { if (value == getLineBlur(klass)) return; impl->paint.set(value, klass); diff --git a/src/mbgl/style/layers/line_layer_impl.cpp b/src/mbgl/style/layers/line_layer_impl.cpp index 477579a43c1..ef0131e3d57 100644 --- a/src/mbgl/style/layers/line_layer_impl.cpp +++ b/src/mbgl/style/layers/line_layer_impl.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -20,31 +20,25 @@ bool LineLayer::Impl::evaluate(const PropertyEvaluationParameters& parameters) { paint.evaluate(parameters); - passes = (paint.evaluated.get() > 0 && paint.evaluated.get().a > 0 && paint.evaluated.get() > 0) + passes = (paint.evaluated.get().constantOr(1.0) > 0 + && paint.evaluated.get().constantOr(Color::black()).a > 0 + && paint.evaluated.get() > 0) ? RenderPass::Translucent : RenderPass::None; return paint.hasTransition(); } -std::unique_ptr LineLayer::Impl::createBucket(BucketParameters& parameters, const GeometryTileLayer& layer) const { - auto bucket = std::make_unique(parameters.tileID.overscaleFactor()); - - bucket->layout = layout.evaluate(PropertyEvaluationParameters(parameters.tileID.overscaledZ)); - - parameters.eachFilteredFeature(filter, layer, [&] (const auto& feature, std::size_t index, const std::string& layerName) { - auto geometries = feature.getGeometries(); - bucket->addGeometry(geometries); - parameters.featureIndex.insert(geometries, index, layerName, id); - }); - - return std::move(bucket); +std::unique_ptr LineLayer::Impl::createBucket(const BucketParameters& parameters, const std::vector& layers) const { + return std::make_unique(parameters, layers, layout); } float LineLayer::Impl::getLineWidth() const { - if (paint.evaluated.get() > 0) { - return paint.evaluated.get() + 2 * paint.evaluated.get(); + float lineWidth = paint.evaluated.get(); + float gapWidth = paint.evaluated.get().constantOr(0); + if (gapWidth) { + return gapWidth + 2 * lineWidth; } else { - return paint.evaluated.get(); + return lineWidth; } } @@ -80,7 +74,8 @@ optional offsetLine(const GeometryCollection& rings, const d float LineLayer::Impl::getQueryRadius() const { const std::array& translate = paint.evaluated.get(); - return getLineWidth() / 2.0 + std::abs(paint.evaluated.get()) + util::length(translate[0], translate[1]); + auto offset = paint.evaluated.get().constantOr(LineOffset::defaultValue()); + return getLineWidth() / 2.0 + std::abs(offset) + util::length(translate[0], translate[1]); } bool LineLayer::Impl::queryIntersectsGeometry( @@ -93,7 +88,9 @@ bool LineLayer::Impl::queryIntersectsGeometry( auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry( queryGeometry, paint.evaluated.get(), paint.evaluated.get(), bearing, pixelsToTileUnits); - auto offsetGeometry = offsetLine(geometry, paint.evaluated.get() * pixelsToTileUnits); + + auto offset = paint.evaluated.get().constantOr(LineOffset::defaultValue()); + auto offsetGeometry = offsetLine(geometry, offset * pixelsToTileUnits); return util::polygonIntersectsBufferedMultiLine( translatedQueryGeometry.value_or(queryGeometry), diff --git a/src/mbgl/style/layers/line_layer_impl.hpp b/src/mbgl/style/layers/line_layer_impl.hpp index 1955c019af2..67e793f2ea7 100644 --- a/src/mbgl/style/layers/line_layer_impl.hpp +++ b/src/mbgl/style/layers/line_layer_impl.hpp @@ -16,7 +16,7 @@ class LineLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) override; bool evaluate(const PropertyEvaluationParameters&) override; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const override; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const override; float getQueryRadius() const override; bool queryIntersectsGeometry( diff --git a/src/mbgl/style/layers/line_layer_properties.hpp b/src/mbgl/style/layers/line_layer_properties.hpp index 2ea7f6b125d..724026e3a64 100644 --- a/src/mbgl/style/layers/line_layer_properties.hpp +++ b/src/mbgl/style/layers/line_layer_properties.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace mbgl { namespace style { @@ -29,11 +30,11 @@ struct LineRoundLimit : LayoutProperty { static float defaultValue() { return 1; } }; -struct LineOpacity : PaintProperty { +struct LineOpacity : DataDrivenPaintProperty { static float defaultValue() { return 1; } }; -struct LineColor : PaintProperty { +struct LineColor : DataDrivenPaintProperty { static Color defaultValue() { return Color::black(); } }; @@ -49,15 +50,15 @@ struct LineWidth : PaintProperty { static float defaultValue() { return 1; } }; -struct LineGapWidth : PaintProperty { +struct LineGapWidth : DataDrivenPaintProperty { static float defaultValue() { return 0; } }; -struct LineOffset : PaintProperty { +struct LineOffset : DataDrivenPaintProperty> { static float defaultValue() { return 0; } }; -struct LineBlur : PaintProperty { +struct LineBlur : DataDrivenPaintProperty { static float defaultValue() { return 0; } }; diff --git a/src/mbgl/style/layers/raster_layer_impl.cpp b/src/mbgl/style/layers/raster_layer_impl.cpp index a78614aee9e..a667ccb5a87 100644 --- a/src/mbgl/style/layers/raster_layer_impl.cpp +++ b/src/mbgl/style/layers/raster_layer_impl.cpp @@ -16,7 +16,8 @@ bool RasterLayer::Impl::evaluate(const PropertyEvaluationParameters& parameters) return paint.hasTransition(); } -std::unique_ptr RasterLayer::Impl::createBucket(BucketParameters&, const GeometryTileLayer&) const { +std::unique_ptr RasterLayer::Impl::createBucket(const BucketParameters&, const std::vector&) const { + assert(false); return nullptr; } diff --git a/src/mbgl/style/layers/raster_layer_impl.hpp b/src/mbgl/style/layers/raster_layer_impl.hpp index 8e69c21ca8d..42985ce0f1a 100644 --- a/src/mbgl/style/layers/raster_layer_impl.hpp +++ b/src/mbgl/style/layers/raster_layer_impl.hpp @@ -16,7 +16,7 @@ class RasterLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) override; bool evaluate(const PropertyEvaluationParameters&) override; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const override; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const override; RasterPaintProperties paint; }; diff --git a/src/mbgl/style/layers/raster_layer_properties.hpp b/src/mbgl/style/layers/raster_layer_properties.hpp index caa6d0c58d0..219fe34d8ce 100644 --- a/src/mbgl/style/layers/raster_layer_properties.hpp +++ b/src/mbgl/style/layers/raster_layer_properties.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace mbgl { namespace style { diff --git a/src/mbgl/style/layers/symbol_layer.cpp b/src/mbgl/style/layers/symbol_layer.cpp index c9014e7ee73..94c47f48b76 100644 --- a/src/mbgl/style/layers/symbol_layer.cpp +++ b/src/mbgl/style/layers/symbol_layer.cpp @@ -217,15 +217,15 @@ void SymbolLayer::setIconImage(PropertyValue value) { impl->layout.unevaluated.get() = value; impl->observer->onLayerLayoutPropertyChanged(*this, "icon-image"); } -PropertyValue SymbolLayer::getDefaultIconRotate() { +DataDrivenPropertyValue SymbolLayer::getDefaultIconRotate() { return IconRotate::defaultValue(); } -PropertyValue SymbolLayer::getIconRotate() const { +DataDrivenPropertyValue SymbolLayer::getIconRotate() const { return impl->layout.unevaluated.get(); } -void SymbolLayer::setIconRotate(PropertyValue value) { +void SymbolLayer::setIconRotate(DataDrivenPropertyValue value) { if (value == getIconRotate()) return; impl->layout.unevaluated.get() = value; @@ -259,15 +259,15 @@ void SymbolLayer::setIconKeepUpright(PropertyValue value) { impl->layout.unevaluated.get() = value; impl->observer->onLayerLayoutPropertyChanged(*this, "icon-keep-upright"); } -PropertyValue> SymbolLayer::getDefaultIconOffset() { +DataDrivenPropertyValue> SymbolLayer::getDefaultIconOffset() { return IconOffset::defaultValue(); } -PropertyValue> SymbolLayer::getIconOffset() const { +DataDrivenPropertyValue> SymbolLayer::getIconOffset() const { return impl->layout.unevaluated.get(); } -void SymbolLayer::setIconOffset(PropertyValue> value) { +void SymbolLayer::setIconOffset(DataDrivenPropertyValue> value) { if (value == getIconOffset()) return; impl->layout.unevaluated.get() = value; diff --git a/src/mbgl/style/layers/symbol_layer_impl.cpp b/src/mbgl/style/layers/symbol_layer_impl.cpp index f058598f5f3..32547e465a2 100644 --- a/src/mbgl/style/layers/symbol_layer_impl.cpp +++ b/src/mbgl/style/layers/symbol_layer_impl.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include @@ -24,52 +24,17 @@ bool SymbolLayer::Impl::evaluate(const PropertyEvaluationParameters& parameters) return paint.hasTransition(); } -std::unique_ptr SymbolLayer::Impl::createBucket(BucketParameters&, const GeometryTileLayer&) const { +std::unique_ptr SymbolLayer::Impl::createBucket(const BucketParameters&, const std::vector&) const { assert(false); // Should be calling createLayout() instead. return nullptr; } -std::unique_ptr SymbolLayer::Impl::createLayout(BucketParameters& parameters, - const GeometryTileLayer& layer, - std::vector group) const { - PropertyEvaluationParameters p(parameters.tileID.overscaledZ); - SymbolLayoutProperties::Evaluated evaluated = layout.evaluate(p); - - if (evaluated.get() == AlignmentType::Auto) { - if (evaluated.get() == SymbolPlacementType::Line) { - evaluated.get() = AlignmentType::Map; - } else { - evaluated.get() = AlignmentType::Viewport; - } - } - - if (evaluated.get() == AlignmentType::Auto) { - if (evaluated.get() == SymbolPlacementType::Line) { - evaluated.get() = AlignmentType::Map; - } else { - evaluated.get() = AlignmentType::Viewport; - } - } - - // If unspecified `text-pitch-alignment` inherits `text-rotation-alignment` - if (evaluated.get() == AlignmentType::Auto) { - evaluated.get() = evaluated.get(); - } - - float textMaxSize = layout.evaluate(PropertyEvaluationParameters(18)); - - evaluated.get() = layout.evaluate(PropertyEvaluationParameters(p.z + 1)); - evaluated.get() = layout.evaluate(PropertyEvaluationParameters(p.z + 1)); - - return std::make_unique(std::move(group), - layer.getName(), - parameters.tileID.overscaleFactor(), - parameters.tileID.overscaledZ, - parameters.mode, +std::unique_ptr SymbolLayer::Impl::createLayout(const BucketParameters& parameters, + const std::vector& group, + const GeometryTileLayer& layer) const { + return std::make_unique(parameters, + group, layer, - filter, - evaluated, - textMaxSize, *spriteAtlas); } diff --git a/src/mbgl/style/layers/symbol_layer_impl.hpp b/src/mbgl/style/layers/symbol_layer_impl.hpp index db18da07e2a..c00c2b0bbac 100644 --- a/src/mbgl/style/layers/symbol_layer_impl.hpp +++ b/src/mbgl/style/layers/symbol_layer_impl.hpp @@ -50,9 +50,9 @@ class SymbolLayer::Impl : public Layer::Impl { void cascade(const CascadeParameters&) override; bool evaluate(const PropertyEvaluationParameters&) override; - std::unique_ptr createBucket(BucketParameters&, const GeometryTileLayer&) const override; - std::unique_ptr createLayout(BucketParameters&, const GeometryTileLayer&, - std::vector) const; + std::unique_ptr createBucket(const BucketParameters&, const std::vector&) const override; + std::unique_ptr createLayout(const BucketParameters&, const std::vector&, + const GeometryTileLayer&) const; SymbolPropertyValues iconPropertyValues(const SymbolLayoutProperties::Evaluated&) const; SymbolPropertyValues textPropertyValues(const SymbolLayoutProperties::Evaluated&) const; diff --git a/src/mbgl/style/layers/symbol_layer_properties.hpp b/src/mbgl/style/layers/symbol_layer_properties.hpp index f5fd6ce3df3..6663e6e0c57 100644 --- a/src/mbgl/style/layers/symbol_layer_properties.hpp +++ b/src/mbgl/style/layers/symbol_layer_properties.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace mbgl { namespace style { @@ -64,8 +65,8 @@ struct IconImage : LayoutProperty { static std::string defaultValue() { return ""; } }; -struct IconRotate : LayoutProperty { - static constexpr const char * key = "icon-rotate"; +struct IconRotate : DataDrivenLayoutProperty { + static constexpr const char * key = "icon-image"; static float defaultValue() { return 0; } }; @@ -79,7 +80,7 @@ struct IconKeepUpright : LayoutProperty { static bool defaultValue() { return false; } }; -struct IconOffset : LayoutProperty> { +struct IconOffset : DataDrivenLayoutProperty> { static constexpr const char * key = "icon-offset"; static std::array defaultValue() { return {{ 0, 0 }}; } }; diff --git a/src/mbgl/style/layout_property.hpp b/src/mbgl/style/layout_property.hpp index 6ea06ce5567..7ce2ecc7b87 100644 --- a/src/mbgl/style/layout_property.hpp +++ b/src/mbgl/style/layout_property.hpp @@ -1,6 +1,9 @@ #pragma once +#include +#include #include +#include #include namespace mbgl { @@ -11,11 +14,19 @@ class PropertyEvaluationParameters; template class LayoutProperty { public: - using EvaluatorType = PropertyEvaluator; using UnevaluatedType = PropertyValue; + using EvaluatorType = PropertyEvaluator; using EvaluatedType = T; }; +template +class DataDrivenLayoutProperty { +public: + using UnevaluatedType = DataDrivenPropertyValue; + using EvaluatorType = DataDrivenPropertyEvaluator; + using EvaluatedType = PossiblyEvaluatedPropertyValue; +}; + template class LayoutProperties { public: diff --git a/src/mbgl/style/paint_property.hpp b/src/mbgl/style/paint_property.hpp index 15df2a77c79..7ea230155bc 100644 --- a/src/mbgl/style/paint_property.hpp +++ b/src/mbgl/style/paint_property.hpp @@ -1,11 +1,15 @@ #pragma once #include +#include +#include #include #include +#include +#include #include #include -#include +#include #include #include #include @@ -15,17 +19,18 @@ #include namespace mbgl { + +class GeometryTileFeature; + namespace style { -template +template class UnevaluatedPaintProperty { public: - using Result = typename Evaluator::ResultType; - UnevaluatedPaintProperty() = default; - UnevaluatedPaintProperty(PropertyValue value_, - UnevaluatedPaintProperty prior_, + UnevaluatedPaintProperty(Value value_, + UnevaluatedPaintProperty prior_, TransitionOptions transition, TimePoint now) : begin(now + transition.delay.value_or(Duration::zero())), @@ -36,19 +41,20 @@ class UnevaluatedPaintProperty { } } - Result evaluate(const PropertyEvaluationParameters& parameters, T defaultValue) { - Result finalValue = value.evaluate(Evaluator(parameters, defaultValue)); + template + auto evaluate(const Evaluator& evaluator, TimePoint now) { + auto finalValue = value.evaluate(evaluator); if (!prior) { // No prior value. return finalValue; - } else if (parameters.now >= end) { + } else if (now >= end) { // Transition from prior value is now complete. prior = {}; return finalValue; } else { // Interpolate between recursively-calculated prior value and final. - float t = std::chrono::duration(parameters.now - begin) / (end - begin); - return util::interpolate(prior->get().evaluate(parameters, defaultValue), finalValue, util::DEFAULT_TRANSITION_EASE.solve(t, 0.001)); + float t = std::chrono::duration(now - begin) / (end - begin); + return util::interpolate(prior->get().evaluate(evaluator, now), finalValue, util::DEFAULT_TRANSITION_EASE.solve(t, 0.001)); } } @@ -60,27 +66,31 @@ class UnevaluatedPaintProperty { return value.isUndefined(); } + const Value& getValue() const { + return value; + } + private: - optional>> prior; + optional>> prior; TimePoint begin; TimePoint end; - PropertyValue value; + Value value; }; -template +template class CascadingPaintProperty { public: bool isUndefined() const { return values.find(ClassID::Default) == values.end(); } - const PropertyValue& get(const optional& klass) const { - static const PropertyValue staticValue; + const Value& get(const optional& klass) const { + static const Value staticValue{}; const auto it = values.find(klass ? ClassDictionary::Get().lookup(*klass) : ClassID::Default); return it == values.end() ? staticValue : it->second; } - void set(const PropertyValue& value_, const optional& klass) { + void set(const Value& value_, const optional& klass) { values[klass ? ClassDictionary::Get().lookup(*klass) : ClassID::Default] = value_; } @@ -91,7 +101,7 @@ class CascadingPaintProperty { template UnevaluatedPaintProperty cascade(const CascadeParameters& params, UnevaluatedPaintProperty prior) const { TransitionOptions transition; - PropertyValue value; + Value value; for (const auto classID : params.classes) { if (values.find(classID) != values.end()) { @@ -114,7 +124,7 @@ class CascadingPaintProperty { } private: - std::unordered_map> values; + std::unordered_map values; std::unordered_map transitions; }; @@ -122,26 +132,48 @@ template class PaintProperty { public: using ValueType = PropertyValue; - using CascadingType = CascadingPaintProperty; + using CascadingType = CascadingPaintProperty; + using UnevaluatedType = UnevaluatedPaintProperty; using EvaluatorType = PropertyEvaluator; - using UnevaluatedType = UnevaluatedPaintProperty; using EvaluatedType = T; + static constexpr bool IsDataDriven = false; +}; + +template +class DataDrivenPaintProperty { +public: + using ValueType = DataDrivenPropertyValue; + using CascadingType = CascadingPaintProperty; + using UnevaluatedType = UnevaluatedPaintProperty; + using EvaluatorType = DataDrivenPropertyEvaluator; + using EvaluatedType = PossiblyEvaluatedPropertyValue; + static constexpr bool IsDataDriven = true; + + using Type = T; + using Attribute = A; }; template class CrossFadedPaintProperty { public: using ValueType = PropertyValue; - using CascadingType = CascadingPaintProperty; + using CascadingType = CascadingPaintProperty; + using UnevaluatedType = UnevaluatedPaintProperty; using EvaluatorType = CrossFadedPropertyEvaluator; - using UnevaluatedType = UnevaluatedPaintProperty; using EvaluatedType = Faded; + static constexpr bool IsDataDriven = false; }; +template +struct IsDataDriven : std::integral_constant {}; + template class PaintProperties { public: using Properties = TypeList; + using DataDrivenProperties = FilteredTypeList; + using Binders = PaintPropertyBinders; + using EvaluatedTypes = TypeList; using UnevaluatedTypes = TypeList; using CascadingTypes = TypeList; @@ -183,7 +215,9 @@ class PaintProperties { template auto evaluate(const PropertyEvaluationParameters& parameters) { - return unevaluated.template get

().evaluate(parameters, P::defaultValue()); + using Evaluator = typename P::EvaluatorType; + return unevaluated.template get

() + .evaluate(Evaluator(parameters, P::defaultValue()), parameters.now); } void evaluate(const PropertyEvaluationParameters& parameters) { diff --git a/src/mbgl/style/paint_property_binder.hpp b/src/mbgl/style/paint_property_binder.hpp new file mode 100644 index 00000000000..964f33d2ec9 --- /dev/null +++ b/src/mbgl/style/paint_property_binder.hpp @@ -0,0 +1,283 @@ +#pragma once + +#include +#include +#include +#include + +namespace mbgl { +namespace style { + +template +class ConstantPaintPropertyBinder { +public: + using Attribute = A; + using AttributeValue = typename Attribute::Value; + using AttributeBinding = typename Attribute::Binding; + + ConstantPaintPropertyBinder(T constant_) + : constant(std::move(constant_)) { + } + + void populateVertexVector(const GeometryTileFeature&, std::size_t) {} + void upload(gl::Context&) {} + + AttributeBinding minAttributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const { + return typename Attribute::ConstantBinding { + Attribute::value(currentValue.constantOr(constant)) + }; + } + + AttributeBinding maxAttributeBinding(const PossiblyEvaluatedPropertyValue&) const { + return AttributeBinding(); + } + + float interpolationFactor(float) const { + return 0.0f; + } + +private: + T constant; +}; + +template +class SourceFunctionPaintPropertyBinder { +public: + using Attribute = A; + using AttributeValue = typename Attribute::Value; + using AttributeBinding = typename Attribute::Binding; + + using Attributes = gl::Attributes; + using Vertex = typename Attributes::Vertex; + + SourceFunctionPaintPropertyBinder(SourceFunction function_) + : function(std::move(function_)) { + } + + void populateVertexVector(const GeometryTileFeature& feature, std::size_t length) { + AttributeValue value = Attribute::value(function.evaluate(feature)); + for (std::size_t i = vertexVector.vertexSize(); i < length; ++i) { + vertexVector.emplace_back(Vertex { value }); + } + } + + void upload(gl::Context& context) { + vertexBuffer = context.createVertexBuffer(std::move(vertexVector)); + } + + AttributeBinding minAttributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const { + if (currentValue.isConstant()) { + return typename Attribute::ConstantBinding { + Attribute::value(*currentValue.constant()) + }; + } else { + return Attributes::allVariableBindings(*vertexBuffer) + .template get(); + } + } + + AttributeBinding maxAttributeBinding(const PossiblyEvaluatedPropertyValue&) const { + return AttributeBinding(); + } + + float interpolationFactor(float) const { + return 0.0f; + } + +private: + SourceFunction function; + gl::VertexVector vertexVector; + optional> vertexBuffer; +}; + +template +class CompositeFunctionPaintPropertyBinder { +public: + using Attribute = A; + using AttributeValue = typename Attribute::Value; + using AttributeBinding = typename Attribute::Binding; + + using MinAttribute = attributes::Min; + using MaxAttribute = attributes::Max; + + using Attributes = gl::Attributes; + using Vertex = typename Attributes::Vertex; + + CompositeFunctionPaintPropertyBinder(CompositeFunction function_, float zoom) + : function(std::move(function_)), + coveringRanges(function.coveringRanges(zoom)) { + } + + void populateVertexVector(const GeometryTileFeature& feature, std::size_t length) { + Range range = function.evaluate(std::get<1>(coveringRanges), feature); + AttributeValue min = Attribute::value(range.min); + AttributeValue max = Attribute::value(range.max); + for (std::size_t i = vertexVector.vertexSize(); i < length; ++i) { + vertexVector.emplace_back(Vertex { min, max }); + } + } + + void upload(gl::Context& context) { + vertexBuffer = context.createVertexBuffer(std::move(vertexVector)); + } + + AttributeBinding minAttributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const { + if (currentValue.isConstant()) { + return typename Attribute::ConstantBinding { + Attribute::value(*currentValue.constant()) + }; + } else { + return Attributes::allVariableBindings(*vertexBuffer) + .template get(); + } + } + + AttributeBinding maxAttributeBinding(const PossiblyEvaluatedPropertyValue& currentValue) const { + if (currentValue.isConstant()) { + return AttributeBinding(); + } else { + return Attributes::allVariableBindings(*vertexBuffer) + .template get(); + } + } + + float interpolationFactor(float currentZoom) const { + return util::interpolationFactor(1.0f, std::get<0>(coveringRanges), currentZoom); + } + +private: + using InnerStops = typename CompositeFunction::InnerStops; + CompositeFunction function; + std::tuple, Range> coveringRanges; + gl::VertexVector vertexVector; + optional> vertexBuffer; +}; + +template +class PaintPropertyBinder { +public: + using Type = typename PaintProperty::Type; + using Attribute = typename PaintProperty::Attribute; + using PropertyValue = typename PaintProperty::EvaluatedType; + + using Binder = variant< + ConstantPaintPropertyBinder, + SourceFunctionPaintPropertyBinder, + CompositeFunctionPaintPropertyBinder>; + + PaintPropertyBinder(const PropertyValue& value, float zoom) + : binder(value.match( + [&] (const Type& constant) -> Binder { + return ConstantPaintPropertyBinder(constant); + }, + [&] (const SourceFunction& function) { + return SourceFunctionPaintPropertyBinder(function); + }, + [&] (const CompositeFunction& function) { + return CompositeFunctionPaintPropertyBinder(function, zoom); + } + )) { + } + + void populateVertexVector(const GeometryTileFeature& feature, std::size_t length) { + binder.match([&] (auto& b) { + b.populateVertexVector(feature, length); + }); + } + + void upload(gl::Context& context) { + binder.match([&] (auto& b) { + b.upload(context); + }); + } + + using MinAttribute = attributes::Min; + using MaxAttribute = attributes::Max; + using AttributeBinding = typename Attribute::Binding; + + AttributeBinding minAttributeBinding(const PropertyValue& currentValue) const { + return binder.match([&] (const auto& b) { + return b.minAttributeBinding(currentValue); + }); + } + + AttributeBinding maxAttributeBinding(const PropertyValue& currentValue) const { + return binder.match([&] (const auto& b) { + return b.maxAttributeBinding(currentValue); + }); + } + + using InterpolationUniform = attributes::InterpolationUniform; + using InterpolationUniformValue = typename InterpolationUniform::Value; + + InterpolationUniformValue interpolationUniformValue(float currentZoom) const { + return InterpolationUniformValue { + binder.match([&] (const auto& b) { + return b.interpolationFactor(currentZoom); + }) + }; + } + +private: + Binder binder; +}; + +template +class PaintPropertyBinders; + +template +class PaintPropertyBinders> { +public: + using Binders = IndexedTuple, TypeList...>>; + + template + PaintPropertyBinders(const EvaluatedProperties& properties, float z) + : binders(PaintPropertyBinder(properties.template get(), z)...) { + (void)z; // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56958 + } + + void populateVertexVectors(const GeometryTileFeature& feature, std::size_t length) { + util::ignore({ + (binders.template get().populateVertexVector(feature, length), 0)... + }); + } + + void upload(gl::Context& context) { + util::ignore({ + (binders.template get().upload(context), 0)... + }); + } + + using MinAttributes = gl::Attributes::MinAttribute...>; + using MaxAttributes = gl::Attributes::MaxAttribute...>; + + using Attributes = gl::ConcatenateAttributes; + using AttributeBindings = typename Attributes::Bindings; + + template + AttributeBindings attributeBindings(const EvaluatedProperties& currentProperties) const { + const typename MinAttributes::Bindings min { + binders.template get().minAttributeBinding(currentProperties.template get())... + }; + const typename MaxAttributes::Bindings max { + binders.template get().maxAttributeBinding(currentProperties.template get())... + }; + return min.concat(max); + } + + using Uniforms = gl::Uniforms::InterpolationUniform...>; + using UniformValues = typename Uniforms::Values; + + UniformValues uniformValues(float currentZoom) const { + (void)currentZoom; // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56958 + return UniformValues { + binders.template get().interpolationUniformValue(currentZoom)... + }; + } + +private: + Binders binders; +}; + +} // namespace style +} // namespace mbgl diff --git a/src/mbgl/style/parser.cpp b/src/mbgl/style/parser.cpp index c6c6e50dd7c..926c2437337 100644 --- a/src/mbgl/style/parser.cpp +++ b/src/mbgl/style/parser.cpp @@ -241,10 +241,14 @@ std::vector Parser::fontStacks() const { result.insert({"Open Sans Regular", "Arial Unicode MS Regular"}); } else if (textFont.isConstant()) { result.insert(textFont.asConstant()); - } else if (textFont.isFunction()) { - for (const auto& stop : textFont.asFunction().getStops()) { - result.insert(stop.second); - } + } else if (textFont.isCameraFunction()) { + textFont.asCameraFunction().stops.match( + [&] (const auto& stops) { + for (const auto& stop : stops.stops) { + result.insert(stop.second); + } + } + ); } } } diff --git a/src/mbgl/style/possibly_evaluated_property_value.hpp b/src/mbgl/style/possibly_evaluated_property_value.hpp new file mode 100644 index 00000000000..bb917442f6e --- /dev/null +++ b/src/mbgl/style/possibly_evaluated_property_value.hpp @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include +#include + +namespace mbgl { + +class GeometryTileFeature; + +namespace style { + +template +class PossiblyEvaluatedPropertyValue { +private: + using Value = variant< + T, + SourceFunction, + CompositeFunction>; + + Value value; + +public: + PossiblyEvaluatedPropertyValue() = default; + PossiblyEvaluatedPropertyValue(Value v) : value(std::move(v)) {} + + bool isConstant() const { + return value.template is(); + } + + optional constant() const { + return value.match( + [&] (const T& t) { return optional(t); }, + [&] (const auto&) { return optional(); }); + } + + T constantOr(const T& t) const { + return constant().value_or(t); + } + + template + auto match(Ts&&... ts) const { + return value.match(std::forward(ts)...); + } + + T evaluate(float z, const GeometryTileFeature& feature) const { + return value.match( + [&] (const T& t) { return t; }, + [&] (const SourceFunction& t) { return t.evaluate(feature); }, + [&] (const CompositeFunction& t) { return t.evaluate(z, feature); }); + } +}; + +} // namespace style + +namespace util { + +template +struct Interpolator> { + style::PossiblyEvaluatedPropertyValue operator()(const style::PossiblyEvaluatedPropertyValue& a, + const style::PossiblyEvaluatedPropertyValue& b, + const double t) const { + if (a.isConstant() && b.isConstant()) { + return { interpolate(*a.constant(), *b.constant(), t) }; + } else { + return { a }; + } + } +}; + +} // namespace util + +} // namespace mbgl diff --git a/src/mbgl/style/property_evaluator.hpp b/src/mbgl/style/property_evaluator.hpp index ca4962d9482..3f629ada4f7 100644 --- a/src/mbgl/style/property_evaluator.hpp +++ b/src/mbgl/style/property_evaluator.hpp @@ -17,7 +17,7 @@ class PropertyEvaluator { T operator()(const Undefined&) const { return defaultValue; } T operator()(const T& constant) const { return constant; } - T operator()(const Function& fn) const { return fn.evaluate(parameters.z); } + T operator()(const CameraFunction& fn) const { return fn.evaluate(parameters.z); } private: const PropertyEvaluationParameters& parameters; diff --git a/src/mbgl/text/quads.cpp b/src/mbgl/text/quads.cpp index 1a05e6f94f2..10c4dfea90a 100644 --- a/src/mbgl/text/quads.cpp +++ b/src/mbgl/text/quads.cpp @@ -62,7 +62,7 @@ SymbolQuads getIconQuads(Anchor& anchor, const PositionedIcon& shapedIcon, bl = {left, bottom}; } - float angle = layout.get() * util::DEG2RAD; + float angle = shapedIcon.angle; if (placement == style::SymbolPlacementType::Line) { assert(static_cast(anchor.segment) < line.size()); const GeometryCoordinate &prev= line[anchor.segment]; diff --git a/src/mbgl/text/shaping.cpp b/src/mbgl/text/shaping.cpp index 062066aaf4f..b43ba0220ce 100644 --- a/src/mbgl/text/shaping.cpp +++ b/src/mbgl/text/shaping.cpp @@ -1,19 +1,18 @@ #include -#include +#include namespace mbgl { -using namespace style; - -PositionedIcon shapeIcon(const SpriteAtlasElement& image, const SymbolLayoutProperties::Evaluated& layout) { - float dx = layout.get()[0]; - float dy = layout.get()[1]; +PositionedIcon shapeIcon(const SpriteAtlasElement& image, + const SymbolFeature& feature) { + float dx = feature.iconOffset[0]; + float dy = feature.iconOffset[1]; float x1 = dx - image.spriteImage->getWidth() / 2.0f; float x2 = x1 + image.spriteImage->getWidth(); float y1 = dy - image.spriteImage->getHeight() / 2.0f; float y2 = y1 + image.spriteImage->getHeight(); - return PositionedIcon(image, y1, y2, x1, x2); + return PositionedIcon(image, y1, y2, x1, x2, feature.iconRotation); } } // namespace mbgl diff --git a/src/mbgl/text/shaping.hpp b/src/mbgl/text/shaping.hpp index 30375179b6b..b0e6ae3b1dd 100644 --- a/src/mbgl/text/shaping.hpp +++ b/src/mbgl/text/shaping.hpp @@ -3,29 +3,40 @@ #include #include #include -#include #include namespace mbgl { class SpriteAtlasElement; +class SymbolFeature; class PositionedIcon { - public: - explicit PositionedIcon() {} - explicit PositionedIcon(const SpriteAtlasElement& _image, - float _top, float _bottom, float _left, float _right) : - image(_image), top(_top), bottom(_bottom), left(_left), right(_right) {} - - optional image; - float top = 0; - float bottom = 0; - float left = 0; - float right = 0; - - explicit operator bool() const { return image && (*image).pos.hasArea(); } +public: + PositionedIcon() = default; + PositionedIcon(const SpriteAtlasElement& image_, + float top_, + float bottom_, + float left_, + float right_, + float angle_) + : image(image_), + top(top_), + bottom(bottom_), + left(left_), + right(right_), + angle(angle_) {} + + optional image; + float top = 0; + float bottom = 0; + float left = 0; + float right = 0; + float angle = 0; + + explicit operator bool() const { return image && (*image).pos.hasArea(); } }; -PositionedIcon shapeIcon(const SpriteAtlasElement& image, const style::SymbolLayoutProperties::Evaluated&); +PositionedIcon shapeIcon(const SpriteAtlasElement&, + const SymbolFeature&); } // namespace mbgl diff --git a/src/mbgl/tile/geometry_tile_worker.cpp b/src/mbgl/tile/geometry_tile_worker.cpp index 2a86b7fedaf..b1fd7a852e5 100644 --- a/src/mbgl/tile/geometry_tile_worker.cpp +++ b/src/mbgl/tile/geometry_tile_worker.cpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -212,7 +214,7 @@ void GeometryTileWorker::redoLayout() { std::unordered_map> symbolLayoutMap; std::unordered_map> buckets; auto featureIndex = std::make_unique(); - BucketParameters parameters { id, obsolete, *featureIndex, mode }; + BucketParameters parameters { id, mode }; std::vector> groups = groupByLayout(*layers); for (auto& group : groups) { @@ -240,12 +242,27 @@ void GeometryTileWorker::redoLayout() { if (leader.is()) { symbolLayoutMap.emplace(leader.getID(), - leader.as()->impl->createLayout(parameters, *geometryLayer, layerIDs)); + leader.as()->impl->createLayout(parameters, group, *geometryLayer)); } else { - std::shared_ptr bucket = leader.baseImpl->createBucket(parameters, *geometryLayer); + const Filter& filter = leader.baseImpl->filter; + const std::string& sourceLayerID = leader.baseImpl->sourceLayer; + std::shared_ptr bucket = leader.baseImpl->createBucket(parameters, group); + + for (std::size_t i = 0; !obsolete && i < geometryLayer->featureCount(); i++) { + std::unique_ptr feature = geometryLayer->getFeature(i); + + if (!filter(feature->getType(), feature->getID(), [&] (const auto& key) { return feature->getValue(key); })) + continue; + + GeometryCollection geometries = feature->getGeometries(); + bucket->addFeature(*feature, geometries); + featureIndex->insert(geometries, i, sourceLayerID, leader.getID()); + } + if (!bucket->hasData()) { continue; } + for (const auto& layer : group) { buckets.emplace(layer->getID(), bucket); } @@ -324,8 +341,8 @@ void GeometryTileWorker::attemptPlacement() { } std::shared_ptr bucket = symbolLayout->place(*collisionTile); - for (const auto& layerID : symbolLayout->layerIDs) { - buckets.emplace(layerID, bucket); + for (const auto& pair : symbolLayout->layerPaintProperties) { + buckets.emplace(pair.first, bucket); } } diff --git a/src/mbgl/util/ignore.hpp b/src/mbgl/util/ignore.hpp index 955b1de2fae..577bcf4d910 100644 --- a/src/mbgl/util/ignore.hpp +++ b/src/mbgl/util/ignore.hpp @@ -19,5 +19,8 @@ template void ignore(Ts&&...) {} // template void ignore(const std::initializer_list&) {} +// Handle the zero-argument case. +inline void ignore(const std::initializer_list&) {} + } // namespace util } // namespace mbgl diff --git a/src/mbgl/util/indexed_tuple.hpp b/src/mbgl/util/indexed_tuple.hpp index 110e7dce12b..a414639530d 100644 --- a/src/mbgl/util/indexed_tuple.hpp +++ b/src/mbgl/util/indexed_tuple.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include @@ -14,8 +16,6 @@ struct TypeIndex : std::integral_constant {}; template struct TypeIndex : std::integral_constant::value> {}; -template class TypeList {}; - template class IndexedTuple; // A tuple of Ts, where individual members can be accessed via `t.get()` for I ∈ Is. @@ -42,6 +42,15 @@ class IndexedTuple, TypeList> : public std::tuple const auto& get() const { return std::get>(*this); } + + template + IndexedTuple, TypeList> + concat(const IndexedTuple, TypeList>& other) const { + return IndexedTuple, TypeList> { + get()..., + other.template get()... + }; + } }; } // namespace mbgl diff --git a/src/mbgl/util/interpolate.cpp b/src/mbgl/util/interpolate.cpp new file mode 100644 index 00000000000..306a5c6630d --- /dev/null +++ b/src/mbgl/util/interpolate.cpp @@ -0,0 +1,19 @@ +#include + +#include + +namespace mbgl { +namespace util { + +float interpolationFactor(float base, Range range, float z) { + const float zoomDiff = range.max - range.min; + const float zoomProgress = z - range.min; + if (base == 1.0f) { + return zoomProgress / zoomDiff; + } else { + return (std::pow(base, zoomProgress) - 1) / (std::pow(base, zoomDiff) - 1); + } +} + +} // namespace util +} // namespace mbgl diff --git a/src/mbgl/util/interpolate.hpp b/src/mbgl/util/interpolate.hpp index ef066377dae..d463ffc056a 100644 --- a/src/mbgl/util/interpolate.hpp +++ b/src/mbgl/util/interpolate.hpp @@ -1,15 +1,19 @@ #pragma once +#include +#include + #include #include #include #include #include -#include namespace mbgl { namespace util { +float interpolationFactor(float base, Range range, float z); + template struct Interpolator; @@ -78,5 +82,8 @@ template struct Interpolator> : Uninterpolated {}; +template +constexpr bool Interpolatable = !std::is_base_of>::value; + } // namespace util } // namespace mbgl diff --git a/src/mbgl/util/type_list.hpp b/src/mbgl/util/type_list.hpp new file mode 100644 index 00000000000..4a5e95c8a44 --- /dev/null +++ b/src/mbgl/util/type_list.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +namespace mbgl { + +template +class TypeList {}; + +namespace detail { + +template +struct TypeCons; + +template +struct TypeCons> { + using Type = TypeList; +}; + +template class> +struct TypeFilter; + +template