start porting dash lines from js

- switches to dash units that are scaled by line width
- adds a lineatlas to store patterns line dashed lines
- adds linesdf shader which renders line fill from the lineatlas

js: 8e83d76af3bd877eb9639c02e296363e2c0186f8
This commit is contained in:
Ansis Brammanis
2015-01-14 20:56:18 -05:00
parent c6ca57045f
commit 2643a0efc7
15 changed files with 365 additions and 9 deletions

View File

@@ -30,6 +30,7 @@ class FileSource;
class View;
class GlyphAtlas;
class SpriteAtlas;
class LineAtlas;
class Map : private util::noncopyable {
public:
@@ -182,6 +183,7 @@ private:
util::ptr<GlyphStore> glyphStore;
const std::unique_ptr<SpriteAtlas> spriteAtlas;
util::ptr<Sprite> sprite;
const std::unique_ptr<LineAtlas> lineAtlas;
util::ptr<TexturePool> texturePool;
const std::unique_ptr<Painter> painter;

View File

@@ -0,0 +1,126 @@
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/platform/gl.hpp>
#include <mbgl/platform/platform.hpp>
#include <sstream>
#include <cmath>
using namespace mbgl;
LineAtlas::LineAtlas(uint16_t w, uint16_t h)
: width(w),
height(h),
data(new char[w * h]),
dirty(true) {
}
LineAtlas::~LineAtlas() {
}
LinePatternPos LineAtlas::getDashPosition(std::vector<float> &dasharray, bool round) {
std::ostringstream sskey;
for (const float &part : dasharray) {
sskey << part << "-";
}
sskey << round;
std::string key = sskey.str();
if (positions.find(key) == positions.end()) {
fprintf(stderr, "add %s\n", key.c_str());
positions[key] = addDash(dasharray, round);
}
return positions[key];
}
LinePatternPos LineAtlas::addDash(std::vector<float> &dasharray, bool round) {
int n = round ? 7 : 0;
int dashheight = 2 * n + 1;
const uint8_t offset = 128;
// TODO check if enough space
float length = 0;
for (const float &part : dasharray) {
length += part;
}
float stretch = width / length;
float halfWidth = stretch * 0.5;
for (int y = -n; y <= n; y++) {
int row = nextRow + n + y;
int index = width * row;
float left = 0;
float right = dasharray[0];
int partIndex = 1;
for (int x = 0; x < width; x++) {
while (right < x / stretch) {
left = right;
right = right + dasharray[partIndex];
partIndex++;
}
float distLeft = fabs(x - left * stretch);
float distRight = fabs(x - right * stretch);
float dist = fmin(distLeft, distRight);
bool inside = (partIndex % 2) == 1;
int signedDistance;
if (round) {
float distMiddle = n ? y / n * halfWidth : 0;
float distEdge = halfWidth - fabs(distMiddle);
if (inside) {
signedDistance = sqrt(dist * dist + distEdge * distEdge);
} else {
signedDistance = halfWidth = sqrt(dist * dist + distMiddle * distMiddle);
}
} else {
signedDistance = int((inside ? 1 : -1) * dist);
}
data[index + x] = fmax(0, fmin(255, signedDistance + offset));
}
}
LinePatternPos position;
position.y = (0.5 + nextRow + n) / height;
position.height = 2 * n / height;
position.width = length;
nextRow += dashheight;
dirty = true;
bind();
return position;
};
void LineAtlas::bind() {
if (!texture) {
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
dirty = true;
} else {
glBindTexture(GL_TEXTURE_2D, texture);
}
dirty = true;
if (dirty) {
// TODO use texsubimage for updates
// TODO lock?
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data);
dirty = false;
}
};

View File

@@ -0,0 +1,40 @@
#ifndef MBGL_GEOMETRY_LINE_ATLAS
#define MBGL_GEOMETRY_LINE_ATLAS
#include <vector>
#include <map>
#include <atomic>
namespace mbgl {
typedef struct {
float width;
float height;
float y;
} LinePatternPos;
class LineAtlas {
public:
LineAtlas(uint16_t width, uint16_t height);
~LineAtlas();
void bind();
LinePatternPos getDashPosition(std::vector<float>&, bool);
LinePatternPos addDash(std::vector<float> &dasharray, bool round);
const int width;
const int height;
private:
char *const data = nullptr;
std::atomic<bool> dirty;
uint32_t texture = 0;
uint32_t nextRow = 0;
std::map<std::string, LinePatternPos> positions;
};
};
#endif

