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
|
import MapData from '../model/data/MapData';
import { nextPowerOf2 } from '../util';
import Renderer from './renderer/Renderer';
import { SpriteCoords, SpriteView, SpriteViewBuilder } from './sprite';
import { loadImage, mkTexture } from './util/image';
interface Tileset {
texture: WebGLTexture;
tiles: SpriteCoords[];
}
function loadTiles(tiles: string[]): Promise<HTMLImageElement[]> {
return Promise.all(tiles.map((t) => loadImage(`resources/sprite/tile/${t}.png`)));
}
function mkTileset(
gl: WebGLRenderingContext,
tiles: HTMLImageElement[],
): Tileset {
const tileSize = 32;
const canvasDim = nextPowerOf2(Math.sqrt(tiles.length));
const canvasSize = canvasDim * tileSize;
const canvas = document.createElement('canvas');
canvas.width = canvas.height = canvasSize;
let x = 0, y = 0;
const tileCoords: SpriteCoords[] = [];
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
for (const tile of tiles) {
ctx.drawImage(tile, x * tileSize, y * tileSize);
tileCoords.push([x / canvasDim, y / canvasDim, (x + 1) / canvasDim, (y + 1) / canvasDim]);
x++;
if (x === canvasDim) {
x = 0;
y++;
}
}
return {
texture: mkTexture(gl, canvas),
tiles: tileCoords,
};
}
function addSprite(builder: SpriteViewBuilder, tileset: Tileset, x: number, y: number, tile: number) {
if (tile === 0)
return;
const tilePos = tileset.tiles[tile - 1];
builder.addSprite([x, y, x + 1, y + 1], tilePos);
}
export async function loadMap(r: Renderer, map: MapData): Promise<SpriteView> {
const tiles = await loadTiles(map.tiles);
const tileset = mkTileset(r.getContext(), tiles);
const builder = new SpriteViewBuilder(r, tileset.texture);
for (const layer of map.layers)
for (let x = 0; x < map.width; x++)
for (let y = 0; y < map.height; y++)
addSprite(builder, tileset, x, y, layer[y][x]);
return builder.build();
}
|