summaryrefslogtreecommitdiff
path: root/src/mbgl/map/sprite.cpp
blob: cfc0974571df7dc39b86de8ae8ca3e99709d38f4 (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
#include <mbgl/map/sprite.hpp>
#include <mbgl/util/raster.hpp>
#include <mbgl/platform/log.hpp>

#include <string>
#include <mbgl/platform/platform.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/storage/resource.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <mbgl/util/std.hpp>

#include <rapidjson/document.h>

using namespace mbgl;

SpritePosition::SpritePosition(uint16_t x_, uint16_t y_, uint16_t width_, uint16_t height_, float pixelRatio_, bool sdf_)
    : x(x_),
      y(y_),
      width(width_),
      height(height_),
      pixelRatio(pixelRatio_),
      sdf(sdf_) {
}

Sprite::Sprite(const std::string& baseUrl, float pixelRatio_)
    : pixelRatio(pixelRatio_ > 1 ? 2 : 1),
      raster(),
      loadedImage(false),
      loadedJSON(false),
      env(Environment::Get()) {
    if (baseUrl.empty()) {
        // Treat a non-existent sprite as a successfully loaded empty sprite.
        loadedImage = true;
        loadedJSON = true;
        return;
    }

    std::string spriteURL(baseUrl + (pixelRatio_ > 1 ? "@2x" : "") + ".png");
    std::string jsonURL(baseUrl + (pixelRatio_ > 1 ? "@2x" : "") + ".json");

    jsonRequest = env.request({ Resource::Kind::JSON, jsonURL }, [this](const Response &res) {
        jsonRequest = nullptr;
        if (res.status == Response::Successful) {
            body = res.data;
            parseJSON();
        } else {
            Log::Warning(Event::Sprite, "Failed to load sprite info: %s", res.message.c_str());
        }
        loadedJSON = true;
        emitSpriteLoadedIfComplete();
    });

    spriteRequest = env.request({ Resource::Kind::Image, spriteURL }, [this](const Response &res) {
        spriteRequest = nullptr;
        if (res.status == Response::Successful) {
            image = res.data;
            parseImage();
        } else {
            Log::Warning(Event::Sprite, "Failed to load sprite image: %s", res.message.c_str());
        }
        loadedImage = true;
        emitSpriteLoadedIfComplete();
    });
}

Sprite::~Sprite() {
    if (jsonRequest) {
        env.cancelRequest(jsonRequest);
    }

    if (spriteRequest) {
        env.cancelRequest(spriteRequest);
    }
}

void Sprite::emitSpriteLoadedIfComplete() {
    if (isLoaded() && observer) {
        observer->onSpriteLoaded();
    }
}

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) {
        raster.reset();
    }
    image.clear();
}

void Sprite::parseJSON() {
    rapidjson::Document d;
    d.Parse<0>(body.c_str());
    body.clear();

    if (d.HasParseError()) {
        Log::Warning(Event::Sprite, "sprite JSON is invalid");
    } else if (d.IsObject()) {
        for (rapidjson::Value::ConstMemberIterator itr = d.MemberBegin(); itr != d.MemberEnd(); ++itr) {
            const std::string& name = itr->name.GetString();
            const rapidjson::Value& value = itr->value;

            if (value.IsObject()) {
                uint16_t x = 0;
                uint16_t y = 0;
                uint16_t width = 0;
                uint16_t height = 0;
                float spritePixelRatio = 1.0f;
                bool sdf = false;

                if (value.HasMember("x")) x = value["x"].GetInt();
                if (value.HasMember("y")) y = value["y"].GetInt();
                if (value.HasMember("width")) width = value["width"].GetInt();
                if (value.HasMember("height")) height = value["height"].GetInt();
                if (value.HasMember("pixelRatio")) spritePixelRatio = value["pixelRatio"].GetInt();
                if (value.HasMember("sdf")) sdf = value["sdf"].GetBool();
                pos.emplace(name, SpritePosition { x, y, width, height, spritePixelRatio, sdf });
            }
        }
    } else {
        Log::Warning(Event::Sprite, "sprite JSON root is not an object");
    }
}

const SpritePosition &Sprite::getSpritePosition(const std::string& name) const {
    if (!isLoaded()) return empty;
    auto it = pos.find(name);
    return it == pos.end() ? empty : it->second;
}

void Sprite::setObserver(Observer* observer_) {
    observer = observer_;
}