BoxLayer.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { Color } from "../filler/common";
  2. import { fillRectangle } from "./2d"
  3. import { LayerAB, Scene } from "./Scene"
  4. import { createProgram, createShader } from "./utils"
  5. export class BoxLayer extends LayerAB {
  6. private vertexShaderCode = /*glsl*/ `
  7. attribute vec2 a_position;
  8. uniform mat4 u_matrix;
  9. void main() {
  10. gl_Position = u_matrix * vec4(a_position, 0, 1);
  11. }
  12. `;
  13. private fragmentShaderCode = /*glsl*/ `
  14. precision mediump float;
  15. uniform vec4 u_color;
  16. void main() {
  17. gl_FragColor = u_color;
  18. }
  19. `
  20. program: WebGLProgram
  21. aPositionLoc: number
  22. uMatrixLoc: WebGLUniformLocation
  23. uColorLoc: WebGLUniformLocation
  24. vertexBuffer: WebGLBuffer
  25. vertexArray = new Float32Array(12)
  26. colorArray: Float32Array
  27. constructor(
  28. public readonly scene: Scene,
  29. public readonly x: number,
  30. public readonly y: number,
  31. public readonly width: number,
  32. public readonly height: number,
  33. public readonly color: number = 0xffffffff, //abgr
  34. private fragmentShader: string | null = null
  35. ) {
  36. super()
  37. const gl = scene.gl;
  38. this.program = createProgram(gl,
  39. createShader(gl, gl.VERTEX_SHADER, this.vertexShaderCode)!,
  40. createShader(gl, gl.FRAGMENT_SHADER, fragmentShader || this.fragmentShaderCode)!)!
  41. this.aPositionLoc = gl.getAttribLocation(this.program, "a_position")
  42. this.uMatrixLoc = gl.getUniformLocation(this.program, "u_matrix")!
  43. this.uColorLoc = gl.getUniformLocation(this.program, "u_color")!
  44. fillRectangle(this.vertexArray, 0, x, y, width, height)
  45. this.vertexBuffer = gl.createBuffer()!;
  46. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  47. gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW);
  48. this.colorArray = new Color(color).toFloatArray()
  49. }
  50. override draw() {
  51. const gl = this.scene.gl;
  52. gl.useProgram(this.program);
  53. gl.enableVertexAttribArray(this.aPositionLoc);
  54. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  55. gl.vertexAttribPointer(this.aPositionLoc, 2, gl.FLOAT, false, 0, 0)
  56. gl.uniformMatrix4fv(this.uMatrixLoc, false, this.scene.drawMatrix)
  57. gl.uniform4fv(this.uColorLoc, this.colorArray)
  58. gl.drawArrays(gl.TRIANGLES, 0, 6);
  59. }
  60. toString(): string {
  61. return `BoxLayer()`
  62. }
  63. }