~mil/mepo

ref: 34c0f8a47f4846f8b27093f7a454a2fd0eed11ce mepo/src/TileCache.zig -rw-r--r-- 10.2 KiB
34c0f8a4Miles Alan Prevent bad tiledata loaded from filesystem from crashing application 2 months ago
                                                                                
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
const std = @import("std");
const curl = @cImport({
    @cInclude("curl/curl.h");
});
const cstdio = @cImport({
    @cInclude("stdio.h");
});
const wordexp = @cImport({
    @cInclude("wordexp.h");
});
const sdl = @import("./sdlshim.zig");
const types = @import("./types.zig");
const config = @import("./config.zig");
const sdlutil = @import("./util/sdlutil.zig");

pub const TransferDatum = struct { client: *curl.CURL, coords: types.TileSpec, data: std.ArrayList(u8), progress_dl_now: ?c_long, progress_dl_total: ?c_long, load_to_surface: bool };
const TileDataTag = enum { transfer_datum, surface, queued_position };
pub const TileData = union(TileDataTag) { transfer_datum: TransferDatum, surface: *sdl.SDL_Surface, queued_position: u32 };

source_url: ?[:0]const u8,
cache_dir: ?std.fs.Dir,
n_current_transfers: u32,
queue_map: std.array_hash_map.AutoArrayHashMap(types.TileSpec, bool),
transfer_map: std.array_hash_map.AutoArrayHashMap(types.TileSpec, *TransferDatum),
surface_map: std.array_hash_map.AutoArrayHashMap(types.TileSpec, *sdl.SDL_Surface),
curl_multi: *curl.CURLM,

fn tile_xferinfo_curl_callback(user_data: *c_void, dl_total: curl.curl_off_t, dl_now: curl.curl_off_t, ul_total: curl.curl_off_t, ul_now: curl.curl_off_t) callconv(.C) c_uint {
    //std.debug.warn("Progress: {} {}\n", .{ dl_now, dl_total });
    var tile_data = @intToPtr(*TransferDatum, @ptrToInt(user_data));
    tile_data.progress_dl_now = dl_now;
    tile_data.progress_dl_total = dl_total;
    return curl.CURL_PROGRESSFUNC_CONTINUE;
}

fn tile_write_curl_callback(data: *c_void, size: c_uint, nmemb: c_uint, user_data: *c_void) callconv(.C) c_uint {
    std.debug.warn("Got some bytes in download for tile {any}\n", .{user_data});
    var transfer_datum = @intToPtr(*TransferDatum, @ptrToInt(user_data));
    var typed_data = @intToPtr([*]u8, @ptrToInt(data));
    transfer_datum.data.appendSlice(typed_data[0 .. nmemb * size]) catch return 0;
    return nmemb * size;
}

fn png_path(allocator: *std.mem.Allocator, source: []const u8, coords: types.TileSpec) ![]u8 {
    var source_hash: [32:0]u8 = undefined;
    std.crypto.hash.sha2.Sha256.hash(source, &source_hash, .{});
    return try std.fmt.allocPrint(allocator, "{s}_{d}_{d}_{d}.png", .{ std.fmt.fmtSliceHexLower(source_hash[0..8]), coords.z, coords.x, coords.y });
}

pub fn tile_retrieve(tile_cache: *@This(), coords: types.TileSpec) !TileData {
    var file_cached_png_opt: ?[]u8 = null;

    if (tile_cache.surface_map.get(coords)) |tile| {
        return TileData{ .surface = tile };
    } else if (tile_cache.transfer_map.get(coords)) |transfer| {
        return TileData{ .transfer_datum = transfer.* };
    } else if (tile_cache.cache_dir) |cache_dir| load_from_fs: {
        const png = try png_path(std.heap.c_allocator, tile_cache.source_url.?, coords);
        defer std.heap.c_allocator.free(png);
        file_cached_png_opt = cache_dir.readFileAlloc(std.heap.c_allocator, png, 500000) catch null;
        if (file_cached_png_opt) |file_cached_png| {
            const surf = tile_cache.load_data_to_surface(coords, file_cached_png) catch { break :load_from_fs; };
            return TileData{ .surface = surf };
        }
    }

    try tile_cache.queue_map.put(coords, true);

    return TileData{ .queued_position = @intCast(u32, if (tile_cache.queue_map.getIndex(coords)) |index| index else 0) };
}

