import fragmentShaderSrc from './default.fs'; import vertexShaderSrc from './default.vs'; export default class Shaders { public readonly viewportLoc: WebGLUniformLocation; public readonly translateLoc: WebGLUniformLocation; public readonly vertexPosLoc: number; public readonly textureCoordLoc: number; public readonly samplerLoc: WebGLUniformLocation; constructor(private readonly gl: WebGLRenderingContext) { const shaderProgram = this.gl.createProgram(); if (!shaderProgram) throw new Error('Unable to create shader program'); const vertexShader = this.compileShader(this.gl.VERTEX_SHADER, vertexShaderSrc); const fragmentShader = this.compileShader(this.gl.FRAGMENT_SHADER, fragmentShaderSrc); this.gl.attachShader(shaderProgram, vertexShader); this.gl.attachShader(shaderProgram, fragmentShader); this.gl.linkProgram(shaderProgram); if (!this.gl.getProgramParameter(shaderProgram, this.gl.LINK_STATUS)) { const err = this.gl.getProgramInfoLog(shaderProgram); this.gl.deleteShader(vertexShader); this.gl.deleteShader(fragmentShader); this.gl.deleteProgram(shaderProgram); throw new Error('Unable to link shader: ' + err); } this.gl.useProgram(shaderProgram); this.vertexPosLoc = this.getAttribLocation(shaderProgram, 'aVertexPos'); this.gl.enableVertexAttribArray(this.vertexPosLoc); this.textureCoordLoc = this.getAttribLocation(shaderProgram, 'aTextureCoord'); this.gl.enableVertexAttribArray(this.textureCoordLoc); this.viewportLoc = this.getUniformLocation(shaderProgram, 'uViewport'); this.translateLoc = this.getUniformLocation(shaderProgram, 'uTranslate'); this.samplerLoc = this.getUniformLocation(shaderProgram, 'uSampler'); } private compileShader(type: number, src: string): WebGLShader { const shader = this.gl.createShader(type); if (!shader) throw new Error('Unable to create shader'); this.gl.shaderSource(shader, src); this.gl.compileShader(shader); if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { const err = this.gl.getShaderInfoLog(shader); this.gl.deleteShader(shader); throw new Error('Unable to compile shader: ' + err); } return shader; } private getAttribLocation(program: WebGLProgram, name: string): number { const ret = this.gl.getAttribLocation(program, name); if (ret < 0) throw new Error("unable to get location of attribute '" + name + "'"); return ret; } private getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation { const ret = this.gl.getUniformLocation(program, name); if (!ret) throw new Error("unable to get location of uniform '" + name + "'"); return ret; } }