diff options
96 files changed, 985 insertions, 525 deletions
diff --git a/.travis.yml b/.travis.yml index 058d4e8c74..653b61037e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,11 +19,13 @@ matrix: env: global: - - secure: "bG4YYWMfl9API0MSRgmOaJrlGLv06tRg9KJNawBieZvBJbITPpxVGJZT3/l/SEJ+Rl15e2dRex4k+MGQlmT2SqPQxTEYWv1qxNigKPPcla7IWeNmWWqW8uVvFjdglojgBOK2k/xErVQtA4zDfi3mwSXH4DKwquXWsoEKmX2SV7M=" - - secure: "Cbvap9ubVKgjPe3hUhI6JGeDZzBXHpOG9RaYKh+SdoIPhKnlJiNOYm1egomi+e4uqJInlFKuVHTw7Ng9Cun6Zm0jIxpkSchv1GpsR7hmB3UGnGed19Dw8121FwuUaktN+4YnbVlsyd+u8EHD3+h58t4eELrLrZolM4rS7DL6caA=" + - secure: "HPlPuLk531F7bCyADMcxQ+I1CfGhJlhX9A3q3auNCdLsjqaZbktaCIGuq4R1IPZz0UTtO8RfrTfVaoktyZdq2QyU3iD8oj6BeZ/Jypr4TCBJxI5IeyU3gyPMFHqUYIJuHL9k40Xu7Dhf4HT123zr8KoeVqCHauZP1/TumA0nezg=" + - secure: "R/+uOeccl7GqjJbknailAV7VtjAtGwHHM9xToVnhfPVUXp9fzJs+oNk3IWcs3Eg4sw4WsYxXRfbCQG9bA3MnPlTOsxETGRioO9CAuXap6mwcwNAzeWuq7ePFki2u01pJGQD5b6WFqBCdnAQ4o2SgHgGzhs0TJzYd9tONQxSmkCI=" - secure: "RiBIBfVhhaMjU5ksuwJO3shdvG9FpinBjdSv4co9jg9171SR8edNriedHjVKSIeBhSGNmZmX+twS3dJS/By6tl/LKh9sTynA+ZAYYljkE7jn881B/gMrlYvdAA6og5KvkhV1/0iJWlhuZrMTkhpDR200iLgg3EWBhWjltzmDW/I=" + - AWS_S3_BUCKET: 'node-mapbox-gl-native' before_install: +- source ./scripts/travis_helper.sh - source ./scripts/flags.sh - (git clone https://github.com/mapbox/mason.git ~/.mason ; sudo ln -s ~/.mason/mason /usr/local/bin/mason) - ./scripts/travis_before_install.sh @@ -31,6 +33,11 @@ before_install: install: - make config.gypi - ./scripts/travis_install_test_suite.sh +- ulimit -c + +before_script: + # Set the core file limit to unlimited so a core file is generated upon crash + - ulimit -c unlimited -S script: - ./scripts/travis_script.sh @@ -104,5 +104,5 @@ clean: clear_xcode_cache distclean: clean -rm -rf ./mason_packages -.PHONY: mbgl test linux clear_xcode_cache build/test/Makefile +.PHONY: mbgl test linux clear_xcode_cache build/test/Makefile clean distclean # DO NOT DELETE diff --git a/common.gypi b/common.gypi index 97481c1bb2..89a82fbdb9 100644 --- a/common.gypi +++ b/common.gypi @@ -1,17 +1,27 @@ { 'target_defaults': { 'default_configuration': 'Release', - 'xcode_settings': { - 'CLANG_CXX_LIBRARY': 'libc++', - 'CLANG_CXX_LANGUAGE_STANDARD':'c++11', - 'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0', - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', - 'GCC_ENABLE_CPP_RTTI':'YES', - 'OTHER_CPLUSPLUSFLAGS': [ '-Wall', '-Wextra', '-Wno-variadic-macros' ], - 'GCC_WARN_PEDANTIC': 'YES', - 'GCC_WARN_UNINITIALIZED_AUTOS': 'YES_AGGRESSIVE' - }, - 'cflags_cc': ['-std=c++11', '-Wall', '-Wextra'], + 'conditions': [ + ['OS=="mac"', { + 'xcode_settings': { + 'CLANG_CXX_LIBRARY': 'libc++', + 'CLANG_CXX_LANGUAGE_STANDARD':'c++11', + 'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0', + 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', + 'GCC_ENABLE_CPP_RTTI':'YES', + 'OTHER_CPLUSPLUSFLAGS': [ '-Wall', '-Wextra', '-Wshadow', '-Wno-variadic-macros', '-frtti', '-fexceptions' ], + 'GCC_WARN_PEDANTIC': 'YES', + 'GCC_WARN_UNINITIALIZED_AUTOS': 'YES_AGGRESSIVE', + }, + }], + ['OS=="linux"', { + 'cflags_cc': [ + '-Wno-unknown-pragmas', # We are using '#pragma mark', but it is only available on Darwin. + '-Wno-literal-suffix', # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61653 + ], + }], + ], + 'cflags_cc': [ '-std=c++11', '-Werror', '-Wall', '-Wextra', '-Wshadow', '-frtti', '-fexceptions' ], 'configurations': { 'Debug': { 'cflags_cc': [ '-g', '-O0', '-fno-omit-frame-pointer','-fwrapv', '-fstack-protector-all', '-fno-common' ], @@ -31,7 +41,7 @@ 'GCC_OPTIMIZATION_LEVEL': '3', 'GCC_GENERATE_DEBUGGING_SYMBOLS': 'NO', 'DEAD_CODE_STRIPPING': 'YES', - 'GCC_INLINES_ARE_PRIVATE_EXTERN': 'YES' + 'GCC_INLINES_ARE_PRIVATE_EXTERN': 'NO' } }, }, diff --git a/common/glx.h b/common/glx.h new file mode 100644 index 0000000000..6b7d9a3df9 --- /dev/null +++ b/common/glx.h @@ -0,0 +1,2 @@ +#include <GL/glx.h> +#undef None diff --git a/common/headless_display.cpp b/common/headless_display.cpp new file mode 100644 index 0000000000..3aaf2020b9 --- /dev/null +++ b/common/headless_display.cpp @@ -0,0 +1,74 @@ +#include "headless_display.hpp" + +#include <cstring> +#include <stdexcept> + +namespace mbgl { + +HeadlessDisplay::HeadlessDisplay() { +#if MBGL_USE_CGL + // TODO: test if OpenGL 4.1 with GL_ARB_ES2_compatibility is supported + // If it is, use kCGLOGLPVersion_3_2_Core and enable that extension. + CGLPixelFormatAttribute attributes[] = { + kCGLPFAOpenGLProfile, + (CGLPixelFormatAttribute) kCGLOGLPVersion_Legacy, + kCGLPFAAccelerated, + (CGLPixelFormatAttribute) 0 + }; + + GLint num; + CGLError error = CGLChoosePixelFormat(attributes, &pixelFormat, &num); + if (error) { + fprintf(stderr, "Error pixel format: %s\n", CGLErrorString(error)); + return; + } +#endif + +#if MBGL_USE_GLX + if (!XInitThreads()) { + throw std::runtime_error("Failed to XInitThreads"); + } + + x_display = XOpenDisplay(nullptr); + if (x_display == nullptr) { + throw std::runtime_error("Failed to open X display"); + } + + const char *extensions = (char *)glXQueryServerString(x_display, DefaultScreen(x_display), GLX_EXTENSIONS); + if (!extensions) { + throw std::runtime_error("Cannot read GLX extensions"); + } + if (!strstr(extensions,"GLX_SGIX_fbconfig")) { + throw std::runtime_error("Extension GLX_SGIX_fbconfig was not found"); + } + if (!strstr(extensions, "GLX_SGIX_pbuffer")) { + throw std::runtime_error("Cannot find glXCreateContextAttribsARB"); + } + + // We're creating a dummy pbuffer anyway that we're not using. + static int pixelFormat[] = { + GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, + None + }; + + int configs = 0; + fb_configs = glXChooseFBConfig(x_display, DefaultScreen(x_display), pixelFormat, &configs); + if (configs <= 0) { + throw std::runtime_error("No Framebuffer configurations"); + } +#endif +} + +HeadlessDisplay::~HeadlessDisplay() { +#if MBGL_USE_CGL + CGLDestroyPixelFormat(pixelFormat); +#endif + +#if MBGL_USE_GLX + XFree(fb_configs); + XCloseDisplay(x_display); +#endif +} + +} + diff --git a/common/headless_display.hpp b/common/headless_display.hpp new file mode 100644 index 0000000000..5b33fd6990 --- /dev/null +++ b/common/headless_display.hpp @@ -0,0 +1,25 @@ +#ifndef MBGL_COMMON_HEADLESS_DISPLAY +#define MBGL_COMMON_HEADLESS_DISPLAY + +#include "headless_view.hpp" + +namespace mbgl { + +class HeadlessDisplay { +public: + HeadlessDisplay(); + ~HeadlessDisplay(); + +#if MBGL_USE_CGL + CGLPixelFormatObj pixelFormat; +#endif + +#if MBGL_USE_GLX + Display *x_display = nullptr; + GLXFBConfig *fb_configs = nullptr; +#endif +}; + +} + +#endif diff --git a/include/csscolorparser/csscolorparser.hpp b/include/csscolorparser/csscolorparser.hpp index 1d074627f6..6caf796943 100644 --- a/include/csscolorparser/csscolorparser.hpp +++ b/include/csscolorparser/csscolorparser.hpp @@ -31,8 +31,8 @@ namespace CSSColorParser { struct Color { inline Color() {} - inline Color(unsigned char r, unsigned char g, unsigned char b, float a) - : r(r), g(g), b(b), a(a) {} + inline Color(unsigned char r_, unsigned char g_, unsigned char b_, float a_) + : r(r_), g(g_), b(b_), a(a_) {} unsigned char r = 0, g = 0, b = 0; float a = 1.0f; }; diff --git a/include/mbgl/geometry/anchor.hpp b/include/mbgl/geometry/anchor.hpp index ab006530ff..d30394f0b9 100644 --- a/include/mbgl/geometry/anchor.hpp +++ b/include/mbgl/geometry/anchor.hpp @@ -12,10 +12,10 @@ struct Anchor { float scale = 0.0f; int segment = -1; - explicit Anchor(float x, float y, float angle, float scale) - : x(x), y(y), angle(angle), scale(scale) {} - explicit Anchor(float x, float y, float angle, float scale, int segment) - : x(x), y(y), angle(angle), scale(scale), segment(segment) {} + explicit Anchor(float x_, float y_, float angle_, float scale_) + : x(x_), y(y_), angle(angle_), scale(scale_) {} + explicit Anchor(float x_, float y_, float angle_, float scale_, int segment_) + : x(x_), y(y_), angle(angle_), scale(scale_), segment(segment_) {} }; typedef std::vector<Anchor> Anchors; diff --git a/include/mbgl/geometry/buffer.hpp b/include/mbgl/geometry/buffer.hpp index 446177d443..80cc6b9d1a 100644 --- a/include/mbgl/geometry/buffer.hpp +++ b/include/mbgl/geometry/buffer.hpp @@ -84,15 +84,15 @@ protected: } // Get a pointer to the item at a given index. - inline void *getElement(size_t index) { + inline void *getElement(size_t i) { if (array == nullptr) { throw std::runtime_error("Buffer was already deleted or doesn't contain elements"); } - if (index * itemSize >= pos) { + if (i * itemSize >= pos) { throw new std::runtime_error("Can't get element after array bounds"); } else { - return static_cast<char *>(array) + (index * itemSize); + return static_cast<char *>(array) + (i * itemSize); } } diff --git a/include/mbgl/geometry/elements_buffer.hpp b/include/mbgl/geometry/elements_buffer.hpp index 56080e29fe..045560f9aa 100644 --- a/include/mbgl/geometry/elements_buffer.hpp +++ b/include/mbgl/geometry/elements_buffer.hpp @@ -16,9 +16,9 @@ struct ElementGroup : public util::noncopyable { uint32_t elements_length; ElementGroup() : vertex_length(0), elements_length(0) {} - ElementGroup(uint32_t vertex_length, uint32_t elements_length) - : vertex_length(vertex_length), - elements_length(elements_length) { + ElementGroup(uint32_t vertex_length_, uint32_t elements_length_) + : vertex_length(vertex_length_), + elements_length(elements_length_) { } ElementGroup(ElementGroup &&rhs) noexcept diff --git a/include/mbgl/geometry/geometry.hpp b/include/mbgl/geometry/geometry.hpp index 961569204d..484d17b36d 100644 --- a/include/mbgl/geometry/geometry.hpp +++ b/include/mbgl/geometry/geometry.hpp @@ -30,8 +30,8 @@ private: int32_t ox, oy; }; -Geometry::Geometry(pbf& data) - : data(data), +Geometry::Geometry(pbf& data_) + : data(data_), cmd(1), length(0), x(0), y(0), diff --git a/include/mbgl/geometry/glyph_atlas.hpp b/include/mbgl/geometry/glyph_atlas.hpp index 336c4af284..5b09cbcd6d 100644 --- a/include/mbgl/geometry/glyph_atlas.hpp +++ b/include/mbgl/geometry/glyph_atlas.hpp @@ -18,8 +18,8 @@ public: private: struct GlyphValue { - GlyphValue(const Rect<uint16_t>& rect, uint64_t id) - : rect(rect), ids({ id }) {} + GlyphValue(const Rect<uint16_t>& rect_, uint64_t id) + : rect(rect_), ids({ id }) {} Rect<uint16_t> rect; std::set<uint64_t> ids; }; diff --git a/include/mbgl/map/map.hpp b/include/mbgl/map/map.hpp index bea82e6b4c..ab9775a8c9 100644 --- a/include/mbgl/map/map.hpp +++ b/include/mbgl/map/map.hpp @@ -63,6 +63,9 @@ public: // Triggers a cleanup that releases resources. void cleanup(); + // Releases resources immediately + void terminate(); + // Controls buffer swapping. bool needsSwap(); void swapped(); diff --git a/include/mbgl/map/tile.hpp b/include/mbgl/map/tile.hpp index b9f0556add..1ae13dd79d 100644 --- a/include/mbgl/map/tile.hpp +++ b/include/mbgl/map/tile.hpp @@ -37,8 +37,8 @@ public: const int8_t z = 0; const int32_t x = 0, y = 0; - inline explicit ID(int8_t z, int32_t x, int32_t y) - : w((x < 0 ? x - (1 << z) + 1 : x) / (1 << z)), z(z), x(x), y(y) {} + inline explicit ID(int8_t z_, int32_t x_, int32_t y_) + : w((x_ < 0 ? x_ - (1 << z_) + 1 : x_) / (1 << z_)), z(z_), x(x_), y(y_) {} inline uint64_t to_uint64() const { return ((std::pow(2, z) * y + x) * 32) + z; diff --git a/include/mbgl/map/view.hpp b/include/mbgl/map/view.hpp index bbdcd97c79..513c73b483 100644 --- a/include/mbgl/map/view.hpp +++ b/include/mbgl/map/view.hpp @@ -22,8 +22,8 @@ enum MapChange : uint8_t { class View { public: - virtual void initialize(Map *map) { - this->map = map; + virtual void initialize(Map *map_) { + map = map_; } // Called from the render (=GL) thread. Signals that the context should @@ -35,11 +35,9 @@ public: // renderer setup since the render thread doesn't switch the contexts. virtual void make_active() = 0; - // Returns the base framebuffer object, if any, and 0 if using the system - // provided framebuffer. - virtual unsigned int root_fbo() { - return 0; - } + // Called from the render thread. Makes the GL context inactive in the current + // thread. This is called once just before the rendering thread terminates. + virtual void make_inactive() = 0; virtual void notify() = 0; diff --git a/include/mbgl/platform/default/glfw_view.hpp b/include/mbgl/platform/default/glfw_view.hpp index 481b1598bb..6e91c1125e 100644 --- a/include/mbgl/platform/default/glfw_view.hpp +++ b/include/mbgl/platform/default/glfw_view.hpp @@ -17,6 +17,7 @@ public: void initialize(mbgl::Map *map); void swap(); void make_active(); + void make_inactive(); void notify(); void notify_map_change(mbgl::MapChange change, mbgl::timestamp delay = 0); diff --git a/include/mbgl/platform/default/headless_view.hpp b/include/mbgl/platform/default/headless_view.hpp index 42f9c46da2..c0baddb884 100644 --- a/include/mbgl/platform/default/headless_view.hpp +++ b/include/mbgl/platform/default/headless_view.hpp @@ -1,51 +1,63 @@ -#ifndef MBGL_COMMON_HEADLESS_CGL -#define MBGL_COMMON_HEADLESS_CGL +#ifndef MBGL_COMMON_HEADLESS_VIEW +#define MBGL_COMMON_HEADLESS_VIEW #ifdef __APPLE__ #define MBGL_USE_CGL 1 #else +#define GL_GLEXT_PROTOTYPES #include <GL/glx.h> #define MBGL_USE_GLX 1 #endif #include <mbgl/map/view.hpp> #include <mbgl/platform/gl.hpp> -#include <mbgl/util/time.hpp> + +#include <memory> namespace mbgl { +class HeadlessDisplay; + class HeadlessView : public View { public: HeadlessView(); + HeadlessView(std::shared_ptr<HeadlessDisplay> display); ~HeadlessView(); + void createContext(); + void resize(uint16_t width, uint16_t height, float pixelRatio); + const std::unique_ptr<uint32_t[]> readPixels(); void notify(); void notify_map_change(MapChange change, timestamp delay = 0); void make_active(); + void make_inactive(); void swap(); - unsigned int root_fbo(); private: void clear_buffers(); - private: + std::shared_ptr<HeadlessDisplay> display_; + uint16_t width_; + uint16_t height_; + float pixelRatio_; + #if MBGL_USE_CGL CGLContextObj gl_context; - GLuint fbo = 0; - GLuint fbo_depth_stencil = 0; - GLuint fbo_color = 0; #endif #if MBGL_USE_GLX - GLXContext gl_context = nullptr; - XVisualInfo *x_info = nullptr; Display *x_display = nullptr; - Pixmap x_pixmap = 0; - GLXPixmap glx_pixmap = 0; + GLXFBConfig *fb_configs = nullptr; + GLXContext gl_context = 0; + GLXPbuffer glx_pbuffer = 0; #endif + + GLuint fbo = 0; + GLuint fbo_depth_stencil = 0; + GLuint fbo_color = 0; }; } diff --git a/include/mbgl/renderer/frame_history.hpp b/include/mbgl/renderer/frame_history.hpp index b1f0bcb597..61bb59da33 100644 --- a/include/mbgl/renderer/frame_history.hpp +++ b/include/mbgl/renderer/frame_history.hpp @@ -11,7 +11,7 @@ namespace mbgl { struct FrameSnapshot { - explicit inline FrameSnapshot(timestamp t, float z) : t(t), z(z) {} + explicit inline FrameSnapshot(timestamp t_, float z_) : t(t_), z(z_) {} float t; float z; }; diff --git a/include/mbgl/renderer/painter.hpp b/include/mbgl/renderer/painter.hpp index 13c2050bd0..a8229a0978 100644 --- a/include/mbgl/renderer/painter.hpp +++ b/include/mbgl/renderer/painter.hpp @@ -64,6 +64,7 @@ public: // lazy initialization) in case rendering continues. void cleanup(); + void terminate(); // Renders the backdrop of the OpenGL view. This also paints in areas where we don't have any // tiles whatsoever. @@ -124,6 +125,7 @@ public: private: void setupShaders(); + void deleteShaders(); mat4 translatedMatrix(const mat4& matrix, const std::array<float, 2> &translation, const Tile::ID &id, TranslateAnchorType anchor); void prepareTile(const Tile& tile); @@ -152,10 +154,10 @@ public: // used to composite images and flips the geometry upside down const mat4 flipMatrix = []{ - mat4 flipMatrix; - matrix::ortho(flipMatrix, 0, 4096, -4096, 0, 0, 1); - matrix::translate(flipMatrix, flipMatrix, 0, -4096, 0); - return flipMatrix; + mat4 flip; + matrix::ortho(flip, 0, 4096, -4096, 0, 0, 1); + matrix::translate(flip, flip, 0, -4096, 0); + return flip; }(); const mat4 identityMatrix = []{ diff --git a/include/mbgl/style/class_dictionary.hpp b/include/mbgl/style/class_dictionary.hpp index c7f9c6a284..ecf80be3e3 100644 --- a/include/mbgl/style/class_dictionary.hpp +++ b/include/mbgl/style/class_dictionary.hpp @@ -14,17 +14,22 @@ enum class ClassID : uint32_t { }; class ClassDictionary { +private: + ClassDictionary(); + public: + static ClassDictionary &Get(); + // Returns an ID for a class name. If the class name does not yet have an ID, one is // auto-generated and stored for future reference. - static ClassID Lookup(const std::string &class_name); + ClassID lookup(const std::string &class_name); // Returns either Fallback, Default or Named, depending on the type of the class id. - static ClassID Normalize(ClassID id); + ClassID normalize(ClassID id); private: - static std::unordered_map<std::string, ClassID> store; - static uint32_t offset; + std::unordered_map<std::string, ClassID> store = { { "", ClassID::Default } }; + uint32_t offset = 0; }; } diff --git a/include/mbgl/style/class_properties.hpp b/include/mbgl/style/class_properties.hpp index 84b6f483bd..888a90c5d7 100644 --- a/include/mbgl/style/class_properties.hpp +++ b/include/mbgl/style/class_properties.hpp @@ -12,8 +12,8 @@ namespace mbgl { class ClassProperties { public: inline ClassProperties() {} - inline ClassProperties(ClassProperties &&properties) - : properties(std::move(properties.properties)) {} + inline ClassProperties(ClassProperties &&properties_) + : properties(std::move(properties_.properties)) {} inline void set(PropertyKey key, const PropertyValue &value) { properties.emplace(key, value); diff --git a/include/mbgl/style/filter_comparison.hpp b/include/mbgl/style/filter_comparison.hpp index bf48744f1e..1b0a9b5486 100644 --- a/include/mbgl/style/filter_comparison.hpp +++ b/include/mbgl/style/filter_comparison.hpp @@ -24,8 +24,8 @@ public: class Instance { public: - Instance(Operator op, std::vector<Value> &&values) - : op(op), values(values) {} + Instance(Operator op_, std::vector<Value> &&values_) + : op(op_), values(values_) {} bool compare(const std::vector<Value> &property_values) const; @@ -37,7 +37,7 @@ public: }; public: - FilterComparison(const std::string &field) : field(field) {}; + FilterComparison(const std::string &field_) : field(field_) {}; const std::string &getField() const; template <typename Extractor> inline bool compare(const Extractor &extractor) const; diff --git a/include/mbgl/style/filter_expression.hpp b/include/mbgl/style/filter_expression.hpp index 2a96578792..915d3931d1 100644 --- a/include/mbgl/style/filter_expression.hpp +++ b/include/mbgl/style/filter_expression.hpp @@ -28,7 +28,7 @@ public: public: FilterExpression() = default; - FilterExpression(Operator op) : op(op) {}; + FilterExpression(Operator op_) : op(op_) {}; bool empty() const; diff --git a/include/mbgl/style/function_properties.hpp b/include/mbgl/style/function_properties.hpp index 56092f9a63..924f192330 100644 --- a/include/mbgl/style/function_properties.hpp +++ b/include/mbgl/style/function_properties.hpp @@ -9,7 +9,7 @@ namespace mbgl { template <typename T> struct ConstantFunction { - inline ConstantFunction(const T &value) : value(value) {} + inline ConstantFunction(const T &value_) : value(value_) {} inline T evaluate(float) const { return value; } private: @@ -18,7 +18,7 @@ private: template <typename T> struct StopsFunction { - inline StopsFunction(const std::vector<std::pair<float, T>> &values, float base) : values(values), base(base) {} + inline StopsFunction(const std::vector<std::pair<float, T>> &values_, float base_) : values(values_), base(base_) {} T evaluate(float z) const; private: @@ -36,7 +36,7 @@ using Function = mapbox::util::variant< template <typename T> struct FunctionEvaluator { typedef T result_type; - inline FunctionEvaluator(float z) : z(z) {} + inline FunctionEvaluator(float z_) : z(z_) {} inline result_type operator()(const std::false_type &) { return result_type(); diff --git a/include/mbgl/style/style_source.hpp b/include/mbgl/style/style_source.hpp index 00c48431a1..86473079cf 100644 --- a/include/mbgl/style/style_source.hpp +++ b/include/mbgl/style/style_source.hpp @@ -36,8 +36,8 @@ public: bool enabled = false; util::ptr<Source> source; - StyleSource(const util::ptr<SourceInfo> &info) - : info(info) + StyleSource(const util::ptr<SourceInfo> &info_) + : info(info_) {} }; diff --git a/include/mbgl/text/collision.hpp b/include/mbgl/text/collision.hpp index b7ee6b4520..dfefab689e 100644 --- a/include/mbgl/text/collision.hpp +++ b/include/mbgl/text/collision.hpp @@ -6,6 +6,7 @@ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wshadow" #ifdef __clang__ #pragma GCC diagnostic ignored "-Wdeprecated-register" #else diff --git a/include/mbgl/text/glyph.hpp b/include/mbgl/text/glyph.hpp index de7f55bdc6..4fbb75fc1e 100644 --- a/include/mbgl/text/glyph.hpp +++ b/include/mbgl/text/glyph.hpp @@ -30,9 +30,9 @@ struct GlyphMetrics { struct Glyph { inline explicit Glyph() : rect(0, 0, 0, 0), metrics() {} - inline explicit Glyph(const Rect<uint16_t> &rect, - const GlyphMetrics &metrics) - : rect(rect), metrics(metrics) {} + inline explicit Glyph(const Rect<uint16_t> &rect_, + const GlyphMetrics &metrics_) + : rect(rect_), metrics(metrics_) {} operator bool() const { return metrics || rect; @@ -46,8 +46,8 @@ typedef std::map<uint32_t, Glyph> GlyphPositions; class PositionedGlyph { public: - inline explicit PositionedGlyph(uint32_t glyph, float x, float y) - : glyph(glyph), x(x), y(y) {} + inline explicit PositionedGlyph(uint32_t glyph_, float x_, float y_) + : glyph(glyph_), x(x_), y(y_) {} uint32_t glyph = 0; float x = 0; diff --git a/include/mbgl/text/types.hpp b/include/mbgl/text/types.hpp index dbb483ea8f..23f49aa748 100644 --- a/include/mbgl/text/types.hpp +++ b/include/mbgl/text/types.hpp @@ -3,11 +3,10 @@ #include <mbgl/util/vec.hpp> #include <mbgl/util/rect.hpp> +#include <mbgl/util/optional.hpp> #include <array> #include <vector> -#include <boost/optional.hpp> - namespace mbgl { typedef vec2<float> CollisionPoint; @@ -29,31 +28,31 @@ struct CollisionRect { CollisionPoint::Type bx, CollisionPoint::Type by) : tl(ax, ay), br(bx, by) {} - inline explicit CollisionRect(const CollisionPoint &tl, - const CollisionPoint &br) - : tl(tl), br(br) {} + inline explicit CollisionRect(const CollisionPoint &tl_, + const CollisionPoint &br_) + : tl(tl_), br(br_) {} }; // These are the glyph boxes that we want to have placed. struct GlyphBox { explicit GlyphBox() {} - explicit GlyphBox(const CollisionRect &box, - const CollisionAnchor &anchor, - float minScale, - float maxScale, - float padding) - : box(box), anchor(anchor), minScale(minScale), maxScale(maxScale), padding(padding) {} - explicit GlyphBox(const CollisionRect &box, - float minScale, - float padding) - : box(box), minScale(minScale), padding(padding) {} + explicit GlyphBox(const CollisionRect &box_, + const CollisionAnchor &anchor_, + float minScale_, + float maxScale_, + float padding_) + : box(box_), anchor(anchor_), minScale(minScale_), maxScale(maxScale_), padding(padding_) {} + explicit GlyphBox(const CollisionRect &box_, + float minScale_, + float padding_) + : box(box_), minScale(minScale_), padding(padding_) {} CollisionRect box; CollisionAnchor anchor; float minScale = 0.0f; float maxScale = std::numeric_limits<float>::infinity(); float padding = 0.0f; - boost::optional<CollisionRect> hBox; + mapbox::util::optional<CollisionRect> hBox; }; typedef std::vector<GlyphBox> GlyphBoxes; @@ -61,19 +60,19 @@ typedef std::vector<GlyphBox> GlyphBoxes; // TODO: Transform the vec2<float>s to vec2<int16_t> to save bytes struct PlacedGlyph { - explicit PlacedGlyph(const vec2<float> &tl, const vec2<float> &tr, - const vec2<float> &bl, const vec2<float> &br, - const Rect<uint16_t> &tex, float angle, const vec2<float> &anchor, - float minScale, float maxScale) - : tl(tl), - tr(tr), - bl(bl), - br(br), - tex(tex), - angle(angle), - anchor(anchor), - minScale(minScale), - maxScale(maxScale) {} + explicit PlacedGlyph(const vec2<float> &tl_, const vec2<float> &tr_, + const vec2<float> &bl_, const vec2<float> &br_, + const Rect<uint16_t> &tex_, float angle_, const vec2<float> &anchor_, + float minScale_, float maxScale_) + : tl(tl_), + tr(tr_), + bl(bl_), + br(br_), + tex(tex_), + angle(angle_), + anchor(anchor_), + minScale(minScale_), + maxScale(maxScale_) {} vec2<float> tl, tr, bl, br; Rect<uint16_t> tex; @@ -88,7 +87,7 @@ typedef std::vector<PlacedGlyph> PlacedGlyphs; struct PlacementBox { CollisionAnchor anchor; CollisionRect box; - boost::optional<CollisionRect> hBox; + mapbox::util::optional<CollisionRect> hBox; PlacementRange placementRange = {{0.0f, 0.0f}}; float placementScale = 0.0f; float maxScale = std::numeric_limits<float>::infinity(); @@ -97,8 +96,8 @@ struct PlacementBox { struct PlacementProperty { explicit PlacementProperty() {} - explicit PlacementProperty(float zoom, const PlacementRange &rotationRange) - : zoom(zoom), rotationRange(rotationRange) {} + explicit PlacementProperty(float zoom_, const PlacementRange &rotationRange_) + : zoom(zoom_), rotationRange(rotationRange_) {} inline operator bool() const { return !std::isnan(zoom) && zoom != std::numeric_limits<float>::infinity() && diff --git a/include/mbgl/util/enum.hpp b/include/mbgl/util/enum.hpp index 195aaab5a5..3c3e4a5c4e 100644 --- a/include/mbgl/util/enum.hpp +++ b/include/mbgl/util/enum.hpp @@ -21,11 +21,11 @@ private: static constexpr inline bool compare(const char *a, const char *b) { return *a == *b && (*a == '\0' || compare(a + 1, b + 1)); } - static constexpr inline const char *lookup_type(Type e, EnumValue<Type> const * const l, size_t r) { - return r == 0 ? "" : l->value == e ? l->name : lookup_type(e, l + 1, r - 1); + static constexpr inline const char *lookup_type(Type e, EnumValue<Type> const * const list, size_t r) { + return r == 0 ? "" : list->value == e ? list->name : lookup_type(e, list + 1, r - 1); } - static constexpr inline Type lookup_name(const char *n, EnumValue<Type> const * const l, size_t r) { - return r == 0 ? Type(-1) : compare(l->name, n) ? l->value : lookup_name(n, l + 1, r - 1); + static constexpr inline Type lookup_name(const char *n, EnumValue<Type> const * const list, size_t r) { + return r == 0 ? Type(-1) : compare(list->name, n) ? list->value : lookup_name(n, list + 1, r - 1); } public: inline constexpr Enum(const char *n) : value(lookup_name(n, names, length)) {} diff --git a/include/mbgl/util/error.hpp b/include/mbgl/util/error.hpp index 99e27f770c..09fa8d3e21 100644 --- a/include/mbgl/util/error.hpp +++ b/include/mbgl/util/error.hpp @@ -8,7 +8,7 @@ namespace mbgl { namespace error { struct style_parse : std::exception { - inline style_parse(size_t offset, const char *msg) : offset(offset), msg(msg) {} + inline style_parse(size_t offset_, const char *msg_) : offset(offset_), msg(msg_) {} inline const char* what() const noexcept { return msg.c_str(); } const size_t offset; const std::string msg; diff --git a/include/mbgl/util/optional.hpp b/include/mbgl/util/optional.hpp new file mode 100644 index 0000000000..133e2c8f97 --- /dev/null +++ b/include/mbgl/util/optional.hpp @@ -0,0 +1,69 @@ +#ifndef MAPBOX_UTIL_OPTIONAL_HPP +#define MAPBOX_UTIL_OPTIONAL_HPP + +#include <type_traits> + +#include "variant.hpp" + +namespace mapbox +{ +namespace util +{ + +template <typename T> class optional +{ + static_assert(!std::is_reference<T>::value, "optional doesn't support references"); + + struct none_type + { + }; + + variant<none_type, T> variant_; + + public: + optional() = default; + + optional(optional const &rhs) + { + if (this != &rhs) + { // protect against invalid self-assignment + variant_ = rhs.variant_; + } + } + + optional(T const &v) { variant_ = v; } + + explicit operator bool() const noexcept { return variant_.template is<T>(); } + + T const &get() const { return variant_.template get<T>(); } + T &get() { return variant_.template get<T>(); } + + T const &operator*() const { return this->get(); } + T operator*() { return this->get(); } + + optional &operator=(T const &v) + { + variant_ = v; + return *this; + } + + optional &operator=(optional const &rhs) + { + if (this != &rhs) + { + variant_ = rhs.variant_; + } + return *this; + } + + template <typename... Args> void emplace(Args &&... args) + { + variant_ = T{std::forward<Args>(args)...}; + } + + void reset() { variant_ = none_type{}; } +}; +} +} + +#endif diff --git a/include/mbgl/util/pbf.hpp b/include/mbgl/util/pbf.hpp index 1f78a0072f..d017219a52 100644 --- a/include/mbgl/util/pbf.hpp +++ b/include/mbgl/util/pbf.hpp @@ -49,9 +49,9 @@ struct pbf { uint32_t tag = 0; }; -pbf::pbf(const unsigned char *data, size_t length) - : data(data), - end(data + length), +pbf::pbf(const unsigned char *data_, size_t length) + : data(data_), + end(data_ + length), value(0), tag(0) { } @@ -132,9 +132,9 @@ double pbf::float64() { std::string pbf::string() { uint32_t bytes = static_cast<uint32_t>(varint()); - const char *string = reinterpret_cast<const char*>(data); + const char *string_data = reinterpret_cast<const char*>(data); skipBytes(bytes); - return std::string(string, bytes); + return std::string(string_data, bytes); } bool pbf::boolean() { diff --git a/include/mbgl/util/rect.hpp b/include/mbgl/util/rect.hpp index dedd4afc94..f5c77f93d1 100644 --- a/include/mbgl/util/rect.hpp +++ b/include/mbgl/util/rect.hpp @@ -6,7 +6,7 @@ namespace mbgl { template <typename T> struct Rect { inline Rect() {} - inline Rect(T x, T y, T w, T h) : x(x), y(y), w(w), h(h) {} + inline Rect(T x_, T y_, T w_, T h_) : x(x_), y(y_), w(w_), h(h_) {} T x = 0, y = 0; T w = 0, h = 0; diff --git a/include/mbgl/util/transition.hpp b/include/mbgl/util/transition.hpp index 8a6836c885..b78abfa8fd 100644 --- a/include/mbgl/util/transition.hpp +++ b/include/mbgl/util/transition.hpp @@ -15,9 +15,9 @@ public: complete }; - inline transition(timestamp start, timestamp duration) - : start(start), - duration(duration) {} + inline transition(timestamp start_, timestamp duration_) + : start(start_), + duration(duration_) {} inline float progress(timestamp now) const { if (duration == 0) return 1; @@ -36,11 +36,11 @@ protected: template <typename T> class ease_transition : public transition { public: - ease_transition(T from, T to, T& value, timestamp start, timestamp duration) - : transition(start, duration), - from(from), - to(to), - value(value) {} + ease_transition(T from_, T to_, T& value_, timestamp start_, timestamp duration_) + : transition(start_, duration_), + from(from_), + to(to_), + value(value_) {} state update(timestamp now) const; @@ -53,10 +53,10 @@ private: template <typename T> class timeout : public transition { public: - timeout(T final_value, T& value, timestamp start, timestamp duration) - : transition(start, duration), - final_value(final_value), - value(value) {} + timeout(T final_value_, T& value_, timestamp start_, timestamp duration_) + : transition(start_, duration_), + final_value(final_value_), + value(value_) {} state update(timestamp now) const { if (progress(now) >= 1) { diff --git a/include/mbgl/util/uv_detail.hpp b/include/mbgl/util/uv_detail.hpp index f80ca1bff5..b4b41f31af 100644 --- a/include/mbgl/util/uv_detail.hpp +++ b/include/mbgl/util/uv_detail.hpp @@ -68,7 +68,7 @@ private: class lock { public: - lock(mutex &mtx) : mtx(mtx) { mtx.lock(); } + lock(mutex &mtx_) : mtx(mtx_) { mtx.lock(); } ~lock() { mtx.unlock(); } private: @@ -94,8 +94,8 @@ private: class readlock { public: - inline readlock(rwlock &mtx) : mtx(mtx) { mtx.rdlock(); } - inline readlock(const std::unique_ptr<rwlock> &mtx) : mtx(*mtx) { mtx->rdlock(); } + inline readlock(rwlock &mtx_) : mtx(mtx_) { mtx.rdlock(); } + inline readlock(const std::unique_ptr<rwlock> &mtx_) : mtx(*mtx_) { mtx.rdlock(); } inline ~readlock() { mtx.rdunlock(); } private: @@ -104,8 +104,8 @@ private: class writelock { public: - inline writelock(rwlock &mtx) : mtx(mtx) { mtx.wrlock(); } - inline writelock(const std::unique_ptr<rwlock> &mtx) : mtx(*mtx) { mtx->wrlock(); } + inline writelock(rwlock &mtx_) : mtx(mtx_) { mtx.wrlock(); } + inline writelock(const std::unique_ptr<rwlock> &mtx_) : mtx(*mtx_) { mtx.wrlock(); } inline ~writelock() { mtx.wrunlock(); } private: @@ -148,10 +148,10 @@ public: typedef void (*after_work_callback)(T &object); template<typename... Args> - work(worker &worker, work_callback work_cb, after_work_callback after_work_cb, Args&&... args) + work(worker &worker, work_callback work_cb_, after_work_callback after_work_cb_, Args&&... args) : data(std::forward<Args>(args)...), - work_cb(work_cb), - after_work_cb(after_work_cb) { + work_cb(work_cb_), + after_work_cb(after_work_cb_) { worker.add(this, do_work, after_work); } diff --git a/include/mbgl/util/variant.hpp b/include/mbgl/util/variant.hpp index 1eca5160c7..3b5659425a 100644 --- a/include/mbgl/util/variant.hpp +++ b/include/mbgl/util/variant.hpp @@ -4,7 +4,6 @@ #include <utility> #include <typeinfo> #include <type_traits> -#include <algorithm> // std::move/swap #include <stdexcept> // runtime_error #include <new> // operator new #include <cstddef> // size_t @@ -515,22 +514,13 @@ public: VARIANT_INLINE variant(no_init) : type_index(detail::invalid_value) {} + // http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers template <typename T, class = typename std::enable_if< - detail::is_valid_type<T, Types...>::value>::type> - VARIANT_INLINE explicit variant(T const& val) noexcept - : type_index(detail::value_traits<T, Types...>::index) - { - constexpr std::size_t index = sizeof...(Types) - detail::value_traits<T, Types...>::index - 1; - using target_type = typename detail::select_type<index, Types...>::type; - new (&data) target_type(val); - } - - template <typename T, class = typename std::enable_if< - detail::is_valid_type<T, Types...>::value>::type> + detail::is_valid_type<typename std::remove_reference<T>::type, Types...>::value>::type> VARIANT_INLINE variant(T && val) noexcept - : type_index(detail::value_traits<T, Types...>::index) + : type_index(detail::value_traits<typename std::remove_reference<T>::type, Types...>::index) { - constexpr std::size_t index = sizeof...(Types) - detail::value_traits<T, Types...>::index - 1; + constexpr std::size_t index = sizeof...(Types) - detail::value_traits<typename std::remove_reference<T>::type, Types...>::index - 1; using target_type = typename detail::select_type<index, Types...>::type; new (&data) target_type(std::forward<T>(val)); // nothrow } @@ -565,7 +555,7 @@ public: template <typename T> VARIANT_INLINE variant<Types...>& operator=(T && rhs) noexcept { - variant<Types...> temp(std::move(rhs)); + variant<Types...> temp(std::forward<T>(rhs)); swap(*this, temp); return *this; } diff --git a/include/mbgl/util/vec.hpp b/include/mbgl/util/vec.hpp index a5fbee477b..0179254fda 100644 --- a/include/mbgl/util/vec.hpp +++ b/include/mbgl/util/vec.hpp @@ -29,7 +29,7 @@ struct vec2 { template<typename U> inline vec2(const U& u) : x(u.x), y(u.y) {} - inline vec2(T x, T y) : x(x), y(y) {} + inline vec2(T x_, T y_) : x(x_), y(y_) {} inline bool operator==(const vec2& rhs) const { return x == rhs.x && y == rhs.y; @@ -86,7 +86,7 @@ struct vec3 { inline vec3() {} inline vec3(const vec3& o) : x(o.x), y(o.y), z(o.z) {} - inline vec3(T x, T y, T z) : x(x), y(y), z(z) {} + inline vec3(T x_, T y_, T z_) : x(x_), y(y_), z(z_) {} inline bool operator==(const vec3& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z; } @@ -98,7 +98,7 @@ struct vec4 { inline vec4() {} inline vec4(const vec4& o) : x(o.x), y(o.y), z(o.z), w(o.w) {} - inline vec4(T x, T y, T z, T w) : x(x), y(y), z(z), w(w) {} + inline vec4(T x_, T y_, T z_, T w_) : x(x_), y(y_), z(z_), w(w_) {} inline bool operator==(const vec4& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } diff --git a/platform/default/glfw_view.cpp b/platform/default/glfw_view.cpp index fed21f7d96..baacfbfd9c 100644 --- a/platform/default/glfw_view.cpp +++ b/platform/default/glfw_view.cpp @@ -2,16 +2,19 @@ #include <mbgl/util/string.hpp> -GLFWView::GLFWView(bool fullscreen) : fullscreen(fullscreen) { +GLFWView::GLFWView(bool fullscreen_) : fullscreen(fullscreen_) { #ifdef NVIDIA glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)glfwGetProcAddress("glDiscardFramebufferEXT"); #endif } -GLFWView::~GLFWView() { glfwTerminate(); } +GLFWView::~GLFWView() { + map->terminate(); + glfwTerminate(); +} -void GLFWView::initialize(mbgl::Map *map) { - View::initialize(map); +void GLFWView::initialize(mbgl::Map *map_) { + View::initialize(map_); if (!glfwInit()) { fprintf(stderr, "Failed to initialize glfw\n"); @@ -194,6 +197,10 @@ void GLFWView::make_active() { glfwMakeContextCurrent(window); } +void GLFWView::make_inactive() { + glfwMakeContextCurrent(nullptr); +} + void GLFWView::notify() { glfwPostEmptyEvent(); } diff --git a/platform/default/headless_view.cpp b/platform/default/headless_view.cpp index ace41d38c0..d1d13db5f8 100644 --- a/platform/default/headless_view.cpp +++ b/platform/default/headless_view.cpp @@ -1,88 +1,158 @@ #include "headless_view.hpp" -#include <mbgl/util/timer.hpp> +#include "headless_display.hpp" #include <stdexcept> +#include <sstream> +#include <string> + +#if MBGL_USE_GLX +#ifdef GLX_ARB_create_context +static PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = nullptr; +#endif +#endif namespace mbgl { -HeadlessView::HeadlessView() { -#if MBGL_USE_CGL - // TODO: test if OpenGL 4.1 with GL_ARB_ES2_compatibility is supported - // If it is, use kCGLOGLPVersion_3_2_Core and enable that extension. - CGLPixelFormatAttribute attributes[] = { - kCGLPFAOpenGLProfile, - (CGLPixelFormatAttribute) kCGLOGLPVersion_Legacy, - kCGLPFAAccelerated, - (CGLPixelFormatAttribute) 0 - }; +HeadlessView::HeadlessView() + : display_(std::make_shared<HeadlessDisplay>()) { + createContext(); +} - CGLPixelFormatObj pixelFormat; - GLint num; - CGLError error = CGLChoosePixelFormat(attributes, &pixelFormat, &num); - if (error) { - fprintf(stderr, "Error pixel format\n"); - return; +HeadlessView::HeadlessView(std::shared_ptr<HeadlessDisplay> display) + : display_(display) { + createContext(); +} + + +#if MBGL_USE_GLX +#ifdef GLX_ARB_create_context + +// These are all of the OpenGL Core profile version that we know about. +struct core_profile_version { int major, minor; }; +static const core_profile_version core_profile_versions[] = { + {4, 5}, + {4, 4}, + {4, 3}, + {4, 2}, + {4, 1}, + {4, 0}, + {3, 3}, + {3, 2}, + {3, 1}, + {3, 0}, + {0, 0}, +}; + +GLXContext createCoreProfile(Display *dpy, GLXFBConfig fbconfig) { + static bool context_creation_failed = false; + GLXContext ctx = 0; + + // Set the Error Handler to avoid crashing the program when the context creation fails. + // It is expected that some context creation attempts fail, e.g. because the OpenGL + // implementation does not support the version we're requesting. + int (*previous_error_handler)(Display *, XErrorEvent *) = XSetErrorHandler([](Display *, XErrorEvent *) { + context_creation_failed = true; + return 0; + }); + + // Try to create core profiles from the highest known version on down. + for (int i = 0; !ctx && core_profile_versions[i].major; i++) { + context_creation_failed = false; + const int context_flags[] = { + GLX_CONTEXT_MAJOR_VERSION_ARB, core_profile_versions[i].major, + GLX_CONTEXT_MINOR_VERSION_ARB, core_profile_versions[i].minor, + None + }; + ctx = glXCreateContextAttribsARB(dpy, fbconfig, 0, True, context_flags); + if (context_creation_failed) { + ctx = 0; + } } - error = CGLCreateContext(pixelFormat, NULL, &gl_context); - CGLDestroyPixelFormat(pixelFormat); + // Restore the old error handler. + XSetErrorHandler(previous_error_handler); + return ctx; +} +#endif +#endif + +void HeadlessView::createContext() { +#if MBGL_USE_CGL + CGLError error = CGLCreateContext(display_->pixelFormat, NULL, &gl_context); if (error) { - fprintf(stderr, "Error creating GL context object\n"); - return; + throw std::runtime_error("Error creating GL context object\n"); + } + + error = CGLEnable(gl_context, kCGLCEMPEngine); + if (error != kCGLNoError ) { + throw std::runtime_error("Error enabling OpenGL multithreading\n"); } #endif #if MBGL_USE_GLX - x_display = XOpenDisplay(0); - - if (x_display == nullptr) { - throw std::runtime_error("Failed to open X display"); +#ifdef GLX_ARB_create_context + if (glXCreateContextAttribsARB == nullptr) { + glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddressARB((const GLubyte *)"glXCreateContextAttribsARB"); } +#endif - static int pixelFormat[] = { - GLX_RGBA, - GLX_DOUBLEBUFFER, - GLX_RED_SIZE, 8, - GLX_GREEN_SIZE, 8, - GLX_BLUE_SIZE, 8, - GLX_ALPHA_SIZE, 8, - GLX_DEPTH_SIZE, 24, - GLX_STENCIL_SIZE, 8, - None - }; + x_display = display_->x_display; + fb_configs = display_->fb_configs; - x_info = glXChooseVisual(x_display, DefaultScreen(x_display), pixelFormat); +#ifdef GLX_ARB_create_context + if (glXCreateContextAttribsARB) { + // Try to create a core profile context. + gl_context = createCoreProfile(x_display, fb_configs[0]); + } +#endif - if (x_info == nullptr) { - throw std::runtime_error("Error pixel format"); + if (!gl_context) { + // Try to create a legacy context + gl_context = glXCreateNewContext(x_display, fb_configs[0], GLX_RGBA_TYPE, 0, True); + if (gl_context) { + if (!glXIsDirect(x_display, gl_context)) { + glXDestroyContext(x_display, gl_context); + gl_context = 0; + } + } } - gl_context = glXCreateContext(x_display, x_info, 0, GL_TRUE); - if (gl_context == nullptr) { + if (gl_context == 0) { throw std::runtime_error("Error creating GL context object"); } + + // Create a dummy pbuffer. We will render to framebuffers anyway, but we need a pbuffer to + // activate the context. + int pbuffer_attributes[] = { + GLX_PBUFFER_WIDTH, 8, + GLX_PBUFFER_HEIGHT, 8, + None + }; + glx_pbuffer = glXCreatePbuffer(x_display, fb_configs[0], pbuffer_attributes); #endif } - void HeadlessView::resize(uint16_t width, uint16_t height, float pixelRatio) { clear_buffers(); - width *= pixelRatio; - height *= pixelRatio; + width_ = width; + height_ = height; + pixelRatio_ = pixelRatio; + + const unsigned int w = width_ * pixelRatio_; + const unsigned int h = height_ * pixelRatio_; -#if MBGL_USE_CGL make_active(); // Create depth/stencil buffer glGenRenderbuffersEXT(1, &fbo_depth_stencil); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo_depth_stencil); - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, width, height); + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, w, h); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glGenRenderbuffersEXT(1, &fbo_color); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fbo_color); - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, width, height); + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA8, w, h); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glGenFramebuffersEXT(1, &fbo); @@ -94,29 +164,39 @@ void HeadlessView::resize(uint16_t width, uint16_t height, float pixelRatio) { GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { - fprintf(stderr, "Couldn't create framebuffer: "); + std::stringstream error("Couldn't create framebuffer: "); switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: fprintf(stderr, "incomplete attachment\n"); break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: fprintf(stderr, "incomplete missing attachment\n"); break; - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: fprintf(stderr, "incomplete draw buffer\n"); break; - case GL_FRAMEBUFFER_UNSUPPORTED: fprintf(stderr, "unsupported\n"); break; - default: fprintf(stderr, "other\n"); break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: (error << "incomplete attachment\n"); break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: error << "incomplete missing attachment\n"; break; + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: error << "incomplete dimensions\n"; break; + case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: error << "incomplete formats\n"; break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: error << "incomplete draw buffer\n"; break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: error << "incomplete read buffer\n"; break; + case GL_FRAMEBUFFER_UNSUPPORTED: error << "unsupported\n"; break; + default: error << "other\n"; break; } - return; + throw std::runtime_error(error.str()); } -#endif -#if MBGL_USE_GLX - x_pixmap = XCreatePixmap(x_display, DefaultRootWindow(x_display), width, height, 32); - glx_pixmap = glXCreateGLXPixmap(x_display, x_info, x_pixmap); + make_inactive(); +} + +const std::unique_ptr<uint32_t[]> HeadlessView::readPixels() { + const unsigned int w = width_ * pixelRatio_; + const unsigned int h = height_ * pixelRatio_; + + std::unique_ptr<uint32_t[]> pixels(new uint32_t[w * h]); make_active(); -#endif + glReadPixels(0, 0, width_, height_, GL_RGBA, GL_UNSIGNED_BYTE, pixels.get()); + make_inactive(); + return pixels; } void HeadlessView::clear_buffers() { -#if MBGL_USE_CGL + make_active(); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); if (fbo) { @@ -133,19 +213,8 @@ void HeadlessView::clear_buffers() { glDeleteRenderbuffersEXT(1, &fbo_depth_stencil); fbo_depth_stencil = 0; } -#endif -#if MBGL_USE_GLX - if (glx_pixmap) { - glXDestroyGLXPixmap(x_display, glx_pixmap); - glx_pixmap = 0; - } - - if (x_pixmap) { - XFreePixmap(x_display, x_pixmap); - x_pixmap = 0; - } -#endif + make_inactive(); } HeadlessView::~HeadlessView() { @@ -156,10 +225,12 @@ HeadlessView::~HeadlessView() { #endif #if MBGL_USE_GLX - glXMakeCurrent(x_display, None, NULL); + if (glx_pbuffer) { + glXDestroyPbuffer(x_display, glx_pbuffer); + glx_pbuffer = 0; + } + glXDestroyContext(x_display, gl_context); - XFree(x_info); - XCloseDisplay(x_display); #endif } @@ -175,26 +246,33 @@ void HeadlessView::make_active() { #if MBGL_USE_CGL CGLError error = CGLSetCurrentContext(gl_context); if (error) { - fprintf(stderr, "Switching OpenGL context failed\n"); + throw std::runtime_error("Switching OpenGL context failed\n"); } #endif #if MBGL_USE_GLX - if (!glXMakeCurrent(x_display, glx_pixmap, gl_context)) { - fprintf(stderr, "Switching OpenGL context failed\n"); + if (!glXMakeContextCurrent(x_display, glx_pbuffer, glx_pbuffer, gl_context)) { + throw std::runtime_error("Switching OpenGL context failed\n"); } #endif } -void HeadlessView::swap() {} - -unsigned int HeadlessView::root_fbo() { +void HeadlessView::make_inactive() { #if MBGL_USE_CGL - return fbo; + CGLError error = CGLSetCurrentContext(nullptr); + if (error) { + throw std::runtime_error("Removing OpenGL context failed\n"); + } #endif - return 0; +#if MBGL_USE_GLX + if (!glXMakeContextCurrent(x_display, 0, 0, nullptr)) { + throw std::runtime_error("Removing OpenGL context failed\n"); + } +#endif } +void HeadlessView::swap() {} + } diff --git a/platform/default/http_request_baton_curl.cpp b/platform/default/http_request_baton_curl.cpp index d4753266c0..0c3d2b43fc 100644 --- a/platform/default/http_request_baton_curl.cpp +++ b/platform/default/http_request_baton_curl.cpp @@ -154,11 +154,11 @@ void curl_perform(uv_poll_t *req, int, int events) { while ((message = curl_multi_info_read(multi, &pending))) { switch (message->msg) { case CURLMSG_DONE: { - CURLContext *context = nullptr; - curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&context); + CURLContext *ctx = nullptr; + curl_easy_getinfo(message->easy_handle, CURLINFO_PRIVATE, (char *)&ctx); // Make a copy so that the Baton stays around even after we are calling finish_request - util::ptr<HTTPRequestBaton> baton = context->baton; + util::ptr<HTTPRequestBaton> baton = ctx->baton; // Add human-readable error code if (message->data.result != CURLE_OK) { @@ -242,8 +242,8 @@ int handle_socket(CURL *handle, curl_socket_t sockfd, int action, void *, void * } if (action == CURL_POLL_REMOVE && socketp) { uv_poll_stop(context->poll_handle); - uv_close((uv_handle_t *)context->poll_handle, [](uv_handle_t *handle) { - delete (uv_poll_t *)handle; + uv_close((uv_handle_t *)context->poll_handle, [](uv_handle_t *poll_handle) { + delete (uv_poll_t *)poll_handle; }); context->poll_handle = nullptr; curl_multi_assign(multi, sockfd, NULL); @@ -267,7 +267,7 @@ void on_timeout(uv_timer_t *) { void start_timeout(CURLM *, long timeout_ms, void *) { if (timeout_ms <= 0) { - on_timeout(&timeout); + on_timeout(&timeout, 0); } else { uv_timer_start(&timeout, on_timeout, timeout_ms, 0); } diff --git a/scripts/flags.sh b/scripts/flags.sh index b1de8f3c71..0b1f69ae1c 100755 --- a/scripts/flags.sh +++ b/scripts/flags.sh @@ -2,6 +2,7 @@ if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then export DISPLAY=:99.0 + sh -e /etc/init.d/xvfb start # use g++ that supports c++11 @@ -15,17 +16,17 @@ if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then # but it's not worth a standalone matrix so here # we just test address->gcc and thread->clang for # some limited coverage - if [[ ${BUILDTYPE} == "Debug" ]]; then - if [[ ${CXX} == "g++" ]]; then - export CXXFLAGS="-fsanitize=address -g ${CXXFLAGS}" - export CFLAGS="-fsanitize=address -g ${CFLAGS}" - export LDFLAGS="-fsanitize=address ${LDFLAGS}" - elif [[ ${CXX} == "clang++" ]]; then - export CXXFLAGS="-fsanitize=thread -g -fPIC ${CXXFLAGS}" - export CFLAGS="-fsanitize=thread -g ${CFLAGS}" - export LDFLAGS="-fsanitize=thread -pie ${LDFLAGS}" - fi - fi + # if [[ ${BUILDTYPE} == "Debug" ]]; then + # if [[ ${CXX} == "g++" ]]; then + # export CXXFLAGS="-fsanitize=address -g ${CXXFLAGS}" + # export CFLAGS="-fsanitize=address -g ${CFLAGS}" + # export LDFLAGS="-fsanitize=address ${LDFLAGS}" + # elif [[ ${CXX} == "clang++" ]]; then + # export CXXFLAGS="-fsanitize=thread -g -fPIC ${CXXFLAGS}" + # export CFLAGS="-fsanitize=thread -g ${CFLAGS}" + # export LDFLAGS="-fsanitize=thread -pie ${LDFLAGS}" + # fi + # fi fi # turn off a few warnings diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh index dd9ee3f260..6b42b79911 100755 --- a/scripts/run_tests.sh +++ b/scripts/run_tests.sh @@ -6,5 +6,28 @@ set -o pipefail cd build/${BUILDTYPE:-Release} for TEST in ./test_* ; do - ${TEST} + # allow writing core files + ulimit -c unlimited -S + echo 'ulimit -c: '`ulimit -c` + echo '/proc/sys/kernel/core_pattern: '`cat /proc/sys/kernel/core_pattern` + sysctl kernel.core_pattern + + RESULT=0 + ${TEST} || RESULT=$? + + if [[ ${RESULT} != 0 ]]; then + echo "The program crashed with exit code ${RESULT}. We're now trying to output the core dump." + fi + + # output core dump if we got one + for DUMP in $(find ./ -maxdepth 1 -name 'core*' -print); do + gdb ${TEST} ${DUMP} -ex "thread apply all bt" -ex "set pagination 0" -batch + rm -rf ${DUMP} + done + + # now we should present travis with the original + # error code so the run cleanly stops + if [[ ${RESULT} != 0 ]]; then + exit $RESULT + fi done diff --git a/scripts/travis_before_install.sh b/scripts/travis_before_install.sh index 59bd15d3ba..fefd6937f2 100755 --- a/scripts/travis_before_install.sh +++ b/scripts/travis_before_install.sh @@ -11,21 +11,34 @@ if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then sudo add-apt-repository --yes ppa:ubuntu-toolchain-r/test fi sudo add-apt-repository --yes ppa:boost-latest/ppa + + mapbox_time "apt_update" \ sudo apt-get update -y + + mapbox_time "install_gcc" \ sudo apt-get -y install gcc-4.8 g++-4.8 - sudo apt-get -y install git build-essential zlib1g-dev automake \ + + mapbox_time "install_build_tools" \ + sudo apt-get -y install git build-essential zlib1g-dev automake gdb \ libtool xutils-dev make cmake pkg-config python-pip \ libboost1.55-dev libboost-regex1.55-dev libcurl4-openssl-dev \ libpng-dev libsqlite3-dev + + mapbox_time "install_opengl" \ sudo apt-get -y install libxi-dev libglu1-mesa-dev x11proto-randr-dev \ x11proto-xext-dev libxrandr-dev \ x11proto-xf86vidmode-dev libxxf86vm-dev \ libxcursor-dev libxinerama-dev + + mapbox_time "install_awscli" \ sudo pip install awscli elif [[ ${TRAVIS_OS_NAME} == "osx" ]]; then # # install OS X dependencies # + mapbox_time "install_build_tools" \ brew install autoconf automake libtool makedepend cmake pkg-config node git boost + + mapbox_time "install_awscli" \ sudo pip install awscli fi diff --git a/scripts/travis_helper.sh b/scripts/travis_helper.sh new file mode 100755 index 0000000000..040ef29443 --- /dev/null +++ b/scripts/travis_helper.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +function mapbox_time_start { + local name=$1 + mapbox_timer_name=$name + + travis_fold start $name + + mapbox_timer_id=$(printf %08x $(( RANDOM * RANDOM ))) + eval "mapbox_start_time_$mapbox_timer_id=$(travis_nanoseconds)" + echo -en "travis_time:start:$mapbox_timer_id\n" +} + +function mapbox_time_finish { + local name=${1:-$mapbox_timer_name} + local timer_id=${2:-$mapbox_timer_id} + local timer_start="mapbox_start_time_$timer_id" + eval local start_time=\${$timer_start} + local end_time=$(travis_nanoseconds) + local duration=$(($end_time-$start_time)) + echo -en "travis_time:end:$timer_id:start=$start_time,finish=$end_time,duration=$duration\n" + + travis_fold end $name +} + +function mapbox_time { + local name=$1 ; shift + mapbox_time_start $name + local timer_id=$mapbox_timer_id + echo "\$ $@" + $@ + mapbox_time_finish $name $timer_id +} + + +export ANSI_CLEAR +export -f travis_fold +export -f travis_nanoseconds +export -f mapbox_time +export -f mapbox_time_start +export -f mapbox_time_finish diff --git a/scripts/travis_install_test_suite.sh b/scripts/travis_install_test_suite.sh index eca24e719c..cb2422d70c 100755 --- a/scripts/travis_install_test_suite.sh +++ b/scripts/travis_install_test_suite.sh @@ -4,5 +4,6 @@ if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then # # we'll need the test suite on Linux # + mapbox_time "install_test_suite" \ npm install git+https://github.com/mapbox/mapbox-gl-test-suite.git fi diff --git a/scripts/travis_script.sh b/scripts/travis_script.sh index f1cad6b9d3..f306dbcb79 100755 --- a/scripts/travis_script.sh +++ b/scripts/travis_script.sh @@ -7,26 +7,46 @@ if [[ ${TRAVIS_OS_NAME} == "linux" ]]; then # # build & test Linux # + mapbox_time "compile_program" \ make linux -j4 BUILDTYPE=${BUILDTYPE} + + mapbox_time "compile_tests" \ make test -j4 BUILDTYPE=${BUILDTYPE} + + mapbox_time "run_tests" \ ./scripts/run_tests.sh + + mapbox_time_start "compare_results" (cd ./node_modules/mapbox-gl-test-suite/ && (./bin/compare_images.js || true)) + mapbox_time_finish if [ ! -z "${AWS_ACCESS_KEY_ID}" ] && [ ! -z "${AWS_SECRET_ACCESS_KEY}" ] ; then + mapbox_time_start "deploy_results" (cd ./node_modules/mapbox-gl-test-suite/ && ./bin/deploy_results.sh) + mapbox_time_finish fi elif [[ ${TRAVIS_OS_NAME} == "osx" ]]; then # # build OS X # + mapbox_time "create_osx_project" \ make xproj-cli + + mapbox_time "build_osx" \ xcodebuild -project ./build/macosx/mapboxgl-app.xcodeproj -jobs 4 + # # build iOS # git submodule init + + mapbox_time "load_submodules" \ git submodule update + + mapbox_time "create_ios_project" \ make iproj-cli + + mapbox_time "build_ios" \ xcodebuild -project ./build/ios/mapbox-gl-cocoa/app/mapboxgl-app.xcodeproj -sdk iphonesimulator ONLY_ACTIVE_ARCH=NO -jobs 4 fi diff --git a/src/clipper/clipper.cpp b/src/clipper/clipper.cpp index 56ad58416d..ea468d69e4 100755 --- a/src/clipper/clipper.cpp +++ b/src/clipper/clipper.cpp @@ -48,6 +48,8 @@ #include <ostream> #include <functional> +#pragma GCC diagnostic ignored "-Wshadow" + namespace ClipperLib { #ifdef use_int32 @@ -3242,7 +3244,7 @@ void Clipper::BuildResult(Paths &polys) int cnt = PointCount(p); if (cnt < 2) continue; pg.reserve(cnt); - for (int i = 0; i < cnt; ++i) + for (int j = 0; j < cnt; ++j) { pg.push_back(p->Pt); p = p->Prev; diff --git a/src/geometry/debug_font.cpp b/src/geometry/debug_font.cpp index 2da0c67841..8ee9f6811f 100644 --- a/src/geometry/debug_font.cpp +++ b/src/geometry/debug_font.cpp @@ -98,10 +98,10 @@ const int8_t simplex_94[] = { 3, 6, 3, 8, 4, 11, 6, 12, 8, 12, 10, 11, 14, 8, 16 struct glyph { glyph() : width(0), length(0), data(nullptr) { } - glyph(uint8_t width, uint8_t length, const int8_t *data) - : width(width), - length(length), - data(data) {} + glyph(uint8_t width_, uint8_t length_, const int8_t *data_) + : width(width_), + length(length_), + data(data_) {} uint8_t width; uint8_t length; const int8_t *data; diff --git a/src/geometry/debug_font_buffer.cpp b/src/geometry/debug_font_buffer.cpp index 387a646299..2a0924a1c4 100644 --- a/src/geometry/debug_font_buffer.cpp +++ b/src/geometry/debug_font_buffer.cpp @@ -10,9 +10,9 @@ using namespace mbgl; void DebugFontBuffer::addText(const char *text, double left, double baseline, double scale) { uint16_t *coords = nullptr; - size_t length = strlen(text); - for (size_t i = 0; i < length; ++i) { - if (text[i] < 32 || text[i] > 127) { + const size_t len = strlen(text); + for (size_t i = 0; i < len; ++i) { + if (text[i] < 32 || (unsigned char)(text[i]) > 127) { continue; } diff --git a/src/geometry/glyph_atlas.cpp b/src/geometry/glyph_atlas.cpp index 76df941d90..6bee475da3 100644 --- a/src/geometry/glyph_atlas.cpp +++ b/src/geometry/glyph_atlas.cpp @@ -9,11 +9,11 @@ using namespace mbgl; -GlyphAtlas::GlyphAtlas(uint16_t width, uint16_t height) - : width(width), - height(height), - bin(width, height), - data(new char[width *height]), +GlyphAtlas::GlyphAtlas(uint16_t width_, uint16_t height_) + : width(width_), + height(height_), + bin(width_, height_), + data(new char[width_ *height_]), dirty(true) { } diff --git a/src/geometry/sprite_atlas.cpp b/src/geometry/sprite_atlas.cpp index 7ea9d4ce7d..10922790c0 100644 --- a/src/geometry/sprite_atlas.cpp +++ b/src/geometry/sprite_atlas.cpp @@ -14,10 +14,10 @@ using namespace mbgl; -SpriteAtlas::SpriteAtlas(dimension width, dimension height) - : width(width), - height(height), - bin(width, height), +SpriteAtlas::SpriteAtlas(dimension width_, dimension height_) + : width(width_), + height(height_), + bin(width_, height_), dirty(true) { } @@ -88,10 +88,10 @@ void copy_bitmap(const uint32_t *src, const int src_stride, const int src_x, con } } -Rect<SpriteAtlas::dimension> SpriteAtlas::allocateImage(size_t width, size_t height) { +Rect<SpriteAtlas::dimension> SpriteAtlas::allocateImage(size_t pixel_width, size_t pixel_height) { // We have to allocate a new area in the bin, and store an empty image in it. // Add a 1px border around every image. - Rect<dimension> rect = bin.allocate(width + 2 * buffer, height + 2 * buffer); + Rect<dimension> rect = bin.allocate(pixel_width + 2 * buffer, pixel_height + 2 * buffer); if (rect.w == 0) { return rect; } diff --git a/src/map/map.cpp b/src/map/map.cpp index f255c3ff65..a7520b2517 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -30,17 +30,17 @@ using namespace mbgl; -Map::Map(View& view) +Map::Map(View& view_) : loop(std::make_shared<uv::loop>()), thread(std::make_unique<uv::thread>()), async_terminate(new uv_async_t()), async_render(new uv_async_t()), async_cleanup(new uv_async_t()), - view(view), + view(view_), #ifndef NDEBUG main_thread(uv_thread_self()), #endif - transform(view), + transform(view_), glyphAtlas(std::make_shared<GlyphAtlas>(1024, 1024)), spriteAtlas(std::make_shared<SpriteAtlas>(512, 512)), texturepool(std::make_shared<Texturepool>()), @@ -163,7 +163,6 @@ void Map::run() { // If the map rendering wasn't started asynchronously, we perform one render // *after* all events have been processed. if (!async) { - prepare(); render(); #ifndef NDEBUG map_thread = -1; @@ -206,10 +205,13 @@ void Map::cleanup(uv_async_t *async) { #endif Map *map = static_cast<Map *>(async->data); - map->view.make_active(); map->painter.cleanup(); } +void Map::terminate() { + painter.terminate(); +} + void Map::setReachability(bool reachable) { // Note: This function may be called from *any* thread. if (reachable) { @@ -271,8 +273,8 @@ void Map::terminate(uv_async_t *async) { void Map::setup() { assert(uv_thread_self() == map_thread); view.make_active(); - painter.setup(); + view.make_inactive(); } void Map::setStyleURL(const std::string &url) { @@ -605,8 +607,6 @@ void Map::updateRenderState() { } void Map::prepare() { - view.make_active(); - if (!fileSource) { fileSource = std::make_shared<FileSource>(**loop, platform::defaultCacheDatabase()); glyphStore = std::make_shared<GlyphStore>(fileSource); @@ -651,9 +651,8 @@ void Map::prepare() { } void Map::render() { -#if defined(DEBUG) - std::vector<std::string> debug; -#endif + view.make_active(); + painter.clear(); painter.resize(); @@ -685,6 +684,8 @@ void Map::render() { } glFlush(); + + view.make_inactive(); } void Map::renderLayers(util::ptr<StyleLayerGroup> group) { diff --git a/src/map/raster_tile_data.cpp b/src/map/raster_tile_data.cpp index e7725b7abd..99ca327fe7 100644 --- a/src/map/raster_tile_data.cpp +++ b/src/map/raster_tile_data.cpp @@ -5,8 +5,8 @@ using namespace mbgl; -RasterTileData::RasterTileData(Tile::ID id, Map &map, const util::ptr<SourceInfo> &source) - : TileData(id, map, source), +RasterTileData::RasterTileData(Tile::ID id_, Map &map_, const util::ptr<SourceInfo> &source_) + : TileData(id_, map_, source_), bucket(map.getTexturepool(), properties) { } diff --git a/src/map/source.cpp b/src/map/source.cpp index 36f1a71c84..9c0f7caf28 100644 --- a/src/map/source.cpp +++ b/src/map/source.cpp @@ -18,10 +18,12 @@ #include <mbgl/map/vector_tile_data.hpp> #include <mbgl/map/raster_tile_data.hpp> +#include <algorithm> + namespace mbgl { -Source::Source(const util::ptr<SourceInfo>& info) - : info(info) +Source::Source(const util::ptr<SourceInfo>& info_) + : info(info_) { } @@ -219,15 +221,15 @@ std::forward_list<Tile::ID> Source::coveringTiles(const TransformState& state) c box points = state.cornersToBox(z); const vec2<double>& center = points.center; - std::forward_list<Tile::ID> tiles = Tile::cover(z, points); + std::forward_list<Tile::ID> covering_tiles = Tile::cover(z, points); - tiles.sort([¢er](const Tile::ID& a, const Tile::ID& b) { + covering_tiles.sort([¢er](const Tile::ID& a, const Tile::ID& b) { // Sorts by distance from the box center return std::fabs(a.x - center.x) + std::fabs(a.y - center.y) < std::fabs(b.x - center.x) + std::fabs(b.y - center.y); }); - return tiles; + return covering_tiles; } /** diff --git a/src/map/sprite.cpp b/src/map/sprite.cpp index c069ece45a..876586e4b0 100644 --- a/src/map/sprite.cpp +++ b/src/map/sprite.cpp @@ -13,13 +13,13 @@ using namespace mbgl; -SpritePosition::SpritePosition(uint16_t x, uint16_t y, uint16_t width, uint16_t height, float pixelRatio, bool sdf) - : x(x), - y(y), - width(width), - height(height), - pixelRatio(pixelRatio), - sdf(sdf) { +SpritePosition::SpritePosition(uint16_t x_, uint16_t y_, uint16_t width_, uint16_t height_, float pixelRatio_, bool sdf_) + : x(x_), + y(y_), + width(width_), + height(height_), + pixelRatio(pixelRatio_), + sdf(sdf_) { } util::ptr<Sprite> Sprite::Create(const std::string& base_url, float pixelRatio, const util::ptr<FileSource> &fileSource) { @@ -28,11 +28,11 @@ util::ptr<Sprite> Sprite::Create(const std::string& base_url, float pixelRatio, return sprite; } -Sprite::Sprite(const Key &, const std::string& base_url, float pixelRatio) +Sprite::Sprite(const Key &, const std::string& base_url, float pixelRatio_) : valid(base_url.length() > 0), - pixelRatio(pixelRatio), - spriteURL(base_url + (pixelRatio > 1 ? "@2x" : "") + ".png"), - jsonURL(base_url + (pixelRatio > 1 ? "@2x" : "") + ".json"), + pixelRatio(pixelRatio_), + spriteURL(base_url + (pixelRatio_ > 1 ? "@2x" : "") + ".png"), + jsonURL(base_url + (pixelRatio_ > 1 ? "@2x" : "") + ".json"), raster(), loadedImage(false), loadedJSON(false), @@ -123,16 +123,16 @@ void Sprite::parseJSON() { uint16_t y = 0; uint16_t width = 0; uint16_t height = 0; - float pixelRatio = 1.0f; + float spritePixelRatio = 1.0f; bool sdf = false; if (value.HasMember("x")) x = value["x"].GetInt(); if (value.HasMember("y")) y = value["y"].GetInt(); if (value.HasMember("width")) width = value["width"].GetInt(); if (value.HasMember("height")) height = value["height"].GetInt(); - if (value.HasMember("pixelRatio")) pixelRatio = value["pixelRatio"].GetInt(); + if (value.HasMember("pixelRatio")) spritePixelRatio = value["pixelRatio"].GetInt(); if (value.HasMember("sdf")) sdf = value["sdf"].GetBool(); - pos.emplace(name, SpritePosition { x, y, width, height, pixelRatio, sdf }); + pos.emplace(name, SpritePosition { x, y, width, height, spritePixelRatio, sdf }); } } } else { diff --git a/src/map/tile.cpp b/src/map/tile.cpp index 863fbfbece..3070d3fd96 100644 --- a/src/map/tile.cpp +++ b/src/map/tile.cpp @@ -7,8 +7,8 @@ using namespace mbgl; #include <iostream> -Tile::Tile(const ID& id) - : id(id) { +Tile::Tile(const ID& id_) + : id(id_) { } Tile::ID Tile::ID::parent(int8_t parent_z) const { @@ -25,13 +25,13 @@ std::forward_list<Tile::ID> Tile::ID::children(int32_t child_z) const { assert(child_z > z); int32_t factor = std::pow(2, child_z - z); - std::forward_list<ID> children; + std::forward_list<ID> child_ids; for (int32_t ty = y * factor, y_max = (y + 1) * factor; ty < y_max; ++ty) { for (int32_t tx = x * factor, x_max = (x + 1) * factor; tx < x_max; ++tx) { - children.emplace_front(child_z, tx, ty); + child_ids.emplace_front(child_z, tx, ty); } } - return children; + return child_ids; } Tile::ID Tile::ID::normalized() const { @@ -42,13 +42,13 @@ Tile::ID Tile::ID::normalized() const { return ID { z, nx, ny }; } -bool Tile::ID::isChildOf(const Tile::ID &parent) const { - if (parent.z >= z || parent.w != w) { +bool Tile::ID::isChildOf(const Tile::ID &parent_id) const { + if (parent_id.z >= z || parent_id.w != w) { return false; } - int32_t scale = std::pow(2, z - parent.z); - return parent.x == ((x < 0 ? x - scale + 1 : x) / scale) && - parent.y == y / scale; + int32_t scale = std::pow(2, z - parent_id.z); + return parent_id.x == ((x < 0 ? x - scale + 1 : x) / scale) && + parent_id.y == y / scale; } diff --git a/src/map/tile_data.cpp b/src/map/tile_data.cpp index 44e3826bf5..7e4d1a1de1 100644 --- a/src/map/tile_data.cpp +++ b/src/map/tile_data.cpp @@ -9,14 +9,14 @@ using namespace mbgl; -TileData::TileData(Tile::ID id, Map &map, const util::ptr<SourceInfo> &source) - : id(id), +TileData::TileData(Tile::ID id_, Map &map_, const util::ptr<SourceInfo> &source_) + : id(id_), state(State::initial), - map(map), - source(source), + map(map_), + source(source_), debugBucket(debugFontBuffer) { // Initialize tile debug coordinates - const std::string str = util::sprintf<32>("%d/%d/%d", id.z, id.x, id.y); + const std::string str = util::sprintf<32>("%d/%d/%d", id_.z, id_.x, id_.y); debugFontBuffer.addText(str.c_str(), 50, 200, 5); } diff --git a/src/map/tile_parser.cpp b/src/map/tile_parser.cpp index 3dc5cb9cef..235151cd47 100644 --- a/src/map/tile_parser.cpp +++ b/src/map/tile_parser.cpp @@ -37,14 +37,14 @@ namespace mbgl { // its header file. TileParser::~TileParser() = default; -TileParser::TileParser(const std::string &data, VectorTileData &tile, +TileParser::TileParser(const std::string &data, VectorTileData &tile_, const util::ptr<const Style> &style_, const util::ptr<GlyphAtlas> &glyphAtlas_, const util::ptr<GlyphStore> &glyphStore_, const util::ptr<SpriteAtlas> &spriteAtlas_, const util::ptr<Sprite> &sprite_) : vector_data(pbf((const uint8_t *)data.data(), data.size())), - tile(tile), + tile(tile_), style(style_), glyphAtlas(glyphAtlas_), glyphStore(glyphStore_), diff --git a/src/map/transform.cpp b/src/map/transform.cpp index baa615b94a..b42f24a83d 100644 --- a/src/map/transform.cpp +++ b/src/map/transform.cpp @@ -17,7 +17,7 @@ const double R2D = 180.0 / M_PI; const double M2PI = 2 * M_PI; const double MIN_ROTATE_SCALE = 8; -Transform::Transform(View &view) : view(view), mtx(std::make_unique<uv::rwlock>()) { +Transform::Transform(View &view_) : view(view_), mtx(std::make_unique<uv::rwlock>()) { setScale(current.scale); setAngle(current.angle); } diff --git a/src/map/transform_state.cpp b/src/map/transform_state.cpp index 4b1bc4161e..0a858bce6a 100644 --- a/src/map/transform_state.cpp +++ b/src/map/transform_state.cpp @@ -96,8 +96,8 @@ float TransformState::lngX(float lon) const { } float TransformState::latY(float lat) const { - float y = 180 / M_PI * std::log(std::tan(M_PI / 4 + lat * M_PI / 360)); - return (180 - y) * worldSize() / 360; + float lat_y = 180 / M_PI * std::log(std::tan(M_PI / 4 + lat * M_PI / 360)); + return (180 - lat_y) * worldSize() / 360; } std::array<float, 2> TransformState::locationCoordinate(float lon, float lat) const { diff --git a/src/map/vector_tile.cpp b/src/map/vector_tile.cpp index 4ec25d6cf6..8f097c8292 100644 --- a/src/map/vector_tile.cpp +++ b/src/map/vector_tile.cpp @@ -103,9 +103,9 @@ VectorTileLayer::VectorTileLayer(pbf layer) : data(layer) { } } -FilteredVectorTileLayer::FilteredVectorTileLayer(const VectorTileLayer& layer, const FilterExpression &filterExpression) - : layer(layer), - filterExpression(filterExpression) { +FilteredVectorTileLayer::FilteredVectorTileLayer(const VectorTileLayer& layer_, const FilterExpression &filterExpression_) + : layer(layer_), + filterExpression(filterExpression_) { } FilteredVectorTileLayer::iterator FilteredVectorTileLayer::begin() const { @@ -116,10 +116,10 @@ FilteredVectorTileLayer::iterator FilteredVectorTileLayer::end() const { return iterator(*this, pbf(layer.data.end, 0)); } -FilteredVectorTileLayer::iterator::iterator(const FilteredVectorTileLayer& parent, const pbf& data) - : parent(parent), +FilteredVectorTileLayer::iterator::iterator(const FilteredVectorTileLayer& parent_, const pbf& data_) + : parent(parent_), feature(pbf()), - data(data) { + data(data_) { operator++(); } diff --git a/src/map/vector_tile_data.cpp b/src/map/vector_tile_data.cpp index 48b46059a5..b94bc66dea 100644 --- a/src/map/vector_tile_data.cpp +++ b/src/map/vector_tile_data.cpp @@ -8,8 +8,8 @@ using namespace mbgl; -VectorTileData::VectorTileData(Tile::ID id, Map &map, const util::ptr<SourceInfo> &source) - : TileData(id, map, source), +VectorTileData::VectorTileData(Tile::ID id_, Map &map_, const util::ptr<SourceInfo> &source_) + : TileData(id_, map_, source_), depth(id.z >= source->max_zoom ? map.getMaxZoom() - id.z : 1) { } diff --git a/src/renderer/debug_bucket.cpp b/src/renderer/debug_bucket.cpp index 699c1c1db9..58fbf8a35b 100644 --- a/src/renderer/debug_bucket.cpp +++ b/src/renderer/debug_bucket.cpp @@ -10,8 +10,8 @@ struct geometry_too_long_exception : std::exception {}; using namespace mbgl; -DebugBucket::DebugBucket(DebugFontBuffer& fontBuffer) - : fontBuffer(fontBuffer) { +DebugBucket::DebugBucket(DebugFontBuffer& fontBuffer_) + : fontBuffer(fontBuffer_) { } void DebugBucket::render(Painter& painter, util::ptr<StyleLayer> /*layer_desc*/, const Tile::ID& /*id*/, const mat4 &matrix) { diff --git a/src/renderer/fill_bucket.cpp b/src/renderer/fill_bucket.cpp index 5358cae0b2..0a7d77935d 100644 --- a/src/renderer/fill_bucket.cpp +++ b/src/renderer/fill_bucket.cpp @@ -30,11 +30,11 @@ void FillBucket::free(void *, void *ptr) { ::free(ptr); } -FillBucket::FillBucket(FillVertexBuffer &vertexBuffer, - TriangleElementsBuffer &triangleElementsBuffer, - LineElementsBuffer &lineElementsBuffer, - const StyleBucketFill &properties) - : properties(properties), +FillBucket::FillBucket(FillVertexBuffer &vertexBuffer_, + TriangleElementsBuffer &triangleElementsBuffer_, + LineElementsBuffer &lineElementsBuffer_, + const StyleBucketFill &properties_) + : properties(properties_), allocator(new TESSalloc{&alloc, &realloc, &free, nullptr, // userData 64, // meshEdgeBucketSize 64, // meshVertexBucketSize @@ -44,11 +44,11 @@ FillBucket::FillBucket(FillVertexBuffer &vertexBuffer, 128, // extraVertices allocated for the priority queue. }), tesselator(tessNewTess(allocator)), - vertexBuffer(vertexBuffer), - triangleElementsBuffer(triangleElementsBuffer), - lineElementsBuffer(lineElementsBuffer), - vertex_start(vertexBuffer.index()), - triangle_elements_start(triangleElementsBuffer.index()), + vertexBuffer(vertexBuffer_), + triangleElementsBuffer(triangleElementsBuffer_), + lineElementsBuffer(lineElementsBuffer_), + vertex_start(vertexBuffer_.index()), + triangle_elements_start(triangleElementsBuffer_.index()), line_elements_start(lineElementsBuffer.index()) { assert(tesselator); } @@ -123,10 +123,10 @@ void FillBucket::tessellate() { const size_t group_count = polygon.size(); assert(group_count >= 3); - std::vector<TESSreal> line; + std::vector<TESSreal> clipped_line; for (const ClipperLib::IntPoint& pt : polygon) { - line.push_back(pt.X); - line.push_back(pt.Y); + clipped_line.push_back(pt.X); + clipped_line.push_back(pt.Y); vertexBuffer.add(pt.X, pt.Y); } @@ -137,7 +137,7 @@ void FillBucket::tessellate() { lineIndex += group_count; - tessAddContour(tesselator, vertexSize, line.data(), stride, (int)line.size() / vertexSize); + tessAddContour(tesselator, vertexSize, clipped_line.data(), stride, (int)clipped_line.size() / vertexSize); } lineGroup.elements_length += total_vertex_count; diff --git a/src/renderer/line_bucket.cpp b/src/renderer/line_bucket.cpp index 3ef7411be6..8267cbaba2 100644 --- a/src/renderer/line_bucket.cpp +++ b/src/renderer/line_bucket.cpp @@ -17,17 +17,17 @@ struct geometry_too_long_exception : std::exception {}; using namespace mbgl; -LineBucket::LineBucket(LineVertexBuffer& vertexBuffer, - TriangleElementsBuffer& triangleElementsBuffer, - PointElementsBuffer& pointElementsBuffer, - const StyleBucketLine& properties) - : properties(properties), - vertexBuffer(vertexBuffer), - triangleElementsBuffer(triangleElementsBuffer), - pointElementsBuffer(pointElementsBuffer), - vertex_start(vertexBuffer.index()), - triangle_elements_start(triangleElementsBuffer.index()), - point_elements_start(pointElementsBuffer.index()) +LineBucket::LineBucket(LineVertexBuffer& vertexBuffer_, + TriangleElementsBuffer& triangleElementsBuffer_, + PointElementsBuffer& pointElementsBuffer_, + const StyleBucketLine& properties_) + : properties(properties_), + vertexBuffer(vertexBuffer_), + triangleElementsBuffer(triangleElementsBuffer_), + pointElementsBuffer(pointElementsBuffer_), + vertex_start(vertexBuffer_.index()), + triangle_elements_start(triangleElementsBuffer_.index()), + point_elements_start(pointElementsBuffer_.index()) { } @@ -53,7 +53,7 @@ void LineBucket::addGeometry(pbf& geom) { } struct TriangleElement { - TriangleElement(uint16_t a, uint16_t b, uint16_t c) : a(a), b(b), c(c) {} + TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) : a(a_), b(b_), c(c_) {} uint16_t a, b, c; }; diff --git a/src/renderer/painter.cpp b/src/renderer/painter.cpp index 474b7b954f..38c2176aed 100644 --- a/src/renderer/painter.cpp +++ b/src/renderer/painter.cpp @@ -21,8 +21,8 @@ using namespace mbgl; #define BUFFER_OFFSET(i) ((char *)nullptr + (i)) -Painter::Painter(Map &map) - : map(map) { +Painter::Painter(Map &map_) + : map(map_) { } Painter::~Painter() { @@ -85,9 +85,29 @@ void Painter::setupShaders() { if (!gaussianShader) gaussianShader = std::make_unique<GaussianShader>(); } +void Painter::deleteShaders() { + plainShader = nullptr; + outlineShader = nullptr; + lineShader = nullptr; + linejoinShader = nullptr; + linepatternShader = nullptr; + patternShader = nullptr; + iconShader = nullptr; + rasterShader = nullptr; + sdfGlyphShader = nullptr; + sdfIconShader = nullptr; + dotShader = nullptr; + gaussianShader = nullptr; +} + void Painter::cleanup() { } +void Painter::terminate() { + cleanup(); + deleteShaders(); +} + void Painter::resize() { const TransformState &state = map.getState(); if (gl_viewport != state.getFramebufferDimensions()) { @@ -108,10 +128,10 @@ void Painter::useProgram(uint32_t program) { } } -void Painter::lineWidth(float lineWidth) { - if (gl_lineWidth != lineWidth) { - glLineWidth(lineWidth); - gl_lineWidth = lineWidth; +void Painter::lineWidth(float line_width) { + if (gl_lineWidth != line_width) { + glLineWidth(line_width); + gl_lineWidth = line_width; } } diff --git a/src/renderer/prerendered_texture.cpp b/src/renderer/prerendered_texture.cpp index 0a47816323..adb7a59105 100644 --- a/src/renderer/prerendered_texture.cpp +++ b/src/renderer/prerendered_texture.cpp @@ -5,8 +5,8 @@ using namespace mbgl; -PrerenderedTexture::PrerenderedTexture(const StyleBucketRaster &properties) - : properties(properties) { +PrerenderedTexture::PrerenderedTexture(const StyleBucketRaster &properties_) + : properties(properties_) { } PrerenderedTexture::~PrerenderedTexture() { diff --git a/src/renderer/raster_bucket.cpp b/src/renderer/raster_bucket.cpp index fc5e3dd3c8..7adb3f845e 100644 --- a/src/renderer/raster_bucket.cpp +++ b/src/renderer/raster_bucket.cpp @@ -3,9 +3,9 @@ using namespace mbgl; -RasterBucket::RasterBucket(const util::ptr<Texturepool> &texturepool, const StyleBucketRaster& properties) -: properties(properties), - texture(properties), +RasterBucket::RasterBucket(const util::ptr<Texturepool> &texturepool, const StyleBucketRaster& properties_) +: properties(properties_), + texture(properties_), raster(texturepool) { } @@ -24,8 +24,8 @@ void RasterBucket::drawRaster(RasterShader& shader, StaticVertexBuffer &vertices glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices.index()); } -void RasterBucket::drawRaster(RasterShader& shader, StaticVertexBuffer &vertices, VertexArrayObject &array, GLuint texture) { - raster.bind(texture); +void RasterBucket::drawRaster(RasterShader& shader, StaticVertexBuffer &vertices, VertexArrayObject &array, GLuint texture_) { + raster.bind(texture_); shader.u_image = 0; array.bind(shader, vertices, BUFFER_OFFSET(0)); glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices.index()); diff --git a/src/renderer/symbol_bucket.cpp b/src/renderer/symbol_bucket.cpp index 3a4b017ef3..47cc4db44c 100644 --- a/src/renderer/symbol_bucket.cpp +++ b/src/renderer/symbol_bucket.cpp @@ -19,8 +19,8 @@ namespace mbgl { -SymbolBucket::SymbolBucket(const StyleBucketSymbol &properties, Collision &collision) - : properties(properties), collision(collision) {} +SymbolBucket::SymbolBucket(const StyleBucketSymbol &properties_, Collision &collision_) + : properties(properties_), collision(collision_) {} void SymbolBucket::render(Painter &painter, util::ptr<StyleLayer> layer_desc, const Tile::ID &id, const mat4 &matrix) { @@ -52,12 +52,12 @@ std::vector<SymbolFeature> SymbolBucket::processFeatures(const VectorTileLayer & const FilterExpression &filter, GlyphStore &glyphStore, const Sprite &sprite) { - const bool text = properties.text.field.size(); - const bool icon = properties.icon.image.size(); + const bool has_text = properties.text.field.size(); + const bool has_icon = properties.icon.image.size(); std::vector<SymbolFeature> features; - if (!text && !icon) { + if (!has_text && !has_icon) { return features; } @@ -72,7 +72,7 @@ std::vector<SymbolFeature> SymbolBucket::processFeatures(const VectorTileLayer & SymbolFeature ft; - if (text) { + if (has_text) { std::string u8string = util::replaceTokens(properties.text.field, feature.properties); if (properties.text.transform == TextTransformType::Uppercase) { @@ -91,7 +91,7 @@ std::vector<SymbolFeature> SymbolBucket::processFeatures(const VectorTileLayer & } } - if (icon) { + if (has_icon) { ft.sprite = util::replaceTokens(properties.icon.image, feature.properties); } diff --git a/src/shader/shader.cpp b/src/shader/shader.cpp index 91c9b58c89..d9f63cae12 100644 --- a/src/shader/shader.cpp +++ b/src/shader/shader.cpp @@ -8,8 +8,8 @@ using namespace mbgl; -Shader::Shader(const char *name, const GLchar *vertSource, const GLchar *fragSource) - : name(name), +Shader::Shader(const char *name_, const GLchar *vertSource, const GLchar *fragSource) + : name(name_), valid(false), program(0) { util::timer timer("shader compilation", Event::Shader); diff --git a/src/storage/file_request_baton.cpp b/src/storage/file_request_baton.cpp index 64c6c13b12..1b41a53706 100644 --- a/src/storage/file_request_baton.cpp +++ b/src/storage/file_request_baton.cpp @@ -2,6 +2,8 @@ #include <mbgl/storage/file_request.hpp> #include <mbgl/storage/response.hpp> +#include <limits> + namespace mbgl { FileRequestBaton::FileRequestBaton(FileRequest *request_, const std::string &path, uv_loop_t *loop) @@ -97,8 +99,7 @@ void FileRequestBaton::file_stated(uv_fs_t *req) { uv_fs_req_cleanup(req); uv_fs_close(req->loop, req, ptr->fd, file_closed); } else { - const unsigned int size = - (unsigned int)(stat->st_size); + const unsigned int size = (unsigned int)(stat->st_size); ptr->body.resize(size); ptr->buffer = uv_buf_init(const_cast<char *>(ptr->body.data()), size); uv_fs_req_cleanup(req); diff --git a/src/storage/file_source.cpp b/src/storage/file_source.cpp index 12d924416c..70b4abe4c7 100644 --- a/src/storage/file_source.cpp +++ b/src/storage/file_source.cpp @@ -27,12 +27,12 @@ FileSource::~FileSource() { // NOTE: We don't need to delete the messenger since it will be deleted by the // uv_messenger_stop() function. - util::ptr<BaseRequest> request; + util::ptr<BaseRequest> req; // Send a cancel() message to all requests that we are still holding. for (const std::pair<std::string, std::weak_ptr<BaseRequest>> &pair : pending) { - if ((request = pair.second.lock())) { - request->cancel(); + if ((req = pair.second.lock())) { + req->cancel(); } } } @@ -61,25 +61,25 @@ std::unique_ptr<Request> FileSource::request(ResourceType type, const std::strin } }(); - util::ptr<BaseRequest> request; + util::ptr<BaseRequest> req; // First, try to find an existing Request object. auto it = pending.find(absoluteURL); if (it != pending.end()) { - request = it->second.lock(); + req = it->second.lock(); } - if (!request) { + if (!req) { if (absoluteURL.substr(0, 7) == "file://") { - request = std::make_shared<FileRequest>(absoluteURL.substr(7), loop); + req = std::make_shared<FileRequest>(absoluteURL.substr(7), loop); } else { - request = std::make_shared<HTTPRequest>(type, absoluteURL, loop, store); + req = std::make_shared<HTTPRequest>(type, absoluteURL, loop, store); } - pending.emplace(absoluteURL, request); + pending.emplace(absoluteURL, req); } - return std::unique_ptr<Request>(new Request(request)); + return std::unique_ptr<Request>(new Request(req)); } void FileSource::prepare(std::function<void()> fn) { @@ -93,10 +93,10 @@ void FileSource::prepare(std::function<void()> fn) { void FileSource::retryAllPending() { assert(thread_id == uv_thread_self()); - util::ptr<BaseRequest> request; + util::ptr<BaseRequest> req; for (const std::pair<std::string, std::weak_ptr<BaseRequest>> &pair : pending) { - if ((request = pair.second.lock())) { - request->retryImmediately(); + if ((req = pair.second.lock())) { + req->retryImmediately(); } } diff --git a/src/storage/http_request.cpp b/src/storage/http_request.cpp index ca1412fd9e..46b1d5e194 100644 --- a/src/storage/http_request.cpp +++ b/src/storage/http_request.cpp @@ -20,8 +20,8 @@ struct CacheRequestBaton { util::ptr<SQLiteStore> store; }; -HTTPRequest::HTTPRequest(ResourceType type_, const std::string &path, uv_loop_t *loop_, util::ptr<SQLiteStore> store_) - : BaseRequest(path), thread_id(uv_thread_self()), loop(loop_), store(store_), type(type_) { +HTTPRequest::HTTPRequest(ResourceType type_, const std::string &path_, uv_loop_t *loop_, util::ptr<SQLiteStore> store_) + : BaseRequest(path_), thread_id(uv_thread_self()), loop(loop_), store(store_), type(type_) { if (store) { startCacheRequest(); } else { @@ -82,19 +82,19 @@ void HTTPRequest::startHTTPRequest(std::unique_ptr<Response> &&res) { #else uv_async_init(loop, http_baton->async, [](uv_async_t *async) { #endif - util::ptr<HTTPRequestBaton> &http_baton = *(util::ptr<HTTPRequestBaton> *)async->data; + util::ptr<HTTPRequestBaton> &baton = *(util::ptr<HTTPRequestBaton> *)async->data; - if (http_baton->request) { - HTTPRequest *request = http_baton->request; + if (baton->request) { + HTTPRequest *request = baton->request; request->http_baton.reset(); - http_baton->request = nullptr; - request->handleHTTPResponse(http_baton->type, std::move(http_baton->response)); + baton->request = nullptr; + request->handleHTTPResponse(baton->type, std::move(baton->response)); } delete (util::ptr<HTTPRequestBaton> *)async->data; uv_close((uv_handle_t *)async, [](uv_handle_t *handle) { - uv_async_t *async = (uv_async_t *)handle; - delete async; + uv_async_t *async_handle = (uv_async_t *)handle; + delete async_handle; }); }); attempts++; diff --git a/src/storage/response.cpp b/src/storage/response.cpp index cdaf33e4e4..f1e1c35874 100644 --- a/src/storage/response.cpp +++ b/src/storage/response.cpp @@ -9,7 +9,7 @@ int64_t Response::parseCacheControl(const char *value) { uint64_t seconds = 0; // TODO: cache-control may contain other information as well: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 - if (std::sscanf(value, "max-age=%llu", &seconds) == 1) { + if (std::sscanf(value, "max-age=%lu", &seconds) == 1) { return std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()).count() + seconds; diff --git a/src/storage/sqlite_store.cpp b/src/storage/sqlite_store.cpp index 763100f411..e0757ecc36 100644 --- a/src/storage/sqlite_store.cpp +++ b/src/storage/sqlite_store.cpp @@ -68,8 +68,8 @@ SQLiteStore::~SQLiteStore() { // Nothing to do. This function needs to be here because we're forward-declaring // Database, so we need the actual definition here to be able to properly destruct it. if (worker) { - uv_worker_close(worker, [](uv_worker_t *worker) { - delete worker; + uv_worker_close(worker, [](uv_worker_t *worker_handle) { + delete worker_handle; }); } } diff --git a/src/style/applied_class_properties.cpp b/src/style/applied_class_properties.cpp index ca9c09436c..9037c6ad5d 100644 --- a/src/style/applied_class_properties.cpp +++ b/src/style/applied_class_properties.cpp @@ -2,11 +2,11 @@ namespace mbgl { -AppliedClassProperty::AppliedClassProperty(ClassID class_id, timestamp begin, timestamp end, const PropertyValue &value) +AppliedClassProperty::AppliedClassProperty(ClassID class_id, timestamp begin_, timestamp end_, const PropertyValue &value_) : name(class_id), - begin(begin), - end(end), - value(value) {} + begin(begin_), + end(end_), + value(value_) {} // Returns thie ID of the most recent ClassID AppliedClassProperties::mostRecent() const { diff --git a/src/style/class_dictionary.cpp b/src/style/class_dictionary.cpp index 6e1eb5a879..ba7c0d55be 100644 --- a/src/style/class_dictionary.cpp +++ b/src/style/class_dictionary.cpp @@ -1,8 +1,34 @@ #include <mbgl/style/class_dictionary.hpp> +#include <uv.h> + namespace mbgl { -ClassID ClassDictionary::Lookup(const std::string &class_name) { +ClassDictionary::ClassDictionary() {} + +ClassDictionary &ClassDictionary::Get() { + // Note: We should eventually switch to uv_key_* functions, but libuv 0.10 doesn't have these + // yet. Instead, we're using the pthread functions directly for now. + static pthread_once_t store_once = PTHREAD_ONCE_INIT; + static pthread_key_t store_key; + + // Create the key. + pthread_once(&store_once, []() { + pthread_key_create(&store_key, [](void *ptr) { + delete reinterpret_cast<ClassDictionary *>(ptr); + }); + }); + + ClassDictionary *ptr = reinterpret_cast<ClassDictionary *>(pthread_getspecific(store_key)); + if (ptr == nullptr) { + ptr = new ClassDictionary(); + pthread_setspecific(store_key, ptr); + } + + return *ptr; +} + +ClassID ClassDictionary::lookup(const std::string &class_name) { auto it = store.find(class_name); if (it == store.end()) { // Insert the class name into the store. @@ -14,7 +40,7 @@ ClassID ClassDictionary::Lookup(const std::string &class_name) { } } -ClassID ClassDictionary::Normalize(ClassID id) { +ClassID ClassDictionary::normalize(ClassID id) { if (id >= ClassID::Named) { return ClassID::Named; } else { @@ -22,8 +48,4 @@ ClassID ClassDictionary::Normalize(ClassID id) { } } - -std::unordered_map<std::string, ClassID> ClassDictionary::store = { { "", ClassID::Default } }; -uint32_t ClassDictionary::offset = 0; - } diff --git a/src/style/style.cpp b/src/style/style.cpp index 6f0a0e3b28..aa5b150882 100644 --- a/src/style/style.cpp +++ b/src/style/style.cpp @@ -12,6 +12,7 @@ #include <rapidjson/document.h> +#include <algorithm> namespace mbgl { diff --git a/src/style/style_layer.cpp b/src/style/style_layer.cpp index d78750195b..4d64386be8 100644 --- a/src/style/style_layer.cpp +++ b/src/style/style_layer.cpp @@ -7,8 +7,8 @@ namespace mbgl { -StyleLayer::StyleLayer(const std::string &id, std::map<ClassID, ClassProperties> &&styles) - : id(id), styles(std::move(styles)) {} +StyleLayer::StyleLayer(const std::string &id_, std::map<ClassID, ClassProperties> &&styles_) + : id(id_), styles(std::move(styles_)) {} bool StyleLayer::isBackground() const { return type == StyleLayerType::Background; @@ -23,7 +23,7 @@ void StyleLayer::setClasses(const std::vector<std::string> &class_names, const t for (auto it = class_names.rbegin(); it != class_names.rend(); it++) { const std::string &class_name = *it; // From here on, we're only dealing with IDs to avoid comparing strings all the time. - const ClassID class_id = ClassDictionary::Lookup(class_name); + const ClassID class_id = ClassDictionary::Get().lookup(class_name); applyClassProperties(class_id, already_applied, now, defaultTransition); } @@ -70,8 +70,8 @@ void StyleLayer::applyClassProperties(const ClassID class_id, // Loop through all the properties in this style, and add transitions to them, if they're // not already the most recent transition. - const ClassProperties &properties = style_it->second; - for (const std::pair<PropertyKey, PropertyValue> &property_pair : properties) { + const ClassProperties &class_properties = style_it->second; + for (const std::pair<PropertyKey, PropertyValue> &property_pair : class_properties) { PropertyKey key = property_pair.first; if (already_applied.find(key) != already_applied.end()) { // This property has already been set by a previous class. @@ -87,7 +87,7 @@ void StyleLayer::applyClassProperties(const ClassID class_id, AppliedClassProperties &appliedProperties = appliedStyle[key]; if (appliedProperties.mostRecent() != class_id) { const PropertyTransition &transition = - properties.getTransition(key, defaultTransition); + class_properties.getTransition(key, defaultTransition); const timestamp begin = now + transition.delay * 1_millisecond; const timestamp end = begin + transition.duration * 1_millisecond; const PropertyValue &value = property_pair.second; @@ -99,7 +99,7 @@ void StyleLayer::applyClassProperties(const ClassID class_id, template <typename T> struct PropertyEvaluator { typedef T result_type; - PropertyEvaluator(float z) : z(z) {} + PropertyEvaluator(float z_) : z(z_) {} template <typename P, typename std::enable_if<std::is_convertible<P, T>::value, int>::type = 0> T operator()(const P &value) const { @@ -269,11 +269,11 @@ void StyleLayer::cleanupAppliedStyleProperties(timestamp now) { auto it = appliedStyle.begin(); const auto end = appliedStyle.end(); while (it != end) { - AppliedClassProperties &properties = it->second; - properties.cleanup(now); + AppliedClassProperties &applied_properties = it->second; + applied_properties.cleanup(now); // If the current properties object is empty, remove it from the map entirely. - if (properties.empty()) { + if (applied_properties.empty()) { appliedStyle.erase(it++); } else { ++it; diff --git a/src/style/style_parser.cpp b/src/style/style_parser.cpp index 3aa12a6670..47ff0c30ab 100644 --- a/src/style/style_parser.cpp +++ b/src/style/style_parser.cpp @@ -6,6 +6,8 @@ #include <mbgl/platform/log.hpp> #include <csscolorparser/csscolorparser.hpp> +#include <algorithm> + namespace mbgl { using JSVal = const rapidjson::Value&; @@ -108,13 +110,13 @@ template<> bool StyleParser::parseRenderProperty(JSVal value, uint16_t &target, if (value.HasMember(name)) { JSVal property = replaceConstant(value[name]); if (property.IsUint()) { - unsigned int value = property.GetUint(); - if (value > std::numeric_limits<uint16_t>::max()) { + unsigned int int_value = property.GetUint(); + if (int_value > std::numeric_limits<uint16_t>::max()) { Log::Warning(Event::ParseStyle, "values for %s that are larger than %d are not supported", name, std::numeric_limits<uint16_t>::max()); return false; } - target = value; + target = int_value; return true; } else { Log::Warning(Event::ParseStyle, "%s must be an unsigned integer", name); @@ -554,7 +556,7 @@ void StyleParser::parseStyles(JSVal value, std::map<ClassID, ClassProperties> &s if (name == "style") { parseStyle(replaceConstant(itr->value), styles[ClassID::Default]); } else if (name.compare(0, 6, "style.") == 0 && name.length() > 6) { - const ClassID class_id = ClassDictionary::Lookup(name.substr(6)); + const ClassID class_id = ClassDictionary::Get().lookup(name.substr(6)); parseStyle(replaceConstant(itr->value), styles[class_id]); } } @@ -763,11 +765,11 @@ FilterExpression StyleParser::parseFilter(JSVal value, FilterExpression::Operato FilterComparison comparison(name); JSVal filterValue = replaceConstant(itr->value); if (filterValue.IsObject()) { - rapidjson::Value::ConstMemberIterator itr = filterValue.MemberBegin(); - for (; itr != filterValue.MemberEnd(); ++itr) { + rapidjson::Value::ConstMemberIterator filter_itr = filterValue.MemberBegin(); + for (; filter_itr != filterValue.MemberEnd(); ++filter_itr) { comparison.add( - parseFilterComparisonOperator({ itr->name.GetString(), itr->name.GetStringLength() }), - parseValues(replaceConstant(itr->value)) + parseFilterComparisonOperator({ filter_itr->name.GetString(), filter_itr->name.GetStringLength() }), + parseValues(replaceConstant(filter_itr->value)) ); } } else if (filterValue.IsArray()) { diff --git a/src/text/collision.cpp b/src/text/collision.cpp index 6326bea825..2e0ec6dce2 100644 --- a/src/text/collision.cpp +++ b/src/text/collision.cpp @@ -19,11 +19,11 @@ Box getBox(const CollisionAnchor &anchor, const CollisionRect &bbox, float minSc }; }; -Collision::Collision(float zoom, float tileExtent, float tileSize, float placementDepth) +Collision::Collision(float zoom_, float tileExtent, float tileSize, float placementDepth) // tile pixels per screen pixels at the tile's zoom level : tilePixelRatio(tileExtent / tileSize), - zoom(zoom), + zoom(zoom_), // Calculate the maximum scale we can go down in our fake-3d rtree so that // placement still makes sense. This is calculated so that the minimum @@ -33,7 +33,7 @@ Collision::Collision(float zoom, float tileExtent, float tileSize, float placeme // We don't want to place labels all the way to 25.5. This lets too many // glyphs be placed, slowing down collision checking. Only place labels if // they will show up within the intended zoom range of the tile. - maxPlacementScale(std::exp(std::log(2) * util::min(3.0f, placementDepth, 25.5f - zoom))) { + maxPlacementScale(std::exp(std::log(2) * util::min(3.0f, placementDepth, 25.5f - zoom_))) { const float m = 4096; const float edge = m * tilePixelRatio * 2; diff --git a/src/text/glyph_store.cpp b/src/text/glyph_store.cpp index 1723bd3d94..5619c4f93f 100644 --- a/src/text/glyph_store.cpp +++ b/src/text/glyph_store.cpp @@ -228,7 +228,7 @@ void GlyphPBF::parse(FontStack &stack) { data.clear(); } -GlyphStore::GlyphStore(const util::ptr<FileSource> &fileSource) : fileSource(fileSource) {} +GlyphStore::GlyphStore(const util::ptr<FileSource> &fileSource_) : fileSource(fileSource_) {} void GlyphStore::setURL(const std::string &url) { glyphURL = url; diff --git a/src/text/placement.cpp b/src/text/placement.cpp index 0c95e3a80d..84d4e20b2f 100644 --- a/src/text/placement.cpp +++ b/src/text/placement.cpp @@ -12,10 +12,10 @@ namespace mbgl { const float Placement::globalMinScale = 0.5; // underscale by 1 zoom level struct GlyphInstance { - explicit GlyphInstance(const vec2<float> &anchor) : anchor(anchor) {} - explicit GlyphInstance(const vec2<float> &anchor, float offset, float minScale, float maxScale, - float angle) - : anchor(anchor), offset(offset), minScale(minScale), maxScale(maxScale), angle(angle) {} + explicit GlyphInstance(const vec2<float> &anchor_) : anchor(anchor_) {} + explicit GlyphInstance(const vec2<float> &anchor_, float offset_, float minScale_, float maxScale_, + float angle_) + : anchor(anchor_), offset(offset_), minScale(minScale_), maxScale(maxScale_), angle(angle_) {} const vec2<float> anchor; const float offset = 0.0f; diff --git a/src/util/image.cpp b/src/util/image.cpp index 28906c4e91..fd0d34de2d 100644 --- a/src/util/image.cpp +++ b/src/util/image.cpp @@ -1,4 +1,5 @@ #include <mbgl/util/image.hpp> + #include <png.h> #include <cassert> @@ -30,8 +31,8 @@ std::string mbgl::util::compress_png(int width, int height, void *rgba, bool fli } std::string result; - png_set_write_fn(png_ptr, &result, [](png_structp png_ptr, png_bytep data, png_size_t length) { - std::string *out = static_cast<std::string *>(png_get_io_ptr(png_ptr)); + png_set_write_fn(png_ptr, &result, [](png_structp png_ptr_, png_bytep data, png_size_t length) { + std::string *out = static_cast<std::string *>(png_get_io_ptr(png_ptr_)); out->append(reinterpret_cast<char *>(data), length); }, NULL); @@ -57,8 +58,8 @@ using namespace mbgl::util; struct Buffer { - Buffer(const std::string& data) - : data(data.data()), length(data.size()) {} + Buffer(const std::string& data_) + : data(data_.data()), length(data_.size()) {} const char *const data = 0; const size_t length = 0; size_t pos = 0; diff --git a/src/util/raster.cpp b/src/util/raster.cpp index 7b52c51037..76cd411223 100644 --- a/src/util/raster.cpp +++ b/src/util/raster.cpp @@ -6,15 +6,13 @@ #include <mbgl/util/uv_detail.hpp> #include <mbgl/util/std.hpp> -#include <png.h> - #include <cassert> #include <cstring> using namespace mbgl; -Raster::Raster(const util::ptr<Texturepool> &texturepool) - : texturepool(texturepool) +Raster::Raster(const util::ptr<Texturepool> &texturepool_) + : texturepool(texturepool_) {} Raster::~Raster() { @@ -59,32 +57,32 @@ void Raster::bind(bool linear) { glBindTexture(GL_TEXTURE_2D, texture); } - GLuint filter = linear ? GL_LINEAR : GL_NEAREST; - if (filter != this->filter) { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); - this->filter = filter; + GLuint new_filter = linear ? GL_LINEAR : GL_NEAREST; + if (new_filter != this->filter) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, new_filter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, new_filter); + filter = new_filter; } } // overload ::bind for prerendered raster textures -void Raster::bind(const GLuint texture) { +void Raster::bind(const GLuint custom_texture) { if (img && !textured) { - glBindTexture(GL_TEXTURE_2D, texture); + glBindTexture(GL_TEXTURE_2D, custom_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img->getData()); img.reset(); textured = true; } else if (textured) { - glBindTexture(GL_TEXTURE_2D, texture); + glBindTexture(GL_TEXTURE_2D, custom_texture); } - GLuint filter = GL_LINEAR; - if (filter != this->filter) { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); - this->filter = filter; + GLuint new_filter = GL_LINEAR; + if (new_filter != this->filter) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, new_filter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, new_filter); + filter = new_filter; } } diff --git a/src/util/timer.cpp b/src/util/timer.cpp index d56860d193..5c4af51da4 100644 --- a/src/util/timer.cpp +++ b/src/util/timer.cpp @@ -8,22 +8,22 @@ using namespace mbgl::util; -timer::timer(Event event) - : event(event), start(now()) {} +timer::timer(Event event_) + : event(event_), start(now()) {} -timer::timer(EventSeverity severity, Event event) - : severity(severity), event(event), start(now()) {} +timer::timer(EventSeverity severity_, Event event_) + : severity(severity_), event(event_), start(now()) {} -timer::timer(const std::string &name, Event event) - : name(name), event(event), start(now()) {} +timer::timer(const std::string &name_, Event event_) + : name(name_), event(event_), start(now()) {} -timer::timer(const std::string &name, EventSeverity severity, Event event) - : name(name), severity(severity), event(event), start(now()) {} +timer::timer(const std::string &name_, EventSeverity severity_, Event event_) + : name(name_), severity(severity_), event(event_), start(now()) {} -void timer::report(const std::string &name) { +void timer::report(const std::string &name_) { timestamp duration = now() - start; - Log::Record(severity, event, name + ": " + std::to_string((double)(duration) / 1_millisecond) + "ms"); + Log::Record(severity, event, name_ + ": " + std::to_string((double)(duration) / 1_millisecond) + "ms"); start += duration; } diff --git a/src/util/uv-messenger.c b/src/util/uv-messenger.c index 82df1cae75..bfa1565768 100644 --- a/src/util/uv-messenger.c +++ b/src/util/uv-messenger.c @@ -8,7 +8,6 @@ typedef struct { void *queue[2]; } uv__messenger_item_t; - #if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" diff --git a/test/comparisons.cpp b/test/comparisons.cpp index e1e991d41c..4ffcf2e2ec 100644 --- a/test/comparisons.cpp +++ b/test/comparisons.cpp @@ -10,7 +10,7 @@ class MockExtractor { public: - inline MockExtractor(const std::multimap<std::string, mbgl::Value> &values) : values(values) {} + inline MockExtractor(const std::multimap<std::string, mbgl::Value> &values_) : values(values_) {} inline MockExtractor() {} inline std::vector<mbgl::Value> getValues(const std::string &key) const { diff --git a/test/enums.cpp b/test/enums.cpp index 67ff0aa7e8..b45fc0ed0d 100644 --- a/test/enums.cpp +++ b/test/enums.cpp @@ -8,8 +8,6 @@ using namespace mbgl; TEST(Enums, StyleLayerType) { - std::cerr << StyleLayerType::Raster; - ASSERT_EQ(StyleLayerType::Unknown, StyleLayerTypeClass("unknown")); ASSERT_EQ(StyleLayerType::Fill, StyleLayerTypeClass("fill")); ASSERT_EQ(StyleLayerType::Line, StyleLayerTypeClass("line")); diff --git a/test/fixtures/fixture_log.cpp b/test/fixtures/fixture_log.cpp index c2c10fc9eb..1b1646e665 100644 --- a/test/fixtures/fixture_log.cpp +++ b/test/fixtures/fixture_log.cpp @@ -9,25 +9,25 @@ FixtureLogBackend::~FixtureLogBackend() { } size_t FixtureLogBackend::count(const LogMessage &message) const { - size_t count = 0; + size_t message_count = 0; for (const LogMessage &msg : messages) { if (msg == message) { - count++; + message_count++; msg.checked = true; } } - return count; + return message_count; } std::vector<FixtureLogBackend::LogMessage> FixtureLogBackend::unchecked() const { - std::vector<LogMessage> unchecked; + std::vector<LogMessage> unchecked_messages; for (const LogMessage &msg : messages) { if (!msg.checked) { - unchecked.push_back(msg); + unchecked_messages.push_back(msg); msg.checked = true; } } - return unchecked; + return unchecked_messages; } ::std::ostream& operator<<(::std::ostream& os, const std::vector<FixtureLogBackend::LogMessage>& messages) { diff --git a/test/fixtures/fixture_log.hpp b/test/fixtures/fixture_log.hpp index 263871575b..99097a2c47 100644 --- a/test/fixtures/fixture_log.hpp +++ b/test/fixtures/fixture_log.hpp @@ -3,8 +3,7 @@ #include <mbgl/platform/log.hpp> #include <mbgl/util/noncopyable.hpp> - -#include <boost/optional.hpp> +#include <mbgl/util/optional.hpp> #include <vector> #include <cstdarg> @@ -14,14 +13,14 @@ namespace mbgl { class FixtureLogBackend : public LogBackend, private util::noncopyable { public: struct LogMessage { - inline LogMessage(EventSeverity severity, Event event, int64_t code, const std::string &msg) - : severity(severity), event(event), code(code), msg(msg) {} - inline LogMessage(EventSeverity severity, Event event, int64_t code) - : severity(severity), event(event), code(code) {} - inline LogMessage(EventSeverity severity, Event event, const std::string &msg) - : severity(severity), event(event), msg(msg) {} - inline LogMessage(EventSeverity severity, Event event) - : severity(severity), event(event) {} + inline LogMessage(EventSeverity severity_, Event event_, int64_t code_, const std::string &msg_) + : severity(severity_), event(event_), code(code_), msg(msg_) {} + inline LogMessage(EventSeverity severity_, Event event_, int64_t code_) + : severity(severity_), event(event_), code(code_), msg() {} + inline LogMessage(EventSeverity severity_, Event event_, const std::string &msg_) + : severity(severity_), event(event_), code(), msg(msg_) {} + inline LogMessage(EventSeverity severity_, Event event_) + : severity(severity_), event(event_), code(), msg() {} inline bool operator==(const LogMessage &rhs) const { return (!severity || !rhs.severity || severity.get() == rhs.severity.get()) && @@ -30,10 +29,10 @@ public: (!msg || !rhs.msg || msg.get() == rhs.msg.get()); } - const boost::optional<EventSeverity> severity; - const boost::optional<Event> event; - const boost::optional<int64_t> code; - const boost::optional<std::string> msg; + const mapbox::util::optional<EventSeverity> severity; + const mapbox::util::optional<Event> event; + const mapbox::util::optional<int64_t> code; + const mapbox::util::optional<std::string> msg; mutable bool checked = false; }; diff --git a/test/fixtures/fixture_request.cpp b/test/fixtures/fixture_request.cpp index d1687bbf57..f3b41681a6 100644 --- a/test/fixtures/fixture_request.cpp +++ b/test/fixtures/fixture_request.cpp @@ -4,6 +4,7 @@ #include <mbgl/util/url.hpp> #include <mbgl/util/std.hpp> #include <mbgl/platform/log.hpp> +#include <iostream> #include <uv.h> diff --git a/test/headless.cpp b/test/headless.cpp index 3255cff062..02dd0165ec 100644 --- a/test/headless.cpp +++ b/test/headless.cpp @@ -10,6 +10,7 @@ #include <rapidjson/stringbuffer.h> #include "../common/headless_view.hpp" +#include "../common/headless_display.hpp" #include "./fixtures/fixture_log.hpp" @@ -22,6 +23,8 @@ const std::string base_directory = []{ return fn + "/node_modules/mapbox-gl-test-suite/"; }(); +auto display_ = std::make_shared<mbgl::HeadlessDisplay>(); + class HeadlessTest : public ::testing::TestWithParam<std::string> {}; TEST_P(HeadlessTest, render) { @@ -78,7 +81,7 @@ TEST_P(HeadlessTest, render) { } } - HeadlessView view; + HeadlessView view(display_); Map map(view); map.setStyleJSON(style, base_directory); @@ -95,10 +98,7 @@ TEST_P(HeadlessTest, render) { const unsigned int w = width * pixelRatio; const unsigned int h = height * pixelRatio; - const std::unique_ptr<uint32_t[]> pixels(new uint32_t[w * h]); - glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels.get()); - - const std::string image = util::compress_png(w, h, pixels.get(), true); + const std::string image = util::compress_png(w, h, view.readPixels().get(), true); util::write_file(actual_image, image); } } diff --git a/test/test.gyp b/test/test.gyp index 865bac8673..49cc33739d 100644 --- a/test/test.gyp +++ b/test/test.gyp @@ -168,6 +168,8 @@ "./headless.cpp", "../common/headless_view.hpp", "../common/headless_view.cpp", + "../common/headless_display.hpp", + "../common/headless_display.cpp", "../common/platform_default.cpp", "./fixtures/fixture_request.cpp", "./fixtures/fixture_log.hpp", diff --git a/test/variant.cpp b/test/variant.cpp index dd4578b49d..4557465cfa 100644 --- a/test/variant.cpp +++ b/test/variant.cpp @@ -4,13 +4,6 @@ #include <mbgl/style/value.hpp> #include <mbgl/style/value_comparison.hpp> -#pragma GCC diagnostic push -#ifndef __clang__ -#pragma GCC diagnostic ignored "-Wunused-local-typedefs" -#endif -#include <boost/lexical_cast.hpp> -#pragma GCC diagnostic pop - using namespace mbgl; TEST(Variant, toString) { diff --git a/travis/travis-resources.template b/travis/travis-resources.template index afe0478e33..e1b0cff8ca 100644 --- a/travis/travis-resources.template +++ b/travis/travis-resources.template @@ -1,7 +1,7 @@ { "AWSTemplateFormatVersion": "2010-09-09", - "Description": "mapbox-gl-native travis resources", + "Description": "node-mapbox-gl-native travis resources", "Resources": { "BuildUser": { "Type": "AWS::IAM::User", @@ -17,7 +17,7 @@ ], "Effect": "Allow", "Resource": [ - "arn:aws:s3:::mapbox-gl-testing" + "arn:aws:s3:::node-mapbox-gl-native" ] } ] @@ -37,6 +37,42 @@ ], "Effect": "Allow", "Resource": [ + "arn:aws:s3:::node-mapbox-gl-native/*" + ] + } + ] + } + }, + { + "PolicyName": "list-testing", + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "s3:ListBucket" + ], + "Effect": "Allow", + "Resource": [ + "arn:aws:s3:::mapbox-gl-testing" + ] + } + ] + } + }, + { + "PolicyName": "build-testing", + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "s3:DeleteObject", + "s3:GetObject", + "s3:GetObjectAcl", + "s3:PutObject", + "s3:PutObjectAcl" + ], + "Effect": "Allow", + "Resource": [ "arn:aws:s3:::mapbox-gl-testing/*" ] } |