planet-wars/frontend/www/webgl/texture.ts

107 lines
2.6 KiB
TypeScript
Raw Permalink Normal View History

2019-09-19 17:52:48 +02:00
import { Renderer } from "./renderer";
2019-09-16 21:18:01 +02:00
export class Texture {
texture: WebGLTexture;
2019-09-19 17:52:48 +02:00
width: number;
height: number;
2019-09-16 21:18:01 +02:00
loaded: boolean;
name: string;
2019-09-19 17:52:48 +02:00
static fromImage(
2019-09-16 21:18:01 +02:00
gl: WebGLRenderingContext,
path: string,
name: string,
2019-09-19 17:52:48 +02:00
): Texture {
const out = new Texture(gl, name);
const image = new Image();
image.onload = out.setImage.bind(out, gl, image);
image.onerror = error;
image.src = path;
return out;
}
static fromRenderer(
gl: WebGLRenderingContext,
name: string,
width: number,
height: number,
renderer: Renderer
): Texture {
const out = new Texture(gl, name);
out.width = width;
out.height = height;
gl.texImage2D(
gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0,
gl.RGBA, gl.UNSIGNED_BYTE, null);
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
const attachmentPoint = gl.COLOR_ATTACHMENT0;
gl.framebufferTexture2D(gl.FRAMEBUFFER, attachmentPoint, gl.TEXTURE_2D, out.texture, 0);
renderer.render(gl, fb, width, height);
out.loaded = true;
return out;
}
constructor(
gl: WebGLRenderingContext,
name: string,
2019-09-16 21:18:01 +02:00
) {
this.loaded = false;
this.name = name;
this.texture = gl.createTexture();
this.bind(gl);
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);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA,
gl.UNSIGNED_BYTE, new Uint8Array([255, 0, 0, 255]));
}
2019-09-19 17:52:48 +02:00
setImage(gl: WebGLRenderingContext, image: HTMLImageElement) {
2019-09-16 21:18:01 +02:00
this.bind(gl);
2019-09-19 17:52:48 +02:00
this.width = image.width;
this.height = image.height;
2019-09-16 21:18:01 +02:00
2019-09-19 17:52:48 +02:00
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
2019-09-16 21:18:01 +02:00
this.unbind(gl);
this.loaded = true;
}
bind(gl: WebGLRenderingContext, location=0) {
gl.activeTexture(gl.TEXTURE0 + location);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
}
unbind(gl: WebGLRenderingContext) {
gl.bindTexture(gl.TEXTURE_2D, null);
}
getWidth(): number {
2019-09-19 17:52:48 +02:00
return this.width;
2019-09-16 21:18:01 +02:00
}
getHeight(): number {
2019-09-19 17:52:48 +02:00
return this.height;
2019-09-16 21:18:01 +02:00
}
}
function error(e: any) {
console.error("IMAGE LOAD ERROR");
console.error(e);
}