Merge branch 'master' into new-labelling

Conflicts:
	src/mbgl/map/tile_parser.cpp
	src/mbgl/map/tile_parser.hpp
	src/mbgl/renderer/painter.hpp
	src/mbgl/renderer/painter_symbol.cpp
	src/mbgl/renderer/symbol_bucket.cpp
	src/mbgl/renderer/symbol_bucket.hpp
	src/mbgl/text/collision.cpp
	src/mbgl/text/collision.hpp
	src/mbgl/text/placement.cpp
This commit is contained in:
Ansis Brammanis
2015-05-19 11:09:33 -04:00
548 changed files with 36596 additions and 5382 deletions

View File

@@ -23,7 +23,11 @@ public:
if (width <= ref.w && height <= ref.h) {
if (smallest == free.end() || (ref.y <= rect.y && ref.x <= rect.x)) {
smallest = it;
} else {
// Our current "smallest" rect is already closer to 0/0.
}
} else {
// The rect in the free list is not big enough.
}
}

View File

@@ -2,6 +2,7 @@
#define MBGL_GEOMETRY_BUFFER
#include <mbgl/platform/gl.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/map/environment.hpp>
@@ -38,17 +39,16 @@ public:
}
// Transfers this buffer to the GPU and binds the buffer to the GL context.
void bind(bool force = false) {
if (buffer == 0) {
void bind() {
if (buffer) {
MBGL_CHECK_ERROR(glBindBuffer(bufferType, buffer));
} else {
MBGL_CHECK_ERROR(glGenBuffers(1, &buffer));
force = true;
}
MBGL_CHECK_ERROR(glBindBuffer(bufferType, buffer));
if (force) {
MBGL_CHECK_ERROR(glBindBuffer(bufferType, buffer));
if (array == nullptr) {
throw std::runtime_error("Buffer was already deleted or doesn't contain elements");
Log::Debug(Event::OpenGL, "Buffer doesn't contain elements");
pos = 0;
}
MBGL_CHECK_ERROR(glBufferData(bufferType, pos, array, GL_STATIC_DRAW));
if (!retainAfterUpload) {
cleanup();
@@ -67,6 +67,13 @@ public:
return buffer;
}
// Uploads the buffer to the GPU to be available when we need it.
inline void upload() {
if (!buffer) {
bind();
}
}
protected:
// increase the buffer size by at least /required/ bytes.
inline void *addElement() {

View File

@@ -4,6 +4,8 @@
#include <mbgl/platform/log.hpp>
#include <mbgl/platform/platform.hpp>
#include <mbgl/util/std.hpp>
#include <cassert>
#include <algorithm>
@@ -14,7 +16,7 @@ GlyphAtlas::GlyphAtlas(uint16_t width_, uint16_t height_)
: width(width_),
height(height_),
bin(width_, height_),
data(new char[width_ *height_]),
data(util::make_unique<uint8_t[]>(width_ * height_)),
dirty(true) {
}
@@ -88,13 +90,12 @@ Rect<uint16_t> GlyphAtlas::addGlyph(uintptr_t tileUID,
face.emplace(glyph.id, GlyphValue { rect, tileUID });
// Copy the bitmap
char *target = data.get();
const char *source = glyph.bitmap.data();
const uint8_t* source = reinterpret_cast<const uint8_t*>(glyph.bitmap.data());
for (uint32_t y = 0; y < buffered_height; y++) {
uint32_t y1 = width * (rect.y + y) + rect.x;
uint32_t y2 = buffered_width * y;
for (uint32_t x = 0; x < buffered_width; x++) {
target[y1 + x] = source[y2 + x];
data[y1 + x] = source[y2 + x];
}
}
@@ -116,7 +117,7 @@ void GlyphAtlas::removeGlyphs(uintptr_t tileUID) {
const Rect<uint16_t>& rect = value.rect;
// Clear out the bitmap.
char *target = data.get();
uint8_t *target = data.get();
for (uint32_t y = 0; y < rect.h; y++) {
uint32_t y1 = width * (rect.y + y) + rect.x;
for (uint32_t x = 0; x < rect.w; x++) {
@@ -124,8 +125,6 @@ void GlyphAtlas::removeGlyphs(uintptr_t tileUID) {
}
}
dirty = true;
bin.release(rect);
// Make sure to post-increment the iterator: This will return the
@@ -140,6 +139,47 @@ void GlyphAtlas::removeGlyphs(uintptr_t tileUID) {
}
}
void GlyphAtlas::upload() {
if (dirty) {
const bool first = !texture;
bind();
std::lock_guard<std::mutex> lock(mtx);
if (first) {
MBGL_CHECK_ERROR(glTexImage2D(
GL_TEXTURE_2D, // GLenum target
0, // GLint level
GL_ALPHA, // GLint internalformat
width, // GLsizei width
height, // GLsizei height
0, // GLint border
GL_ALPHA, // GLenum format
GL_UNSIGNED_BYTE, // GLenum type
data.get() // const GLvoid* data
));
} else {
MBGL_CHECK_ERROR(glTexSubImage2D(
GL_TEXTURE_2D, // GLenum target
0, // GLint level
0, // GLint xoffset
0, // GLint yoffset
width, // GLsizei width
height, // GLsizei height
GL_ALPHA, // GLenum format
GL_UNSIGNED_BYTE, // GLenum type
data.get() // const GLvoid* data
));
}
dirty = false;
#if defined(DEBUG)
// platform::showDebugImage("Glyph Atlas", data.get(), width, height);
#endif
}
}
void GlyphAtlas::bind() {
if (!texture) {
MBGL_CHECK_ERROR(glGenTextures(1, &texture));
@@ -154,14 +194,4 @@ void GlyphAtlas::bind() {
} else {
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture));
}
if (dirty) {
std::lock_guard<std::mutex> lock(mtx);
MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data.get()));
dirty = false;
#if defined(DEBUG)
// platform::showDebugImage("Glyph Atlas", data, width, height);
#endif
}
};

View File

@@ -24,8 +24,13 @@ public:
GlyphPositions&);
void removeGlyphs(uintptr_t tileUID);
// Binds the atlas texture to the GPU, and uploads data if it is out of date.
void bind();
// Uploads the texture to the GPU to be available when we need it. This is a lazy operation;
// the texture is only bound when the data is out of date (=dirty).
void upload();
const uint16_t width = 0;
const uint16_t height = 0;
@@ -44,7 +49,7 @@ private:
std::mutex mtx;
BinPack<uint16_t> bin;
std::map<std::string, std::map<uint32_t, GlyphValue>> index;
std::unique_ptr<char[]> data;
const std::unique_ptr<uint8_t[]> data;
std::atomic<bool> dirty;
uint32_t texture = 0;
};

View File

@@ -3,6 +3,7 @@
#include <mbgl/platform/gl.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/platform/platform.hpp>
#include <mbgl/util/std.hpp>
#include <boost/functional/hash.hpp>
@@ -14,7 +15,7 @@ using namespace mbgl;
LineAtlas::LineAtlas(uint16_t w, uint16_t h)
: width(w),
height(h),
data(new char[w * h]),
data(util::make_unique<uint8_t[]>(w * h)),
dirty(true) {
}
@@ -23,8 +24,6 @@ LineAtlas::~LineAtlas() {
Environment::Get().abandonTexture(texture);
texture = 0;
delete[] data;
}
LinePatternPos LineAtlas::getDashPosition(const std::vector<float> &dasharray, bool round) {
@@ -129,6 +128,12 @@ LinePatternPos LineAtlas::addDash(const std::vector<float> &dasharray, bool roun
return position;
};
void LineAtlas::upload() {
if (dirty) {
bind();
}
}
void LineAtlas::bind() {
std::lock_guard<std::recursive_mutex> lock(mtx);
@@ -147,7 +152,7 @@ void LineAtlas::bind() {
if (dirty) {
if (first) {
glTexImage2D(
MBGL_CHECK_ERROR(glTexImage2D(
GL_TEXTURE_2D, // GLenum target
0, // GLint level
GL_ALPHA, // GLint internalformat
@@ -156,10 +161,10 @@ void LineAtlas::bind() {
0, // GLint border
GL_ALPHA, // GLenum format
GL_UNSIGNED_BYTE, // GLenum type
data // const GLvoid * data
);
data.get() // const GLvoid * data
));
} else {
glTexSubImage2D(
MBGL_CHECK_ERROR(glTexSubImage2D(
GL_TEXTURE_2D, // GLenum target
0, // GLint level
0, // GLint xoffset
@@ -168,8 +173,8 @@ void LineAtlas::bind() {
height, // GLsizei height
GL_ALPHA, // GLenum format
GL_UNSIGNED_BYTE, // GLenum type
data // const GLvoid *pixels
);
data.get() // const GLvoid *pixels
));
}

View File

@@ -19,8 +19,13 @@ public:
LineAtlas(uint16_t width, uint16_t height);
~LineAtlas();
// Binds the atlas texture to the GPU, and uploads data if it is out of date.
void bind();
// Uploads the texture to the GPU to be available when we need it. This is a lazy operation;
// the texture is only bound when the data is out of date (=dirty).
void upload();
LinePatternPos getDashPosition(const std::vector<float>&, bool);
LinePatternPos addDash(const std::vector<float> &dasharray, bool round);
@@ -29,7 +34,7 @@ public:
private:
std::recursive_mutex mtx;
char *const data = nullptr;
const std::unique_ptr<uint8_t[]> data;
std::atomic<bool> dirty;
uint32_t texture = 0;
int nextRow = 0;

View File

@@ -33,9 +33,7 @@ bool SpriteAtlas::resize(const float newRatio) {
pixelRatio = newRatio;
if (data) {
uint32_t *old_data = data;
data = nullptr;
const auto oldData = std::move(data);
allocate();
const int old_w = width * oldRatio;
@@ -44,20 +42,17 @@ bool SpriteAtlas::resize(const float newRatio) {
const int new_h = height * newRatio;
// Basic image scaling. TODO: Replace this with better image scaling.
uint32_t *img_new = reinterpret_cast<uint32_t *>(data);
const uint32_t *img_old = reinterpret_cast<const uint32_t *>(old_data);
for (int y = 0; y < new_h; y++) {
const int old_yoffset = ((y * old_h) / new_h) * old_w;
const int new_yoffset = y * new_w;
for (int x = 0; x < new_w; x++) {
const int old_x = (x * old_w) / new_w;
img_new[new_yoffset + x] = img_old[old_yoffset + old_x];
data[new_yoffset + x] = oldData[old_yoffset + old_x];
}
}
::operator delete(old_data);
dirty = true;
fullUploadRequired = true;
// Mark all sprite images as in need of update
for (const auto &pair : images) {
@@ -143,8 +138,8 @@ void SpriteAtlas::allocate() {
if (!data) {
dimension w = static_cast<dimension>(width * pixelRatio);
dimension h = static_cast<dimension>(height * pixelRatio);
data = static_cast<uint32_t*>(::operator new(w * h * sizeof(uint32_t)));
std::fill(data, data + w * h, 0);
data = util::make_unique<uint32_t[]>(w * h);
std::fill(data.get(), data.get() + w * h, 0);
}
}
@@ -157,7 +152,7 @@ void SpriteAtlas::copy(const Rect<dimension>& dst, const SpritePosition& src, co
const Rect<uint32_t> srcPos { src.x, src.y, src.width, src.height };
allocate();
uint32_t *dstData = reinterpret_cast<uint32_t *>(data);
uint32_t *const dstData = data.get();
const vec2<uint32_t> dstSize { static_cast<unsigned int>(width * pixelRatio),
static_cast<unsigned int>(height * pixelRatio) };
const Rect<uint32_t> dstPos { static_cast<uint32_t>(dst.x * pixelRatio),
@@ -230,8 +225,13 @@ void SpriteAtlas::setSprite(util::ptr<Sprite> sprite_) {
});
}
void SpriteAtlas::upload() {
if (dirty) {
bind();
}
}
void SpriteAtlas::bind(bool linear) {
bool first = false;
if (!texture) {
MBGL_CHECK_ERROR(glGenTextures(1, &texture));
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture));
@@ -242,7 +242,7 @@ void SpriteAtlas::bind(bool linear) {
// We use those when the pixelRatio isn't a power of two, e.g. on iPhone 6 Plus.
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
first = true;
fullUploadRequired = true;
} else {
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture));
}
@@ -258,7 +258,7 @@ void SpriteAtlas::bind(bool linear) {
std::lock_guard<std::recursive_mutex> lock(mtx);
allocate();
if (first) {
if (fullUploadRequired) {
MBGL_CHECK_ERROR(glTexImage2D(
GL_TEXTURE_2D, // GLenum target
0, // GLint level
@@ -268,8 +268,9 @@ void SpriteAtlas::bind(bool linear) {
0, // GLint border
GL_RGBA, // GLenum format
GL_UNSIGNED_BYTE, // GLenum type
data // const GLvoid * data
data.get() // const GLvoid * data
));
fullUploadRequired = false;
} else {
MBGL_CHECK_ERROR(glTexSubImage2D(
GL_TEXTURE_2D, // GLenum target
@@ -280,7 +281,7 @@ void SpriteAtlas::bind(bool linear) {
height * pixelRatio, // GLsizei height
GL_RGBA, // GLenum format
GL_UNSIGNED_BYTE, // GLenum type
data // const GLvoid *pixels
data.get() // const GLvoid *pixels
));
}
@@ -296,5 +297,4 @@ SpriteAtlas::~SpriteAtlas() {
std::lock_guard<std::recursive_mutex> lock(mtx);
Environment::Get().abandonTexture(texture);
texture = 0;
::operator delete(data), data = nullptr;
}

View File

@@ -50,10 +50,13 @@ public:
SpriteAtlasPosition getPosition(const std::string& name, bool repeating = false);
// Binds the image buffer of this sprite atlas to the GPU, and uploads data if it is out
// of date.
// Binds the atlas texture to the GPU, and uploads data if it is out of date.
void bind(bool linear = false);
// Uploads the texture to the GPU to be available when we need it. This is a lazy operation;
// the texture is only bound when the data is out of date (=dirty).
void upload();
inline float getWidth() const { return width; }
inline float getHeight() const { return height; }
inline float getTextureWidth() const { return width * pixelRatio; }
@@ -74,8 +77,9 @@ private:
util::ptr<Sprite> sprite;
std::map<std::string, Rect<dimension>> images;
std::set<std::string> uninitialized;
uint32_t *data = nullptr;
std::unique_ptr<uint32_t[]> data;
std::atomic<bool> dirty;
bool fullUploadRequired = true;
uint32_t texture = 0;
uint32_t filter = 0;
static const int buffer = 1;

View File

@@ -5,11 +5,46 @@
namespace mbgl {
static gl::ExtensionFunction<
void (GLuint array)>
BindVertexArray({
{"GL_ARB_vertex_array_object", "glBindVertexArray"},
{"GL_OES_vertex_array_object", "glBindVertexArrayOES"},
{"GL_APPLE_vertex_array_object", "glBindVertexArrayAPPLE"}
});
static gl::ExtensionFunction<
void (GLsizei n,
const GLuint* arrays)>
DeleteVertexArrays({
{"GL_ARB_vertex_array_object", "glDeleteVertexArrays"},
{"GL_OES_vertex_array_object", "glDeleteVertexArraysOES"},
{"GL_APPLE_vertex_array_object", "glDeleteVertexArraysAPPLE"}
});
static gl::ExtensionFunction<
void (GLsizei n,
GLuint* arrays)>
GenVertexArrays({
{"GL_ARB_vertex_array_object", "glGenVertexArrays"},
{"GL_OES_vertex_array_object", "glGenVertexArraysOES"},
{"GL_APPLE_vertex_array_object", "glGenVertexArraysAPPLE"}
});
void VertexArrayObject::Unbind() {
if (!BindVertexArray) return;
MBGL_CHECK_ERROR(BindVertexArray(0));
}
void VertexArrayObject::Delete(GLsizei n, const GLuint* arrays) {
MBGL_CHECK_ERROR(DeleteVertexArrays(n, arrays));
}
VertexArrayObject::VertexArrayObject() {
}
VertexArrayObject::~VertexArrayObject() {
if (!gl::DeleteVertexArrays) return;
if (!DeleteVertexArrays) return;
if (vao) {
Environment::Get().abandonVAO(vao);
@@ -17,7 +52,7 @@ VertexArrayObject::~VertexArrayObject() {
}
void VertexArrayObject::bindVertexArrayObject() {
if (!gl::GenVertexArrays || !gl::BindVertexArray) {
if (!GenVertexArrays || !BindVertexArray) {
static bool reported = false;
if (!reported) {
Log::Warning(Event::OpenGL, "Not using Vertex Array Objects");
@@ -27,9 +62,9 @@ void VertexArrayObject::bindVertexArrayObject() {
}
if (!vao) {
MBGL_CHECK_ERROR(gl::GenVertexArrays(1, &vao));
MBGL_CHECK_ERROR(GenVertexArrays(1, &vao));
}
MBGL_CHECK_ERROR(gl::BindVertexArray(vao));
MBGL_CHECK_ERROR(BindVertexArray(vao));
}
void VertexArrayObject::verifyBinding(Shader &shader, GLuint vertexBuffer, GLuint elementsBuffer,

View File

@@ -11,6 +11,9 @@ namespace mbgl {
class VertexArrayObject : public util::noncopyable {
public:
static void Unbind();
static void Delete(GLsizei n, const GLuint* arrays);
VertexArrayObject();
~VertexArrayObject();

195
src/mbgl/gl/debugging.cpp Normal file
View File

@@ -0,0 +1,195 @@
#include <mbgl/gl/debugging.hpp>
#include <mbgl/platform/gl.hpp>
#include <mbgl/platform/event.hpp>
#include <mbgl/platform/log.hpp>
#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242
#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243
#define GL_DEBUG_CALLBACK_FUNCTION 0x8244
#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245
#define GL_DEBUG_SOURCE_API 0x8246
#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247
#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248
#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249
#define GL_DEBUG_SOURCE_APPLICATION 0x824A
#define GL_DEBUG_SOURCE_OTHER 0x824B
#define GL_DEBUG_TYPE_ERROR 0x824C
#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D
#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E
#define GL_DEBUG_TYPE_PORTABILITY 0x824F
#define GL_DEBUG_TYPE_PERFORMANCE 0x8250
#define GL_DEBUG_TYPE_OTHER 0x8251
#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143
#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144
#define GL_DEBUG_LOGGED_MESSAGES 0x9145
#define GL_DEBUG_SEVERITY_HIGH 0x9146
#define GL_DEBUG_SEVERITY_MEDIUM 0x9147
#define GL_DEBUG_SEVERITY_LOW 0x9148
#define GL_DEBUG_TYPE_MARKER 0x8268
#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269
#define GL_DEBUG_TYPE_POP_GROUP 0x826A
#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B
#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C
#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D
#define GL_BUFFER 0x82E0
#define GL_SHADER 0x82E1
#define GL_PROGRAM 0x82E2
#define GL_QUERY 0x82E3
#define GL_PROGRAM_PIPELINE 0x82E4
#define GL_SAMPLER 0x82E6
#define GL_MAX_LABEL_LENGTH 0x82E8
#define GL_DEBUG_OUTPUT 0x92E0
#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002
#define GL_DISPLAY_LIST 0x82E7
#define GL_VERTEX_ARRAY 0x8074
#define GL_TRANSFORM_FEEDBACK 0x8E22
#define GL_TEXTURE 0x1702
#define GL_RENDERBUFFER 0x8D41
#define GL_FRAMEBUFFER 0x8D40
namespace mbgl {
namespace gl {
namespace debugging {
typedef void (*GLDEBUGPROC)(GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar *message,
const void *userParam);
static ExtensionFunction<
void (GLenum source,
GLenum type,
GLenum severity,
GLsizei count,
const GLuint *ids,
GLboolean enabled)>
DebugMessageControl({
{"GL_KHR_debug", "glDebugMessageControl"},
{"GL_ARB_debug_output", "glDebugMessageControlARB"}
});
static ExtensionFunction<
void (GLDEBUGPROC callback,
const void *userParam)>
DebugMessageCallback({
{"GL_KHR_debug", "glDebugMessageCallback"},
{"GL_ARB_debug_output", "glDebugMessageCallbackARB"}
});
static ExtensionFunction<
void (GLenum source,
GLuint id,
GLsizei length,
const GLchar *message)>
PushDebugGroup({
{"GL_KHR_debug", "glPushDebugGroup"}
});
static ExtensionFunction<
void ()>
PopDebugGroup({
{"GL_KHR_debug", "glPopDebugGroup"}
});
static ExtensionFunction<
void (GLsizei length,
const GLchar *marker)>
PushGroupMarkerEXT({
{"GL_EXT_debug_marker", "glPushGroupMarkerEXT"}
});
static ExtensionFunction<
void ()>
PopGroupMarkerEXT({
{"GL_EXT_debug_marker", "glPopGroupMarkerEXT"}
});
void debugCallback(GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei /*length*/,
const GLchar* message,
const void* /*userParam*/)
{
std::string strSource;
switch (source) {
case GL_DEBUG_SOURCE_API: strSource = "DEBUG_SOURCE_API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: strSource = "DEBUG_SOURCE_WINDOW_SYSTEM"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: strSource = "DEBUG_SOURCE_SHADER_COMPILER"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: strSource = "DEBUG_SOURCE_THIRD_PARTY"; break;
case GL_DEBUG_SOURCE_APPLICATION: strSource = "DEBUG_SOURCE_APPLICATION"; break;
case GL_DEBUG_SOURCE_OTHER: strSource = "DEBUG_SOURCE_OTHER"; break;
default: strSource = "(unknown)"; break;
}
std::string strType;
switch (type) {
case GL_DEBUG_TYPE_ERROR: strType = "DEBUG_TYPE_ERROR"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: strType = "DEBUG_TYPE_DEPRECATED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: strType = "DEBUG_TYPE_UNDEFINED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_PERFORMANCE: strType = "DEBUG_TYPE_PERFORMANCE"; break;
case GL_DEBUG_TYPE_PORTABILITY: strType = "DEBUG_TYPE_PORTABILITY"; break;
case GL_DEBUG_TYPE_OTHER: strType = "DEBUG_TYPE_OTHER"; break;
case GL_DEBUG_TYPE_MARKER: strType = "DEBUG_TYPE_MARKER"; break;
case GL_DEBUG_TYPE_PUSH_GROUP: strType = "DEBUG_TYPE_OTHER"; break;
case GL_DEBUG_TYPE_POP_GROUP: strType = "DEBUG_TYPE_POP_GROUP"; break;
default: strSource = "(unknown)"; break;
}
std::string strSeverity;
mbgl::EventSeverity evtSeverity;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH: strSeverity = "DEBUG_SEVERITY_HIGH"; evtSeverity = mbgl::EventSeverity::Error; break;
case GL_DEBUG_SEVERITY_MEDIUM: strSeverity = "DEBUG_SEVERITY_MEDIUM"; evtSeverity = mbgl::EventSeverity::Warning; break;
case GL_DEBUG_SEVERITY_LOW: strSeverity = "DEBUG_SEVERITY_LOW"; evtSeverity = mbgl::EventSeverity::Info; break;
case GL_DEBUG_SEVERITY_NOTIFICATION: strSeverity = "DEBUG_SEVERITY_NOTIFICATION"; evtSeverity = mbgl::EventSeverity::Debug; break;
default: strSource = "(unknown)"; evtSeverity = mbgl::EventSeverity::Debug; break;
}
mbgl::Log::Record(evtSeverity, mbgl::Event::OpenGL, "GL_%s GL_%s %u GL_%s - %s", strSource.c_str(), strType.c_str(), id, strSeverity.c_str(), message);
}
void enable() {
if (!DebugMessageControl || !DebugMessageCallback) {
return;
}
// This will enable all messages including performance hints
//MBGL_CHECK_ERROR(DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE));
// This will only enable high and medium severity messages
MBGL_CHECK_ERROR(DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE));
MBGL_CHECK_ERROR(DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE));
MBGL_CHECK_ERROR(DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE));
MBGL_CHECK_ERROR(DebugMessageCallback(debugCallback, nullptr));
}
#if defined(DEBUG)
group::group(const std::string& str) {
if (PushDebugGroup) {
PushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0, GLsizei(str.size()), str.c_str());
} else if (PushGroupMarkerEXT) {
PushGroupMarkerEXT(GLsizei(str.size()), str.c_str());
}
}
group::~group() {
if (PopDebugGroup) {
PopDebugGroup();
} else if (PopGroupMarkerEXT) {
PopGroupMarkerEXT();
}
}
#else
group::group(const std::string&) {}
group::~group() = default;
#endif
}
}
}

21
src/mbgl/gl/debugging.hpp Normal file
View File

@@ -0,0 +1,21 @@
#ifndef MBGL_GL_DEBUG_MESSAGES
#define MBGL_GL_DEBUG_MESSAGES
#include <string>
namespace mbgl {
namespace gl {
namespace debugging {
void enable();
struct group {
group(const std::string&);
~group();
};
}
}
}
#endif

View File

@@ -2,6 +2,8 @@
#include <mbgl/map/map.hpp>
#include <mbgl/map/tile_id.hpp>
#include <mbgl/map/live_tile.hpp>
#include <mbgl/map/map_data.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/util/std.hpp>
@@ -83,8 +85,10 @@ vec2<double> AnnotationManager::projectPoint(const LatLng& point) {
return { x, y };
}
std::pair<std::vector<TileID>, AnnotationIDs> AnnotationManager::addPointAnnotations(
const std::vector<LatLng>& points, const std::vector<std::string>& symbols, const Map& map) {
std::pair<std::vector<TileID>, AnnotationIDs>
AnnotationManager::addPointAnnotations(const std::vector<LatLng>& points,
const std::vector<std::string>& symbols,
const MapData& data) {
std::lock_guard<std::mutex> lock(mtx);
// We pre-generate tiles to contain each annotation up to the map's max zoom.
@@ -109,7 +113,7 @@ std::pair<std::vector<TileID>, AnnotationIDs> AnnotationManager::addPointAnnotat
util::make_unique<Annotation>(AnnotationType::Point,
AnnotationSegments({ { points[i] } })));
const uint8_t maxZoom = map.getMaxZoom();
const uint8_t maxZoom = data.transform.getMaxZoom();
// side length of map at this zoom
uint32_t z2 = 1 << maxZoom;
@@ -181,13 +185,14 @@ std::pair<std::vector<TileID>, AnnotationIDs> AnnotationManager::addPointAnnotat
return std::make_pair(affectedTiles, annotationIDs);
}
std::vector<TileID> AnnotationManager::removeAnnotations(const AnnotationIDs& ids, const Map& map) {
std::vector<TileID> AnnotationManager::removeAnnotations(const AnnotationIDs& ids,
const MapData& data) {
std::lock_guard<std::mutex> lock(mtx);
std::vector<TileID> affectedTiles;
std::vector<uint32_t> z2s;
uint8_t zoomCount = map.getMaxZoom() + 1;
const uint8_t zoomCount = data.transform.getMaxZoom() + 1;
z2s.reserve(zoomCount);
for (uint8_t z = 0; z < zoomCount; ++z) {
z2s.emplace_back(1<< z);
@@ -231,10 +236,10 @@ std::vector<TileID> AnnotationManager::removeAnnotations(const AnnotationIDs& id
}
std::vector<uint32_t> AnnotationManager::getAnnotationsInBounds(const LatLngBounds& queryBounds,
const Map& map) const {
const MapData& data) const {
std::lock_guard<std::mutex> lock(mtx);
const uint8_t z = map.getMaxZoom();
const uint8_t z = data.transform.getMaxZoom();
const uint32_t z2 = 1 << z;
const vec2<double> swPoint = projectPoint(queryBounds.sw);
const vec2<double> nePoint = projectPoint(queryBounds.ne);

View File

@@ -19,6 +19,7 @@ namespace mbgl {
class Annotation;
class Map;
class LiveTile;
class MapData;
using AnnotationIDs = std::vector<uint32_t>;
@@ -29,9 +30,9 @@ public:
void setDefaultPointAnnotationSymbol(const std::string& symbol);
std::pair<std::vector<TileID>, AnnotationIDs> addPointAnnotations(
const std::vector<LatLng>&, const std::vector<std::string>& symbols, const Map&);
std::vector<TileID> removeAnnotations(const AnnotationIDs&, const Map&);
AnnotationIDs getAnnotationsInBounds(const LatLngBounds&, const Map&) const;
const std::vector<LatLng>&, const std::vector<std::string>& symbols, const MapData&);
std::vector<TileID> removeAnnotations(const AnnotationIDs&, const MapData&);
AnnotationIDs getAnnotationsInBounds(const LatLngBounds&, const MapData&) const;
LatLngBounds getBoundsForAnnotations(const AnnotationIDs&) const;
const LiveTile* getTile(const TileID& id);

View File

@@ -1,6 +1,8 @@
#include <mbgl/map/environment.hpp>
#include <mbgl/storage/file_source.hpp>
#include <mbgl/platform/gl.hpp>
#include <mbgl/util/run_loop.hpp>
#include <mbgl/geometry/vao.hpp>
#include <uv.h>
@@ -34,10 +36,7 @@ public:
void registerThread(Environment* env, ThreadType type, const std::string& name) {
std::lock_guard<std::mutex> lock(mtx);
// FIXME: We should never need to overwrite a thread here and we only allow
// this today because on the Static mode, the Map thread and the Main thread
// are same. Replace this with emplace() when this gets fixed.
threadSet[std::this_thread::get_id()] = ThreadInfo{ env, type, name };
threadSet.emplace(std::this_thread::get_id(), ThreadInfo{ env, type, name });
}
void unregisterThread() {
@@ -88,7 +87,7 @@ EnvironmentScope::~EnvironmentScope() {
}
Environment::Environment(FileSource& fs)
: id(makeEnvironmentID()), fileSource(fs), loop(uv_loop_new()) {
: id(makeEnvironmentID()), fileSource(fs) {
}
Environment::~Environment() {
@@ -120,15 +119,9 @@ unsigned Environment::getID() const {
return id;
}
void Environment::requestAsync(const Resource& resource,
std::function<void(const Response&)> callback) {
fileSource.request(resource, *this, std::move(callback));
}
Request* Environment::request(const Resource& resource,
std::function<void(const Response&)> callback) {
assert(currentlyOn(ThreadType::Map));
return fileSource.request(resource, loop, *this, std::move(callback));
return fileSource.request(resource, util::RunLoop::current.get()->get(), std::move(callback));
}
void Environment::cancelRequest(Request* req) {
@@ -160,8 +153,8 @@ void Environment::performCleanup() {
assert(currentlyOn(ThreadType::Map));
if (!abandonedVAOs.empty()) {
MBGL_CHECK_ERROR(gl::DeleteVertexArrays(static_cast<GLsizei>(abandonedVAOs.size()),
abandonedVAOs.data()));
MBGL_CHECK_ERROR(VertexArrayObject::Delete(static_cast<GLsizei>(abandonedVAOs.size()),
abandonedVAOs.data()));
abandonedVAOs.clear();
}
@@ -178,10 +171,4 @@ void Environment::performCleanup() {
}
}
// #############################################################################################
void Environment::terminate() {
fileSource.abort(*this);
}
}

View File

@@ -11,7 +11,7 @@ using namespace mbgl;
LiveTileData::LiveTileData(const TileID& id_,
AnnotationManager& annotationManager_,
float mapMaxZoom,
util::ptr<Style> style_,
Style& style_,
GlyphAtlas& glyphAtlas_,
GlyphStore& glyphStore_,
SpriteAtlas& spriteAtlas_,
@@ -21,13 +21,17 @@ LiveTileData::LiveTileData(const TileID& id_,
spriteAtlas_, sprite_, source_),
annotationManager(annotationManager_) {
// live features are always ready
state = State::loaded;
setState(State::loaded);
}
LiveTileData::~LiveTileData() {}
LiveTileData::~LiveTileData() {
// Cancel in most derived class destructor so that worker tasks are joined before
// any member data goes away.
cancel();
}
void LiveTileData::parse() {
if (state != State::loaded) {
if (getState() != State::loaded) {
return;
}
@@ -35,32 +39,19 @@ void LiveTileData::parse() {
if (tile) {
try {
if (!style) {
throw std::runtime_error("style isn't present in LiveTileData object anymore");
}
// Parsing creates state that is encapsulated in TileParser. While parsing,
// the TileParser object writes results into this objects. All other state
// is going to be discarded afterwards.
TileParser parser(*tile, *this, style, glyphAtlas, glyphStore, spriteAtlas, sprite);
// Clear the style so that we don't have a cycle in the shared_ptr references.
style.reset();
parser.parse();
} catch (const std::exception& ex) {
Log::Error(Event::ParseTile, "Live-parsing [%d/%d/%d] failed: %s", id.z, id.x, id.y, ex.what());
state = State::obsolete;
setState(State::obsolete);
return;
}
} else {
// Clear the style so that we don't have a cycle in the shared_ptr references.
style.reset();
state = State::obsolete;
}
if (state != State::obsolete) {
state = State::parsed;
if (getState() != State::obsolete) {
setState(State::parsed);
}
}

View File

@@ -12,7 +12,7 @@ public:
LiveTileData(const TileID&,
AnnotationManager&,
float mapMaxZoom,
util::ptr<Style>,
Style&,
GlyphAtlas&,
GlyphStore&,
SpriteAtlas&,

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,277 @@
#include <mbgl/map/map_context.hpp>
#include <mbgl/map/map_data.hpp>
#include <mbgl/map/view.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/map/source.hpp>
#include <mbgl/map/still_image.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/renderer/painter.hpp>
#include <mbgl/text/glyph_store.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <mbgl/util/worker.hpp>
#include <mbgl/util/texture_pool.hpp>
#include <mbgl/util/mapbox.hpp>
#include <mbgl/util/exception.hpp>
namespace mbgl {
MapContext::MapContext(uv_loop_t* loop, View& view_, FileSource& fileSource, MapData& data_)
: view(view_),
data(data_),
env(fileSource),
envScope(env, ThreadType::Map, "Map"),
updated(static_cast<UpdateType>(Update::Nothing)),
asyncUpdate(util::make_unique<uv::async>(loop, [this] { update(); })),
glyphStore(util::make_unique<GlyphStore>(loop, env)),
glyphAtlas(util::make_unique<GlyphAtlas>(1024, 1024)),
spriteAtlas(util::make_unique<SpriteAtlas>(512, 512)),
lineAtlas(util::make_unique<LineAtlas>(512, 512)),
texturePool(util::make_unique<TexturePool>()) {
assert(Environment::currentlyOn(ThreadType::Map));
asyncUpdate->unref();
view.activate();
}
MapContext::~MapContext() {
view.notify();
// Explicit resets currently necessary because these abandon resources that need to be
// cleaned up by env.performCleanup();
resourceLoader.reset();
style.reset();
painter.reset();
texturePool.reset();
lineAtlas.reset();
spriteAtlas.reset();
glyphAtlas.reset();
glyphStore.reset();
env.performCleanup();
view.deactivate();
}
void MapContext::pause() {
MBGL_CHECK_ERROR(glFinish());
view.deactivate();
std::unique_lock<std::mutex> lockPause(data.mutexPause);
data.condPaused.notify_all();
data.condResume.wait(lockPause);
view.activate();
}
void MapContext::resize(uint16_t width, uint16_t height, float ratio) {
view.resize(width, height, ratio);
triggerUpdate();
}
void MapContext::triggerUpdate(const Update u) {
updated |= static_cast<UpdateType>(u);
asyncUpdate->send();
}
void MapContext::setStyleURL(const std::string& url) {
styleURL = mbgl::util::mapbox::normalizeStyleURL(url, data.getAccessToken());
styleJSON.clear();
const size_t pos = styleURL.rfind('/');
std::string base = "";
if (pos != std::string::npos) {
base = styleURL.substr(0, pos + 1);
}
env.request({ Resource::Kind::JSON, styleURL }, [this, base](const Response &res) {
if (res.status == Response::Successful) {
loadStyleJSON(res.data, base);
} else {
Log::Error(Event::Setup, "loading style failed: %s", res.message.c_str());
}
});
}
void MapContext::setStyleJSON(const std::string& json, const std::string& base) {
styleURL.clear();
styleJSON = json;
loadStyleJSON(json, base);
}
void MapContext::loadStyleJSON(const std::string& json, const std::string& base) {
assert(Environment::currentlyOn(ThreadType::Map));
resourceLoader.reset();
style.reset();
style = util::make_unique<Style>();
style->base = base;
style->loadJSON((const uint8_t *)json.c_str());
style->cascade(data.getClasses());
style->setDefaultTransitionDuration(data.getDefaultTransitionDuration());
const std::string glyphURL = util::mapbox::normalizeGlyphsURL(style->glyph_url, data.getAccessToken());
glyphStore->setURL(glyphURL);
resourceLoader = util::make_unique<ResourceLoader>();
resourceLoader->setAccessToken(data.getAccessToken());
resourceLoader->setObserver(this);
resourceLoader->setStyle(style.get());
resourceLoader->setGlyphStore(glyphStore.get());
triggerUpdate(Update::Zoom);
}
void MapContext::updateTiles() {
assert(Environment::currentlyOn(ThreadType::Map));
resourceLoader->update(data, transformState, *glyphAtlas, *spriteAtlas, *texturePool);
}
void MapContext::updateAnnotationTiles(const std::vector<TileID>& ids) {
assert(Environment::currentlyOn(ThreadType::Map));
if (!style) return;
for (const auto &source : style->sources) {
if (source->info.type == SourceType::Annotations) {
source->invalidateTiles(ids);
}
}
triggerUpdate();
}
void MapContext::update() {
assert(Environment::currentlyOn(ThreadType::Map));
const auto now = Clock::now();
data.setAnimationTime(now);
updated |= data.transform.updateTransitions(now);
transformState = data.transform.currentState();
if (style) {
if (updated & static_cast<UpdateType>(Update::DefaultTransitionDuration)) {
style->setDefaultTransitionDuration(data.getDefaultTransitionDuration());
}
if (updated & static_cast<UpdateType>(Update::Classes)) {
style->cascade(data.getClasses());
}
if (updated & static_cast<UpdateType>(Update::Classes) ||
updated & static_cast<UpdateType>(Update::Zoom)) {
style->recalculate(transformState.getNormalizedZoom(), now);
}
updateTiles();
if (style->isLoaded() && resourceLoader->getSprite()->isLoaded()) {
if (!data.getFullyLoaded()) {
data.setFullyLoaded(true);
}
} else {
if (data.getFullyLoaded()) {
data.setFullyLoaded(false);
}
}
view.invalidate([this] { render(); });
}
updated = static_cast<UpdateType>(Update::Nothing);
}
void MapContext::renderStill(StillImageCallback fn) {
if (data.mode != MapMode::Still) {
throw util::Exception("Map is not in still image render mode");
}
if (callback) {
throw util::Exception("Map is currently rendering an image");
}
callback = fn;
triggerUpdate(Update::RenderStill);
}
void MapContext::render() {
assert(Environment::currentlyOn(ThreadType::Map));
// Cleanup OpenGL objects that we abandoned since the last render call.
env.performCleanup();
if (data.mode == MapMode::Still && (!callback || !data.getFullyLoaded())) {
// We are either not waiting for a map to be rendered, or we don't have all resources yet.
return;
}
assert(style);
if (!painter) {
painter = util::make_unique<Painter>(*spriteAtlas, *glyphAtlas, *lineAtlas);
painter->setup();
}
painter->setDebug(data.getDebug());
painter->render(*style, transformState, data.getAnimationTime());
if (data.mode == MapMode::Still) {
callback(view.readStillImage());
callback = nullptr;
}
// Schedule another rerender when we definitely need a next frame.
if (data.transform.needsTransition() || style->hasTransitions()) {
triggerUpdate();
}
}
double MapContext::getTopOffsetPixelsForAnnotationSymbol(const std::string& symbol) {
assert(Environment::currentlyOn(ThreadType::Map));
const SpritePosition pos = resourceLoader->getSprite()->getSpritePosition(symbol);
return -pos.height / pos.pixelRatio / 2;
}
void MapContext::setSourceTileCacheSize(size_t size) {
assert(Environment::currentlyOn(ThreadType::Map));
if (size != sourceCacheSize) {
sourceCacheSize = size;
if (!style) return;
for (const auto &source : style->sources) {
source->setCacheSize(sourceCacheSize);
}
view.invalidate([this] { render(); });
}
}
void MapContext::onLowMemory() {
assert(Environment::currentlyOn(ThreadType::Map));
if (!style) return;
for (const auto &source : style->sources) {
source->onLowMemory();
}
view.invalidate([this] { render(); });
}
void MapContext::onTileDataChanged() {
assert(Environment::currentlyOn(ThreadType::Map));
triggerUpdate();
}
}

View File

@@ -0,0 +1,102 @@
#ifndef MBGL_MAP_MAP_CONTEXT
#define MBGL_MAP_MAP_CONTEXT
#include <mbgl/map/tile_id.hpp>
#include <mbgl/map/update.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/map/resource_loader.hpp>
#include <mbgl/map/transform_state.hpp>
#include <mbgl/util/ptr.hpp>
#include <vector>
typedef struct uv_loop_s uv_loop_t;
namespace uv {
class async;
}
namespace mbgl {
class View;
class MapData;
class GlyphStore;
class GlyphAtlas;
class SpriteAtlas;
class LineAtlas;
class TexturePool;
class Painter;
class Sprite;
class Style;
class Worker;
class StillImage;
struct LatLng;
struct LatLngBounds;
class MapContext : public ResourceLoader::Observer {
public:
MapContext(uv_loop_t*, View&, FileSource&, MapData&);
~MapContext();
void pause();
void render();
void resize(uint16_t width, uint16_t height, float ratio);
using StillImageCallback = std::function<void(std::unique_ptr<const StillImage>)>;
void renderStill(StillImageCallback callback);
void triggerUpdate(Update = Update::Nothing);
void setStyleURL(const std::string&);
void setStyleJSON(const std::string& json, const std::string& base);
std::string getStyleURL() const { return styleURL; }
std::string getStyleJSON() const { return styleJSON; }
double getTopOffsetPixelsForAnnotationSymbol(const std::string& symbol);
void updateAnnotationTiles(const std::vector<TileID>&);
void setSourceTileCacheSize(size_t size);
void onLowMemory();
// ResourceLoader::Observer implementation.
void onTileDataChanged() override;
private:
void updateTiles();
// Update the state indicated by the accumulated Update flags, then render.
void update();
// Loads the actual JSON object an creates a new Style object.
void loadStyleJSON(const std::string& json, const std::string& base);
View& view;
MapData& data;
Environment env;
EnvironmentScope envScope;
UpdateType updated { static_cast<UpdateType>(Update::Nothing) };
std::unique_ptr<uv::async> asyncUpdate;
std::unique_ptr<GlyphStore> glyphStore;
std::unique_ptr<GlyphAtlas> glyphAtlas;
std::unique_ptr<SpriteAtlas> spriteAtlas;
std::unique_ptr<LineAtlas> lineAtlas;
std::unique_ptr<TexturePool> texturePool;
std::unique_ptr<Painter> painter;
std::unique_ptr<Style> style;
std::unique_ptr<ResourceLoader> resourceLoader;
std::string styleURL;
std::string styleJSON;
StillImageCallback callback;
size_t sourceCacheSize;
TransformState transformState;
};
}
#endif

View File

@@ -7,33 +7,26 @@
#include <mutex>
#include <atomic>
#include <vector>
#include <cassert>
#include <condition_variable>
#include <mbgl/map/mode.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/map/transform.hpp>
#include <mbgl/map/transform_state.hpp>
#include <mbgl/map/annotation.hpp>
namespace mbgl {
struct StyleInfo {
std::string url;
std::string base;
std::string json;
};
class MapData {
using Lock = std::lock_guard<std::mutex>;
public:
inline MapData() {
inline MapData(View& view, MapMode mode_) : transform(view), mode(mode_) {
setAnimationTime(TimePoint::min());
setDefaultTransitionDuration(Duration::zero());
}
inline StyleInfo getStyleInfo() const {
Lock lock(mtx);
return styleInfo;
}
inline void setStyleInfo(StyleInfo&& info) {
Lock lock(mtx);
styleInfo = info;
}
inline std::string getAccessToken() const {
Lock lock(mtx);
return accessToken;
@@ -71,6 +64,13 @@ public:
debug = value;
}
inline bool getFullyLoaded() const {
return loaded;
}
inline void setFullyLoaded(bool value) {
loaded = value;
}
inline TimePoint getAnimationTime() const {
// We're casting the TimePoint to and from a Duration because libstdc++
// has a bug that doesn't allow TimePoints to be atomic.
@@ -87,15 +87,26 @@ public:
defaultTransitionDuration = duration;
};
public:
Transform transform;
AnnotationManager annotationManager;
const MapMode mode;
private:
mutable std::mutex mtx;
StyleInfo styleInfo;
std::string accessToken;
std::vector<std::string> classes;
std::atomic<uint8_t> debug { false };
std::atomic<bool> loaded { false };
std::atomic<Duration> animationTime;
std::atomic<Duration> defaultTransitionDuration;
// TODO: make private
public:
std::mutex mutexPause;
std::condition_variable condPaused;
std::condition_variable condResume;
};
}

View File

@@ -1,4 +1,3 @@
#include <mbgl/map/map.hpp>
#include <mbgl/map/raster_tile_data.hpp>
#include <mbgl/style/style.hpp>
@@ -10,24 +9,23 @@ RasterTileData::RasterTileData(const TileID& id_, TexturePool &texturePool,
}
RasterTileData::~RasterTileData() {
// Cancel in most derived class destructor so that worker tasks are joined before
// any member data goes away.
cancel();
}
void RasterTileData::parse() {
if (state != State::loaded) {
if (getState() != State::loaded) {
return;
}
if (bucket.setImage(data)) {
state = State::parsed;
setState(State::parsed);
} else {
state = State::invalid;
setState(State::invalid);
}
}
void RasterTileData::render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) {
bucket.render(painter, layer_desc, id, matrix);
}
bool RasterTileData::hasData(StyleLayer const& /*layer_desc*/) const {
return bucket.hasData();
Bucket* RasterTileData::getBucket(StyleLayer const&) {
return &bucket;
}

View File

@@ -20,8 +20,7 @@ public:
~RasterTileData();
void parse() override;
void render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) override;
bool hasData(StyleLayer const &layer_desc) const override;
Bucket* getBucket(StyleLayer const &layer_desc) override;
protected:
StyleLayoutRaster layout;

View File

@@ -0,0 +1,133 @@
#include <mbgl/map/resource_loader.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/map/source.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/map/transform.hpp>
#include <mbgl/style/style.hpp>
#include <cassert>
namespace mbgl {
ResourceLoader::ResourceLoader() {
assert(Environment::currentlyOn(ThreadType::Map));
}
ResourceLoader::~ResourceLoader() {
assert(Environment::currentlyOn(ThreadType::Map));
for (const auto& source : style_->sources) {
source->setObserver(nullptr);
}
if (sprite_) {
sprite_->setObserver(nullptr);
}
if (glyphStore_) {
glyphStore_->setObserver(nullptr);
}
}
void ResourceLoader::setObserver(Observer* observer) {
assert(Environment::currentlyOn(ThreadType::Map));
assert(!observer_);
observer_ = observer;
}
void ResourceLoader::setStyle(Style* style) {
assert(style);
style_ = style;
for (const auto& source : style->sources) {
source->setObserver(this);
source->load(accessToken_);
}
}
void ResourceLoader::setGlyphStore(GlyphStore* glyphStore) {
assert(glyphStore);
if (glyphStore_) {
glyphStore_->setObserver(nullptr);
}
glyphStore_ = glyphStore;
glyphStore_->setObserver(this);
}
void ResourceLoader::setAccessToken(const std::string& accessToken) {
accessToken_ = accessToken;
}
void ResourceLoader::update(MapData& data,
const TransformState& transform,
GlyphAtlas& glyphAtlas,
SpriteAtlas& spriteAtlas,
TexturePool& texturePool) {
if (!style_) {
return;
}
const float pixelRatio = transform.getPixelRatio();
if (!sprite_ || !sprite_->hasPixelRatio(pixelRatio)) {
sprite_ = util::make_unique<Sprite>(style_->getSpriteURL(), pixelRatio);
sprite_->setObserver(this);
spriteAtlas.resize(pixelRatio);
spriteAtlas.setSprite(sprite_);
}
bool allTilesUpdated = true;
for (const auto& source : style_->sources) {
if (!source->update(data, transform, *style_, glyphAtlas, *glyphStore_,
spriteAtlas, sprite_, texturePool, shouldReparsePartialTiles_)) {
allTilesUpdated = false;
}
}
// We can only stop updating "partial" tiles when all of them
// were notified of the arrival of the new resources.
if (allTilesUpdated) {
shouldReparsePartialTiles_ = false;
}
}
void ResourceLoader::onGlyphRangeLoaded() {
shouldReparsePartialTiles_ = true;
emitTileDataChanged();
}
void ResourceLoader::onSourceLoaded() {
emitTileDataChanged();
}
void ResourceLoader::onTileLoaded(bool isNewTile) {
if (isNewTile) {
shouldReparsePartialTiles_ = true;
}
emitTileDataChanged();
}
void ResourceLoader::onSpriteLoaded() {
shouldReparsePartialTiles_ = true;
emitTileDataChanged();
}
void ResourceLoader::emitTileDataChanged() {
assert(Environment::currentlyOn(ThreadType::Map));
if (observer_) {
observer_->onTileDataChanged();
}
}
}

View File

@@ -0,0 +1,89 @@
#ifndef MBGL_MAP_RESOURCE_LOADER
#define MBGL_MAP_RESOURCE_LOADER
#include <mbgl/map/source.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/text/glyph_store.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <string>
namespace mbgl {
class GlyphAtlas;
class GlyphStore;
class MapData;
class SpriteAtlas;
class Style;
class TexturePool;
class TransformState;
// ResourceLoader is responsible for loading and updating the Source(s) owned
// by the Style. The Source object currently owns all the tiles, thus this
// class will notify its observers of any change on these tiles which will
// ultimately cause a new rendering to be triggered.
class ResourceLoader : public GlyphStore::Observer,
public Source::Observer,
public Sprite::Observer,
private util::noncopyable {
public:
class Observer {
public:
virtual ~Observer() = default;
virtual void onTileDataChanged() = 0;
};
ResourceLoader();
~ResourceLoader();
void setObserver(Observer* observer);
// The style object currently owns all the sources. When setting
// a new style we will go through all of them and try to load.
void setStyle(Style* style);
// TODO: Move GlyphStore to ResourceLoader. We cannot do it now
// because we reset the ResourceLoader every time we change the
// style.
void setGlyphStore(GlyphStore* glyphStore);
// Set the access token to be used for loading the tile data.
void setAccessToken(const std::string& accessToken);
// Fetch the tiles needed by the current viewport and emit a signal when
// a tile is ready so observers can render the tile.
void update(MapData&, const TransformState&, GlyphAtlas&, SpriteAtlas&, TexturePool&);
// FIXME: There is probably a better place for this.
inline util::ptr<Sprite> getSprite() const {
return sprite_;
}
// GlyphStore::Observer implementation.
void onGlyphRangeLoaded() override;
// Source::Observer implementation.
void onSourceLoaded() override;
void onTileLoaded(bool isNewTile) override;
// Sprite::Observer implementation.
void onSpriteLoaded() override;
private:
void emitTileDataChanged();
bool shouldReparsePartialTiles_ = false;
std::string accessToken_;
util::ptr<Sprite> sprite_;
GlyphStore* glyphStore_ = nullptr;
Style* style_ = nullptr;
Observer* observer_ = nullptr;
};
}
#endif

View File

@@ -1,30 +1,27 @@
#include <mbgl/map/source.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/map/map_data.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/map/transform.hpp>
#include <mbgl/map/tile.hpp>
#include <mbgl/renderer/painter.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/raster.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/texture_pool.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/util/vec.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/box.hpp>
#include <mbgl/util/mapbox.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <mbgl/util/token.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/tile_cover.hpp>
#include <mbgl/map/vector_tile_data.hpp>
#include <mbgl/map/raster_tile_data.hpp>
#include <mbgl/map/live_tile_data.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/gl/debugging.hpp>
#include <algorithm>
@@ -117,27 +114,41 @@ std::string SourceInfo::tileURL(const TileID& id, float pixelRatio) const {
return result;
}
Source::Source()
{
Source::Source() {}
Source::~Source() {
if (req) {
Environment::Get().cancelRequest(req);
}
}
Source::~Source() {}
bool Source::isLoaded() const {
if (!loaded) {
return false;
}
for (const auto& tile : tiles) {
if (tile.second->data->getState() != TileData::State::parsed) {
return false;
}
}
return true;
}
// Note: This is a separate function that must be called exactly once after creation
// The reason this isn't part of the constructor is that calling shared_from_this() in
// the constructor fails.
void Source::load(const std::string& accessToken,
Environment& env,
std::function<void()> callback) {
void Source::load(const std::string& accessToken) {
if (info.url.empty()) {
loaded = true;
return;
}
util::ptr<Source> source = shared_from_this();
const std::string url = util::mapbox::normalizeSourceURL(info.url, accessToken);
env.request({ Resource::Kind::JSON, url }, [source, callback](const Response &res) {
req = Environment::Get().request({ Resource::Kind::JSON, url }, [this](const Response &res) {
req = nullptr;
if (res.status != Response::Successful) {
Log::Warning(Event::General, "Failed to load source TileJSON: %s", res.message.c_str());
return;
@@ -147,14 +158,14 @@ void Source::load(const std::string& accessToken,
d.Parse<0>(res.data.c_str());
if (d.HasParseError()) {
Log::Warning(Event::General, "Invalid source TileJSON; Parse Error at %d: %s", d.GetErrorOffset(), d.GetParseError());
Log::Error(Event::General, "Invalid source TileJSON; Parse Error at %d: %s", d.GetErrorOffset(), d.GetParseError());
return;
}
source->info.parseTileJSONProperties(d);
source->loaded = true;
info.parseTileJSONProperties(d);
loaded = true;
callback();
emitSourceLoaded();
});
}
@@ -169,21 +180,11 @@ void Source::updateMatrices(const mat4 &projMatrix, const TransformState &transf
void Source::drawClippingMasks(Painter &painter) {
for (const auto& pair : tiles) {
Tile &tile = *pair.second;
gl::group group(std::string { "mask: " } + std::string(tile.id));
gl::debugging::group group(std::string { "mask: " } + std::string(tile.id));
painter.drawClippingMask(tile.matrix, tile.clip);
}
}
void Source::render(Painter &painter, const StyleLayer &layer_desc) {
gl::group group(std::string { "layer: " } + layer_desc.id);
for (const auto& pair : tiles) {
Tile &tile = *pair.second;
if (tile.data && tile.data->state == TileData::State::parsed) {
painter.renderTileLayer(tile, layer_desc, tile.matrix);
}
}
}
void Source::finishRender(Painter &painter) {
for (const auto& pair : tiles) {
Tile &tile = *pair.second;
@@ -191,35 +192,68 @@ void Source::finishRender(Painter &painter) {
}
}
std::forward_list<Tile *> Source::getLoadedTiles() const {
std::forward_list<Tile *> ptrs;
std::forward_list<Tile*> Source::getLoadedTiles() const {
std::forward_list<Tile*> ptrs;
auto it = ptrs.before_begin();
for (const auto &pair : tiles) {
if (pair.second->data->ready()) {
for (const auto& pair : tiles) {
if (pair.second->data->isReady()) {
it = ptrs.insert_after(it, pair.second.get());
}
}
return ptrs;
}
const std::vector<Tile*>& Source::getTiles() const {
return tilePtrs;
}
TileData::State Source::hasTile(const TileID& id) {
auto it = tiles.find(id);
if (it != tiles.end()) {
Tile &tile = *it->second;
Tile& tile = *it->second;
if (tile.id == id && tile.data) {
return tile.data->state;
return tile.data->getState();
}
}
return TileData::State::invalid;
}
TileData::State Source::addTile(Map &map, Worker &worker,
util::ptr<Style> style, GlyphAtlas &glyphAtlas,
GlyphStore &glyphStore, SpriteAtlas &spriteAtlas,
util::ptr<Sprite> sprite, TexturePool &texturePool,
const TileID &id, std::function<void()> callback) {
bool Source::handlePartialTile(const TileID& id, Worker& worker) {
const TileID normalized_id = id.normalized();
auto it = tile_data.find(normalized_id);
if (it == tile_data.end()) {
return true;
}
util::ptr<TileData> data = it->second.lock();
if (!data) {
return true;
}
// The signal is only emitted if there was an actual change on the tile. The
// tile can be in a "partial" state waiting for resources and get reparsed on
// the arrival of new resources that were needed by another tile.
size_t bucketCount = static_cast<VectorTileData*>(data.get())->countBuckets();
auto callback = [this, data, bucketCount]() {
if (static_cast<VectorTileData*>(data.get())->countBuckets() > bucketCount) {
emitTileLoaded(false);
}
};
return data->reparse(worker, callback);
}
TileData::State Source::addTile(MapData& data,
const TransformState& transformState,
Style& style,
GlyphAtlas& glyphAtlas,
GlyphStore& glyphStore,
SpriteAtlas& spriteAtlas,
util::ptr<Sprite> sprite,
TexturePool& texturePool,
const TileID& id) {
const TileData::State state = hasTile(id);
if (state != TileData::State::invalid) {
@@ -239,7 +273,7 @@ TileData::State Source::addTile(Map &map, Worker &worker,
new_tile.data = it->second.lock();
}
if (new_tile.data && new_tile.data->state == TileData::State::obsolete) {
if (new_tile.data && new_tile.data->getState() == TileData::State::obsolete) {
// Do not consider the tile if it's already obsolete.
new_tile.data.reset();
}
@@ -248,29 +282,29 @@ TileData::State Source::addTile(Map &map, Worker &worker,
new_tile.data = cache.get(normalized_id.to_uint64());
}
auto callback = std::bind(&Source::emitTileLoaded, this, true);
if (!new_tile.data) {
// If we don't find working tile data, we're just going to load it.
if (info.type == SourceType::Vector) {
new_tile.data =
std::make_shared<VectorTileData>(normalized_id, map.getMaxZoom(), style, glyphAtlas,
std::make_shared<VectorTileData>(normalized_id, data.transform.getMaxZoom(), style, glyphAtlas,
glyphStore, spriteAtlas, sprite, info);
new_tile.data->request(worker, map.getState().getPixelRatio(), callback);
new_tile.data->request(style.workers, transformState.getPixelRatio(), callback);
} else if (info.type == SourceType::Raster) {
new_tile.data = std::make_shared<RasterTileData>(normalized_id, texturePool, info);
new_tile.data->request(worker, map.getState().getPixelRatio(), callback);
new_tile.data->request(style.workers, transformState.getPixelRatio(), callback);
} else if (info.type == SourceType::Annotations) {
AnnotationManager& annotationManager = map.getAnnotationManager();
new_tile.data = std::make_shared<LiveTileData>(normalized_id, annotationManager,
map.getMaxZoom(), style, glyphAtlas,
new_tile.data = std::make_shared<LiveTileData>(normalized_id, data.annotationManager,
data.transform.getMaxZoom(), style, glyphAtlas,
glyphStore, spriteAtlas, sprite, info);
new_tile.data->reparse(worker, callback);
new_tile.data->reparse(style.workers, callback);
} else {
throw std::runtime_error("source type not implemented");
}
tile_data.emplace(new_tile.data->id, new_tile.data);
}
return new_tile.data->state;
return new_tile.data->getState();
}
double Source::getZoom(const TransformState& state) const {
@@ -318,7 +352,7 @@ bool Source::findLoadedChildren(const TileID& id, int32_t maxCoveringZoom, std::
auto ids = id.children(z + 1);
for (const auto& child_id : ids) {
const TileData::State state = hasTile(child_id);
if (state == TileData::State::parsed) {
if (TileData::isReadyState(state)) {
retain.emplace_front(child_id);
} else {
complete = false;
@@ -344,7 +378,7 @@ bool Source::findLoadedParent(const TileID& id, int32_t minCoveringZoom, std::fo
for (int32_t z = id.z - 1; z >= minCoveringZoom; --z) {
const TileID parent_id = id.parent(z);
const TileData::State state = hasTile(parent_id);
if (state == TileData::State::parsed) {
if (TileData::isReadyState(state)) {
retain.emplace_front(parent_id);
return true;
}
@@ -352,21 +386,23 @@ bool Source::findLoadedParent(const TileID& id, int32_t minCoveringZoom, std::fo
return false;
}
void Source::update(Map &map,
Worker &worker,
util::ptr<Style> style,
GlyphAtlas &glyphAtlas,
GlyphStore &glyphStore,
SpriteAtlas &spriteAtlas,
bool Source::update(MapData& data,
const TransformState& transformState,
Style& style,
GlyphAtlas& glyphAtlas,
GlyphStore& glyphStore,
SpriteAtlas& spriteAtlas,
util::ptr<Sprite> sprite,
TexturePool &texturePool,
std::function<void()> callback) {
if (!loaded || map.getTime() <= updated) {
return;
TexturePool& texturePool,
bool shouldReparsePartialTiles) {
bool allTilesUpdated = true;
if (!loaded || data.getAnimationTime() <= updated) {
return allTilesUpdated;
}
int32_t zoom = std::floor(getZoom(map.getState()));
std::forward_list<TileID> required = coveringTiles(map.getState());
int32_t zoom = std::floor(getZoom(transformState));
std::forward_list<TileID> required = coveringTiles(transformState);
// Determine the overzooming/underzooming amounts.
int32_t minCoveringZoom = util::clamp<int32_t>(zoom - 10, info.min_zoom, info.max_zoom);
@@ -379,10 +415,25 @@ void Source::update(Map &map,
// Add existing child/parent tiles if the actual tile is not yet loaded
for (const auto& id : required) {
const TileData::State state = addTile(map, worker, style, glyphAtlas, glyphStore,
spriteAtlas, sprite, texturePool, id, callback);
TileData::State state = hasTile(id);
if (state != TileData::State::parsed) {
switch (state) {
case TileData::State::partial:
if (shouldReparsePartialTiles) {
if (!handlePartialTile(id, style.workers)) {
allTilesUpdated = false;
}
}
break;
case TileData::State::invalid:
state = addTile(data, transformState, style, glyphAtlas, glyphStore,
spriteAtlas, sprite, texturePool, id);
break;
default:
break;
}
if (!TileData::isReadyState(state)) {
// The tile we require is not yet loaded. Try to find a parent or
// child tile that we already have.
@@ -399,9 +450,9 @@ void Source::update(Map &map,
}
if (info.type != SourceType::Raster && cache.getSize() == 0) {
size_t conservativeCacheSize = ((float)map.getState().getWidth() / util::tileSize) *
((float)map.getState().getHeight() / util::tileSize) *
(map.getMaxZoom() - map.getMinZoom() + 1) *
size_t conservativeCacheSize = ((float)transformState.getWidth() / util::tileSize) *
((float)transformState.getHeight() / util::tileSize) *
(data.transform.getMaxZoom() - data.transform.getMinZoom() + 1) *
0.5;
cache.setSize(conservativeCacheSize);
}
@@ -417,7 +468,10 @@ void Source::update(Map &map,
bool obsolete = std::find(retain.begin(), retain.end(), tile.id) == retain.end();
if (!obsolete) {
retain_data.insert(tile.data->id);
} else if (type != SourceType::Raster && tile.data->ready()) {
} else if (type != SourceType::Raster && tile.data->getState() == TileData::State::parsed) {
// Partially parsed tiles are never added to the cache because otherwise
// they never get updated if the go out from the viewport and the pending
// resources arrive.
tileCache.add(tile.id.normalized().to_uint64(), tile.data);
}
return obsolete;
@@ -441,7 +495,11 @@ void Source::update(Map &map,
}
});
updated = map.getTime();
updateTilePtrs();
updated = data.getAnimationTime();
return allTilesUpdated;
}
void Source::invalidateTiles(const std::vector<TileID>& ids) {
@@ -450,6 +508,14 @@ void Source::invalidateTiles(const std::vector<TileID>& ids) {
tiles.erase(id);
tile_data.erase(id);
}
updateTilePtrs();
}
void Source::updateTilePtrs() {
tilePtrs.clear();
for (const auto& pair : tiles) {
tilePtrs.push_back(pair.second.get());
}
}
void Source::setCacheSize(size_t size) {
@@ -460,4 +526,20 @@ void Source::onLowMemory() {
cache.clear();
}
void Source::setObserver(Observer* observer) {
observer_ = observer;
}
void Source::emitSourceLoaded() {
if (observer_) {
observer_->onSourceLoaded();
}
}
void Source::emitTileLoaded(bool isNewTile) {
if (observer_) {
observer_->onTileLoaded(isNewTile);
}
}
}

View File

@@ -20,9 +20,8 @@
namespace mbgl {
class Map;
class MapData;
class Environment;
class Worker;
class GlyphAtlas;
class GlyphStore;
class SpriteAtlas;
@@ -30,7 +29,7 @@ class Sprite;
class TexturePool;
class Style;
class Painter;
class StyleLayer;
class Request;
class TransformState;
class Tile;
struct ClipID;
@@ -52,44 +51,77 @@ public:
std::string tileURL(const TileID& id, float pixelRatio) const;
};
class Source : public std::enable_shared_from_this<Source>, private util::noncopyable {
class Source : private util::noncopyable {
public:
class Observer {
public:
virtual ~Observer() = default;
virtual void onSourceLoaded() = 0;
virtual void onTileLoaded(bool isNewTile) = 0;
};
Source();
~Source();
void load(const std::string& accessToken,
Environment&,
std::function<void()> callback);
void load(const std::string& accessToken);
bool isLoaded() const;
void update(Map &, Worker &, util::ptr<Style>, GlyphAtlas &, GlyphStore &,
SpriteAtlas &, util::ptr<Sprite>, TexturePool &, std::function<void()> callback);
void load(MapData&, Environment&, std::function<void()> callback);
// Request or parse all the tiles relevant for the "TransformState". This method
// will return true if all the tiles were scheduled for updating of false if
// they were not. shouldReparsePartialTiles must be set to "true" if there is
// new data available that a tile in the "partial" state might be interested at.
bool update(MapData&,
const TransformState&,
Style&,
GlyphAtlas&,
GlyphStore&,
SpriteAtlas&,
util::ptr<Sprite>,
TexturePool&,
bool shouldReparsePartialTiles);
void invalidateTiles(const std::vector<TileID>&);
void updateMatrices(const mat4 &projMatrix, const TransformState &transform);
void drawClippingMasks(Painter &painter);
void render(Painter &painter, const StyleLayer &layer_desc);
void finishRender(Painter &painter);
std::forward_list<Tile *> getLoadedTiles() const;
const std::vector<Tile*>& getTiles() const;
void setCacheSize(size_t);
void onLowMemory();
void setObserver(Observer* observer);
SourceInfo info;
bool enabled;
private:
void emitSourceLoaded();
void emitTileLoaded(bool isNewTile);
bool handlePartialTile(const TileID &id, Worker &worker);
bool findLoadedChildren(const TileID& id, int32_t maxCoveringZoom, std::forward_list<TileID>& retain);
bool findLoadedParent(const TileID& id, int32_t minCoveringZoom, std::forward_list<TileID>& retain);
int32_t coveringZoomLevel(const TransformState&) const;
std::forward_list<TileID> coveringTiles(const TransformState&) const;
TileData::State addTile(Map &, Worker &, util::ptr<Style>, GlyphAtlas &,
GlyphStore &, SpriteAtlas &, util::ptr<Sprite>, TexturePool &,
const TileID &, std::function<void()> callback);
TileData::State addTile(MapData&,
const TransformState&,
Style&,
GlyphAtlas&,
GlyphStore&,
SpriteAtlas&,
util::ptr<Sprite>,
TexturePool&,
const TileID&);
TileData::State hasTile(const TileID& id);
void updateTilePtrs();
double getZoom(const TransformState &state) const;
@@ -99,8 +131,12 @@ private:
TimePoint updated = TimePoint::min();
std::map<TileID, std::unique_ptr<Tile>> tiles;
std::vector<Tile*> tilePtrs;
std::map<TileID, std::weak_ptr<TileData>> tile_data;
TileCache cache;
Request* req = nullptr;
Observer* observer_ = nullptr;
};
}

View File

@@ -1,5 +1,4 @@
#include <mbgl/map/sprite.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/util/raster.hpp>
#include <mbgl/platform/log.hpp>
@@ -24,77 +23,60 @@ SpritePosition::SpritePosition(uint16_t x_, uint16_t y_, uint16_t width_, uint16
sdf(sdf_) {
}
util::ptr<Sprite> Sprite::Create(const std::string &base_url, float pixelRatio, Environment &env) {
util::ptr<Sprite> sprite(std::make_shared<Sprite>(Key(), base_url, pixelRatio));
sprite->load(env);
return sprite;
}
Sprite::Sprite(const Key &, const std::string& base_url, float pixelRatio_)
: valid(base_url.length() > 0),
pixelRatio(pixelRatio_ > 1 ? 2 : 1),
spriteURL(base_url + (pixelRatio_ > 1 ? "@2x" : "") + ".png"),
jsonURL(base_url + (pixelRatio_ > 1 ? "@2x" : "") + ".json"),
Sprite::Sprite(const std::string& baseUrl, float pixelRatio_)
: pixelRatio(pixelRatio_ > 1 ? 2 : 1),
raster(),
loadedImage(false),
loadedJSON(false),
future(promise.get_future()) {
}
bool Sprite::hasPixelRatio(float ratio) const {
return pixelRatio == (ratio > 1 ? 2 : 1);
}
void Sprite::waitUntilLoaded() const {
future.wait();
}
Sprite::operator bool() const {
return valid && isLoaded() && !pos.empty();
}
// Note: This is a separate function that must be called exactly once after creation
// The reason this isn't part of the constructor is that calling shared_from_this() in
// the constructor fails.
void Sprite::load(Environment &env) {
if (!valid) {
env(Environment::Get()) {
if (baseUrl.empty()) {
// Treat a non-existent sprite as a successfully loaded empty sprite.
loadedImage = true;
loadedJSON = true;
promise.set_value();
return;
}
util::ptr<Sprite> sprite = shared_from_this();
std::string spriteURL(baseUrl + (pixelRatio_ > 1 ? "@2x" : "") + ".png");
std::string jsonURL(baseUrl + (pixelRatio_ > 1 ? "@2x" : "") + ".json");
env.request({ Resource::Kind::JSON, jsonURL }, [sprite](const Response &res) {
jsonRequest = env.request({ Resource::Kind::JSON, jsonURL }, [this](const Response &res) {
jsonRequest = nullptr;
if (res.status == Response::Successful) {
sprite->body = res.data;
sprite->parseJSON();
body = res.data;
parseJSON();
} else {
Log::Warning(Event::Sprite, "Failed to load sprite info: %s", res.message.c_str());
}
sprite->loadedJSON = true;
sprite->complete();
loadedJSON = true;
emitSpriteLoadedIfComplete();
});
env.request({ Resource::Kind::Image, spriteURL }, [sprite](const Response &res) {
spriteRequest = env.request({ Resource::Kind::Image, spriteURL }, [this](const Response &res) {
spriteRequest = nullptr;
if (res.status == Response::Successful) {
sprite->image = res.data;
sprite->parseImage();
image = res.data;
parseImage();
} else {
Log::Warning(Event::Sprite, "Failed to load sprite image: %s", res.message.c_str());
}
sprite->loadedImage = true;
sprite->complete();
loadedImage = true;
emitSpriteLoadedIfComplete();
});
}
void Sprite::complete() {
if (loadedImage && loadedJSON) {
promise.set_value();
Sprite::~Sprite() {
if (jsonRequest) {
env.cancelRequest(jsonRequest);
}
if (spriteRequest) {
env.cancelRequest(spriteRequest);
}
}
void Sprite::emitSpriteLoadedIfComplete() {
if (isLoaded() && observer) {
observer->onSpriteLoaded();
}
}
@@ -102,6 +84,10 @@ bool Sprite::isLoaded() const {
return loadedImage && loadedJSON;
}
bool Sprite::hasPixelRatio(float ratio) const {
return pixelRatio == (ratio > 1 ? 2 : 1);
}
void Sprite::parseImage() {
raster = util::make_unique<util::Image>(image);
if (!*raster) {
@@ -149,3 +135,7 @@ const SpritePosition &Sprite::getSpritePosition(const std::string& name) const {
auto it = pos.find(name);
return it == pos.end() ? empty : it->second;
}
void Sprite::setObserver(Observer* observer_) {
observer = observer_;
}

View File

@@ -4,17 +4,18 @@
#include <mbgl/util/image.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/storage/request.hpp>
#include <cstdint>
#include <atomic>
#include <iosfwd>
#include <string>
#include <unordered_map>
#include <future>
namespace mbgl {
class Environment;
class Request;
class SpritePosition {
public:
@@ -31,40 +32,34 @@ public:
bool sdf = false;
};
class Sprite : public std::enable_shared_from_this<Sprite>, private util::noncopyable {
private:
struct Key {};
void load(Environment &env);
class Sprite : private util::noncopyable {
public:
Sprite(const Key &, const std::string& base_url, float pixelRatio);
static util::ptr<Sprite>
Create(const std::string &base_url, float pixelRatio, Environment &env);
class Observer {
public:
virtual ~Observer() = default;
virtual void onSpriteLoaded() = 0;
};
Sprite(const std::string& baseUrl, float pixelRatio);
~Sprite();
const SpritePosition &getSpritePosition(const std::string& name) const;
bool hasPixelRatio(float ratio) const;
void waitUntilLoaded() const;
bool isLoaded() const;
operator bool() const;
private:
const bool valid;
public:
const float pixelRatio;
const std::string spriteURL;
const std::string jsonURL;
std::unique_ptr<util::Image> raster;
void setObserver(Observer* observer);
private:
void emitSpriteLoadedIfComplete();
void parseJSON();
void parseImage();
void complete();
private:
std::string body;
std::string image;
std::atomic<bool> loadedImage;
@@ -72,9 +67,10 @@ private:
std::unordered_map<std::string, SpritePosition> pos;
const SpritePosition empty;
std::promise<void> promise;
std::future<void> future;
Environment& env;
Request* jsonRequest = nullptr;
Request* spriteRequest = nullptr;
Observer* observer = nullptr;
};
}

View File

@@ -46,7 +46,7 @@ std::shared_ptr<TileData> TileCache::get(uint64_t key) {
data = it->second;
tiles.erase(it);
orderedKeys.remove(key);
assert(data->ready());
assert(data->isReady());
}
return data;

View File

@@ -4,6 +4,7 @@
#include <mbgl/storage/file_source.hpp>
#include <mbgl/util/worker.hpp>
#include <mbgl/util/work_request.hpp>
#include <mbgl/platform/log.hpp>
using namespace mbgl;
@@ -11,9 +12,9 @@ using namespace mbgl;
TileData::TileData(const TileID& id_, const SourceInfo& source_)
: id(id_),
name(id),
state(State::initial),
source(source_),
env(Environment::Get()),
state(State::initial),
debugBucket(debugFontBuffer) {
// Initialize tile debug coordinates
debugFontBuffer.addText(name.c_str(), 50, 200, 5);
@@ -27,6 +28,12 @@ const std::string TileData::toString() const {
return std::string { "[tile " } + name + "]";
}
void TileData::setState(const State& state_) {
assert(!isImmutable());
state = state_;
}
void TileData::request(Worker& worker, float pixelRatio, std::function<void()> callback) {
std::string url = source.tileURL(id, pixelRatio);
state = State::loading;
@@ -55,18 +62,22 @@ void TileData::cancel() {
env.cancelRequest(req);
req = nullptr;
}
workRequest.reset();
}
void TileData::reparse(Worker& worker, std::function<void()> callback) {
util::ptr<TileData> tile = shared_from_this();
worker.send(
[tile]() {
EnvironmentScope scope(tile->env, ThreadType::TileWorker, "TileWorker_" + tile->name);
tile->parse();
},
[tile, callback]() {
// `tile` is bound in this lambda to ensure that if it's the last owning pointer,
// destruction happens on the map thread, not the worker thread.
callback();
});
bool TileData::mayStartParsing() {
return !parsing.test_and_set(std::memory_order_acquire);
}
void TileData::endParsing() {
parsing.clear(std::memory_order_release);
}
bool TileData::reparse(Worker& worker, std::function<void()> callback) {
if (!mayStartParsing()) {
return false;
}
workRequest = worker.send([this] { parse(); endParsing(); }, callback);
return true;
}

View File

@@ -20,47 +20,90 @@ class SourceInfo;
class StyleLayer;
class Request;
class Worker;
class WorkRequest;
class TileData : public std::enable_shared_from_this<TileData>,
private util::noncopyable {
class TileData : private util::noncopyable {
public:
enum class State {
invalid,
initial,
loading,
loaded,
partial,
parsed,
obsolete
};
// Tile data considered "Ready" can be used for rendering. Data in
// partial state is still waiting for network resources but can also
// be rendered, although layers will be missing.
inline static bool isReadyState(const State& state) {
return state == State::partial || state == State::parsed;
}
TileData(const TileID&, const SourceInfo&);
~TileData();
void request(Worker&, float pixelRatio, std::function<void ()> callback);
void reparse(Worker&, std::function<void ()> callback);
// Schedule a tile reparse on a worker thread and call the callback on
// completion. It will return true if the work was schedule or false it was
// not, which can occur if the tile is already being parsed by another
// worker (see "mayStartParsing()").
bool reparse(Worker&, std::function<void ()> callback);
void cancel();
const std::string toString() const;
inline bool ready() const {
return state == State::parsed;
inline bool isReady() const {
return isReadyState(state);
}
// Returns true if the TileData is in a final state and we cannot
// make changes to it anymore.
inline bool isImmutable() const {
return state == State::parsed || state == State::obsolete;
}
// We let subclasses override setState() so they
// can intercept the state change and react accordingly.
virtual void setState(const State& state);
inline State getState() const {
return state;
}
void endParsing();
// Override this in the child class.
virtual void parse() = 0;
virtual void render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) = 0;
virtual bool hasData(StyleLayer const &layer_desc) const = 0;
virtual Bucket* getBucket(StyleLayer const &layer_desc) = 0;
const TileID id;
const std::string name;
std::atomic<State> state;
std::atomic_flag parsing = ATOMIC_FLAG_INIT;
protected:
// Set the internal parsing state to true so we prevent
// multiple workers to parse the same tile in parallel,
// which can happen if the tile is in the "partial" state.
// It will return true if is possible to start pasing the
// tile or false if not (so some other worker is already
// parsing the tile).
bool mayStartParsing();
const SourceInfo& source;
Environment& env;
Request *req = nullptr;
std::string data;
std::unique_ptr<WorkRequest> workRequest;
private:
std::atomic<State> state;
protected:
// Contains the tile ID string for painting debug information.
DebugFontBuffer debugFontBuffer;

View File

@@ -1,23 +1,15 @@
#include <mbgl/map/tile_parser.hpp>
#include <mbgl/map/vector_tile_data.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/map/source.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/renderer/fill_bucket.hpp>
#include <mbgl/renderer/line_bucket.hpp>
#include <mbgl/renderer/symbol_bucket.hpp>
#include <mbgl/renderer/raster_bucket.hpp>
#include <mbgl/util/raster.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/token.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/text/glyph_store.hpp>
#include <mbgl/text/collision_tile.hpp>
#include <mbgl/text/glyph.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/utf.hpp>
#include <mbgl/style/style.hpp>
#include <locale>
@@ -30,7 +22,7 @@ TileParser::~TileParser() = default;
TileParser::TileParser(const GeometryTile& geometryTile_,
VectorTileData& tile_,
const util::ptr<const Style>& style_,
const Style& style_,
GlyphAtlas& glyphAtlas_,
GlyphStore& glyphStore_,
SpriteAtlas& spriteAtlas_,
@@ -42,16 +34,16 @@ TileParser::TileParser(const GeometryTile& geometryTile_,
glyphStore(glyphStore_),
spriteAtlas(spriteAtlas_),
sprite(sprite_),
collision(util::make_unique<CollisionTile>(tile.id.z, 4096, tile.source.tile_size)) {
assert(style);
partialParse(false) {
assert(sprite);
assert(collision);
}
bool TileParser::obsolete() const { return tile.state == TileData::State::obsolete; }
bool TileParser::obsolete() const {
return tile.getState() == TileData::State::obsolete;
}
void TileParser::parse() {
for (const auto& layer_desc : style->layers) {
for (const auto& layer_desc : style.layers) {
// Cancel early when parsing.
if (obsolete()) {
return;
@@ -65,15 +57,15 @@ void TileParser::parse() {
if (layer_desc->bucket) {
// This is a singular layer. Check if this bucket already exists. If not,
// parse this bucket.
auto bucket_it = tile.buckets.find(layer_desc->bucket->name);
if (bucket_it == tile.buckets.end()) {
// We need to create this bucket since it doesn't exist yet.
std::unique_ptr<Bucket> bucket = createBucket(*layer_desc->bucket);
if (bucket) {
// Bucket creation might fail because the data tile may not
// contain any data that falls into this bucket.
tile.buckets[layer_desc->bucket->name] = std::move(bucket);
}
if (tile.getBucket(*layer_desc)) {
continue;
}
std::unique_ptr<Bucket> bucket = createBucket(*layer_desc->bucket);
if (bucket) {
// Bucket creation might fail because the data tile may not
// contain any data that falls into this bucket.
tile.setBucket(*layer_desc, std::move(bucket));
}
} else {
Log::Warning(Event::ParseTile, "layer '%s' does not have buckets", layer_desc->id.c_str());
@@ -166,7 +158,7 @@ std::unique_ptr<Bucket> TileParser::createFillBucket(const GeometryTileLayer& la
tile.triangleElementsBuffer,
tile.lineElementsBuffer);
addBucketGeometries(bucket, layer, bucket_desc.filter);
return std::move(bucket);
return bucket->hasData() ? std::move(bucket) : nullptr;
}
std::unique_ptr<Bucket> TileParser::createLineBucket(const GeometryTileLayer& layer,
@@ -183,12 +175,12 @@ std::unique_ptr<Bucket> TileParser::createLineBucket(const GeometryTileLayer& la
applyLayoutProperty(PropertyKey::LineRoundLimit, bucket_desc.layout, layout.round_limit, z);
addBucketGeometries(bucket, layer, bucket_desc.filter);
return std::move(bucket);
return bucket->hasData() ? std::move(bucket) : nullptr;
}
std::unique_ptr<Bucket> TileParser::createSymbolBucket(const GeometryTileLayer& layer,
const StyleBucket& bucket_desc) {
auto bucket = util::make_unique<SymbolBucket>(*collision);
auto bucket = util::make_unique<SymbolBucket>(*tile.getCollision());
const float z = tile.id.z;
auto& layout = bucket->layout;
@@ -231,8 +223,22 @@ std::unique_ptr<Bucket> TileParser::createSymbolBucket(const GeometryTileLayer&
applyLayoutProperty(PropertyKey::TextOffset, bucket_desc.layout, layout.text.offset, z);
applyLayoutProperty(PropertyKey::TextAllowOverlap, bucket_desc.layout, layout.text.allow_overlap, z);
if (bucket->needsDependencies(layer, bucket_desc.filter, glyphStore, *sprite)) {
partialParse = true;
}
// We do not proceed if the parser is in a "partial" state because
// the layer ordering needs to be respected when calculating text
// collisions. Although, at this point, we requested all the resources
// needed by this tile.
if (partialParse) {
return nullptr;
}
bucket->addFeatures(
layer, bucket_desc.filter, reinterpret_cast<uintptr_t>(&tile), spriteAtlas, *sprite, glyphAtlas, glyphStore);
return std::move(bucket);
reinterpret_cast<uintptr_t>(&tile), spriteAtlas, *sprite, glyphAtlas, glyphStore);
return bucket->hasData() ? std::move(bucket) : nullptr;
}
}

View File

@@ -29,13 +29,12 @@ class StyleLayoutRaster;
class StyleLayoutLine;
class StyleLayoutSymbol;
class VectorTileData;
class CollisionTile;
class TileParser : private util::noncopyable {
public:
TileParser(const GeometryTile& geometryTile,
VectorTileData& tile,
const util::ptr<const Style>& style,
const Style& style,
GlyphAtlas& glyphAtlas,
GlyphStore& glyphStore,
SpriteAtlas& spriteAtlas,
@@ -44,6 +43,9 @@ public:
public:
void parse();
inline bool isPartialParse() const {
return partialParse;
}
private:
bool obsolete() const;
@@ -60,13 +62,13 @@ private:
VectorTileData& tile;
// Cross-thread shared data.
util::ptr<const Style> style;
const Style& style;
GlyphAtlas& glyphAtlas;
GlyphStore& glyphStore;
SpriteAtlas& spriteAtlas;
util::ptr<Sprite> sprite;
std::unique_ptr<CollisionTile> collision;
bool partialParse;
};
}

View File

@@ -23,7 +23,7 @@ static double _normalizeAngle(double angle, double anchorAngle)
if (std::abs(angle + util::M2PI - anchorAngle) < diff) {
angle += util::M2PI;
}
return angle;
}
@@ -61,6 +61,10 @@ bool Transform::resize(const uint16_t w, const uint16_t h, const float ratio,
#pragma mark - Position
void Transform::moveBy(const double dx, const double dy, const Duration duration) {
if (std::isnan(dx) || std::isnan(dy)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
_moveBy(dx, dy, duration);
@@ -104,6 +108,10 @@ void Transform::_moveBy(const double dx, const double dy, const Duration duratio
}
void Transform::setLatLng(const LatLng latLng, const Duration duration) {
if (std::isnan(latLng.latitude) || std::isnan(latLng.longitude)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
const double m = 1 - 1e-15;
@@ -116,6 +124,10 @@ void Transform::setLatLng(const LatLng latLng, const Duration duration) {
}
void Transform::setLatLngZoom(const LatLng latLng, const double zoom, const Duration duration) {
if (std::isnan(latLng.latitude) || std::isnan(latLng.longitude) || std::isnan(zoom)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
double new_scale = std::pow(2.0, zoom);
@@ -137,6 +149,10 @@ void Transform::setLatLngZoom(const LatLng latLng, const double zoom, const Dura
#pragma mark - Zoom
void Transform::scaleBy(const double ds, const double cx, const double cy, const Duration duration) {
if (std::isnan(ds) || std::isnan(cx) || std::isnan(cy)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
// clamp scale to min/max values
@@ -152,12 +168,20 @@ void Transform::scaleBy(const double ds, const double cx, const double cy, const
void Transform::setScale(const double scale, const double cx, const double cy,
const Duration duration) {
if (std::isnan(scale) || std::isnan(cx) || std::isnan(cy)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
_setScale(scale, cx, cy, duration);
}
void Transform::setZoom(const double zoom, const Duration duration) {
if (std::isnan(zoom)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
_setScale(std::pow(2.0, zoom), -1, -1, duration);
@@ -199,14 +223,14 @@ void Transform::_setScale(double new_scale, double cx, double cy, const Duration
// Zoom in on the center if we don't have click or gesture anchor coordinates.
if (cx < 0 || cy < 0) {
cx = current.width / 2;
cy = current.height / 2;
cx = static_cast<double>(current.width) / 2.0;
cy = static_cast<double>(current.height) / 2.0;
}
// Account for the x/y offset from the center (= where the user clicked or pinched)
const double factor = new_scale / current.scale;
const double dx = (cx - current.width / 2) * (1.0 - factor);
const double dy = (cy - current.height / 2) * (1.0 - factor);
const double dx = (cx - static_cast<double>(current.width) / 2.0) * (1.0 - factor);
const double dy = (cy - static_cast<double>(current.height) / 2.0) * (1.0 - factor);
// Account for angle
const double angle_sin = std::sin(-current.angle);
@@ -238,6 +262,9 @@ void Transform::_setScaleXY(const double new_scale, const double xn, const doubl
current.scale = final.scale;
current.x = final.x;
current.y = final.y;
const double s = current.scale * util::tileSize;
current.Bc = s / 360;
current.Cc = s / util::M2PI;
} else {
const double startS = current.scale;
const double startX = current.x;
@@ -250,6 +277,9 @@ void Transform::_setScaleXY(const double new_scale, const double xn, const doubl
current.scale = util::interpolate(startS, final.scale, t);
current.x = util::interpolate(startX, final.x, t);
current.y = util::interpolate(startY, final.y, t);
const double s = current.scale * util::tileSize;
current.Bc = s / 360;
current.Cc = s / util::M2PI;
return Update::Zoom;
},
[=] {
@@ -258,10 +288,6 @@ void Transform::_setScaleXY(const double new_scale, const double xn, const doubl
}, duration);
}
const double s = final.scale * util::tileSize;
current.Bc = s / 360;
current.Cc = s / util::M2PI;
view.notifyMapChange(duration != Duration::zero() ?
MapChangeRegionDidChangeAnimated :
MapChangeRegionDidChange,
@@ -285,9 +311,13 @@ void Transform::constrain(double& scale, double& y) const {
void Transform::rotateBy(const double start_x, const double start_y, const double end_x,
const double end_y, const Duration duration) {
if (std::isnan(start_x) || std::isnan(start_y) || std::isnan(end_x) || std::isnan(end_y)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
double center_x = current.width / 2, center_y = current.height / 2;
double center_x = static_cast<double>(current.width) / 2.0, center_y = static_cast<double>(current.height) / 2.0;
const double begin_center_x = start_x - center_x;
const double begin_center_y = start_y - center_y;
@@ -315,19 +345,27 @@ void Transform::rotateBy(const double start_x, const double start_y, const doubl
}
void Transform::setAngle(const double new_angle, const Duration duration) {
if (std::isnan(new_angle)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
_setAngle(new_angle, duration);
}
void Transform::setAngle(const double new_angle, const double cx, const double cy) {
if (std::isnan(new_angle) || std::isnan(cx) || std::isnan(cy)) {
return;
}
std::lock_guard<std::recursive_mutex> lock(mtx);
double dx = 0, dy = 0;
if (cx >= 0 && cy >= 0) {
dx = (final.width / 2) - cx;
dy = (final.height / 2) - cy;
dx = (static_cast<double>(final.width) / 2.0) - cx;
dy = (static_cast<double>(final.height) / 2.0) - cy;
_moveBy(dx, dy, Duration::zero());
}

101
src/mbgl/map/transform.hpp Normal file
View File

@@ -0,0 +1,101 @@
#ifndef MBGL_MAP_TRANSFORM
#define MBGL_MAP_TRANSFORM
#include <mbgl/map/transform_state.hpp>
#include <mbgl/util/chrono.hpp>
#include <mbgl/map/update.hpp>
#include <mbgl/util/geo.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/vec.hpp>
#include <cstdint>
#include <cmath>
#include <forward_list>
#include <mutex>
namespace mbgl {
class View;
namespace util { class transition; }
class Transform : private util::noncopyable {
public:
Transform(View &view);
// Map view
// Note: width * ratio does not necessarily equal fb_width
bool resize(uint16_t width, uint16_t height, float ratio,
uint16_t fb_width, uint16_t fb_height);
// Position
void moveBy(double dx, double dy, Duration = Duration::zero());
void setLatLng(LatLng latLng, Duration = Duration::zero());
void setLatLngZoom(LatLng latLng, double zoom, Duration = Duration::zero());
inline const LatLng getLatLng() const { return current.getLatLng(); }
// Zoom
void scaleBy(double ds, double cx = -1, double cy = -1, Duration = Duration::zero());
void setScale(double scale, double cx = -1, double cy = -1, Duration = Duration::zero());
void setZoom(double zoom, Duration = Duration::zero());
double getZoom() const;
double getScale() const;
double getMinZoom() const;
double getMaxZoom() const;
// Angle
void rotateBy(double sx, double sy, double ex, double ey, Duration = Duration::zero());
void setAngle(double angle, Duration = Duration::zero());
void setAngle(double angle, double cx, double cy);
double getAngle() const;
// Transitions
bool needsTransition() const;
UpdateType updateTransitions(TimePoint now);
void cancelTransitions();
// Gesture
void setGestureInProgress(bool);
// Transform state
const TransformState currentState() const;
const TransformState finalState() const;
private:
// Functions prefixed with underscores will *not* perform any locks. It is the caller's
// responsibility to lock this object.
void _moveBy(double dx, double dy, Duration = Duration::zero());
void _setScale(double scale, double cx, double cy, Duration = Duration::zero());
void _setScaleXY(double new_scale, double xn, double yn, Duration = Duration::zero());
void _setAngle(double angle, Duration = Duration::zero());
void constrain(double& scale, double& y) const;
View &view;
mutable std::recursive_mutex mtx;
// This reflects the current state of the transform, representing the actual position of the
// map. After calling a transform function with a timer, this will likely remain the same until
// you render a new frame.
TransformState current;
// This reflects the final position of the transform, after all possible transition took place.
TransformState final;
// Limit the amount of zooming possible on the map.
const double min_scale = std::pow(2, 0);
const double max_scale = std::pow(2, 18);
void startTransition(std::function<Update(double)> frame,
std::function<void()> finish,
Duration);
TimePoint transitionStart;
Duration transitionDuration;
std::function<Update(TimePoint)> transitionFrameFn;
std::function<void()> transitionFinishFn;
};
}
#endif

View File

@@ -31,8 +31,8 @@ box TransformState::cornersToBox(uint32_t z) const {
const double angle_sin = std::sin(-angle);
const double angle_cos = std::cos(-angle);
const double w_2 = width / 2;
const double h_2 = height / 2;
const double w_2 = static_cast<double>(width) / 2.0;
const double h_2 = static_cast<double>(height) / 2.0;
const double ss_0 = scale * util::tileSize;
const double ss_1 = ref_scale / ss_0;
const double ss_2 = ss_0 / 2.0;
@@ -166,8 +166,8 @@ const vec2<double> TransformState::pixelForLatLng(const LatLng latLng) const {
LatLng ll = getLatLng();
double zoom = getZoom();
const double centerX = width / 2;
const double centerY = height / 2;
const double centerX = static_cast<double>(width) / 2.0;
const double centerY = static_cast<double>(height) / 2.0;
const double m = Projection::getMetersPerPixelAtLatitude(0, zoom);

View File

@@ -0,0 +1,93 @@
#ifndef MBGL_MAP_TRANSFORM_STATE
#define MBGL_MAP_TRANSFORM_STATE
#include <mbgl/util/mat4.hpp>
#include <mbgl/util/geo.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/vec.hpp>
#include <cstdint>
#include <array>
#include <limits>
namespace mbgl {
class TileID;
struct box;
class TransformState {
friend class Transform;
public:
// Matrix
void matrixFor(mat4& matrix, const TileID& id) const;
box cornersToBox(uint32_t z) const;
// Dimensions
bool hasSize() const;
uint16_t getWidth() const;
uint16_t getHeight() const;
uint16_t getFramebufferWidth() const;
uint16_t getFramebufferHeight() const;
const std::array<uint16_t, 2> getFramebufferDimensions() const;
float getPixelRatio() const;
float worldSize() const;
float lngX(float lon) const;
float latY(float lat) const;
std::array<float, 2> locationCoordinate(float lon, float lat) const;
void getLonLat(double &lon, double &lat) const;
// Position
const LatLng getLatLng() const;
// Zoom
float getNormalizedZoom() const;
double getZoom() const;
int32_t getIntegerZoom() const;
double getZoomFraction() const;
double getScale() const;
// Rotation
float getAngle() const;
// Projection
const vec2<double> pixelForLatLng(const LatLng latLng) const;
const LatLng latLngForPixel(const vec2<double> pixel) const;
// Changing
bool isChanging() const;
private:
double pixel_x() const;
double pixel_y() const;
private:
// logical dimensions
uint16_t width = 0, height = 0;
// physical (framebuffer) dimensions
std::array<uint16_t, 2> framebuffer = {{ 0, 0 }};
// map scale factor
float pixelRatio = 0;
// animation state
bool rotating = false;
bool scaling = false;
bool panning = false;
bool gestureInProgress = false;
// map position
double x = 0, y = 0;
double angle = 0;
double scale = 1;
// cache values for spherical mercator math
double Bc = (scale * util::tileSize) / 360;
double Cc = (scale * util::tileSize) / util::M2PI;
};
}
#endif

View File

@@ -6,80 +6,104 @@
#include <mbgl/map/source.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/text/collision_tile.hpp>
#include <mbgl/util/pbf.hpp>
using namespace mbgl;
VectorTileData::VectorTileData(const TileID& id_,
float mapMaxZoom,
util::ptr<Style> style_,
Style& style_,
GlyphAtlas& glyphAtlas_,
GlyphStore& glyphStore_,
SpriteAtlas& spriteAtlas_,
util::ptr<Sprite> sprite_,
const SourceInfo& source_)
: TileData(id_, source_),
depth(id_.z >= source_.max_zoom ? mapMaxZoom - id_.z : 1),
glyphAtlas(glyphAtlas_),
glyphStore(glyphStore_),
spriteAtlas(spriteAtlas_),
sprite(sprite_),
style(style_),
depth(id.z >= source.max_zoom ? mapMaxZoom - id.z : 1) {
collision(util::make_unique<CollisionTile>(id_.z, 4096, source_.tile_size)) {
}
VectorTileData::~VectorTileData() {
// Cancel in most derived class destructor so that worker tasks are joined before
// any member data goes away.
cancel();
glyphAtlas.removeGlyphs(reinterpret_cast<uintptr_t>(this));
}
void VectorTileData::parse() {
if (state != State::loaded) {
if (getState() != State::loaded && getState() != State::partial) {
return;
}
try {
if (!style) {
throw std::runtime_error("style isn't present in VectorTileData object anymore");
}
// Parsing creates state that is encapsulated in TileParser. While parsing,
// the TileParser object writes results into this objects. All other state
// is going to be discarded afterwards.
VectorTile vectorTile(pbf((const uint8_t *)data.data(), data.size()));
const VectorTile* vt = &vectorTile;
TileParser parser(*vt, *this, style, glyphAtlas, glyphStore, spriteAtlas, sprite);
// Clear the style so that we don't have a cycle in the shared_ptr references.
style.reset();
parser.parse();
if (getState() == State::obsolete) {
return;
}
if (parser.isPartialParse()) {
setState(State::partial);
} else {
setState(State::parsed);
}
} catch (const std::exception& ex) {
Log::Error(Event::ParseTile, "Parsing [%d/%d/%d] failed: %s", id.z, id.x, id.y, ex.what());
state = State::obsolete;
setState(State::obsolete);
return;
}
}
Bucket* VectorTileData::getBucket(StyleLayer const& layer) {
if (!isReady() || !layer.bucket) {
return nullptr;
}
std::lock_guard<std::mutex> lock(bucketsMutex);
const auto it = buckets.find(layer.bucket->name);
if (it == buckets.end()) {
return nullptr;
}
assert(it->second);
return it->second.get();
}
size_t VectorTileData::countBuckets() const {
std::lock_guard<std::mutex> lock(bucketsMutex);
return buckets.size();
}
void VectorTileData::setBucket(StyleLayer const& layer, std::unique_ptr<Bucket> bucket) {
assert(layer.bucket);
std::lock_guard<std::mutex> lock(bucketsMutex);
if (buckets.find(layer.bucket->name) != buckets.end()) {
return;
}
if (state != State::obsolete) {
state = State::parsed;
}
buckets[layer.bucket->name] = std::move(bucket);
}
void VectorTileData::render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) {
if (state == State::parsed && layer_desc.bucket) {
auto databucket_it = buckets.find(layer_desc.bucket->name);
if (databucket_it != buckets.end()) {
assert(databucket_it->second);
databucket_it->second->render(painter, layer_desc, id, matrix);
}
}
}
void VectorTileData::setState(const State& state_) {
TileData::setState(state_);
bool VectorTileData::hasData(const StyleLayer &layer_desc) const {
if (state == State::parsed && layer_desc.bucket) {
auto databucket_it = buckets.find(layer_desc.bucket->name);
if (databucket_it != buckets.end()) {
assert(databucket_it->second);
return databucket_it->second->hasData();
}
if (isImmutable()) {
collision.reset();
}
return false;
}

View File

@@ -11,11 +11,13 @@
#include <iosfwd>
#include <memory>
#include <mutex>
#include <unordered_map>
namespace mbgl {
class Bucket;
class CollisionTile;
class Painter;
class SourceInfo;
class StyleLayer;
@@ -32,7 +34,7 @@ class VectorTileData : public TileData {
public:
VectorTileData(const TileID&,
float mapMaxZoom,
util::ptr<Style>,
Style&,
GlyphAtlas&,
GlyphStore&,
SpriteAtlas&,
@@ -41,8 +43,18 @@ public:
~VectorTileData();
void parse() override;
void render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) override;
bool hasData(StyleLayer const& layer_desc) const override;
virtual Bucket* getBucket(StyleLayer const &layer_desc) override;
size_t countBuckets() const;
void setBucket(StyleLayer const &layer_desc, std::unique_ptr<Bucket> bucket);
void setState(const State& state) override;
inline CollisionTile* getCollision() const {
return collision.get();
}
const float depth;
protected:
// Holds the actual geometries in this tile.
@@ -52,18 +64,23 @@ protected:
TriangleElementsBuffer triangleElementsBuffer;
LineElementsBuffer lineElementsBuffer;
// Holds the buckets of this tile.
// They contain the location offsets in the buffers stored above
std::unordered_map<std::string, std::unique_ptr<Bucket>> buckets;
GlyphAtlas& glyphAtlas;
GlyphStore& glyphStore;
SpriteAtlas& spriteAtlas;
util::ptr<Sprite> sprite;
util::ptr<Style> style;
Style& style;
public:
const float depth;
private:
// Contains all the Bucket objects for the tile. Buckets are render
// objects and they get added to this std::map<> by the workers doing
// the actual tile parsing as they get processed. Tiles partially
// parsed can get new buckets at any moment but are also fit for
// rendering. That said, access to this list needs locking unless
// the tile is completely parsed.
std::unordered_map<std::string, std::unique_ptr<Bucket>> buckets;
mutable std::mutex bucketsMutex;
std::unique_ptr<CollisionTile> collision;
};
}

View File

@@ -2,6 +2,8 @@
#include <mbgl/map/map.hpp>
#include <mbgl/map/still_image.hpp>
#include <cassert>
namespace mbgl {
void View::initialize(Map *map_) {
@@ -9,7 +11,7 @@ void View::initialize(Map *map_) {
map = map_;
}
void View::discard() {
void View::resize(uint16_t, uint16_t, float) {
// no-op
}
@@ -17,11 +19,6 @@ std::unique_ptr<StillImage> View::readStillImage() {
return nullptr;
}
void View::resize(uint16_t width, uint16_t height, float ratio, uint16_t fbWidth, uint16_t fbHeight) {
assert(map);
map->resize(width, height, ratio, fbWidth, fbHeight);
}
void View::notifyMapChange(MapChange, Duration) {
// no-op
}

View File

@@ -1,78 +1,36 @@
#include <mbgl/platform/gl.hpp>
#include <mbgl/platform/log.hpp>
#include <iostream>
#include <mutex>
namespace mbgl {
namespace gl {
PFNGLDEBUGMESSAGECONTROLPROC DebugMessageControl = nullptr;
PFNGLDEBUGMESSAGEINSERTPROC DebugMessageInsert = nullptr;
PFNGLDEBUGMESSAGECALLBACKPROC DebugMessageCallback = nullptr;
PFNGLGETDEBUGMESSAGELOGPROC GetDebugMessageLog = nullptr;
PFNGLGETPOINTERVPROC GetPointerv = nullptr;
PFNGLPUSHDEBUGGROUPPROC PushDebugGroup = nullptr;
PFNGLPOPDEBUGGROUPPROC PopDebugGroup = nullptr;
PFNGLOBJECTLABELPROC ObjectLabel = nullptr;
PFNGLGETOBJECTLABELPROC GetObjectLabel = nullptr;
PFNGLOBJECTPTRLABELPROC ObjectPtrLabel = nullptr;
PFNGLGETOBJECTPTRLABELPROC GetObjectPtrLabel = nullptr;
void debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei, const GLchar *message, const void *) {
std::string strSource;
switch (source) {
case GL_DEBUG_SOURCE_API: strSource = "DEBUG_SOURCE_API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: strSource = "DEBUG_SOURCE_WINDOW_SYSTEM"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: strSource = "DEBUG_SOURCE_SHADER_COMPILER"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: strSource = "DEBUG_SOURCE_THIRD_PARTY"; break;
case GL_DEBUG_SOURCE_APPLICATION: strSource = "DEBUG_SOURCE_APPLICATION"; break;
case GL_DEBUG_SOURCE_OTHER: strSource = "DEBUG_SOURCE_OTHER"; break;
default: strSource = "(unknown)"; break;
}
std::string strType;
switch (type) {
case GL_DEBUG_TYPE_ERROR: strType = "DEBUG_TYPE_ERROR"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: strType = "DEBUG_TYPE_DEPRECATED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: strType = "DEBUG_TYPE_UNDEFINED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_PERFORMANCE: strType = "DEBUG_TYPE_PERFORMANCE"; break;
case GL_DEBUG_TYPE_PORTABILITY: strType = "DEBUG_TYPE_PORTABILITY"; break;
case GL_DEBUG_TYPE_OTHER: strType = "DEBUG_TYPE_OTHER"; break;
case GL_DEBUG_TYPE_MARKER: strType = "DEBUG_TYPE_MARKER"; break;
case GL_DEBUG_TYPE_PUSH_GROUP: strType = "DEBUG_TYPE_OTHER"; break;
case GL_DEBUG_TYPE_POP_GROUP: strType = "DEBUG_TYPE_POP_GROUP"; break;
default: strSource = "(unknown)"; break;
}
std::string strSeverity;
mbgl::EventSeverity evtSeverity;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH: strSeverity = "DEBUG_SEVERITY_HIGH"; evtSeverity = mbgl::EventSeverity::Error; break;
case GL_DEBUG_SEVERITY_MEDIUM: strSeverity = "DEBUG_SEVERITY_MEDIUM"; evtSeverity = mbgl::EventSeverity::Warning; break;
case GL_DEBUG_SEVERITY_LOW: strSeverity = "DEBUG_SEVERITY_LOW"; evtSeverity = mbgl::EventSeverity::Info; break;
case GL_DEBUG_SEVERITY_NOTIFICATION: strSeverity = "DEBUG_SEVERITY_NOTIFICATION"; evtSeverity = mbgl::EventSeverity::Debug; break;
default: strSource = "(unknown)"; evtSeverity = mbgl::EventSeverity::Debug; break;
}
mbgl::Log::Record(evtSeverity, mbgl::Event::OpenGL, "GL_%s GL_%s %u GL_%s - %s", strSource.c_str(), strType.c_str(), id, strSeverity.c_str(), message);
std::vector<ExtensionFunctionBase*>& ExtensionFunctionBase::functions() {
static std::vector<ExtensionFunctionBase*> functions;
return functions;
}
PFNGLINSERTEVENTMARKEREXTPROC InsertEventMarkerEXT = nullptr;
PFNGLPUSHGROUPMARKEREXTPROC PushGroupMarkerEXT = nullptr;
PFNGLPOPGROUPMARKEREXTPROC PopGroupMarkerEXT = nullptr;
static std::once_flag initializeExtensionsOnce;
PFNGLLABELOBJECTEXTPROC LabelObjectEXT = nullptr;
PFNGLGETOBJECTLABELEXTPROC GetObjectLabelEXT = nullptr;
void InitializeExtensions(glProc (*getProcAddress)(const char *)) {
std::call_once(initializeExtensionsOnce, [getProcAddress] {
const char * extensionsPtr = reinterpret_cast<const char *>(
MBGL_CHECK_ERROR(glGetString(GL_EXTENSIONS)));
PFNGLBINDVERTEXARRAYPROC BindVertexArray = nullptr;
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays = nullptr;
PFNGLGENVERTEXARRAYSPROC GenVertexArrays = nullptr;
PFNGLISVERTEXARRAYPROC IsVertexArray = nullptr;
if (!extensionsPtr)
return;
bool isPackedDepthStencilSupported = false;
bool isDepth24Supported = false;
const std::string extensions = extensionsPtr;
for (auto fn : ExtensionFunctionBase::functions()) {
for (auto probe : fn->probes) {
if (extensions.find(probe.first) != std::string::npos) {
fn->ptr = getProcAddress(probe.second);
break;
}
}
}
});
}
void checkError(const char *cmd, const char *file, int line) {
const GLenum err = glGetError();

View File

@@ -1,6 +1,7 @@
#ifndef MBGL_RENDERER_BUCKET
#define MBGL_RENDERER_BUCKET
#include <mbgl/renderer/render_pass.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/mat4.hpp>
@@ -12,10 +13,23 @@ class TileID;
class Bucket : private util::noncopyable {
public:
// As long as this bucket has a Prepare render pass, this function is getting called. Typically,
// this only happens once when the bucket is being rendered for the first time.
virtual void upload() = 0;
// Every time this bucket is getting rendered, this function is called. This happens either
// once or twice (for Opaque and Transparent render passes).
virtual void render(Painter&, const StyleLayer&, const TileID&, const mat4&) = 0;
virtual bool hasData() const = 0;
virtual ~Bucket() {}
inline bool needsUpload() const {
return !uploaded;
}
protected:
bool uploaded = false;
};
}

View File

@@ -1,23 +1,29 @@
#include <mbgl/renderer/debug_bucket.hpp>
#include <mbgl/renderer/painter.hpp>
#include <mbgl/shader/plain_shader.hpp>
#include <mbgl/platform/gl.hpp>
#include <cassert>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
using namespace mbgl;
DebugBucket::DebugBucket(DebugFontBuffer& fontBuffer_)
: fontBuffer(fontBuffer_) {
}
void DebugBucket::render(Painter &painter, const StyleLayer & /*layer_desc*/,
const TileID & /*id*/, const mat4 &matrix) {
painter.renderDebugText(*this, matrix);
void DebugBucket::upload() {
fontBuffer.upload();
uploaded = true;
}
bool DebugBucket::hasData() const {
return fontBuffer.index() > 0;
void DebugBucket::render(Painter& painter, const StyleLayer&, const TileID&, const mat4& matrix) {
painter.renderDebugText(*this, matrix);
}
void DebugBucket::drawLines(PlainShader& shader) {

View File

@@ -7,10 +7,6 @@
#include <vector>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
namespace mbgl {
class PlainShader;
@@ -19,9 +15,8 @@ class DebugBucket : public Bucket {
public:
DebugBucket(DebugFontBuffer& fontBuffer);
void render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) override;
bool hasData() const override;
void upload() override;
void render(Painter&, const StyleLayer&, const TileID&, const mat4&) override;
void drawLines(PlainShader& shader);
void drawPoints(PlainShader& shader);

View File

@@ -4,18 +4,23 @@
#include <mbgl/renderer/painter.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layout.hpp>
#include <mbgl/shader/plain_shader.hpp>
#include <mbgl/shader/pattern_shader.hpp>
#include <mbgl/shader/outline_shader.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/platform/gl.hpp>
#include <mbgl/platform/log.hpp>
#include <cassert>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
struct geometry_too_long_exception : std::exception {};
using namespace mbgl;
void *FillBucket::alloc(void *, unsigned int size) {
return ::malloc(size);
}
@@ -84,7 +89,7 @@ void FillBucket::tessellate() {
hasVertices = false;
std::vector<std::vector<ClipperLib::IntPoint>> polygons;
clipper.Execute(ClipperLib::ctUnion, polygons, ClipperLib::pftPositive);
clipper.Execute(ClipperLib::ctUnion, polygons, ClipperLib::pftEvenOdd, ClipperLib::pftEvenOdd);
clipper.Clear();
if (polygons.size() == 0) {
@@ -132,7 +137,7 @@ void FillBucket::tessellate() {
lineGroup.elements_length += total_vertex_count;
if (tessTesselate(tesselator, TESS_WINDING_POSITIVE, TESS_POLYGONS, vertices_per_group, vertexSize, 0)) {
if (tessTesselate(tesselator, TESS_WINDING_ODD, TESS_POLYGONS, vertices_per_group, vertexSize, 0)) {
const TESSreal *vertices = tessGetVertices(tesselator);
const size_t vertex_count = tessGetVertexCount(tesselator);
TESSindex *vertex_indices = const_cast<TESSindex *>(tessGetVertexIndices(tesselator));
@@ -195,8 +200,19 @@ void FillBucket::tessellate() {
lineGroup.vertex_length += total_vertex_count;
}
void FillBucket::render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) {
void FillBucket::upload() {
vertexBuffer.upload();
triangleElementsBuffer.upload();
lineElementsBuffer.upload();
// From now on, we're going to render during the opaque and translucent pass.
uploaded = true;
}
void FillBucket::render(Painter& painter,
const StyleLayer& layer_desc,
const TileID& id,
const mat4& matrix) {
painter.renderFill(*this, layer_desc, id, matrix);
}

View File

@@ -11,10 +11,6 @@
#include <vector>
#include <memory>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
namespace mbgl {
class FillVertexBuffer;
@@ -37,9 +33,9 @@ public:
LineElementsBuffer &lineElementsBuffer);
~FillBucket() override;
void render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) override;
bool hasData() const override;
void upload() override;
void render(Painter&, const StyleLayer&, const TileID&, const mat4&) override;
bool hasData() const;
void addGeometry(const GeometryCollection&);
void tessellate();

View File

@@ -0,0 +1,19 @@
#include "gl_config.hpp"
namespace mbgl {
namespace gl {
const ClearDepth::Type ClearDepth::Default = 0;
const ClearColor::Type ClearColor::Default = { 0, 0, 0, 0 };
const ClearStencil::Type ClearStencil::Default = 0;
const StencilMask::Type StencilMask::Default = ~0u;
const DepthMask::Type DepthMask::Default = GL_TRUE;
const ColorMask::Type ColorMask::Default = { false, false, false, false };
const StencilFunc::Type StencilFunc::Default = { GL_ALWAYS, 0, ~0u };
const StencilTest::Type StencilTest::Default = false;
const DepthRange::Type DepthRange::Default = { 0, 1 };
const DepthTest::Type DepthTest::Default = false;
const Blend::Type Blend::Default = false;
}
}

View File

@@ -0,0 +1,149 @@
#ifndef MBGL_RENDERER_GL_CONFIG
#define MBGL_RENDERER_GL_CONFIG
#include <cstdint>
#include <tuple>
#include <array>
#include <mbgl/platform/gl.hpp>
namespace mbgl {
namespace gl {
template <typename T>
class Value {
public:
inline void operator=(const typename T::Type& value) {
if (current != value) {
current = value;
MBGL_CHECK_ERROR(T::Set(current));
}
}
private:
typename T::Type current = T::Default;
};
struct ClearDepth {
using Type = GLfloat;
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glClearDepth(value));
}
};
struct ClearColor {
struct Type { float r, g, b, a; };
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glClearColor(value.r, value.g, value.b, value.a));
}
};
inline bool operator!=(const ClearColor::Type& a, const ClearColor::Type& b) {
return a.r != b.r || a.g != b.g || a.b != b.b || a.a != b.a;
}
struct ClearStencil {
using Type = GLint;
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glClearStencil(value));
}
};
struct StencilMask {
using Type = GLuint;
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glStencilMask(value));
}
};
struct DepthMask {
using Type = GLboolean;
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glDepthMask(value));
}
};
struct ColorMask {
struct Type { bool r, g, b, a; };
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glColorMask(value.r, value.g, value.b, value.a));
}
};
inline bool operator!=(const ColorMask::Type& a, const ColorMask::Type& b) {
return a.r != b.r || a.g != b.g || a.b != b.b || a.a != b.a;
}
struct StencilFunc {
struct Type { GLenum func; GLint ref; GLuint mask; };
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glStencilFunc(value.func, value.ref, value.mask));
}
};
inline bool operator!=(const StencilFunc::Type& a, const StencilFunc::Type& b) {
return a.func != b.func || a.ref != b.ref || a.mask != b.mask;
}
struct StencilTest {
using Type = bool;
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(value ? glEnable(GL_STENCIL_TEST) : glDisable(GL_STENCIL_TEST));
}
};
struct DepthRange {
struct Type { GLfloat near, far; };
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(glDepthRange(value.near, value.far));
}
};
inline bool operator!=(const DepthRange::Type& a, const DepthRange::Type& b) {
return a.near != b.near || a.far != b.far;
}
struct DepthTest {
using Type = bool;
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(value ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST));
}
};
struct Blend {
using Type = bool;
static const Type Default;
inline static void Set(const Type& value) {
MBGL_CHECK_ERROR(value ? glEnable(GL_BLEND) : glDisable(GL_BLEND));
}
};
class Config {
public:
Value<StencilFunc> stencilFunc;
Value<StencilMask> stencilMask;
Value<StencilTest> stencilTest;
Value<DepthRange> depthRange;
Value<DepthMask> depthMask;
Value<DepthTest> depthTest;
Value<Blend> blend;
Value<ColorMask> colorMask;
Value<ClearDepth> clearDepth;
Value<ClearColor> clearColor;
Value<ClearStencil> clearStencil;
};
}
}
#endif

View File

@@ -4,6 +4,9 @@
#include <mbgl/renderer/painter.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layout.hpp>
#include <mbgl/shader/line_shader.hpp>
#include <mbgl/shader/linesdf_shader.hpp>
#include <mbgl/shader/linepattern_shader.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/platform/gl.hpp>
@@ -140,7 +143,7 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
// Find the cosine of the angle between the next and join normals
// using dot product. The inverse of that is the miter length.
const float cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;
const float miterLength = 1 / cosHalfAngle;
const float miterLength = cosHalfAngle != 0 ? 1 / cosHalfAngle: 1;
// The join if a middle vertex, otherwise the cap
const bool middleVertex = prevVertex && nextVertex;
@@ -183,8 +186,9 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
// Almost parallel lines
joinNormal = nextNormal;
} else {
const float direction = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0 ? -1 : 1;
const float bevelLength = miterLength * util::mag(prevNormal + nextNormal) /
util::mag(prevNormal - nextNormal);
util::mag(prevNormal - nextNormal * direction);
joinNormal = util::perp(joinNormal) * bevelLength;
}
@@ -338,6 +342,14 @@ void LineBucket::addCurrentVertex(const Coordinate& currentVertex,
e2 = e3;
}
void LineBucket::upload() {
vertexBuffer.upload();
triangleElementsBuffer.upload();
// From now on, we're only going to render during the translucent pass.
uploaded = true;
}
void LineBucket::render(Painter& painter,
const StyleLayer& layer_desc,
const TileID& id,

View File

@@ -28,9 +28,9 @@ public:
LineBucket(LineVertexBuffer &vertexBuffer, TriangleElementsBuffer &triangleElementsBuffer);
~LineBucket() override;
void render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) override;
bool hasData() const override;
void upload() override;
void render(Painter&, const StyleLayer&, const TileID&, const mat4&) override;
bool hasData() const;
void addGeometry(const GeometryCollection&);
void addGeometry(const std::vector<Coordinate>& line);

View File

@@ -1,16 +1,35 @@
#include <mbgl/renderer/painter.hpp>
#include <mbgl/map/source.hpp>
#include <mbgl/map/tile.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/gl/debugging.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/shader/pattern_shader.hpp>
#include <mbgl/shader/plain_shader.hpp>
#include <mbgl/shader/outline_shader.hpp>
#include <mbgl/shader/line_shader.hpp>
#include <mbgl/shader/linesdf_shader.hpp>
#include <mbgl/shader/linepattern_shader.hpp>
#include <mbgl/shader/icon_shader.hpp>
#include <mbgl/shader/raster_shader.hpp>
#include <mbgl/shader/sdf_shader.hpp>
#include <mbgl/shader/dot_shader.hpp>
#include <mbgl/shader/gaussian_shader.hpp>
#include <mbgl/shader/box_shader.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/clip_id.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/mat3.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/map/source.hpp>
#include <mbgl/map/tile.hpp>
#if defined(DEBUG)
#include <mbgl/util/stopwatch.hpp>
@@ -39,22 +58,7 @@ bool Painter::needsAnimation() const {
}
void Painter::setup() {
#if defined(DEBUG)
util::stopwatch stopwatch("painter setup");
#endif
// Enable GL debugging
if ((gl::DebugMessageControl != nullptr) && (gl::DebugMessageCallback != nullptr)) {
// This will enable all messages including performance hints
//MBGL_CHECK_ERROR(gl::DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE));
// This will only enable high and medium severity messages
MBGL_CHECK_ERROR(gl::DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE));
MBGL_CHECK_ERROR(gl::DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE));
MBGL_CHECK_ERROR(gl::DebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE));
MBGL_CHECK_ERROR(gl::DebugMessageCallback(gl::debug_callback, nullptr));
}
gl::debugging::enable();
setupShaders();
@@ -75,16 +79,15 @@ void Painter::setup() {
// We are blending new pixels on top of old pixels. Since we have depth testing
// and are drawing opaque fragments first front-to-back, then translucent
// fragments back-to-front, this shades the fewest fragments possible.
MBGL_CHECK_ERROR(glEnable(GL_BLEND));
config.blend = true;
MBGL_CHECK_ERROR(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
// Set clear values
MBGL_CHECK_ERROR(glClearColor(0.0f, 0.0f, 0.0f, 0.0f));
MBGL_CHECK_ERROR(glClearDepth(1.0f));
MBGL_CHECK_ERROR(glClearStencil(0x0));
config.clearColor = { 0.0f, 0.0f, 0.0f, 0.0f };
config.clearDepth = 1.0f;
config.clearStencil = 0x0;
// Stencil test
MBGL_CHECK_ERROR(glEnable(GL_STENCIL_TEST));
MBGL_CHECK_ERROR(glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE));
// Depth test
@@ -107,24 +110,6 @@ void Painter::setupShaders() {
if (!collisionBoxShader) collisionBoxShader = util::make_unique<CollisionBoxShader>();
}
void Painter::deleteShaders() {
plainShader = nullptr;
outlineShader = nullptr;
lineShader = nullptr;
linepatternShader = nullptr;
patternShader = nullptr;
iconShader = nullptr;
rasterShader = nullptr;
sdfGlyphShader = nullptr;
sdfIconShader = nullptr;
dotShader = nullptr;
gaussianShader = nullptr;
}
void Painter::terminate() {
deleteShaders();
}
void Painter::resize() {
if (gl_viewport != state.getFramebufferDimensions()) {
gl_viewport = state.getFramebufferDimensions();
@@ -151,21 +136,6 @@ void Painter::lineWidth(float line_width) {
}
}
void Painter::depthMask(bool value) {
if (gl_depthMask != value) {
MBGL_CHECK_ERROR(glDepthMask(value ? GL_TRUE : GL_FALSE));
gl_depthMask = value;
}
}
void Painter::depthRange(const float near, const float far) {
if (gl_depthRange[0] != near || gl_depthRange[1] != far) {
MBGL_CHECK_ERROR(glDepthRange(near, far));
gl_depthRange = {{ near, far }};
}
}
void Painter::changeMatrix() {
// Initialize projection matrix
matrix::ortho(projMatrix, 0, state.getWidth(), state.getHeight(), 0, 0, 1);
@@ -182,28 +152,15 @@ void Painter::changeMatrix() {
}
void Painter::clear() {
gl::group group("clear");
MBGL_CHECK_ERROR(glStencilMask(0xFF));
depthMask(true);
MBGL_CHECK_ERROR(glClearColor(0, 0, 0, 0));
gl::debugging::group group("clear");
config.stencilTest = true;
config.stencilMask = 0xFF;
config.depthTest = false;
config.depthMask = GL_TRUE;
config.clearColor = { 0.0f, 0.0f, 0.0f, 0.0f };
MBGL_CHECK_ERROR(glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
}
void Painter::setOpaque() {
if (pass != RenderPass::Opaque) {
pass = RenderPass::Opaque;
MBGL_CHECK_ERROR(glDisable(GL_BLEND));
}
}
void Painter::setTranslucent() {
if (pass != RenderPass::Translucent) {
pass = RenderPass::Translucent;
MBGL_CHECK_ERROR(glEnable(GL_BLEND));
}
}
void Painter::setStrata(float value) {
strata = value;
}
@@ -211,16 +168,12 @@ void Painter::setStrata(float value) {
void Painter::prepareTile(const Tile& tile) {
const GLint ref = (GLint)tile.clip.reference.to_ulong();
const GLuint mask = (GLuint)tile.clip.mask.to_ulong();
MBGL_CHECK_ERROR(glStencilFunc(GL_EQUAL, ref, mask));
config.stencilFunc = { GL_EQUAL, ref, mask };
}
void Painter::render(const Style& style, TransformState state_, TimePoint time) {
state = state_;
clear();
resize();
changeMatrix();
std::set<Source*> sources;
for (const auto& source : style.sources) {
if (source->enabled) {
@@ -228,14 +181,47 @@ void Painter::render(const Style& style, TransformState state_, TimePoint time)
}
}
// Update all clipping IDs.
ClipIDGenerator generator;
for (const auto& source : sources) {
generator.update(source->getLoadedTiles());
source->updateMatrices(projMatrix, state);
resize();
changeMatrix();
// Figure out what buckets we have to draw and what order we have to draw them in.
const auto order = determineRenderOrder(style);
// - UPLOAD PASS -------------------------------------------------------------------------------
// Uploads all required buffers and images before we do any actual rendering.
{
const gl::debugging::group upload("upload");
tileStencilBuffer.upload();
tileBorderBuffer.upload();
spriteAtlas.upload();
lineAtlas.upload();
glyphAtlas.upload();
for (const auto& item : order) {
if (item.bucket && item.bucket->needsUpload()) {
item.bucket->upload();
}
}
}
drawClippingMasks(sources);
// - CLIPPING MASKS ----------------------------------------------------------------------------
// Draws the clipping masks to the stencil buffer.
{
const gl::debugging::group clip("clip");
// Update all clipping IDs.
ClipIDGenerator generator;
for (const auto& source : sources) {
generator.update(source->getLoadedTiles());
source->updateMatrices(projMatrix, state);
}
clear();
drawClippingMasks(sources);
}
frameHistory.record(time, state.getNormalizedZoom());
@@ -243,122 +229,160 @@ void Painter::render(const Style& style, TransformState state_, TimePoint time)
if (debug::renderTree) { Log::Info(Event::Render, "{"); indent++; }
// TODO: Correctly compute the number of layers recursively beforehand.
float strata_thickness = 1.0f / (style.layers.size() + 1);
const float strataThickness = 1.0f / (order.size() + 1);
// - FIRST PASS ------------------------------------------------------------
// Render everything top-to-bottom by using reverse iterators. Render opaque
// objects first.
// - OPAQUE PASS -------------------------------------------------------------------------------
// Render everything top-to-bottom by using reverse iterators. Render opaque objects first.
renderPass(RenderPass::Opaque,
order.rbegin(), order.rend(),
0, 1, strataThickness);
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s", indent++ * 4, "", "OPAQUE {");
}
int i = 0;
for (auto it = style.layers.rbegin(), end = style.layers.rend(); it != end; ++it, ++i) {
setOpaque();
setStrata(i * strata_thickness);
renderLayer(**it);
}
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s", --indent * 4, "", "}");
}
// - SECOND PASS -----------------------------------------------------------
// Make a second pass, rendering translucent objects. This time, we render
// bottom-to-top.
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s", indent++ * 4, "", "TRANSLUCENT {");
}
--i;
for (auto it = style.layers.begin(), end = style.layers.end(); it != end; ++it, --i) {
setTranslucent();
setStrata(i * strata_thickness);
renderLayer(**it);
}
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s", --indent * 4, "", "}");
}
// - TRANSLUCENT PASS --------------------------------------------------------------------------
// Make a second pass, rendering translucent objects. This time, we render bottom-to-top.
renderPass(RenderPass::Translucent,
order.begin(), order.end(),
order.size() - 1, -1, strataThickness);
if (debug::renderTree) { Log::Info(Event::Render, "}"); indent--; }
// Finalize the rendering, e.g. by calling debug render calls per tile.
// This guarantees that we have at least one function per tile called.
// When only rendering layers via the stylesheet, it's possible that we don't
// ever visit a tile during rendering.
for (const auto& source : sources) {
source->finishRender(*this);
// - DEBUG PASS --------------------------------------------------------------------------------
// Renders debug overlays.
{
const gl::debugging::group _("debug");
// Finalize the rendering, e.g. by calling debug render calls per tile.
// This guarantees that we have at least one function per tile called.
// When only rendering layers via the stylesheet, it's possible that we don't
// ever visit a tile during rendering.
for (const auto& source : sources) {
source->finishRender(*this);
}
}
// TODO: Find a better way to unbind VAOs after we're done with them without introducing
// unnecessary bind(0)/bind(N) sequences.
{
const gl::debugging::group _("cleanup");
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, 0));
MBGL_CHECK_ERROR(VertexArrayObject::Unbind());
}
}
void Painter::renderLayer(const StyleLayer &layer_desc) {
if (layer_desc.bucket->visibility == VisibilityType::None) return;
if (layer_desc.type == StyleLayerType::Background) {
// This layer defines a background color/image.
template <class Iterator>
void Painter::renderPass(RenderPass pass_,
Iterator it, Iterator end,
std::size_t i, int8_t increment,
const float strataThickness) {
pass = pass_;
if (debug::renderTree) {
Log::Info(Event::Render, "%*s- %s (%s)", indent * 4, "", layer_desc.id.c_str(),
StyleLayerTypeClass(layer_desc.type).c_str());
const char * passName = pass == RenderPass::Opaque ? "opaque" : "translucent";
const gl::debugging::group _(passName);
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s {", indent++ * 4, "", passName);
}
config.blend = pass == RenderPass::Translucent;
for (; it != end; ++it, i += increment) {
const auto& item = *it;
if (item.bucket && item.tile) {
if (item.hasRenderPass(pass)) {
const gl::debugging::group group(item.layer.id + " - " + std::string(item.tile->id));
setStrata(i * strataThickness);
prepareTile(*item.tile);
item.bucket->render(*this, item.layer, item.tile->id, item.tile->matrix);
}
} else {
const gl::debugging::group group("background");
setStrata(i * strataThickness);
renderBackground(item.layer);
}
}
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s", --indent * 4, "", "}");
}
}
std::vector<RenderItem> Painter::determineRenderOrder(const Style& style) {
std::vector<RenderItem> order;
for (const auto& layerPtr : style.layers) {
const auto& layer = *layerPtr;
if (layer.bucket->visibility == VisibilityType::None) continue;
if (layer.type == StyleLayerType::Background) {
// This layer defines a background color/image.
order.emplace_back(layer);
continue;
}
renderBackground(layer_desc);
} else {
// This is a singular layer.
if (!layer_desc.bucket) {
Log::Warning(Event::Render, "layer '%s' is missing bucket", layer_desc.id.c_str());
return;
if (!layer.bucket) {
Log::Warning(Event::Render, "layer '%s' is missing bucket", layer.id.c_str());
continue;
}
if (!layer_desc.bucket->source) {
Log::Warning(Event::Render, "can't find source for layer '%s'", layer_desc.id.c_str());
return;
if (!layer.bucket->source) {
Log::Warning(Event::Render, "can't find source for layer '%s'", layer.id.c_str());
continue;
}
// Skip this layer if it's outside the range of min/maxzoom.
// This may occur when there /is/ a bucket created for this layer, but the min/max-zoom
// is set to a fractional value, or value that is larger than the source maxzoom.
const double zoom = state.getZoom();
if (layer_desc.bucket->min_zoom > zoom ||
layer_desc.bucket->max_zoom <= zoom) {
return;
if (layer.bucket->min_zoom > zoom ||
layer.bucket->max_zoom <= zoom) {
continue;
}
// Abort early if we can already deduce from the bucket type that
// we're not going to render anything anyway during this pass.
switch (layer_desc.type) {
case StyleLayerType::Fill:
if (!layer_desc.getProperties<FillProperties>().isVisible()) return;
break;
case StyleLayerType::Line:
if (pass == RenderPass::Opaque) return;
if (!layer_desc.getProperties<LineProperties>().isVisible()) return;
break;
case StyleLayerType::Symbol:
if (pass == RenderPass::Opaque) return;
if (!layer_desc.getProperties<SymbolProperties>().isVisible()) return;
break;
case StyleLayerType::Raster:
if (pass == RenderPass::Opaque) return;
if (!layer_desc.getProperties<RasterProperties>().isVisible()) return;
break;
default:
break;
// Don't include invisible layers.
if (!layer.isVisible()) {
continue;
}
if (debug::renderTree) {
Log::Info(Event::Render, "%*s- %s (%s)", indent * 4, "", layer_desc.id.c_str(),
StyleLayerTypeClass(layer_desc.type).c_str());
}
// Determine what render passes we need for this layer.
const RenderPass passes = determineRenderPasses(layer);
layer_desc.bucket->source->render(*this, layer_desc);
const auto& tiles = layer.bucket->source->getTiles();
for (auto tile : tiles) {
assert(tile);
if (!tile->data && !tile->data->isReady()) {
continue;
}
auto bucket = tile->data->getBucket(layer);
if (bucket) {
order.emplace_back(layer, tile, bucket, passes);
}
}
}
return order;
}
void Painter::renderTileLayer(const Tile& tile, const StyleLayer &layer_desc, const mat4 &matrix) {
assert(tile.data);
if (tile.data->hasData(layer_desc) || layer_desc.type == StyleLayerType::Raster) {
gl::group group(std::string { "render " } + tile.data->name);
prepareTile(tile);
tile.data->render(*this, layer_desc, matrix);
RenderPass Painter::determineRenderPasses(const StyleLayer& layer) {
RenderPass passes = RenderPass::None;
if (layer.properties.is<FillProperties>()) {
const FillProperties &properties = layer.properties.get<FillProperties>();
const float alpha = properties.fill_color[3] * properties.opacity;
if (properties.antialias) {
passes |= RenderPass::Translucent;
}
if (properties.image.from.size() || alpha < 1.0f) {
passes |= RenderPass::Translucent;
} else {
passes |= RenderPass::Opaque;
}
} else {
passes |= RenderPass::Translucent;
}
return passes;
}
void Painter::renderBackground(const StyleLayer &layer_desc) {
@@ -435,10 +459,10 @@ void Painter::renderBackground(const StyleLayer &layer_desc) {
backgroundArray.bind(*plainShader, backgroundBuffer, BUFFER_OFFSET(0));
}
MBGL_CHECK_ERROR(glDisable(GL_STENCIL_TEST));
depthRange(strata + strata_epsilon, 1.0f);
config.stencilTest = false;
config.depthTest = true;
config.depthRange = { strata + strata_epsilon, 1.0f };
MBGL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4));
MBGL_CHECK_ERROR(glEnable(GL_STENCIL_TEST));
}
mat4 Painter::translatedMatrix(const mat4& matrix, const std::array<float, 2> &translation, const TileID &id, TranslateAnchorType anchor) {

View File

@@ -1,61 +1,82 @@
#ifndef MBGL_RENDERER_PAINTER
#define MBGL_RENDERER_PAINTER
#include <mbgl/map/tile_data.hpp>
#include <mbgl/map/transform_state.hpp>
#include <mbgl/renderer/frame_history.hpp>
#include <mbgl/renderer/bucket.hpp>
#include <mbgl/geometry/vao.hpp>
#include <mbgl/geometry/static_vertex_buffer.hpp>
#include <mbgl/util/mat4.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/renderer/frame_history.hpp>
#include <mbgl/renderer/gl_config.hpp>
#include <mbgl/style/types.hpp>
#include <mbgl/shader/plain_shader.hpp>
#include <mbgl/shader/outline_shader.hpp>
#include <mbgl/shader/pattern_shader.hpp>
#include <mbgl/shader/line_shader.hpp>
#include <mbgl/shader/linesdf_shader.hpp>
#include <mbgl/shader/linepattern_shader.hpp>
#include <mbgl/shader/icon_shader.hpp>
#include <mbgl/shader/raster_shader.hpp>
#include <mbgl/shader/sdf_shader.hpp>
#include <mbgl/shader/dot_shader.hpp>
#include <mbgl/shader/gaussian_shader.hpp>
#include <mbgl/shader/box_shader.hpp>
#include <mbgl/platform/gl.hpp>
#include <mbgl/map/transform_state.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/chrono.hpp>
#include <map>
#include <unordered_map>
#include <array>
#include <vector>
#include <set>
namespace mbgl {
enum class RenderPass : bool { Opaque, Translucent };
class Transform;
class Style;
class StyleLayer;
class Tile;
class Sprite;
class SpriteAtlas;
class GlyphAtlas;
class LineAtlas;
class Source;
class DebugBucket;
class FillBucket;
class LineBucket;
class SymbolBucket;
class RasterBucket;
class PrerenderedTexture;
struct FillProperties;
struct RasterProperties;
class LayerDescription;
class RasterTileData;
class SDFShader;
class PlainShader;
class OutlineShader;
class LineShader;
class LinejoinShader;
class LineSDFShader;
class LinepatternShader;
class PatternShader;
class IconShader;
class RasterShader;
class SDFGlyphShader;
class SDFIconShader;
class DotShader;
class GaussianShader;
class CollisionBoxShader;
struct ClipID;
struct RenderItem {
inline RenderItem(const StyleLayer& layer_,
const Tile* tile_ = nullptr,
Bucket* bucket_ = nullptr,
RenderPass passes_ = RenderPass::Opaque)
: tile(tile_), bucket(bucket_), layer(layer_), passes(passes_) {
}
const Tile* const tile;
Bucket* const bucket;
const StyleLayer& layer;
const RenderPass passes;
inline bool hasRenderPass(RenderPass pass) const {
return bool(passes & pass);
}
};
class Painter : private util::noncopyable {
public:
Painter(SpriteAtlas&, GlyphAtlas&, LineAtlas&);
@@ -63,11 +84,6 @@ public:
void setup();
// Perform cleanup tasks that prepare shutting down the app. This doesn't mean that the
// app will be shut down. That means all operations must be automatically be reversed (e.g. through
// lazy initialization) in case rendering continues.
void terminate();
// Renders the backdrop of the OpenGL view. This also paints in areas where we don't have any
// tiles whatsoever.
void clear();
@@ -79,11 +95,6 @@ public:
TransformState state,
TimePoint time);
void renderLayer(const StyleLayer&);
// Renders a particular layer from a tile.
void renderTileLayer(const Tile& tile, const StyleLayer &layer_desc, const mat4 &matrix);
// Renders debug information for a tile.
void renderTileDebug(const Tile& tile);
@@ -113,10 +124,6 @@ public:
// Changes whether debug information is drawn onto the map
void setDebug(bool enabled);
// Opaque/Translucent pass setting
void setOpaque();
void setTranslucent();
// Configures the painter strata that is used for early z-culling of fragments.
void setStrata(float strata);
@@ -133,9 +140,17 @@ public:
private:
void setupShaders();
void deleteShaders();
mat4 translatedMatrix(const mat4& matrix, const std::array<float, 2> &translation, const TileID &id, TranslateAnchorType anchor);
std::vector<RenderItem> determineRenderOrder(const Style& style);
static RenderPass determineRenderPasses(const StyleLayer&);
template <class Iterator>
void renderPass(RenderPass,
Iterator it, Iterator end,
std::size_t i, int8_t iIncrement,
const float strataThickness);
void prepareTile(const Tile& tile);
template <typename BucketProperties, typename StyleProperties>
@@ -152,8 +167,6 @@ private:
public:
void useProgram(uint32_t program);
void lineWidth(float lineWidth);
void depthMask(bool value);
void depthRange(float near, float far);
public:
mat4 projMatrix;
@@ -180,11 +193,11 @@ private:
bool debug = false;
int indent = 0;
gl::Config config;
uint32_t gl_program = 0;
float gl_lineWidth = 0;
bool gl_depthMask = true;
std::array<uint16_t, 2> gl_viewport = {{ 0, 0 }};
std::array<float, 2> gl_depthRange = {{ 0, 1 }};
float strata = 0;
RenderPass pass = RenderPass::Opaque;
const float strata_epsilon = 1.0f / (1 << 16);

View File

@@ -1,20 +1,24 @@
#include <mbgl/renderer/painter.hpp>
#include <mbgl/renderer/fill_bucket.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/map/tile.hpp>
#include <mbgl/map/source.hpp>
#include <mbgl/shader/plain_shader.hpp>
#include <mbgl/util/clip_id.hpp>
#include <mbgl/gl/debugging.hpp>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
using namespace mbgl;
void Painter::drawClippingMasks(const std::set<Source*>& sources) {
gl::group group("clipping masks");
gl::debugging::group group("clipping masks");
useProgram(plainShader->program);
MBGL_CHECK_ERROR(glDisable(GL_DEPTH_TEST));
depthMask(false);
MBGL_CHECK_ERROR(glColorMask(false, false, false, false));
depthRange(1.0f, 1.0f);
config.stencilTest = true;
config.depthTest = true;
config.depthMask = GL_FALSE;
config.colorMask = { false, false, false, false };
config.depthRange = { 1.0f, 1.0f };
coveringPlainArray.bind(*plainShader, tileStencilBuffer, BUFFER_OFFSET(0));
@@ -22,10 +26,10 @@ void Painter::drawClippingMasks(const std::set<Source*>& sources) {
source->drawClippingMasks(*this);
}
MBGL_CHECK_ERROR(glEnable(GL_DEPTH_TEST));
MBGL_CHECK_ERROR(glColorMask(true, true, true, true));
depthMask(true);
MBGL_CHECK_ERROR(glStencilMask(0x0));
config.depthTest = true;
config.colorMask = { true, true, true, true };
config.depthMask = GL_TRUE;
config.stencilMask = 0x0;
}
void Painter::drawClippingMask(const mat4& matrix, const ClipID &clip) {
@@ -33,8 +37,7 @@ void Painter::drawClippingMask(const mat4& matrix, const ClipID &clip) {
const GLint ref = (GLint)(clip.reference.to_ulong());
const GLuint mask = (GLuint)(clip.mask.to_ulong());
MBGL_CHECK_ERROR(glStencilFunc(GL_ALWAYS, ref, mask));
MBGL_CHECK_ERROR(glStencilMask(mask));
config.stencilFunc = { GL_ALWAYS, ref, mask };
config.stencilMask = mask;
MBGL_CHECK_ERROR(glDrawArrays(GL_TRIANGLES, 0, (GLsizei)tileStencilBuffer.index()));
}

View File

@@ -1,13 +1,19 @@
#include <mbgl/renderer/painter.hpp>
#include <mbgl/renderer/debug_bucket.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/map/tile.hpp>
#include <mbgl/map/tile_data.hpp>
#include <mbgl/shader/plain_shader.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/gl/debugging.hpp>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
using namespace mbgl;
void Painter::renderTileDebug(const Tile& tile) {
gl::group group(std::string { "debug " } + std::string(tile.id));
gl::debugging::group group(std::string { "debug " } + std::string(tile.id));
assert(tile.data);
if (debug) {
prepareTile(tile);
@@ -17,9 +23,9 @@ void Painter::renderTileDebug(const Tile& tile) {
}
void Painter::renderDebugText(DebugBucket& bucket, const mat4 &matrix) {
gl::group group("debug text");
gl::debugging::group group("debug text");
MBGL_CHECK_ERROR(glDisable(GL_DEPTH_TEST));
config.depthTest = false;
useProgram(plainShader->program);
plainShader->u_matrix = matrix;
@@ -40,16 +46,17 @@ void Painter::renderDebugText(DebugBucket& bucket, const mat4 &matrix) {
lineWidth(2.0f * state.getPixelRatio());
bucket.drawLines(*plainShader);
MBGL_CHECK_ERROR(glEnable(GL_DEPTH_TEST));
config.depthTest = true;
}
void Painter::renderDebugFrame(const mat4 &matrix) {
gl::group group("debug frame");
gl::debugging::group group("debug frame");
// Disable depth test and don't count this towards the depth buffer,
// but *don't* disable stencil test, as we want to clip the red tile border
// to the tile viewport.
MBGL_CHECK_ERROR(glDisable(GL_DEPTH_TEST));
config.depthTest = false;
config.stencilTest = true;
useProgram(plainShader->program);
plainShader->u_matrix = matrix;
@@ -59,8 +66,6 @@ void Painter::renderDebugFrame(const mat4 &matrix) {
plainShader->u_color = {{ 1.0f, 0.0f, 0.0f, 1.0f }};
lineWidth(4.0f * state.getPixelRatio());
MBGL_CHECK_ERROR(glDrawArrays(GL_LINE_STRIP, 0, (GLsizei)tileBorderBuffer.index()));
MBGL_CHECK_ERROR(glEnable(GL_DEPTH_TEST));
}
void Painter::renderDebugText(const std::vector<std::string> &strings) {
@@ -68,10 +73,11 @@ void Painter::renderDebugText(const std::vector<std::string> &strings) {
return;
}
gl::group group("debug text");
gl::debugging::group group("debug text");
MBGL_CHECK_ERROR(glDisable(GL_DEPTH_TEST));
MBGL_CHECK_ERROR(glStencilFunc(GL_ALWAYS, 0xFF, 0xFF));
config.depthTest = false;
config.stencilTest = true;
config.stencilFunc = { GL_ALWAYS, 0xFF, 0xFF };
useProgram(plainShader->program);
plainShader->u_matrix = nativeMatrix;
@@ -98,6 +104,4 @@ void Painter::renderDebugText(const std::vector<std::string> &strings) {
lineWidth(2.0f * state.getPixelRatio());
MBGL_CHECK_ERROR(glDrawArrays(GL_LINES, 0, (GLsizei)debugFontBuffer.index()));
}
MBGL_CHECK_ERROR(glEnable(GL_DEPTH_TEST));
}

View File

@@ -3,18 +3,18 @@
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_layout.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/map/tile_id.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/shader/outline_shader.hpp>
#include <mbgl/shader/pattern_shader.hpp>
#include <mbgl/shader/plain_shader.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/mat3.hpp>
using namespace mbgl;
void Painter::renderFill(FillBucket& bucket, const StyleLayer &layer_desc, const TileID& id, const mat4 &matrix) {
// Abort early.
if (!bucket.hasData()) return;
const FillProperties &properties = layer_desc.getProperties<FillProperties>();
mat4 vtxMatrix = translatedMatrix(matrix, properties.translate, id, properties.translateAnchor);
@@ -39,6 +39,9 @@ void Painter::renderFill(FillBucket& bucket, const StyleLayer &layer_desc, const
bool outline = properties.antialias && !pattern && stroke_color != fill_color;
bool fringeline = properties.antialias && !pattern && stroke_color == fill_color;
config.stencilTest = true;
config.depthTest = true;
// Because we're drawing top-to-bottom, and we update the stencil mask
// befrom, we have to draw the outline first (!)
if (outline && pass == RenderPass::Translucent) {
@@ -53,7 +56,7 @@ void Painter::renderFill(FillBucket& bucket, const StyleLayer &layer_desc, const
static_cast<float>(state.getFramebufferWidth()),
static_cast<float>(state.getFramebufferHeight())
}};
depthRange(strata, 1.0f);
config.depthRange = { strata, 1.0f };
bucket.drawVertices(*outlineShader);
}
@@ -92,8 +95,8 @@ void Painter::renderFill(FillBucket& bucket, const StyleLayer &layer_desc, const
spriteAtlas.bind(true);
// Draw the actual triangles into the color & stencil buffer.
depthMask(true);
depthRange(strata, 1.0f);
config.depthMask = GL_TRUE;
config.depthRange = { strata, 1.0f };
bucket.drawElements(*patternShader);
}
}
@@ -109,8 +112,8 @@ void Painter::renderFill(FillBucket& bucket, const StyleLayer &layer_desc, const
plainShader->u_color = fill_color;
// Draw the actual triangles into the color & stencil buffer.
depthMask(true);
depthRange(strata + strata_epsilon, 1.0f);
config.depthMask = GL_TRUE;
config.depthRange = { strata + strata_epsilon, 1.0f };
bucket.drawElements(*plainShader);
}
}
@@ -130,7 +133,7 @@ void Painter::renderFill(FillBucket& bucket, const StyleLayer &layer_desc, const
static_cast<float>(state.getFramebufferHeight())
}};
depthRange(strata + strata_epsilon + strata_epsilon, 1.0f);
config.depthRange = { strata + strata_epsilon + strata_epsilon, 1.0f };
bucket.drawVertices(*outlineShader);
}
}

View File

@@ -4,18 +4,22 @@
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_layout.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/map/tile_id.hpp>
#include <mbgl/shader/line_shader.hpp>
#include <mbgl/shader/linesdf_shader.hpp>
#include <mbgl/shader/linepattern_shader.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/map/map.hpp>
using namespace mbgl;
void Painter::renderLine(LineBucket& bucket, const StyleLayer &layer_desc, const TileID& id, const mat4 &matrix) {
// Abort early.
if (pass == RenderPass::Opaque) return;
if (!bucket.hasData()) return;
depthMask(false);
config.stencilTest = true;
config.depthTest = true;
config.depthMask = GL_FALSE;
const auto &properties = layer_desc.getProperties<LineProperties>();
const auto &layout = bucket.layout;
@@ -49,7 +53,7 @@ void Painter::renderLine(LineBucket& bucket, const StyleLayer &layer_desc, const
float ratio = state.getPixelRatio();
mat4 vtxMatrix = translatedMatrix(matrix, properties.translate, id, properties.translateAnchor);
depthRange(strata, 1.0f);
config.depthRange = { strata, 1.0f };
if (properties.dash_array.from.size()) {
@@ -107,7 +111,7 @@ void Painter::renderLine(LineBucket& bucket, const StyleLayer &layer_desc, const
MBGL_CHECK_ERROR(glActiveTexture(GL_TEXTURE0));
spriteAtlas.bind(true);
MBGL_CHECK_ERROR(glDepthRange(strata + strata_epsilon, 1.0f)); // may or may not matter
config.depthRange = { strata + strata_epsilon, 1.0f }; // may or may not matter
bucket.drawLinePatterns(*linepatternShader);

View File

@@ -2,8 +2,8 @@
#include <mbgl/platform/gl.hpp>
#include <mbgl/renderer/raster_bucket.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/shader/raster_shader.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/map/map.hpp>
using namespace mbgl;
@@ -23,8 +23,9 @@ void Painter::renderRaster(RasterBucket& bucket, const StyleLayer &layer_desc, c
rasterShader->u_contrast_factor = contrastFactor(properties.contrast);
rasterShader->u_spin_weights = spinWeights(properties.hue_rotate);
depthRange(strata + strata_epsilon, 1.0f);
config.stencilTest = true;
config.depthTest = true;
config.depthRange = { strata + strata_epsilon, 1.0f };
bucket.drawRaster(*rasterShader, tileStencilBuffer, coveringRasterArray);
}
}

View File

@@ -4,7 +4,10 @@
#include <mbgl/style/style_layout.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/map/map.hpp>
#include <mbgl/shader/sdf_shader.hpp>
#include <mbgl/shader/icon_shader.hpp>
#include <mbgl/shader/box_shader.hpp>
#include <mbgl/map/tile_id.hpp>
#include <mbgl/util/math.hpp>
#include <cmath>
@@ -81,7 +84,7 @@ void Painter::renderSDF(SymbolBucket &bucket,
sdfShader.u_buffer = (haloOffset - styleProperties.halo_width / fontScale) / sdfPx;
depthRange(strata, 1.0f);
config.depthRange = { strata, 1.0f };
(bucket.*drawSDF)(sdfShader);
}
@@ -102,7 +105,7 @@ void Painter::renderSDF(SymbolBucket &bucket,
sdfShader.u_buffer = (256.0f - 64.0f) / 256.0f;
depthRange(strata + strata_epsilon, 1.0f);
config.depthRange = { strata + strata_epsilon, 1.0f };
(bucket.*drawSDF)(sdfShader);
}
}
@@ -116,8 +119,9 @@ void Painter::renderSymbol(SymbolBucket &bucket, const StyleLayer &layer_desc, c
const auto &properties = layer_desc.getProperties<SymbolProperties>();
const auto &layout = bucket.layout;
MBGL_CHECK_ERROR(glDisable(GL_STENCIL_TEST));
depthMask(false);
config.stencilTest = false;
config.depthTest = true;
config.depthMask = GL_FALSE;
if (bucket.hasIconData()) {
bool sdf = bucket.sdfIcons;
@@ -170,7 +174,7 @@ void Painter::renderSymbol(SymbolBucket &bucket, const StyleLayer &layer_desc, c
iconShader->u_fadezoom = state.getNormalizedZoom() * 10;
iconShader->u_opacity = properties.icon.opacity;
depthRange(strata, 1.0f);
config.depthRange = { strata, 1.0f };
bucket.drawIcons(*iconShader);
}
}
@@ -190,7 +194,7 @@ void Painter::renderSymbol(SymbolBucket &bucket, const StyleLayer &layer_desc, c
}
if (bucket.hasCollisionBoxData()) {
MBGL_CHECK_ERROR(glEnable(GL_STENCIL_TEST));
config.stencilTest = true;
useProgram(collisionBoxShader->program);
collisionBoxShader->u_matrix = matrix;
@@ -199,10 +203,9 @@ void Painter::renderSymbol(SymbolBucket &bucket, const StyleLayer &layer_desc, c
collisionBoxShader->u_maxzoom = (id.z + 1) * 10;
lineWidth(3.0f);
depthRange(strata, 1.0f);
config.depthRange = { strata, 1.0f };
bucket.drawCollisionBoxes(*collisionBoxShader);
}
MBGL_CHECK_ERROR(glEnable(GL_STENCIL_TEST));
}

View File

@@ -1,6 +1,11 @@
#include <mbgl/renderer/raster_bucket.hpp>
#include <mbgl/shader/raster_shader.hpp>
#include <mbgl/renderer/painter.hpp>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
using namespace mbgl;
RasterBucket::RasterBucket(TexturePool& texturePool, const StyleLayoutRaster& layout_)
@@ -8,8 +13,17 @@ RasterBucket::RasterBucket(TexturePool& texturePool, const StyleLayoutRaster& la
raster(texturePool) {
}
void RasterBucket::render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) {
void RasterBucket::upload() {
if (hasData()) {
raster.upload();
uploaded = true;
}
}
void RasterBucket::render(Painter& painter,
const StyleLayer& layer_desc,
const TileID& id,
const mat4& matrix) {
painter.renderRaster(*this, layer_desc, id, matrix);
}
@@ -24,13 +38,6 @@ void RasterBucket::drawRaster(RasterShader& shader, StaticVertexBuffer &vertices
MBGL_CHECK_ERROR(glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices.index()));
}
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));
MBGL_CHECK_ERROR(glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices.index()));
}
bool RasterBucket::hasData() const {
return raster.isLoaded();
}

View File

@@ -5,8 +5,6 @@
#include <mbgl/util/raster.hpp>
#include <mbgl/style/style_bucket.hpp>
namespace mbgl {
class StyleLayoutRaster;
@@ -18,9 +16,9 @@ class RasterBucket : public Bucket {
public:
RasterBucket(TexturePool&, const StyleLayoutRaster&);
void render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) override;
bool hasData() const override;
void upload() override;
void render(Painter&, const StyleLayer&, const TileID&, const mat4&) override;
bool hasData() const;
bool setImage(const std::string &data);
@@ -28,8 +26,6 @@ public:
void drawRaster(RasterShader& shader, StaticVertexBuffer &vertices, VertexArrayObject &array);
void drawRaster(RasterShader& shader, StaticVertexBuffer &vertices, VertexArrayObject &array, GLuint texture);
Raster raster;
};

View File

@@ -0,0 +1,31 @@
#ifndef MBGL_RENDERER_RENDER_PASS
#define MBGL_RENDERER_RENDER_PASS
#include <cstdint>
#include <type_traits>
namespace mbgl {
enum class RenderPass : uint8_t {
None = 0,
Opaque = 1 << 0,
Translucent = 1 << 1,
};
constexpr inline RenderPass operator|(RenderPass a, RenderPass b) {
return static_cast<RenderPass>(static_cast<std::underlying_type<RenderPass>::type>(a) |
static_cast<std::underlying_type<RenderPass>::type>(b));
}
inline RenderPass operator|=(RenderPass& a, RenderPass b) {
return (a = a | b);
}
constexpr inline RenderPass operator&(RenderPass a, RenderPass b) {
return static_cast<RenderPass>(static_cast<std::underlying_type<RenderPass>::type>(a) &
static_cast<std::underlying_type<RenderPass>::type>(b));
}
}
#endif

View File

@@ -11,6 +11,9 @@
#include <mbgl/text/glyph_store.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/text/collision_tile.hpp>
#include <mbgl/shader/sdf_shader.hpp>
#include <mbgl/shader/icon_shader.hpp>
#include <mbgl/shader/box_shader.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/util/utf.hpp>
@@ -20,6 +23,10 @@
#include <mbgl/util/clip_lines.hpp>
#include <mbgl/util/std.hpp>
#ifndef BUFFER_OFFSET
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
#endif
namespace mbgl {
SymbolInstance::SymbolInstance(Anchor &anchor, const std::vector<Coordinate> &line,
@@ -54,8 +61,23 @@ SymbolBucket::~SymbolBucket() {
// Do not remove. header file only contains forward definitions to unique pointers.
}
void SymbolBucket::render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) {
void SymbolBucket::upload() {
if (hasTextData()) {
text.vertices.upload();
text.triangles.upload();
}
if (hasIconData()) {
icon.vertices.upload();
icon.triangles.upload();
}
uploaded = true;
}
void SymbolBucket::render(Painter& painter,
const StyleLayer& layer_desc,
const TileID& id,
const mat4& matrix) {
painter.renderSymbol(*this, layer_desc, id, matrix);
}
@@ -67,17 +89,15 @@ bool SymbolBucket::hasIconData() const { return !icon.groups.empty(); }
bool SymbolBucket::hasCollisionBoxData() const { return !collisionBox.groups.empty(); }
std::vector<SymbolFeature> SymbolBucket::processFeatures(const GeometryTileLayer& layer,
const FilterExpression& filter,
GlyphStore &glyphStore,
const Sprite &sprite) {
bool SymbolBucket::needsDependencies(const GeometryTileLayer& layer,
const FilterExpression& filter,
GlyphStore& glyphStore,
Sprite& sprite) {
const bool has_text = !layout.text.field.empty() && !layout.text.font.empty();
const bool has_icon = !layout.icon.image.empty();
std::vector<SymbolFeature> features;
if (!has_text && !has_icon) {
return features;
return false;
}
// Determine and load glyph ranges
@@ -140,21 +160,22 @@ std::vector<SymbolFeature> SymbolBucket::processFeatures(const GeometryTileLayer
util::mergeLines(features);
}
glyphStore.waitForGlyphRanges(layout.text.font, ranges);
sprite.waitUntilLoaded();
if (glyphStore.requestGlyphRangesIfNeeded(layout.text.font, ranges)) {
return true;
}
return features;
if (!sprite.isLoaded()) {
return true;
}
return false;
}
void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
const FilterExpression& filter,
uintptr_t tileUID,
void SymbolBucket::addFeatures(uintptr_t tileUID,
SpriteAtlas& spriteAtlas,
Sprite& sprite,
GlyphAtlas& glyphAtlas,
GlyphStore& glyphStore) {
const std::vector<SymbolFeature> features = processFeatures(layer, filter, glyphStore, sprite);
float horizontalAlign = 0.5;
float verticalAlign = 0.5;
@@ -196,7 +217,7 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
layout.text.justify == TextJustifyType::Left ? 0 :
0.5;
const auto &fontStack = glyphStore.getFontStack(layout.text.font);
auto* fontStack = glyphStore.getFontStack(layout.text.font);
for (const auto& feature : features) {
if (!feature.geometry.size()) continue;
@@ -220,13 +241,12 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
// Add the glyphs we need for this label to the glyph atlas.
if (shapedText) {
glyphAtlas.addGlyphs(tileUID, feature.label, layout.text.font, fontStack, face);
glyphAtlas.addGlyphs(tileUID, feature.label, layout.text.font, *fontStack, face);
}
}
// if feature has icon, get sprite atlas position
if (feature.sprite.length()) {
sprite.waitUntilLoaded();
Rect<uint16_t> image = spriteAtlas.getImage(feature.sprite, false);
shapedIcon = shapeIcon(image, layout);
@@ -241,6 +261,8 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
}
}
features.clear();
placeFeatures();
}

View File

@@ -65,16 +65,14 @@ public:
SymbolBucket(CollisionTile &collision);
~SymbolBucket() override;
void render(Painter &painter, const StyleLayer &layer_desc, const TileID &id,
const mat4 &matrix) override;
bool hasData() const override;
void upload() override;
void render(Painter&, const StyleLayer&, const TileID&, const mat4&) override;
bool hasData() const;
bool hasTextData() const;
bool hasIconData() const;
bool hasCollisionBoxData() const;
void addFeatures(const GeometryTileLayer&,
const FilterExpression&,
uintptr_t tileUID,
void addFeatures(uintptr_t tileUID,
SpriteAtlas&,
Sprite&,
GlyphAtlas&,
@@ -85,11 +83,12 @@ public:
void drawIcons(IconShader& shader);
void drawCollisionBoxes(CollisionBoxShader& shader);
bool needsDependencies(const GeometryTileLayer&,
const FilterExpression&,
GlyphStore&,
Sprite&);
private:
std::vector<SymbolFeature> processFeatures(const GeometryTileLayer&,
const FilterExpression&,
GlyphStore&,
const Sprite&);
void addFeature(const std::vector<std::vector<Coordinate>> &lines,
const Shaping &shapedText, const PositionedIcon &shapedIcon,
const GlyphPositions &face);
@@ -108,6 +107,7 @@ public:
private:
CollisionTile &collision;
std::vector<SymbolInstance> symbolInstances;
std::vector<SymbolFeature> features;
struct TextBuffer {
TextVertexBuffer vertices;
@@ -127,6 +127,7 @@ private:
} collisionBox;
};
}
#endif

View File

@@ -9,7 +9,7 @@ namespace mbgl {
template <typename T>
class Uniform {
public:
Uniform(const GLchar* name, const Shader& shader) {
Uniform(const GLchar* name, const Shader& shader) : current() {
location = MBGL_CHECK_ERROR(glGetUniformLocation(shader.program, name));
}
@@ -32,7 +32,7 @@ class UniformMatrix {
public:
typedef std::array<float, C*R> T;
UniformMatrix(const GLchar* name, const Shader& shader) {
UniformMatrix(const GLchar* name, const Shader& shader) : current() {
location = MBGL_CHECK_ERROR(glGetUniformLocation(shader.program, name));
}

View File

@@ -0,0 +1,23 @@
#ifndef MBGL_STORAGE_DEFAULT_ASSET_CONTEXT
#define MBGL_STORAGE_DEFAULT_ASSET_CONTEXT
#include <mbgl/storage/request_base.hpp>
typedef struct uv_loop_s uv_loop_t;
namespace mbgl {
class AssetContext {
public:
static std::unique_ptr<AssetContext> createContext(uv_loop_t*);
virtual ~AssetContext() = default;
virtual RequestBase* createRequest(const Resource&,
RequestBase::Callback,
uv_loop_t*,
const std::string& assetRoot) = 0;
};
}
#endif

View File

@@ -1,24 +0,0 @@
#ifndef MBGL_STORAGE_DEFAULT_ASSET_REQUEST
#define MBGL_STORAGE_DEFAULT_ASSET_REQUEST
#include "shared_request_base.hpp"
namespace mbgl {
class AssetRequest : public SharedRequestBase {
public:
AssetRequest(DefaultFileSource::Impl *source, const Resource &resource);
void start(uv_loop_t *loop, std::shared_ptr<const Response> response = nullptr);
void cancel();
private:
~AssetRequest();
void *ptr = nullptr;
friend class AssetRequestImpl;
};
}
#endif

View File

@@ -1,7 +1,7 @@
#include <mbgl/storage/default_file_source_impl.hpp>
#include <mbgl/storage/request.hpp>
#include <mbgl/storage/asset_request.hpp>
#include <mbgl/storage/http_request.hpp>
#include <mbgl/storage/asset_context.hpp>
#include <mbgl/storage/http_context.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/platform/platform.hpp>
@@ -10,13 +10,11 @@
#include <mbgl/util/chrono.hpp>
#include <mbgl/util/thread.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/map/environment.hpp>
#pragma GCC diagnostic push
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <boost/algorithm/string.hpp>
#pragma GCC diagnostic pop
@@ -28,97 +26,122 @@ namespace algo = boost::algorithm;
namespace mbgl {
DefaultFileSource::Impl::Impl(FileCache* cache_, const std::string& root)
: assetRoot(root.empty() ? platform::assetRoot() : root), cache(cache_) {
}
DefaultFileSource::DefaultFileSource(FileCache* cache, const std::string& root)
: thread(util::make_unique<util::Thread<Impl>>("FileSource", cache, root)) {
: thread(util::make_unique<util::Thread<Impl>>("FileSource", util::ThreadPriority::Low, cache, root)) {
}
DefaultFileSource::~DefaultFileSource() {
MBGL_VERIFY_THREAD(tid);
}
SharedRequestBase *DefaultFileSource::Impl::find(const Resource &resource) {
// We're using a set of pointers here instead of a map between url and SharedRequestBase because
// we need to find the requests both by pointer and by URL. Given that the number of requests
// is generally very small (typically < 10 at a time), hashing by URL incurs too much overhead
// anyway.
const auto it = pending.find(resource);
if (it != pending.end()) {
return it->second;
}
return nullptr;
}
Request* DefaultFileSource::request(const Resource& resource,
uv_loop_t* l,
const Environment& env,
Callback callback) {
auto req = new Request(resource, l, env, std::move(callback));
// This function can be called from any thread. Make sure we're executing the actual call in the
// file source loop by sending it over the queue.
thread->invoke(&Impl::add, std::move(req), thread->get());
assert(l);
auto req = new Request(resource, l, std::move(callback));
thread->invoke(&Impl::add, req);
return req;
}
void DefaultFileSource::request(const Resource& resource, const Environment& env, Callback callback) {
request(resource, nullptr, env, std::move(callback));
}
void DefaultFileSource::cancel(Request *req) {
req->cancel();
// This function can be called from any thread. Make sure we're executing the actual call in the
// file source loop by sending it over the queue.
thread->invoke(&Impl::cancel, std::move(req));
thread->invoke(&Impl::cancel, req);
}
void DefaultFileSource::abort(const Environment &env) {
thread->invoke(&Impl::abort, std::ref(env));
// ----- Impl -----
DefaultFileSource::Impl::Impl(uv_loop_t* loop_, FileCache* cache_, const std::string& root)
: loop(loop_),
cache(cache_),
assetRoot(root.empty() ? platform::assetRoot() : root),
assetContext(AssetContext::createContext(loop_)),
httpContext(HTTPContext::createContext(loop_)) {
}
void DefaultFileSource::Impl::add(Request* req, uv_loop_t* loop) {
const Resource &resource = req->resource;
// We're adding a new Request.
SharedRequestBase *sharedRequest = find(resource);
if (!sharedRequest) {
// There is no request for this URL yet. Create a new one and start it.
if (algo::starts_with(resource.url, "asset://")) {
sharedRequest = new AssetRequest(this, resource);
} else {
sharedRequest = new HTTPRequest(this, resource);
}
const bool inserted = pending.emplace(resource, sharedRequest).second;
assert(inserted);
(void (inserted)); // silence unused variable warning on Release builds.
// But first, we're going to start querying the database if it exists.
if (!cache) {
sharedRequest->start(loop);
} else {
// Otherwise, first check the cache for existing data so that we can potentially
// revalidate the information without having to redownload everything.
cache->get(resource, [this, resource, loop](std::unique_ptr<Response> response) {
processResult(resource, std::move(response), loop);
});
}
DefaultFileRequest* DefaultFileSource::Impl::find(const Resource& resource) {
const auto it = pending.find(resource);
if (it != pending.end()) {
return &it->second;
}
return nullptr;
}
void DefaultFileSource::Impl::add(Request* req) {
const Resource& resource = req->resource;
DefaultFileRequest* request = find(resource);
if (request) {
request->observers.insert(req);
return;
}
request = &pending.emplace(resource, resource).first->second;
request->observers.insert(req);
if (cache) {
startCacheRequest(resource);
} else {
startRealRequest(resource);
}
}
void DefaultFileSource::Impl::startCacheRequest(const Resource& resource) {
// Check the cache for existing data so that we can potentially
// revalidate the information without having to redownload everything.
cache->get(resource, [this, resource](std::unique_ptr<Response> response) {
DefaultFileRequest* request = find(resource);
if (!request || request->request) {
// There is no request for this URL anymore. Likely, the request was canceled
// before we got around to process the cache result.
// The second possibility is that a request has already been started by another cache
// request. In this case, we don't have to do anything either.
return;
}
auto expired = [&response] {
const int64_t now = std::chrono::duration_cast<std::chrono::seconds>(
SystemClock::now().time_since_epoch()).count();
return response->expires <= now;
};
if (!response || expired()) {
// No response or stale cache. Run the real request.
startRealRequest(resource, std::move(response));
} else {
// The response is fresh. We're good to notify the caller.
notify(request, std::move(response), FileCache::Hint::No);
}
});
}
void DefaultFileSource::Impl::startRealRequest(const Resource& resource, std::shared_ptr<const Response> response) {
DefaultFileRequest* request = find(resource);
auto callback = [request, this] (std::shared_ptr<const Response> res, FileCache::Hint hint) {
notify(request, res, hint);
};
if (algo::starts_with(resource.url, "asset://")) {
request->request = assetContext->createRequest(resource, callback, loop, assetRoot);
} else {
request->request = httpContext->createRequest(resource, callback, loop, response);
}
sharedRequest->subscribe(req);
}
void DefaultFileSource::Impl::cancel(Request* req) {
SharedRequestBase *sharedRequest = find(req->resource);
if (sharedRequest) {
// If the number of dependent requests of the SharedRequestBase drops to zero, the
// unsubscribe callback triggers the removal of the SharedRequestBase pointer from the list
// of pending requests and initiates cancelation.
sharedRequest->unsubscribe(req);
DefaultFileRequest* request = find(req->resource);
if (request) {
// If the number of dependent requests of the DefaultFileRequest drops to zero,
// cancel the request and remove it from the pending list.
request->observers.erase(req);
if (request->observers.empty()) {
if (request->request) {
request->request->cancel();
}
pending.erase(request->resource);
}
} else {
// There is no request for this URL anymore. Likely, the request already completed
// before we got around to process the cancelation request.
@@ -129,78 +152,22 @@ void DefaultFileSource::Impl::cancel(Request* req) {
req->destruct();
}
void DefaultFileSource::Impl::processResult(const Resource& resource, std::shared_ptr<const Response> response, uv_loop_t* loop) {
SharedRequestBase *sharedRequest = find(resource);
if (sharedRequest) {
if (response) {
// This entry was stored in the cache. Now determine if we need to revalidate.
const int64_t now = std::chrono::duration_cast<std::chrono::seconds>(
SystemClock::now().time_since_epoch()).count();
if (response->expires > now) {
// The response is fresh. We're good to notify the caller.
sharedRequest->notify(response, FileCache::Hint::No);
sharedRequest->cancel();
return;
} else {
// The cached response is stale. Now run the real request.
sharedRequest->start(loop, response);
}
} else {
// There is no response. Now run the real request.
sharedRequest->start(loop);
}
} else {
// There is no request for this URL anymore. Likely, the request was canceled
// before we got around to process the cache result.
}
}
// Aborts all requests that are part of the current environment.
void DefaultFileSource::Impl::abort(const Environment& env) {
// Construct a cancellation response.
auto res = util::make_unique<Response>();
res->status = Response::Error;
res->message = "Environment is terminating";
std::shared_ptr<const Response> response = std::move(res);
// Iterate through all pending requests and remove them in case they're abandoned.
util::erase_if(pending, [&](const std::pair<Resource, SharedRequestBase *> &it) -> bool {
// Obtain all pending requests that are in the current environment.
const auto aborted = it.second->removeAllInEnvironment(env);
// Notify all observers.
for (auto req : aborted) {
req->notify(response);
}
// Finally, remove all requests that are now abandoned.
if (it.second->abandoned()) {
it.second->cancel();
return true;
} else {
return false;
}
});
}
void DefaultFileSource::Impl::notify(SharedRequestBase *sharedRequest,
const std::set<Request *> &observers,
std::shared_ptr<const Response> response, FileCache::Hint hint) {
void DefaultFileSource::Impl::notify(DefaultFileRequest* request, std::shared_ptr<const Response> response, FileCache::Hint hint) {
// First, remove the request, since it might be destructed at any point now.
assert(find(sharedRequest->resource) == sharedRequest);
pending.erase(sharedRequest->resource);
assert(find(request->resource) == request);
assert(response);
if (response) {
if (cache) {
// Store response in database
cache->put(sharedRequest->resource, response, hint);
}
// Notify all observers.
for (auto req : observers) {
req->notify(response);
}
// Notify all observers.
for (auto req : request->observers) {
req->notify(response);
}
if (cache) {
// Store response in database
cache->put(request->resource, response, hint);
}
pending.erase(request->resource);
}
}

View File

@@ -2,33 +2,53 @@
#define MBGL_STORAGE_DEFAULT_DEFAULT_FILE_SOURCE_IMPL
#include <mbgl/storage/default_file_source.hpp>
#include <mbgl/storage/asset_context.hpp>
#include <mbgl/storage/http_context.hpp>
#include <set>
#include <unordered_map>
typedef struct uv_loop_s uv_loop_t;
namespace mbgl {
class SharedRequestBase;
class RequestBase;
struct DefaultFileRequest {
const Resource resource;
std::set<Request*> observers;
RequestBase* request = nullptr;
inline DefaultFileRequest(const Resource& resource_)
: resource(resource_) {}
// Make it movable-only
DefaultFileRequest(const DefaultFileRequest&) = delete;
inline DefaultFileRequest(DefaultFileRequest&&) = default;
DefaultFileRequest& operator=(const DefaultFileRequest&) = delete;
inline DefaultFileRequest& operator=(DefaultFileRequest&&) = default;
};
class DefaultFileSource::Impl {
public:
Impl(FileCache *cache, const std::string &root = "");
Impl(uv_loop_t*, FileCache*, const std::string& = "");
void notify(SharedRequestBase *sharedRequest, const std::set<Request *> &observers,
std::shared_ptr<const Response> response, FileCache::Hint hint);
SharedRequestBase *find(const Resource &resource);
void add(Request* request, uv_loop_t* loop);
void cancel(Request* request);
void abort(const Environment& env);
const std::string assetRoot;
void add(Request*);
void cancel(Request*);
private:
void processResult(const Resource& resource, std::shared_ptr<const Response> response, uv_loop_t* loop);
DefaultFileRequest* find(const Resource&);
std::unordered_map<Resource, SharedRequestBase *, Resource::Hash> pending;
FileCache *cache = nullptr;
void startCacheRequest(const Resource&);
void startRealRequest(const Resource&, std::shared_ptr<const Response> = nullptr);
void notify(DefaultFileRequest*, std::shared_ptr<const Response>, FileCache::Hint);
std::unordered_map<Resource, DefaultFileRequest, Resource::Hash> pending;
uv_loop_t* loop = nullptr;
FileCache* cache = nullptr;
const std::string assetRoot;
std::unique_ptr<AssetContext> assetContext;
std::unique_ptr<HTTPContext> httpContext;
};
}

View File

@@ -0,0 +1,30 @@
#include <mbgl/storage/http_context.hpp>
namespace mbgl {
HTTPContext::HTTPContext(uv_loop_t* loop_)
: reachability(loop_, [this] { retryRequests(); }) {
NetworkStatus::Subscribe(reachability.get());
reachability.unref();
}
HTTPContext::~HTTPContext() {
assert(requests.empty());
NetworkStatus::Unsubscribe(reachability.get());
}
void HTTPContext::addRequest(RequestBase* request) {
requests.insert(request);
}
void HTTPContext::removeRequest(RequestBase* request) {
requests.erase(request);
}
void HTTPContext::retryRequests() {
for (auto request : requests) {
request->retry();
}
}
}

View File

@@ -1,76 +1,40 @@
#ifndef MBGL_STORAGE_DEFAULT_HTTP_CONTEXT
#define MBGL_STORAGE_DEFAULT_HTTP_CONTEXT
#include "thread_context.hpp"
#include <mbgl/storage/request_base.hpp>
#include <mbgl/storage/network_status.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <set>
namespace mbgl {
class HTTPRequest;
// This is a template class that provides a per-thread Context object. It can be used by HTTP
// implementations to store global state. It also implements the NetworkStatus mechanism and
// triggers immediate retries on all requests waiting for network status changes.
template <typename Context>
class HTTPContext : public ThreadContext<Context> {
class HTTPContext {
public:
HTTPContext(uv_loop_t *loop);
~HTTPContext();
static std::unique_ptr<HTTPContext> createContext(uv_loop_t*);
void addRequest(HTTPRequest *request);
void removeRequest(HTTPRequest *baton);
HTTPContext(uv_loop_t*);
virtual ~HTTPContext();
virtual RequestBase* createRequest(const Resource&,
RequestBase::Callback,
uv_loop_t*,
std::shared_ptr<const Response>) = 0;
void addRequest(RequestBase*);
void removeRequest(RequestBase*);
private:
void retryRequests();
public:
// Will be fired when the network status becomes reachable.
uv_async_t *reachability = nullptr;
uv::async reachability;
// A list of all pending HTTPRequestImpls that we need to notify when the network status
// changes.
std::set<HTTPRequest *> requests;
std::set<RequestBase*> requests;
};
template <typename Context>
HTTPContext<Context>::HTTPContext(uv_loop_t *loop_)
: ThreadContext<Context>(loop_) {
reachability = new uv_async_t;
reachability->data = this;
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
uv_async_init(loop_, reachability, [](uv_async_t *async, int) {
#else
uv_async_init(loop_, reachability, [](uv_async_t *async) {
#endif
for (auto request : reinterpret_cast<Context *>(async->data)->requests) {
request->retryImmediately();
}
});
// Allow the loop to quit even though this handle is still active.
uv_unref(reinterpret_cast<uv_handle_t *>(reachability));
NetworkStatus::Subscribe(reachability);
}
template <typename Context>
HTTPContext<Context>::~HTTPContext() {
MBGL_VERIFY_THREAD(HTTPContext<Context>::tid);
assert(requests.empty());
NetworkStatus::Unsubscribe(reachability);
uv::close(reachability);
}
template <typename Context>
void HTTPContext<Context>::addRequest(HTTPRequest *request) {
requests.insert(request);
}
template <typename Context>
void HTTPContext<Context>::removeRequest(HTTPRequest *request) {
requests.erase(request);
}
}
#endif

View File

@@ -1,26 +0,0 @@
#ifndef MBGL_STORAGE_DEFAULT_HTTP_REQUEST
#define MBGL_STORAGE_DEFAULT_HTTP_REQUEST
#include "shared_request_base.hpp"
namespace mbgl {
class HTTPRequest : public SharedRequestBase {
public:
HTTPRequest(DefaultFileSource::Impl *source, const Resource &resource);
void start(uv_loop_t *loop, std::shared_ptr<const Response> response = nullptr);
void cancel();
void retryImmediately();
private:
~HTTPRequest();
void *ptr = nullptr;
friend class HTTPRequestImpl;
};
}
#endif

View File

@@ -1,12 +1,11 @@
#include <mbgl/storage/request.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/uv.hpp>
#include <uv.h>
#include <mbgl/util/uv_detail.hpp>
#include <cassert>
#include <functional>
@@ -16,24 +15,14 @@ namespace mbgl {
struct Request::Canceled { std::mutex mutex; bool confirmed = false; };
// Note: This requires that loop is running in the current thread (or not yet running).
Request::Request(const Resource &resource_, uv_loop_t *loop, const Environment &env_, Callback callback_)
: callback(callback_), resource(resource_), env(env_) {
// When there is no loop supplied (== nullptr), the callback will be fired in an arbitrary
// thread (the thread notify() is called from) rather than kicking back to the calling thread.
if (loop) {
async = new uv_async_t;
async->data = this;
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
uv_async_init(loop, async, [](uv_async_t *a, int) { reinterpret_cast<Request *>(a->data)->notifyCallback(); });
#else
uv_async_init(loop, async, [](uv_async_t *a) { reinterpret_cast<Request *>(a->data)->notifyCallback(); });
#endif
}
Request::Request(const Resource &resource_, uv_loop_t *loop, Callback callback_)
: async(util::make_unique<uv::async>(loop, [this] { notifyCallback(); })),
callback(callback_),
resource(resource_) {
}
// Called in the originating thread.
void Request::notifyCallback() {
MBGL_VERIFY_THREAD(tid)
if (!canceled) {
invoke();
} else {
@@ -59,32 +48,18 @@ void Request::invoke() {
delete this;
}
Request::~Request() {
if (async) {
uv_close(reinterpret_cast<uv_handle_t*>(async), [](uv_handle_t* handle) {
delete reinterpret_cast<uv_async_t*>(handle);
});
}
}
Request::~Request() = default;
// Called in the FileSource thread.
void Request::notify(const std::shared_ptr<const Response> &response_) {
assert(!response);
response = response_;
assert(response);
if (async) {
uv_async_send(async);
} else {
// This request is not cancelable. This means that the callback will be executed in an
// arbitrary thread (== FileSource thread).
invoke();
}
async->send();
}
// Called in the originating thread.
void Request::cancel() {
MBGL_VERIFY_THREAD(tid)
assert(async);
assert(!canceled);
canceled = util::make_unique<Canceled>();
@@ -98,7 +73,7 @@ void Request::destruct() {
assert(canceled);
std::unique_lock<std::mutex> lock(canceled->mutex);
canceled->confirmed = true;
uv_async_send(async);
async->send();
// after this method returns, the FileSource thread has no knowledge of
// this object anymore.
}

View File

@@ -0,0 +1,35 @@
#ifndef MBGL_STORAGE_REQUEST
#define MBGL_STORAGE_REQUEST
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/storage/file_cache.hpp>
#include <mbgl/storage/resource.hpp>
#include <memory>
#include <functional>
namespace mbgl {
class Response;
class RequestBase : private util::noncopyable {
public:
using Callback = std::function<void (std::shared_ptr<const Response> response, FileCache::Hint hint)>;
RequestBase(const Resource& resource_, Callback notify_)
: resource(resource_)
, notify(notify_) {
}
virtual ~RequestBase() = default;
virtual void cancel() = 0;
virtual void retry() {};
protected:
Resource resource;
Callback notify;
};
}
#endif

View File

@@ -1,106 +0,0 @@
#ifndef MBGL_STORAGE_DEFAULT_SHARED_REQUEST_BASE
#define MBGL_STORAGE_DEFAULT_SHARED_REQUEST_BASE
#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/file_cache.hpp>
#include <mbgl/storage/default_file_source_impl.hpp>
#include <mbgl/storage/request.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <string>
#include <set>
#include <vector>
#include <cassert>
typedef struct uv_loop_s uv_loop_t;
namespace mbgl {
class Request;
class Response;
class DefaultFileSource;
class SharedRequestBase : private util::noncopyable {
protected:
MBGL_STORE_THREAD(tid)
public:
SharedRequestBase(DefaultFileSource::Impl *source_, const Resource &resource_)
: resource(resource_), source(source_) {}
virtual void start(uv_loop_t *loop, std::shared_ptr<const Response> response = nullptr) = 0;
virtual void cancel() = 0;
void notify(std::shared_ptr<const Response> response, FileCache::Hint hint) {
MBGL_VERIFY_THREAD(tid);
if (source) {
source->notify(this, observers, response, hint);
}
}
void subscribe(Request *request) {
MBGL_VERIFY_THREAD(tid);
observers.insert(request);
}
void unsubscribe(Request *request) {
MBGL_VERIFY_THREAD(tid);
observers.erase(request);
if (abandoned()) {
// There are no observers anymore. We are initiating cancelation.
if (source) {
// First, remove this SharedRequestBase from the source.
source->notify(this, observers, nullptr, FileCache::Hint::No);
}
// Then, initiate cancelation of this request
cancel();
}
}
bool abandoned() const {
return observers.empty();
}
std::vector<Request *> removeAllInEnvironment(const Environment &env) {
MBGL_VERIFY_THREAD(tid);
std::vector<Request *> result;
// Removes all Requests in the supplied environment and returns a list
// of them.
util::erase_if(observers, [&](Request *req) -> bool {
if (&req->env == &env) {
result.push_back(req);
return true;
} else {
return false;
}
});
return result;
}
protected:
virtual ~SharedRequestBase() {
MBGL_VERIFY_THREAD(tid);
}
public:
const Resource resource;
protected:
DefaultFileSource::Impl *source = nullptr;
private:
std::set<Request *> observers;
};
}
#endif

View File

@@ -1,78 +0,0 @@
#ifndef MBGL_STORAGE_DEFAULT_THREAD_CONTEXT
#define MBGL_STORAGE_DEFAULT_THREAD_CONTEXT
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/uv.hpp>
#include <uv.h>
#include <pthread.h>
#include <map>
#include <cassert>
namespace mbgl {
// This is a template class that provides a per-thread and per-loop Context object. It can be used
// by implementations to store global state.
template <typename Context>
class ThreadContext : private util::noncopyable {
protected:
MBGL_STORE_THREAD(tid)
using Map = std::map<uv_loop_t *, std::unique_ptr<Context>>;
public:
static Context *Get(uv_loop_t *loop);
private:
static pthread_key_t key;
static pthread_once_t once;
public:
ThreadContext(uv_loop_t *loop);
~ThreadContext();
public:
uv_loop_t *loop;
};
template <typename Context>
Context *ThreadContext<Context>::Get(uv_loop_t *loop) {
pthread_once(&once, []() {
pthread_key_create(&key, [](void *ptr) {
assert(ptr);
delete reinterpret_cast<Map *>(ptr);
});
});
auto contexts = reinterpret_cast<Map *>(pthread_getspecific(key));
if (!contexts) {
contexts = new Map();
pthread_setspecific(key, contexts);
}
// Now find a ThreadContext that matches the requested loop.
auto it = contexts->find(loop);
if (it == contexts->end()) {
auto result = contexts->emplace(loop, util::make_unique<Context>(loop));
assert(result.second); // Make sure it was actually inserted.
return result.first->second.get();
} else {
return it->second.get();
}
}
template <typename Context>
ThreadContext<Context>::ThreadContext(uv_loop_t *loop_) : loop(loop_) {
}
template <typename Context>
ThreadContext<Context>::~ThreadContext() {
MBGL_VERIFY_THREAD(tid);
}
}
#endif

View File

@@ -59,7 +59,11 @@ FilterExpression parseSetFilter(const rapidjson::Value& value) {
Expression expression;
expression.key = { value[1u].GetString(), value[1u].GetStringLength() };
for (rapidjson::SizeType i = 2; i < value.Size(); ++i) {
expression.values.push_back(parseValue(value[i]));
Value parsedValue = parseValue(value[i]);
if (expression.key == "$type") {
parsedValue = parseFeatureType(parsedValue);
}
expression.values.push_back(parsedValue);
}
return expression;
}

View File

@@ -17,7 +17,8 @@
namespace mbgl {
Style::Style()
: mtx(util::make_unique<uv::rwlock>()) {
: mtx(util::make_unique<uv::rwlock>()),
workers(4) {
}
// Note: This constructor is seemingly empty, but we need to declare it anyway
@@ -84,6 +85,27 @@ void Style::loadJSON(const uint8_t *const data) {
layers = parser.getLayers();
sprite_url = parser.getSprite();
glyph_url = parser.getGlyphURL();
loaded = true;
}
bool Style::isLoaded() const {
// TODO: move loading into Style
if (!loaded) {
return false;
}
for (const auto& source : sources) {
if (!source->isLoaded()) {
return false;
}
}
// TODO: move sprite into Style
// if (sprite && !sprite.isLoaded()) {
// return false;
// }
return true;
}
}

View File

@@ -8,6 +8,7 @@
#include <mbgl/util/ptr.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/chrono.hpp>
#include <mbgl/util/worker.hpp>
#include <cstdint>
#include <string>
@@ -24,6 +25,7 @@ public:
~Style();
void loadJSON(const uint8_t *const data);
bool isLoaded() const;
void cascade(const std::vector<std::string>&);
void recalculate(float z, TimePoint now);
@@ -39,10 +41,14 @@ public:
std::string base;
private:
bool loaded = false;
std::string sprite_url;
PropertyTransition defaultTransition;
std::unique_ptr<uv::rwlock> mtx;
ZoomHistory zoomHistory;
public:
Worker workers;
};
}

View File

@@ -13,6 +13,21 @@ bool StyleLayer::isBackground() const {
return type == StyleLayerType::Background;
}
bool StyleLayer::isVisible() const {
switch (type) {
case StyleLayerType::Fill:
return getProperties<FillProperties>().isVisible();
case StyleLayerType::Line:
return getProperties<LineProperties>().isVisible();
case StyleLayerType::Symbol:
return getProperties<SymbolProperties>().isVisible();
case StyleLayerType::Raster:
return getProperties<RasterProperties>().isVisible();
default:
return false;
}
}
void StyleLayer::setClasses(const std::vector<std::string> &class_names, const TimePoint now,
const PropertyTransition &defaultTransition) {
// Stores all keys that we have already added transitions for.

View File

@@ -35,6 +35,9 @@ public:
// Determines whether this layer is the background layer.
bool isBackground() const;
// Checks whether the layer is currently visible at all.
bool isVisible() const;
// Updates the StyleProperties information in this layer by evaluating all
// pending transitions and applied classes in order.
void updateProperties(float z, TimePoint now, ZoomHistory &zoomHistory);

View File

@@ -10,9 +10,9 @@
#include <csscolorparser/csscolorparser.hpp>
#pragma GCC diagnostic push
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/algorithm/string.hpp>
#pragma GCC diagnostic pop

View File

@@ -35,7 +35,7 @@ struct Glyph {
: rect(rect_), metrics(metrics_) {}
operator bool() const {
return metrics || rect;
return metrics || rect.hasArea();
}
const Rect<uint16_t> rect;

View File

@@ -9,7 +9,9 @@
#include <mbgl/util/constants.hpp>
#include <mbgl/util/token.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <mbgl/storage/file_source.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/platform/platform.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <algorithm>
@@ -155,11 +157,12 @@ void FontStack::lineWrap(Shaping &shaping, const float lineHeight, const float m
shaping.right = shaping.left + maxLineLength;
}
GlyphPBF::GlyphPBF(const std::string &glyphURL,
const std::string &fontStack,
GlyphPBF::GlyphPBF(const std::string& glyphURL,
const std::string& fontStack,
GlyphRange glyphRange,
Environment &env)
: future(promise.get_future().share()) {
Environment& env_,
const GlyphLoadedCallback& callback)
: parsed(false), env(env_) {
// Load the glyph set URL
std::string url = util::replaceTokens(glyphURL, [&](const std::string &name) -> std::string {
if (name == "fontstack") return util::percentEncode(fontStack);
@@ -168,25 +171,29 @@ GlyphPBF::GlyphPBF(const std::string &glyphURL,
});
// The prepare call jumps back to the main thread.
env.requestAsync({ Resource::Kind::Glyphs, url }, [&, url](const Response &res) {
req = env.request({ Resource::Kind::Glyphs, url }, [&, url, callback](const Response &res) {
req = nullptr;
if (res.status != Response::Successful) {
// Something went wrong with loading the glyph pbf. Pass on the error to the future listeners.
const std::string msg = std::string { "[ERROR] failed to load glyphs: " } + res.message;
promise.set_exception(std::make_exception_ptr(std::runtime_error(msg)));
// Something went wrong with loading the glyph pbf.
const std::string msg = std::string { "[ERROR] failed to load glyphs: " } + url + " message: " + res.message;
Log::Error(Event::HttpRequest, msg);
} else {
// Transfer the data to the GlyphSet and signal its availability.
// Once it is available, the caller will need to call parse() to actually
// parse the data we received. We are not doing this here since this callback is being
// called from another (unknown) thread.
data = res.data;
promise.set_value(*this);
parsed = true;
callback(this);
}
});
}
std::shared_future<GlyphPBF &> GlyphPBF::getFuture() {
return future;
GlyphPBF::~GlyphPBF() {
if (req) {
env.cancelRequest(req);
}
}
void GlyphPBF::parse(FontStack &stack) {
@@ -243,68 +250,88 @@ void GlyphPBF::parse(FontStack &stack) {
data.clear();
}
GlyphStore::GlyphStore(Environment& env_) : env(env_), mtx(util::make_unique<uv::mutex>()) {}
bool GlyphPBF::isParsed() const {
return parsed;
}
GlyphStore::GlyphStore(uv_loop_t* loop, Environment& env_)
: env(env_),
asyncEmitGlyphRangeLoaded(util::make_unique<uv::async>(loop, [this] { emitGlyphRangeLoaded(); })),
observer(nullptr) {
asyncEmitGlyphRangeLoaded->unref();
}
GlyphStore::~GlyphStore() {
observer = nullptr;
}
void GlyphStore::setURL(const std::string &url) {
glyphURL = url;
}
bool GlyphStore::requestGlyphRangesIfNeeded(const std::string& fontStack,
const std::set<GlyphRange>& glyphRanges) {
bool requestIsNeeded = false;
void GlyphStore::waitForGlyphRanges(const std::string &fontStack, const std::set<GlyphRange> &glyphRanges) {
// We are implementing a blocking wait with futures: Every GlyphSet has a future that we are
// waiting for until it is loaded.
if (glyphRanges.empty()) {
return;
return requestIsNeeded;
}
uv::exclusive<FontStack> stack(mtx);
auto callback = [this, fontStack](GlyphPBF* glyph) {
glyph->parse(*createFontStack(fontStack));
asyncEmitGlyphRangeLoaded->send();
};
std::vector<std::shared_future<GlyphPBF &>> futures;
futures.reserve(glyphRanges.size());
{
auto &rangeSets = ranges[fontStack];
std::lock_guard<std::mutex> lock(rangesMutex);
auto& rangeSets = ranges[fontStack];
stack << createFontStack(fontStack);
for (const auto& range : glyphRanges) {
const auto& rangeSets_it = rangeSets.find(range);
if (rangeSets_it == rangeSets.end()) {
auto glyph = util::make_unique<GlyphPBF>(glyphURL, fontStack, range, env, callback);
rangeSets.emplace(range, std::move(glyph));
requestIsNeeded = true;
continue;
}
// Attempt to load the glyph range. If the GlyphSet already exists, we are getting back
// the same shared_future.
for (const auto range : glyphRanges) {
futures.emplace_back(loadGlyphRange(fontStack, rangeSets, range));
if (!rangeSets_it->second->isParsed()) {
requestIsNeeded = true;
}
}
// Now that we potentially created all GlyphSets, we are waiting for the results, one by one.
// When we get a result (or the GlyphSet is aready loaded), we are attempting to parse the
// GlyphSet.
for (const auto& future : futures) {
future.get().parse(stack);
}
return requestIsNeeded;
}
std::shared_future<GlyphPBF &> GlyphStore::loadGlyphRange(const std::string &fontStack, std::map<GlyphRange, std::unique_ptr<GlyphPBF>> &rangeSets, const GlyphRange range) {
auto range_it = rangeSets.find(range);
if (range_it == rangeSets.end()) {
// We don't have this glyph set yet for this font stack.
range_it = rangeSets.emplace(range, util::make_unique<GlyphPBF>(glyphURL, fontStack, range, env)).first;
}
FontStack* GlyphStore::createFontStack(const std::string &fontStack) {
std::lock_guard<std::mutex> lock(stacksMutex);
return range_it->second->getFuture();
}
FontStack &GlyphStore::createFontStack(const std::string &fontStack) {
auto stack_it = stacks.find(fontStack);
if (stack_it == stacks.end()) {
stack_it = stacks.emplace(fontStack, util::make_unique<FontStack>()).first;
}
return *stack_it->second.get();
return stack_it->second.get();
}
uv::exclusive<FontStack> GlyphStore::getFontStack(const std::string &fontStack) {
uv::exclusive<FontStack> stack(mtx);
stack << createFontStack(fontStack);
return stack;
FontStack* GlyphStore::getFontStack(const std::string &fontStack) {
std::lock_guard<std::mutex> lock(stacksMutex);
const auto& stack_it = stacks.find(fontStack);
if (stack_it == stacks.end()) {
return nullptr;
}
return stack_it->second.get();
}
void GlyphStore::setObserver(Observer* observer_) {
observer = observer_;
}
void GlyphStore::emitGlyphRangeLoaded() {
if (observer) {
observer->onGlyphRangeLoaded();
}
}
}

View File

@@ -4,19 +4,28 @@
#include <mbgl/text/glyph.hpp>
#include <mbgl/util/vec.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/util/uv.hpp>
#include <cstdint>
#include <vector>
#include <future>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
typedef struct uv_loop_s uv_loop_t;
namespace uv {
class async;
}
namespace mbgl {
class FileSource;
class Environment;
class Request;
class SDFGlyph {
public:
@@ -49,10 +58,17 @@ private:
class GlyphPBF {
public:
using GlyphLoadedCallback = std::function<void(GlyphPBF*)>;
GlyphPBF(const std::string &glyphURL,
const std::string &fontStack,
GlyphRange glyphRange,
Environment &env);
Environment &env,
const GlyphLoadedCallback& callback);
~GlyphPBF();
void parse(FontStack &stack);
bool isParsed() const;
private:
GlyphPBF(const GlyphPBF &) = delete;
@@ -60,43 +76,58 @@ private:
GlyphPBF &operator=(const GlyphPBF &) = delete;
GlyphPBF &operator=(GlyphPBF &&) = delete;
public:
void parse(FontStack &stack);
std::shared_future<GlyphPBF &> getFuture();
private:
std::string data;
std::promise<GlyphPBF &> promise;
std::shared_future<GlyphPBF &> future;
std::mutex mtx;
std::atomic_bool parsed;
Environment& env;
Request* req = nullptr;
mutable std::mutex mtx;
};
// Manages Glyphrange PBF loading.
class GlyphStore {
public:
GlyphStore(Environment &);
class Observer {
public:
virtual ~Observer() = default;
// Block until all specified GlyphRanges of the specified font stack are loaded.
void waitForGlyphRanges(const std::string &fontStack, const std::set<GlyphRange> &glyphRanges);
virtual void onGlyphRangeLoaded() = 0;
};
uv::exclusive<FontStack> getFontStack(const std::string &fontStack);
GlyphStore(uv_loop_t* loop, Environment &);
~GlyphStore();
// Asynchronously request for GlyphRanges and when it gets loaded, notifies the
// observer subscribed to this object. Successive requests for the same range are
// going to be discarded. Returns true if a request was made or false if all the
// GlyphRanges are already available, and thus, no request is performed.
bool requestGlyphRangesIfNeeded(const std::string &fontStack, const std::set<GlyphRange> &glyphRanges);
FontStack* getFontStack(const std::string &fontStack);
void setURL(const std::string &url);
private:
// Loads an individual glyph range from the font stack and adds it to rangeSets
std::shared_future<GlyphPBF &> loadGlyphRange(const std::string &fontStack, std::map<GlyphRange, std::unique_ptr<GlyphPBF>> &rangeSets, GlyphRange range);
void setObserver(Observer* observer);
FontStack &createFontStack(const std::string &fontStack);
private:
void emitGlyphRangeLoaded();
FontStack* createFontStack(const std::string &fontStack);
std::string glyphURL;
Environment &env;
std::unordered_map<std::string, std::map<GlyphRange, std::unique_ptr<GlyphPBF>>> ranges;
std::unordered_map<std::string, std::unique_ptr<FontStack>> stacks;
std::unique_ptr<uv::mutex> mtx;
};
std::unordered_map<std::string, std::map<GlyphRange, std::unique_ptr<GlyphPBF>>> ranges;
std::mutex rangesMutex;
std::unordered_map<std::string, std::unique_ptr<FontStack>> stacks;
std::mutex stacksMutex;
std::unique_ptr<uv::async> asyncEmitGlyphRangeLoaded;
Observer* observer;
};
}

View File

@@ -136,7 +136,7 @@ SymbolQuads getGlyphQuads(Anchor &anchor, const Shaping &shapedText,
if (!glyph)
continue;
if (!rect)
if (!rect.hasArea())
continue;
const float centerX = (positionedGlyph.x + glyph.metrics.advance / 2.0f) * boxScale;

View File

@@ -19,7 +19,7 @@ namespace mbgl {
float left = 0;
float right = 0;
operator bool() const { return image; }
operator bool() const { return image.hasArea(); }
};
class StyleLayoutSymbol;

View File

@@ -75,14 +75,14 @@ void ClipIDGenerator::update(std::forward_list<Tile *> tiles) {
if (pool.size()) {
const uint32_t bit_count = util::ceil_log2(pool.size() + 1);
const std::bitset<8> mask = uint64_t(((1 << bit_count) - 1) << bit_offset);
const std::bitset<8> mask = uint64_t(((1ul << bit_count) - 1) << bit_offset);
// We are starting our count with 1 since we need at least 1 bit set to distinguish between
// areas without any tiles whatsoever and the current area.
uint8_t count = 1;
for (auto& leaf : pool) {
leaf.tile.clip.mask = mask;
leaf.tile.clip.reference = count++ << bit_offset;
leaf.tile.clip.reference = uint32_t(count++) << bit_offset;
}
bit_offset += bit_count;

View File

@@ -87,7 +87,7 @@ void matrix::copy(mat4& out, const mat4& a) {
}
void matrix::translate(mat4& out, const mat4& a, float x, float y, float z) {
if (a == out) {
if (&a == &out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
@@ -124,7 +124,7 @@ void matrix::rotate_z(mat4& out, const mat4& a, float rad) {
a12 = a[6],
a13 = a[7];
if (a != out) { // If the source and destination differ, copy the unchanged last row
if (&a != &out) { // If the source and destination differ, copy the unchanged last row
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];

View File

@@ -46,16 +46,7 @@ void Raster::bind(bool linear) {
}
if (img && !textured) {
texture = texturePool.getTextureID();
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture));
#ifndef GL_ES_VERSION_2_0
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0));
#endif
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img->getData()));
img.reset();
textured = true;
upload();
} else if (textured) {
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture));
}
@@ -68,24 +59,17 @@ void Raster::bind(bool linear) {
}
}
// overload ::bind for prerendered raster textures
void Raster::bind(const GLuint custom_texture) {
void Raster::upload() {
if (img && !textured) {
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, custom_texture));
texture = texturePool.getTextureID();
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture));
#ifndef GL_ES_VERSION_2_0
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0));
#endif
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
MBGL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img->getData()));
img.reset();
textured = true;
} else if (textured) {
MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, custom_texture));
}
GLuint new_filter = GL_LINEAR;
if (new_filter != this->filter) {
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, new_filter));
MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, new_filter));
filter = new_filter;
}
}

View File

@@ -25,8 +25,8 @@ public:
// bind current texture
void bind(bool linear = false);
// bind prerendered texture
void bind(const GLuint texture);
// uploads the texture if it hasn't been uploaded yet.
void upload();
// loaded status
bool isLoaded() const;

View File

@@ -12,11 +12,16 @@ struct Rect {
T originalW = 0, originalH = 0;
template <typename Number>
Rect operator *(Number value) const {
inline Rect operator *(Number value) const {
return Rect(x * value, y * value, w * value, h * value);
}
operator bool() const { return w != 0 && h != 0; }
template <typename R>
inline bool operator==(const R& r) const {
return x == r.x && y == r.y && w == r.w && h == r.h;
}
inline bool hasArea() const { return w != 0 && h != 0; }
};
}

View File

@@ -5,8 +5,13 @@ namespace util {
uv::tls<RunLoop> RunLoop::current;
RunLoop::RunLoop()
: async(*loop, std::bind(&RunLoop::process, this)) {
RunLoop::RunLoop(uv_loop_t* loop)
: async(loop, std::bind(&RunLoop::process, this)) {
current.set(this);
}
RunLoop::~RunLoop() {
current.set(nullptr);
}
void RunLoop::withMutex(std::function<void()>&& fn) {
@@ -24,13 +29,6 @@ void RunLoop::process() {
}
}
void RunLoop::run() {
assert(!current.get());
current.set(this);
loop.run();
current.set(nullptr);
}
void RunLoop::stop() {
invoke([&] { async.unref(); });
}

View File

@@ -14,9 +14,9 @@ namespace util {
class RunLoop : private util::noncopyable {
public:
RunLoop();
RunLoop(uv_loop_t*);
~RunLoop();
void run();
void stop();
// Invoke fn() in the runloop thread.
@@ -29,29 +29,32 @@ public:
// Invoke fn() in the runloop thread, then invoke callback(result) in the current thread.
template <class Fn, class R>
void invokeWithResult(Fn&& fn, std::function<void (R)> callback) {
void invokeWithResult(Fn&& fn, std::function<void (R)>&& callback) {
RunLoop* outer = current.get();
assert(outer);
invoke([fn, callback, outer] {
/*
With C++14, we could write:
outer->invoke([callback, result = std::move(fn())] () mutable {
callback(std::move(result));
});
Instead we're using a workaround with std::bind
to obtain move-capturing semantics with C++11:
http://stackoverflow.com/a/12744730/52207
*/
outer->invoke(std::bind([callback] (R& result) {
invoke([fn = std::move(fn), callback = std::move(callback), outer] () mutable {
outer->invoke([callback = std::move(callback), result = std::move(fn())] () mutable {
callback(std::move(result));
}, std::move(fn())));
});
});
}
uv_loop_t* get() { return *loop; }
// Invoke fn() in the runloop thread, then invoke callback() in the current thread.
template <class Fn>
void invokeWithResult(Fn&& fn, std::function<void ()>&& callback) {
RunLoop* outer = current.get();
assert(outer);
invoke([fn = std::move(fn), callback = std::move(callback), outer] () mutable {
fn();
outer->invoke(std::move(callback));
});
}
uv_loop_t* get() { return async.get()->loop; }
static uv::tls<RunLoop> current;
private:
// A movable type-erasing invokable entity wrapper. This allows to store arbitrary invokable
@@ -71,15 +74,11 @@ private:
using Queue = std::queue<std::unique_ptr<Message>>;
static uv::tls<RunLoop> current;
void withMutex(std::function<void()>&&);
void process();
Queue queue;
std::mutex mutex;
uv::loop loop;
uv::async async;
};

View File

@@ -3,9 +3,11 @@
#include <future>
#include <thread>
#include <atomic>
#include <functional>
#include <mbgl/util/run_loop.hpp>
#include <mbgl/platform/platform.hpp>
namespace {
@@ -33,11 +35,16 @@ namespace util {
// Thread<> constructor blocks until the thread and the Object are fully created, so after the
// object creation, it's safe to obtain the Object stored in this thread.
enum class ThreadPriority : bool {
Regular,
Low,
};
template <class Object>
class Thread {
public:
template <class... Args>
Thread(const std::string& name, Args&&... args);
Thread(const std::string& name, ThreadPriority priority, Args&&... args);
~Thread();
// Invoke object->fn(args...) in the runloop thread.
@@ -48,11 +55,33 @@ public:
// Invoke object->fn(args...) in the runloop thread, then invoke callback(result) in the current thread.
template <typename Fn, class R, class... Args>
void invokeWithResult(Fn fn, std::function<void (R)> callback, Args&&... args) {
loop->invokeWithResult(std::bind(fn, object, args...), callback);
void invokeWithResult(Fn fn, std::function<void (R)>&& callback, Args&&... args) {
loop->invokeWithResult(std::bind(fn, object, std::move(args)...), std::move(callback));
}
uv_loop_t* get() { return loop->get(); }
// Invoke object->fn(args...) in the runloop thread, then invoke callback() in the current thread.
template <typename Fn, class... Args>
void invokeWithResult(Fn fn, std::function<void ()>&& callback, Args&&... args) {
loop->invokeWithResult(std::bind(fn, object, std::move(args)...), std::move(callback));
}
// Invoke object->fn(args...) in the runloop thread, and wait for the result.
template <class R, typename Fn, class... Args>
R invokeSync(Fn fn, Args&&... args) {
std::packaged_task<R ()> task(std::bind(fn, object, args...));
std::future<R> future = task.get_future();
loop->invoke(std::move(task));
return future.get();
}
// Invoke object->fn(args...) in the runloop thread, and wait for it to complete.
template <typename Fn, class... Args>
void invokeSync(Fn fn, Args&&... args) {
std::packaged_task<void ()> task(std::bind(fn, object, args...));
std::future<void> future = task.get_future();
loop->invoke(std::move(task));
return future.get();
}
private:
Thread(const Thread&) = delete;
@@ -74,7 +103,7 @@ private:
template <class Object>
template <class... Args>
Thread<Object>::Thread(const std::string& name, Args&&... args) {
Thread<Object>::Thread(const std::string& name, ThreadPriority priority, Args&&... args) {
// Note: We're using std::tuple<> to store the arguments because GCC 4.9 has a bug
// when expanding parameters packs captured in lambdas.
std::tuple<Args...> params = std::forward_as_tuple(::std::forward<Args>(args)...);
@@ -86,6 +115,10 @@ Thread<Object>::Thread(const std::string& name, Args&&... args) {
(void(name));
#endif
if (priority == ThreadPriority::Low) {
platform::makeThreadLowPriority();
}
constexpr auto seq = typename integer_sequence<sizeof...(Args)>::type();
run(std::move(params), seq);
});
@@ -96,14 +129,24 @@ Thread<Object>::Thread(const std::string& name, Args&&... args) {
template <class Object>
template <typename P, std::size_t... I>
void Thread<Object>::run(P&& params, index_sequence<I...>) {
Object object_(std::get<I>(std::forward<P>(params))...);
object = &object_;
uv::loop l;
RunLoop loop_;
loop = &loop_;
{
RunLoop loop_(l.get());
loop = &loop_;
running.set_value();
loop_.run();
Object object_(l.get(), std::get<I>(std::forward<P>(params))...);
object = &object_;
running.set_value();
l.run();
loop = nullptr;
object = nullptr;
}
// Run the loop again to ensure that async close callbacks have been called.
l.run();
joinable.get_future().get();
}

View File

@@ -1,8 +1,29 @@
#include <mbgl/util/uv.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <mbgl/util/string.hpp>
#include <uv.h>
// Check libuv library version.
const static bool uvVersionCheck = []() {
const unsigned int version = uv_version();
const unsigned int major = (version >> 16) & 0xFF;
const unsigned int minor = (version >> 8) & 0xFF;
const unsigned int patch = version & 0xFF;
#ifndef UV_VERSION_PATCH
// 0.10 doesn't have UV_VERSION_PATCH defined, so we "fake" it by using the library patch level.
const unsigned int UV_VERSION_PATCH = version & 0xFF;
#endif
if (major != UV_VERSION_MAJOR || minor != UV_VERSION_MINOR || patch != UV_VERSION_PATCH) {
throw std::runtime_error(mbgl::util::sprintf<96>(
"libuv version mismatch: headers report %d.%d.%d, but library reports %d.%d.%d", UV_VERSION_MAJOR,
UV_VERSION_MINOR, UV_VERSION_PATCH, major, minor, patch));
}
return true;
}();
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
int uv_key_create(uv_key_t* key) {

View File

@@ -28,13 +28,6 @@ UV_EXTERN void uv_key_set(uv_key_t* key, void* value);
namespace uv {
template <class T>
void close(std::unique_ptr<T> ptr) {
uv_close(reinterpret_cast<uv_handle_t*>(ptr.release()), [](uv_handle_t* handle) {
delete reinterpret_cast<T*>(handle);
});
}
class loop : public mbgl::util::noncopyable {
public:
inline loop() {
@@ -74,36 +67,50 @@ private:
uv_loop_t *l = nullptr;
};
class async : public mbgl::util::noncopyable {
template <class T>
class handle : public mbgl::util::noncopyable {
public:
inline handle() : t(reinterpret_cast<uv_handle_t*>(new T)) {
t->data = this;
}
inline ~handle() {
uv_close(t.release(), [](uv_handle_t* h) {
delete reinterpret_cast<T*>(h);
});
}
inline void ref() {
uv_ref(t.get());
}
inline void unref() {
uv_unref(t.get());
}
inline T* get() {
return reinterpret_cast<T*>(t.get());
}
private:
std::unique_ptr<uv_handle_t> t;
};
class async : public handle<uv_async_t> {
public:
inline async(uv_loop_t* loop, std::function<void ()> fn_)
: a(new uv_async_t)
, fn(fn_)
{
a->data = this;
if (uv_async_init(loop, a.get(), async_cb) != 0) {
: fn(fn_) {
if (uv_async_init(loop, get(), async_cb) != 0) {
throw std::runtime_error("failed to initialize async");
}
}
inline ~async() {
close(std::move(a));
}
inline void send() {
if (uv_async_send(a.get()) != 0) {
if (uv_async_send(get()) != 0) {
throw std::runtime_error("failed to async send");
}
}
inline void ref() {
uv_ref(reinterpret_cast<uv_handle_t*>(a.get()));
}
inline void unref() {
uv_unref(reinterpret_cast<uv_handle_t*>(a.get()));
}
private:
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
static void async_cb(uv_async_t* a, int) {
@@ -113,7 +120,40 @@ private:
reinterpret_cast<async*>(a->data)->fn();
}
std::unique_ptr<uv_async_t> a;
std::function<void ()> fn;
};
class timer : public handle<uv_timer_t> {
public:
inline timer(uv_loop_t* loop) {
if (uv_timer_init(loop, get()) != 0) {
throw std::runtime_error("failed to initialize timer");
}
}
inline void start(uint64_t timeout, uint64_t repeat, std::function<void ()> fn_) {
fn = fn_;
if (uv_timer_start(get(), timer_cb, timeout, repeat) != 0) {
throw std::runtime_error("failed to start timer");
}
}
inline void stop() {
fn = nullptr;
if (uv_timer_stop(get()) != 0) {
throw std::runtime_error("failed to stop timer");
}
}
private:
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
static void timer_cb(uv_timer_t* t, int) {
#else
static void timer_cb(uv_timer_t* t) {
#endif
reinterpret_cast<timer*>(t->data)->fn();
}
std::function<void ()> fn;
};

View File

@@ -0,0 +1,16 @@
#include <mbgl/util/work_request.hpp>
#include <mbgl/util/work_task.hpp>
#include <cassert>
namespace mbgl {
WorkRequest::WorkRequest(Task task_) : task(task_) {
assert(task);
}
WorkRequest::~WorkRequest() {
task->cancel();
}
}

View File

@@ -0,0 +1,24 @@
#ifndef MBGL_UTIL_WORK_REQUEST
#define MBGL_UTIL_WORK_REQUEST
#include <mbgl/util/noncopyable.hpp>
#include <memory>
namespace mbgl {
class WorkTask;
class WorkRequest : public util::noncopyable {
public:
using Task = std::shared_ptr<WorkTask>;
WorkRequest(Task);
~WorkRequest();
private:
std::shared_ptr<WorkTask> task;
};
}
#endif

View File

@@ -0,0 +1,37 @@
#include <mbgl/util/work_task.hpp>
#include <cassert>
namespace mbgl {
WorkTask::WorkTask(std::function<void()> task_, std::function<void()> after_)
: task(task_), after(after_) {
assert(after);
}
void WorkTask::runTask() {
// We are only running the task when there's an after callback to call. This means that an
// empty after callback will be treated as a cancelled request. The mutex will be locked while
// processing so that the cancel() callback will block.
std::lock_guard<std::mutex> lock(mutex);
if (after) {
task();
}
}
void WorkTask::runAfter() {
if (after) {
after();
}
}
void WorkTask::cancel() {
// Remove the after callback to indicate that this callback has been canceled. The mutex will
// block when the task is currently in progres. When the task has not begun yet, the runTask()
// method will not do anything. When the task has been completed already, and the after callback
// was run as well, this will also do nothing.
std::lock_guard<std::mutex> lock(mutex);
after = {};
}
} // end namespace mbgl

Some files were not shown because too many files have changed in this diff Show More