import {nextPowerOf2} from '../util'; import MapData from '../model/MapData'; import Renderer from './renderer/Renderer'; export default class MapView { public static readonly tileSize: number = 32; private redrawPending: boolean = false; private readonly vertexBuffer: WebGLBuffer; private readonly textureBuffer: WebGLBuffer; constructor( private readonly r: Renderer, private readonly map: MapData, private readonly tileTexture: WebGLTexture, private readonly tileMap: Map, ) { const vertexData: number[] = []; const textureData: number[] = []; const tileCount = nextPowerOf2(tileMap.size); for (let x = 0; x < map.width; x++) for (let y = 0; y < map.height; y++) this.addTile(vertexData, textureData, x, y, map.layers[0][y][x], tileCount); const gl = r.getContext(); this.vertexBuffer = r.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexData), gl.STATIC_DRAW); this.textureBuffer = r.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureData), gl.STATIC_DRAW); } public draw(): void { const gl = this.r.getContext(); gl.clear(gl.COLOR_BUFFER_BIT); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.tileTexture); gl.uniform1i(this.r.getSamplerLoc(), 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.vertexAttribPointer(this.r.getVertexPosLoc(), 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer); gl.vertexAttribPointer(this.r.getTextureCoordLoc(), 2, gl.FLOAT, false, 0, 0); gl.drawArrays(gl.TRIANGLES, 0, 6 * this.map.width * this.map.height); } private addTile(vertexData: number[], textureData: number[], x: number, y: number, tile: string, tileCount: number) { const tileID = this.tileMap.get(tile); if (tileID === undefined) throw new Error('invalid tile specifier in map data'); vertexData.push(x); vertexData.push(y); vertexData.push(x + 1); vertexData.push(y); vertexData.push(x); vertexData.push(y + 1); vertexData.push(x); vertexData.push(y + 1); vertexData.push(x + 1); vertexData.push(y); vertexData.push(x + 1); vertexData.push(y + 1); textureData.push((tileID) / tileCount); textureData.push(0); textureData.push((tileID + 1) / tileCount); textureData.push(0); textureData.push((tileID) / tileCount); textureData.push(1); textureData.push((tileID) / tileCount); textureData.push(1); textureData.push((tileID + 1) / tileCount); textureData.push(0); textureData.push((tileID + 1) / tileCount); textureData.push(1); } }