pub fn tile_queue_no_surface_load(tile_cache: *@This(), coords: types.TileSpec) !void {
    if (tile_cache.cache_dir) |cache_dir| check_tile_exists: {
        const png = try png_path(std.heap.c_allocator, tile_cache.source_url.?, coords);
        defer std.heap.c_allocator.free(png);
        cache_dir.access(png, .{}) catch {
            break :check_tile_exists;
        };
        return;
    }

    try tile_cache.queue_map.put(coords, false);
}

fn add_to_curl_multi(tile_cache: *@This(), coords: types.TileSpec, load_to_surface: bool) !void {
    var transfer_datum: *TransferDatum = datum: {
        var dat = try std.heap.c_allocator.create(TransferDatum);
        dat.client = curl.curl_easy_init().?;
        dat.coords = coords;
        dat.data = std.ArrayList(u8).init(std.heap.c_allocator);
        dat.progress_dl_now = null;
        dat.progress_dl_total = null;
        dat.load_to_surface = load_to_surface;
        break :datum dat;
    };
    try tile_cache.transfer_map.put(coords, transfer_datum);

    var tile_url = url: {
        var url = try std.heap.c_allocator.alloc(u8, 2000);
        _ = cstdio.sprintf(&url[0], tile_cache.source_url.?, @intCast(c_int, coords.x), @intCast(c_int, coords.y), @intCast(c_int, coords.z));
        break :url url;
    };
    defer std.heap.c_allocator.free(tile_url);

    try curl_setopt(transfer_datum.client, curl.CURLOPT_URL, @ptrCast(*c_void, tile_url));
    try curl_setopt(transfer_datum.client, curl.CURLOPT_USERAGENT, config.Useragent);
    try curl_setopt(transfer_datum.client, curl.CURLOPT_NOPROGRESS, @intCast(c_long, 0));
    try curl_setopt(transfer_datum.client, curl.CURLOPT_XFERINFOFUNCTION, tile_xferinfo_curl_callback);
    try curl_setopt(transfer_datum.client, curl.CURLOPT_XFERINFODATA, transfer_datum);
    try curl_setopt(transfer_datum.client, curl.CURLOPT_WRITEFUNCTION, tile_write_curl_callback);
    try curl_setopt(transfer_datum.client, curl.CURLOPT_WRITEDATA, transfer_datum);

    _ = curl.curl_multi_add_handle(tile_cache.curl_multi, transfer_datum.client);
    std.debug.warn("Add multi handle {any}\n", .{coords});
}

fn curl_setopt(client: *curl.CURL, opt: c_int, value: anytype) !void {
    if (@intToEnum(curl.CURLcode, curl.CURLE_OK) != curl.curl_easy_setopt(client, @intToEnum(curl.CURLoption, opt), value)) {
        return error.CurlEasySetOptFail;
    }
}

fn curl_msg_to_coords(tile_cache: *@This(), msg: *curl.CURLMsg) ?types.TileSpec {
    var it = tile_cache.transfer_map.iterator();
    while (it.next()) |kv| {
        if (kv.value_ptr.*.client == msg.*.easy_handle) {
            return kv.value_ptr.*.coords;
        }
    }
    return null;
}

fn load_data_to_surface(tile_cache: *@This(), coords: types.TileSpec, data: []u8) !*sdl.SDL_Surface {
    const datum = @ptrCast(*c_void, &data[0]);
    const len = @intCast(c_int, data.len);
    if (sdl.IMG_Load_RW(sdl.SDL_RWFromMem(datum, len), 1)) |surf| {
        try tile_cache.surface_map.put(coords, surf);
        return tile_cache.surface_map.get(coords).?;
    } else {
        return error.LoadToSurfaceFail;
    }
}

