summaryrefslogtreecommitdiff
path: root/src/mbgl/style/style.cpp
blob: 1ffd75bf6959aafceb2f892113a16ba0dd46db90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#include <mbgl/style/style.hpp>
#include <mbgl/map/map_data.hpp>
#include <mbgl/map/source.hpp>
#include <mbgl/map/tile.hpp>
#include <mbgl/map/transform_state.hpp>
#include <mbgl/layer/symbol_layer.hpp>
#include <mbgl/layer/custom_layer.hpp>
#include <mbgl/sprite/sprite_store.hpp>
#include <mbgl/sprite/sprite_atlas.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_parser.hpp>
#include <mbgl/style/property_transition.hpp>
#include <mbgl/style/class_dictionary.hpp>
#include <mbgl/style/style_update_parameters.hpp>
#include <mbgl/style/style_cascade_parameters.hpp>
#include <mbgl/style/style_calculation_parameters.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/platform/log.hpp>
#include <mbgl/layer/background_layer.hpp>

#include <csscolorparser/csscolorparser.hpp>

#include <algorithm>

namespace mbgl {

Style::Style(MapData& data_)
    : data(data_),
      glyphStore(std::make_unique<GlyphStore>()),
      glyphAtlas(std::make_unique<GlyphAtlas>(1024, 1024)),
      spriteStore(std::make_unique<SpriteStore>(data.pixelRatio)),
      spriteAtlas(std::make_unique<SpriteAtlas>(1024, 1024, data.pixelRatio, *spriteStore)),
      lineAtlas(std::make_unique<LineAtlas>(512, 512)),
      workers(4) {
    glyphStore->setObserver(this);
    spriteStore->setObserver(this);
}

void Style::setJSON(const std::string& json, const std::string&) {
    sources.clear();
    layers.clear();

    StyleParser parser;
    parser.parse(json);

    for (auto& source : parser.sources) {
        addSource(std::move(source));
    }

    for (auto& layer : parser.layers) {
        addLayer(std::move(layer));
    }

    glyphStore->setURL(parser.glyphURL);
    spriteStore->setURL(parser.spriteURL);

    loaded = true;
}

Style::~Style() {
    for (const auto& source : sources) {
        source->setObserver(nullptr);
    }

    glyphStore->setObserver(nullptr);
    spriteStore->setObserver(nullptr);
}

void Style::addSource(std::unique_ptr<Source> source) {
    source->setObserver(this);
    sources.emplace_back(std::move(source));
}

std::vector<std::unique_ptr<StyleLayer>> Style::getLayers() const {
    std::vector<std::unique_ptr<StyleLayer>> result;
    result.reserve(layers.size());
    for (const auto& layer : layers) {
        result.push_back(layer->clone());
    }
    return result;
}

std::vector<std::unique_ptr<StyleLayer>>::const_iterator Style::findLayer(const std::string& id) const {
    return std::find_if(layers.begin(), layers.end(), [&](const auto& layer) {
        return layer->id == id;
    });
}

StyleLayer* Style::getLayer(const std::string& id) const {
    auto it = findLayer(id);
    return it != layers.end() ? it->get() : nullptr;
}

void Style::addLayer(std::unique_ptr<StyleLayer> layer, optional<std::string> before) {
    if (SymbolLayer* symbolLayer = layer->as<SymbolLayer>()) {
        if (!symbolLayer->spriteAtlas) {
            symbolLayer->spriteAtlas = spriteAtlas.get();
        }
    }

    if (CustomLayer* customLayer = layer->as<CustomLayer>()) {
        customLayer->initialize();
    }

    layers.emplace(before ? findLayer(*before) : layers.end(), std::move(layer));
}

void Style::removeLayer(const std::string& id) {
    auto it = findLayer(id);
    if (it == layers.end())
        throw std::runtime_error("no such layer");
    layers.erase(it);
}

void Style::update(const TransformState& transform,
                   TexturePool& texturePool) {
    bool allTilesUpdated = true;
    StyleUpdateParameters parameters(data.pixelRatio,
                                     data.getDebug(),
                                     data.getAnimationTime(),
                                     transform,
                                     workers,
                                     texturePool,
                                     shouldReparsePartialTiles,
                                     data.mode,
                                     data,
                                     *this);

    for (const auto& source : sources) {
        if (!source->update(parameters)) {
            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 Style::cascade() {
    std::vector<ClassID> classes;

    std::vector<std::string> classNames = data.getClasses();
    for (auto it = classNames.rbegin(); it != classNames.rend(); it++) {
        classes.push_back(ClassDictionary::Get().lookup(*it));
    }
    classes.push_back(ClassID::Default);
    classes.push_back(ClassID::Fallback);

    StyleCascadeParameters parameters(classes,
                                      data.getAnimationTime(),
                                      PropertyTransition { data.getDefaultTransitionDuration(),
                                                           data.getDefaultTransitionDelay() });

    for (const auto& layer : layers) {
        layer->cascade(parameters);
    }
}

void Style::recalculate(float z) {
    for (const auto& source : sources) {
        source->enabled = false;
    }

    zoomHistory.update(z, data.getAnimationTime());

    StyleCalculationParameters parameters(z,
                                          data.getAnimationTime(),
                                          zoomHistory,
                                          data.getDefaultFadeDuration());

    for (const auto& layer : layers) {
        hasPendingTransitions |= layer->recalculate(parameters);

        Source* source = getSource(layer->source);
        if (source && layer->needsRendering()) {
            source->enabled = true;
            if (!source->loaded && !source->isLoading()) source->load();
        }
    }
}

Source* Style::getSource(const std::string& id) const {
    const auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& source) {
        return source->id == id;
    });

    return it != sources.end() ? it->get() : nullptr;
}

bool Style::hasTransitions() const {
    return hasPendingTransitions;
}

bool Style::isLoaded() const {
    if (!loaded) {
        return false;
    }

    for (const auto& source: sources) {
        if (source->enabled && !source->isLoaded()) return false;
    }

    if (!spriteStore->isLoaded()) {
        return false;
    }

    return true;
}

RenderData Style::getRenderData() const {
    RenderData result;

    for (const auto& source : sources) {
        if (source->enabled) {
            result.sources.insert(source.get());
        }
    }

    for (const auto& layer : layers) {
        if (layer->visibility == VisibilityType::None)
            continue;

        if (const BackgroundLayer* background = layer->as<BackgroundLayer>()) {
            if (layer.get() == layers[0].get() && background->paint.pattern.value.from.empty()) {
                // This is a solid background. We can use glClear().
                result.backgroundColor = background->paint.color;
                result.backgroundColor[0] *= background->paint.opacity;
                result.backgroundColor[1] *= background->paint.opacity;
                result.backgroundColor[2] *= background->paint.opacity;
                result.backgroundColor[3] *= background->paint.opacity;
            } else {
                // This is a textured background, or not the bottommost layer. We need to render it with a quad.
                result.order.emplace_back(*layer);
            }
            continue;
        }

        if (layer->is<CustomLayer>()) {
            result.order.emplace_back(*layer);
            continue;
        }

        Source* source = getSource(layer->source);
        if (!source) {
            Log::Warning(Event::Render, "can't find source for layer '%s'", layer->id.c_str());
            continue;
        }

        for (auto tile : source->getTiles()) {
            if (!tile->data || !tile->data->isReady())
                continue;

            // We're not clipping symbol layers, so when we have both parents and children of symbol
            // layers, we drop all children in favor of their parent to avoid duplicate labels.
            // See https://github.com/mapbox/mapbox-gl-native/issues/2482
            if (layer->is<SymbolLayer>()) {
                bool skip = false;
                // Look back through the buckets we decided to render to find out whether there is
                // already a bucket from this layer that is a parent of this tile. Tiles are ordered
                // by zoom level when we obtain them from getTiles().
                for (auto it = result.order.rbegin(); it != result.order.rend() && (&it->layer == layer.get()); ++it) {
                    if (tile->id.isChildOf(it->tile->id)) {
                        skip = true;
                        break;
                    }
                }
                if (skip) {
                    continue;
                }
            }

            auto bucket = tile->data->getBucket(*layer);
            if (bucket) {
                result.order.emplace_back(*layer, tile, bucket);
            }
        }
    }

    return result;
}

void Style::setSourceTileCacheSize(size_t size) {
    for (const auto& source : sources) {
        source->setCacheSize(size);
    }
}

void Style::onLowMemory() {
    for (const auto& source : sources) {
        source->onLowMemory();
    }
}

void Style::setObserver(Observer* observer_) {
    assert(util::ThreadContext::currentlyOn(util::ThreadType::Map));
    observer = observer_;
}

void Style::onGlyphsLoaded(const std::string& fontStack, const GlyphRange& glyphRange) {
    shouldReparsePartialTiles = true;
    observer->onGlyphsLoaded(fontStack, glyphRange);
    observer->onResourceLoaded();
}

void Style::onGlyphsError(const std::string& fontStack, const GlyphRange& glyphRange, std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load glyph range %d-%d for font stack %s: %s",
               glyphRange.first, glyphRange.second, fontStack.c_str(), util::toString(error).c_str());
    observer->onGlyphsError(fontStack, glyphRange, error);
    observer->onResourceError(error);
}

void Style::onSourceLoaded(Source& source) {
    observer->onSourceLoaded(source);
    observer->onResourceLoaded();
}

void Style::onSourceError(Source& source, std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load source %s: %s",
               source.id.c_str(), util::toString(error).c_str());
    observer->onSourceError(source, error);
    observer->onResourceError(error);
}

void Style::onTileLoaded(Source& source, const TileID& tileID, bool isNewTile) {
    if (isNewTile) {
        shouldReparsePartialTiles = true;
    }

    observer->onTileLoaded(source, tileID, isNewTile);
    observer->onResourceLoaded();
}

void Style::onTileError(Source& source, const TileID& tileID, std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load tile %s for source %s: %s",
               std::string(tileID).c_str(), source.id.c_str(), util::toString(error).c_str());
    observer->onTileError(source, tileID, error);
    observer->onResourceError(error);
}

void Style::onPlacementRedone() {
    observer->onResourceLoaded();
}

void Style::onSpriteLoaded() {
    shouldReparsePartialTiles = true;
    observer->onSpriteLoaded();
    observer->onResourceLoaded();
}

void Style::onSpriteError(std::exception_ptr error) {
    lastError = error;
    Log::Error(Event::Style, "Failed to load sprite: %s", util::toString(error).c_str());
    observer->onSpriteError(error);
    observer->onResourceError(error);
}

void Style::dumpDebugLogs() const {
    for (const auto& source : sources) {
        source->dumpDebugLogs();
    }

    spriteStore->dumpDebugLogs();
}

} // namespace mbgl