UNPKG

@icanvas/components

Version:
71 lines (63 loc) 2.1 kB
import GAME from '@icanvas/core'; export default class Texture extends GAME.Component { texture = null; verticesBuffer = null; offsetVertices = 0; offsetUvs = 0; offsetTotal = 0; indexesBuffer = null; constructor(Key) { super(); this.setTexture(Key); } setTexture(Key) { let gl = GAME.Render.Context; let BaseTexture = GAME.Res.Image.Get(Key); this.width = BaseTexture.width; this.height = BaseTexture.height; this.texture = BaseTexture.texture; let array = new Float32Array(Math.max(BaseTexture.vertices.length, BaseTexture.uvs.length) * 2); for (let i = 0, l = (array.length / 4) | 0; i < l; i++) { array[i * 4] = BaseTexture.vertices[i * 2]; array[i * 4 + 1] = BaseTexture.vertices[i * 2 + 1]; array[i * 4 + 2] = BaseTexture.uvs[i * 2]; array[i * 4 + 3] = BaseTexture.uvs[i * 2 + 1]; } this.verticesBuffer = gl.GetBuffer(array, gl.ARRAY_BUFFER); this.offsetVertices = Float32Array.BYTES_PER_ELEMENT * 2; this.offsetUvs = Float32Array.BYTES_PER_ELEMENT * 2; this.offsetTotal = this.offsetVertices + this.offsetUvs; this.indexesBuffer = gl.GetBuffer(BaseTexture.indexes.Uint16Array, gl.ELEMENT_ARRAY_BUFFER); } size = new GAME.Math.Vector2(); get width() { return this.size.x; } set width(width) { this.size.x = width; } get height() { return this.size.y; } set height(height) { this.size.y = height; } anchorCenter(x = true, y = true) { if (x) this.anchor.x = this.size.x / 2; if (y) this.anchor.y = this.size.y / 2; return this; } setSize(x, y) { this.size.set(x, y); return this; } update(gl) { gl.bindBuffer(gl.ARRAY_BUFFER, this.verticesBuffer); gl.vertexAttribPointer(gl.Program.a_Position.id, 2, gl.FLOAT, false, this.offsetTotal, 0); gl.vertexAttribPointer(gl.Program.a_TexCoord.id, 2, gl.FLOAT, false, this.offsetTotal, this.offsetVertices); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.uniform1i(gl.Program.u_Sampler.id, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexesBuffer); gl.drawElements(gl.TRIANGLE_STRIP, this.indexesBuffer.buffer.length, gl.UNSIGNED_SHORT, 0); } }