fn transfer_complete(tile_cache: *@This(), msg: *curl.CURLMsg) !void {
    if (tile_cache.curl_msg_to_coords(msg)) |coords| {
        const datum = tile_cache.transfer_map.get(coords).?.data.items;

        if (tile_cache.cache_dir) |cache_dir| {
            // Save to FS
            const path = try png_path(std.heap.c_allocator, tile_cache.source_url.?, coords);
            try cache_dir.writeFile(path, datum);
        }
        if (tile_cache.transfer_map.get(coords).?.load_to_surface) {
            // Load to surface
            _ = try tile_cache.load_data_to_surface(coords, datum);
        }

        tile_cache.transfer_map.get(coords).?.data.deinit();
        _ = tile_cache.transfer_map.swapRemove(coords);
    } else {
        std.debug.warn("Failed to find coordinates associated with downloaded data?\n", .{});
    }

    _ = curl.curl_multi_remove_handle(tile_cache.curl_multi, msg.*.easy_handle);
    _ = curl.curl_easy_cleanup(msg.*.easy_handle);
    if (tile_cache.n_current_transfers > 0) {
        tile_cache.n_current_transfers -= 1;
    }
    sdlutil.sdl_push_resize_event();
}

pub fn download_loop(tile_cache: *@This()) !void {
    var running: c_int = undefined;
    var n_msgs: c_int = undefined;

    while (true) {
        _ = curl.curl_multi_perform(tile_cache.curl_multi, &running);
        var msg = curl.curl_multi_info_read(tile_cache.curl_multi, &n_msgs);
        while (msg != null) {
            switch (msg.*.msg) {
                ._DONE => try tile_cache.transfer_complete(msg),
                else => {},
            }
            _ = curl.curl_multi_perform(tile_cache.curl_multi, &running);
            msg = curl.curl_multi_info_read(tile_cache.curl_multi, &n_msgs);
        }

        while (tile_cache.queue_map.count() > 0 and tile_cache.n_current_transfers < config.MaxNTransfers) {
            var coords = tile_cache.queue_map.pop();
            try tile_cache.add_to_curl_multi(coords.key, coords.value);
            tile_cache.n_current_transfers += 1;
        }

        sdl.SDL_Delay(config.DownloaderPollMs);
    }
}

pub fn download_loop_sdl_threadable(userdata: ?*c_void) callconv(.C) c_int {
    var tile_cache = @ptrCast(*@This(), @alignCast(@alignOf(*@This()), userdata.?));
    var err = tile_cache.download_loop();
    return 0;
}

pub fn set_cache_dir(tile_cache: *@This(), path: [:0]const u8) !void {
    var expansion: wordexp.wordexp_t = undefined;
    defer wordexp.wordfree(&expansion);

    if (wordexp.wordexp(&path[0], &expansion, 0) != 0) {
        return error.CacheDirExpansionFail;
    } else {
        const expanded_path: []u8 = try std.fmt.allocPrint(std.heap.c_allocator, "{s}", .{expansion.we_wordv[0]});
        defer std.heap.c_allocator.free(expanded_path);
        try std.fs.cwd().makePath(expanded_path);
        tile_cache.cache_dir = try std.fs.cwd().openDir(expanded_path, .{ .iterate = true });
    }
}

pub fn set_cache_url(tile_cache: *@This(), url: [:0]const u8) !void {
    // Empty Cache
    tile_cache.source_url = url;
    tile_cache.surface_map.clearAndFree();
    tile_cache.queue_map.clearAndFree();
    sdlutil.sdl_push_resize_event();
}

pub fn init() anyerror!@This() {
    if (curl.curl_multi_init()) |curl_multi| {
        var x = @as(@This(), .{
            .source_url = null,
            .cache_dir = null,
            .n_current_transfers = 0,
            .transfer_map = std.array_hash_map.AutoArrayHashMap(types.TileSpec, *TransferDatum).init(std.heap.c_allocator),
            .surface_map = std.array_hash_map.AutoArrayHashMap(types.TileSpec, *sdl.SDL_Surface).init(std.heap.c_allocator),
            .queue_map = std.array_hash_map.AutoArrayHashMap(types.TileSpec, bool).init(std.heap.c_allocator),
            .curl_multi = curl.curl_multi_init().?,
        });
        try x.surface_map.ensureCapacity(2000);
        try x.transfer_map.ensureCapacity(20000);
        try x.queue_map.ensureCapacity(20000);
        return x;
    } else {
        return error.MultiInitFail;
    }
}