BorderLayer.ts 2.2 KB

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