summaryrefslogtreecommitdiffstats
path: root/src/view/MapLoader.ts
blob: 695332148350da8619f884fb8ccb78b3fbc88720 (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
import {mapValues, mapValuesAsync, nextPowerOf2} from '../util';

import MapState from '../model/state/MapState';
import MapView from './MapView';
import Renderer from './renderer/Renderer';

export interface TileMap {
	texture: WebGLTexture;
	tiles: Map<string, [number, number, number, number]>;
}

function loadImage(url: string): Promise<HTMLImageElement> {
	return new Promise((resolve, reject) => {
		const img = new Image();
		img.addEventListener('load', () => { resolve(img); });
		img.addEventListener('error', () => { reject(Error('failed to load ' + url)); });
		img.src = url;
	});
}

function loadImages(urls: Map<string, string>): Promise<Map<string, HTMLImageElement>> {
	return mapValuesAsync(loadImage, urls);
}

function loadTiles(tiles: Map<string, string>): Promise<Map<string, HTMLImageElement>> {
	return loadImages(mapValues((t) => `resources/sprite/tile/${t}.png`, tiles));
}

function mkTexture(gl: WebGLRenderingContext, src: HTMLCanvasElement|HTMLImageElement): WebGLTexture {
	const texture = gl.createTexture();
	if (!texture)
		throw new Error('unable to create texture');

	gl.bindTexture(gl.TEXTURE_2D, texture);
	gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src);
	gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
	gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
	gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
	gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

	return texture;
}

function mkTileMap(
	gl: WebGLRenderingContext,
	tiles: Map<string, HTMLImageElement>,
): TileMap {
	const tileSize = MapView.tileSize;

	const canvasDim = nextPowerOf2(Math.sqrt(tiles.size));
	const canvasSize = canvasDim * tileSize;

	const canvas = document.createElement('canvas');
	canvas.width = canvas.height = canvasSize;

	let x = 0, y = 0;
	const map: Map<string, [number, number, number, number]> = new Map();
	const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;

	for (const [k, tile] of tiles) {
		ctx.drawImage(tile, x * tileSize, y * tileSize);
		map.set(k, [x / canvasDim, y / canvasDim, (x + 1) / canvasDim, (y + 1) / canvasDim]);

		x++;
		if (x === canvasDim) {
			x = 0;
			y++;
		}
	}

	return {
		texture: mkTexture(gl, canvas),
		tiles: map,
	};
}

export async function loadMap(r: Renderer, map: MapState): Promise<MapView> {
	const tiles = await loadTiles(map.data.tiles);
	const tileMap = mkTileMap(r.getContext(), tiles);

	return new MapView(r, map, tileMap);
}