vertex-array.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { Program } from './program';
  7. import { ElementsBuffer, AttributeBuffers } from './buffer';
  8. import { WebGLExtensions } from './extensions';
  9. import { idFactory } from '../../mol-util/id-factory';
  10. const getNextVertexArrayId = idFactory()
  11. function getVertexArray(extensions: WebGLExtensions): WebGLVertexArrayObject {
  12. const { vertexArrayObject } = extensions
  13. if (!vertexArrayObject) {
  14. throw new Error('VertexArrayObject not supported')
  15. }
  16. const vertexArray = vertexArrayObject.createVertexArray()
  17. if (!vertexArray) {
  18. throw new Error('Could not create WebGL vertex array')
  19. }
  20. return vertexArray
  21. }
  22. function getVertexArrayObject(extensions: WebGLExtensions) {
  23. const { vertexArrayObject } = extensions
  24. if (vertexArrayObject === null) {
  25. throw new Error('VertexArrayObject not supported')
  26. }
  27. return vertexArrayObject
  28. }
  29. export interface VertexArray {
  30. readonly id: number
  31. bind: () => void
  32. update: () => void
  33. reset: () => void
  34. destroy: () => void
  35. }
  36. export function createVertexArray(extensions: WebGLExtensions, program: Program, attributeBuffers: AttributeBuffers, elementsBuffer?: ElementsBuffer): VertexArray {
  37. const id = getNextVertexArrayId()
  38. let vertexArray = getVertexArray(extensions)
  39. let vertexArrayObject = getVertexArrayObject(extensions)
  40. function update() {
  41. vertexArrayObject.bindVertexArray(vertexArray)
  42. if (elementsBuffer) elementsBuffer.bind()
  43. program.bindAttributes(attributeBuffers)
  44. vertexArrayObject.bindVertexArray(null)
  45. }
  46. update()
  47. let destroyed = false
  48. return {
  49. id,
  50. bind: () => {
  51. vertexArrayObject.bindVertexArray(vertexArray)
  52. },
  53. update,
  54. reset: () => {
  55. vertexArray = getVertexArray(extensions)
  56. vertexArrayObject = getVertexArrayObject(extensions)
  57. update()
  58. },
  59. destroy: () => {
  60. if (destroyed) return
  61. vertexArrayObject.deleteVertexArray(vertexArray)
  62. destroyed = true
  63. }
  64. }
  65. }