View File

@@ -20,6 +20,7 @@
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/texture_pool.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/storage/file_source.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/util/string.hpp>
@@ -98,8 +99,9 @@ Map::Map(View& view_, FileSource& fileSource_)
glyphAtlas(util::make_unique<GlyphAtlas>(1024, 1024)),
glyphStore(std::make_shared<GlyphStore>(fileSource)),
spriteAtlas(util::make_unique<SpriteAtlas>(512, 512)),
lineAtlas(util::make_unique<LineAtlas>(512, 512)),
texturePool(std::make_shared<TexturePool>()),
painter(util::make_unique<Painter>(*spriteAtlas, *glyphAtlas))
painter(util::make_unique<Painter>(*spriteAtlas, *glyphAtlas, *lineAtlas))
{
view.initialize(this);
// Make sure that we're doing an initial drawing in all cases.

View File

@@ -374,6 +374,20 @@ void LineBucket::drawLines(LineShader& shader) {
}
}
void LineBucket::drawLineSDF(LineSDFShader& shader) {
char *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
char *elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
for (triangle_group_type& group : triangleGroups) {
if (!group.elements_length) {
continue;
}
group.array[2].bind(shader, vertexBuffer, triangleElementsBuffer, vertex_index);
MBGL_CHECK_ERROR(glDrawElements(GL_TRIANGLES, group.elements_length * 3, GL_UNSIGNED_SHORT, elements_index));
vertex_index += group.vertex_length * vertexBuffer.itemSize;
elements_index += group.elements_length * triangleElementsBuffer.itemSize;
}
}
void LineBucket::drawLinePatterns(LinepatternShader& shader) {
char *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
char *elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);

View File

@@ -16,11 +16,12 @@ class LineVertexBuffer;
class TriangleElementsBuffer;
class LineShader;
class LinejoinShader;
class LineSDFShader;
class LinepatternShader;
struct pbf;
class LineBucket : public Bucket {
typedef ElementGroup<2> triangle_group_type;
typedef ElementGroup<3> triangle_group_type;
typedef ElementGroup<1> point_group_type;
public:
@@ -38,6 +39,7 @@ public:
bool hasPoints() const;
void drawLines(LineShader& shader);
void drawLineSDF(LineSDFShader& shader);
void drawLinePatterns(LinepatternShader& shader);
void drawPoints(LinejoinShader& shader);

View File

@@ -24,9 +24,10 @@ using namespace mbgl;
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
Painter::Painter(SpriteAtlas& spriteAtlas_, GlyphAtlas& glyphAtlas_)
Painter::Painter(SpriteAtlas& spriteAtlas_, GlyphAtlas& glyphAtlas_, LineAtlas& lineAtlas_)
: spriteAtlas(spriteAtlas_)
, glyphAtlas(glyphAtlas_)
, lineAtlas(lineAtlas_)
{
}
@@ -93,6 +94,7 @@ void Painter::setupShaders() {
if (!outlineShader) outlineShader = util::make_unique<OutlineShader>();
if (!lineShader) lineShader = util::make_unique<LineShader>();
if (!linejoinShader) linejoinShader = util::make_unique<LinejoinShader>();
if (!linesdfShader) linesdfShader = util::make_unique<LineSDFShader>();
if (!linepatternShader) linepatternShader = util::make_unique<LinepatternShader>();
if (!patternShader) patternShader = util::make_unique<PatternShader>();
if (!iconShader) iconShader = util::make_unique<IconShader>();

View File

@@ -14,6 +14,7 @@
#include <mbgl/shader/pattern_shader.hpp>
#include <mbgl/shader/line_shader.hpp>
#include <mbgl/shader/linejoin_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>
@@ -38,6 +39,7 @@ class Tile;
class Sprite;
class SpriteAtlas;
class GlyphAtlas;
class LineAtlas;
class Source;
class StyleSource;
class StyleLayerGroup;
@@ -56,7 +58,7 @@ class RasterTileData;
class Painter : private util::noncopyable {
public:
Painter(SpriteAtlas&, GlyphAtlas&);
Painter(SpriteAtlas&, GlyphAtlas&, LineAtlas&);
~Painter();
void setup();
@@ -194,11 +196,13 @@ public:
SpriteAtlas& spriteAtlas;
GlyphAtlas& glyphAtlas;
LineAtlas& lineAtlas;
std::unique_ptr<PlainShader> plainShader;
std::unique_ptr<OutlineShader> outlineShader;
std::unique_ptr<LineShader> lineShader;
std::unique_ptr<LinejoinShader> linejoinShader;
std::unique_ptr<LineSDFShader> linesdfShader;
std::unique_ptr<LinepatternShader> linepatternShader;
std::unique_ptr<PatternShader> patternShader;
std::unique_ptr<IconShader> iconShader;

View File

@@ -4,6 +4,7 @@
#include <mbgl/style/style_layer.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/map/map.hpp>
using namespace mbgl;
@@ -41,9 +42,6 @@ void Painter::renderLine(LineBucket& bucket, util::ptr<StyleLayer> layer_desc, c
color[2] *= properties.opacity;
color[3] *= properties.opacity;
float dash_length = properties.dash_array[0];
float dash_gap = properties.dash_array[1];
float ratio = state.getPixelRatio();
mat4 vtxMatrix = translatedMatrix(matrix, properties.translate, id, properties.translateAnchor);
@@ -72,7 +70,33 @@ void Painter::renderLine(LineBucket& bucket, util::ptr<StyleLayer> layer_desc, c
bucket.drawPoints(*linejoinShader);
}
if (properties.image.size()) {
if (properties.dash_array.size() && properties.dash_array[1] > 0) {
useProgram(linesdfShader->program);
linesdfShader->u_matrix = vtxMatrix;
linesdfShader->u_exmatrix = extrudeMatrix;
linesdfShader->u_linewidth = {{ outset, inset }};
linesdfShader->u_ratio = ratio;
linesdfShader->u_blur = blur;
linesdfShader->u_color = color;
std::vector<float> dash = { properties.dash_array[0], properties.dash_array[1] };
LinePatternPos pos = lineAtlas.getDashPosition(dash, false);
lineAtlas.bind();
float patternratio = std::pow(2.0, std::floor(std::log2(state.getScale())) - id.z) / 8.0;
float scaleX = patternratio / pos.width / properties.dash_line_width;
float scaleY = -pos.height / 2.0;
linesdfShader->u_patternscale = {{ scaleX, scaleY }};
linesdfShader->u_tex_y = pos.y;
linesdfShader->u_image = 0;
linesdfShader->u_sdfgamma = lineAtlas.width / (properties.dash_line_width * pos.width * 256.0 * state.getPixelRatio());
bucket.drawLineSDF(*linesdfShader);
} else if (properties.image.size()) {
SpriteAtlasPosition imagePos = spriteAtlas.getPosition(properties.image, true);
float factor = 8.0 / std::pow(2, state.getIntegerZoom() - id.z);
@@ -107,7 +131,7 @@ void Painter::renderLine(LineBucket& bucket, util::ptr<StyleLayer> layer_desc, c
lineShader->u_blur = blur;
lineShader->u_color = color;
lineShader->u_dasharray = {{ dash_length, dash_gap }};
lineShader->u_dasharray = {{ 1, -1 }};
bucket.drawLines(*lineShader);
}

View File

@@ -0,0 +1,23 @@
uniform vec2 u_linewidth;
uniform vec4 u_color;
uniform float u_blur;
uniform sampler2D u_image;
uniform float u_sdfgamma;
varying vec2 v_normal;
varying vec2 v_tex;
void main() {
// Calculate the distance of the pixel from the line in pixels.
float dist = length(v_normal) * u_linewidth.s;
// Calculate the antialiasing fade factor. This is either when fading in
// the line in case of an offset line (v_linewidth.t) or when fading out
// (v_linewidth.s)
float alpha = clamp(min(dist - (u_linewidth.t - u_blur), u_linewidth.s - dist) / u_blur, 0.0, 1.0);
float sdfdist = texture2D(u_image, v_tex).a;
alpha *= smoothstep(0.5 - u_sdfgamma, 0.5 + u_sdfgamma, sdfdist);
gl_FragColor = u_color * alpha;
}

View File

@@ -0,0 +1,49 @@
// floor(127 / 2) == 63.0
// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is
// stored in a byte (-128..127). we scale regular normals up to length 63, but
// there are also "special" normals that have a bigger length (of up to 126 in
// this case).
// #define scale 63.0
#define scale 0.015873016
attribute vec2 a_pos;
attribute vec4 a_data;
// matrix is for the vertex position, exmatrix is for rotating and projecting
// the extrusion vector.
uniform mat4 u_matrix;
uniform mat4 u_exmatrix;
// shared
uniform float u_ratio;
uniform vec2 u_linewidth;
uniform vec2 u_patternscale;
uniform float u_tex_y;
varying vec2 v_normal;
varying vec2 v_tex;
void main() {
vec2 a_extrude = a_data.xy;
float a_linesofar = a_data.z * 128.0 + a_data.w;
// We store the texture normals in the most insignificant bit
// transform y so that 0 => -1 and 1 => 1
// In the texture normal, x is 0 if the normal points straight up/down and 1 if it's a round cap
// y is 1 if the normal points up, and -1 if it points down
vec2 normal = mod(a_pos, 2.0);
normal.y = sign(normal.y - 0.5);
v_normal = normal;
// Scale the extrusion vector down to a normal and then up by the line width
// of this vertex.
vec4 dist = vec4(u_linewidth.s * a_extrude * scale, 0.0, 0.0);
// Remove the texture normal bit of the position before scaling it with the
// model/view matrix. Add the extrusion vector *after* the model/view matrix
// because we're extruding the line in pixel space, regardless of the current
// tile's zoom level.
gl_Position = u_matrix * vec4(floor(a_pos * 0.5), 0.0, 1.0) + u_exmatrix * dist;
v_tex = vec2(a_linesofar * u_patternscale.x, normal.y * u_patternscale.y + u_tex_y);
}

View File

@@ -0,0 +1,30 @@
#include <mbgl/shader/linesdf_shader.hpp>
#include <mbgl/shader/shaders.hpp>
#include <mbgl/platform/gl.hpp>
#include <cstdio>
using namespace mbgl;
LineSDFShader::LineSDFShader()
: Shader(
"line",
shaders[LINESDF_SHADER].vertex,
shaders[LINESDF_SHADER].fragment
) {
if (!valid) {
fprintf(stderr, "invalid line shader\n");
return;
}
a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos"));
a_data = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data"));
}
void LineSDFShader::bind(char *offset) {
MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos));
MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 8, offset + 0));
MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_data));
MBGL_CHECK_ERROR(glVertexAttribPointer(a_data, 4, GL_BYTE, false, 8, offset + 4));
}

View File

@@ -0,0 +1,34 @@
#ifndef MBGL_SHADER_SHADER_LINESDF
#define MBGL_SHADER_SHADER_LINESDF
#include <mbgl/shader/shader.hpp>
#include <mbgl/shader/uniform.hpp>
namespace mbgl {
class LineSDFShader : public Shader {
public:
LineSDFShader();
void bind(char *offset);
UniformMatrix<4> u_matrix = {"u_matrix", *this};
UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this};
Uniform<std::array<float, 4>> u_color = {"u_color", *this};
Uniform<std::array<float, 2>> u_linewidth = {"u_linewidth", *this};
Uniform<float> u_ratio = {"u_ratio", *this};
Uniform<float> u_blur = {"u_blur", *this};
Uniform<std::array<float, 2>> u_patternscale = { "u_patternscale", *this };
Uniform<float> u_tex_y = {"u_tex_y", *this};
Uniform<int32_t> u_image = {"u_image", *this};
Uniform<float> u_sdfgamma = {"u_sdfgamma", *this};
private:
int32_t a_pos = -1;
int32_t a_data = -1;
};
}
#endif

View File

@@ -188,6 +188,9 @@ void StyleLayer::applyStyleProperties<LineProperties>(const float z, const times
applyTransitionedStyleProperty(PropertyKey::LineDashLand, line.dash_array[0], z, now);
applyTransitionedStyleProperty(PropertyKey::LineDashGap, line.dash_array[1], z, now);
applyStyleProperty(PropertyKey::LineImage, line.image, z, now);
// for scaling dasharrays
applyStyleProperty(PropertyKey::LineWidth, line.dash_line_width, std::floor(z), now + 10000);
}
template <>

View File

@@ -37,6 +37,7 @@ struct LineProperties {
float gap_width = 0;
float blur = 0;
std::array<float, 2> dash_array = {{ 1, -1 }};
float dash_line_width = 1;
std::string image;
inline bool isVisible() const {