Home Reference Source

cables_dev/cables/src/core/cgp/cgp_gpubuffer.js

  1. import { EventTarget } from "../eventtarget.js";
  2.  
  3. export default class GPUBuffer extends EventTarget
  4. {
  5. constructor(cgp, name, data = null, options = {})
  6. {
  7. super();
  8.  
  9. this.id = CABLES.shortId();
  10.  
  11. this._name = name;
  12. this.floatArr = null;
  13. this._gpuBuffer = null;
  14.  
  15. this.setData([0, 0, 0, 0]);
  16. this.needsUpdate = true;
  17. this._length = 0;
  18.  
  19. if (options.buffCfg)
  20. {
  21. this._buffCfg = options.buffCfg;
  22. }
  23.  
  24. if (data)
  25. this.setData(data);
  26.  
  27. if (options.length) this.setLength(options.length);
  28.  
  29. this.updateGpuBuffer(cgp);
  30. }
  31.  
  32. setData(d)
  33. {
  34. // console.log((new Error()).stack);
  35.  
  36. this.floatArr = new Float32Array(d);
  37. this.setLength(this.floatArr.length);
  38.  
  39. // console.log(this.name, this.floatArr);
  40. this.needsUpdate = true;
  41. }
  42.  
  43. setLength(s)
  44. {
  45. this._length = s;
  46. if (!this.floatArr || s != this.floatArr.length)
  47. {
  48. this.floatArr = new Float32Array(this._length);
  49. this.needsUpdate = true;
  50. }
  51. }
  52.  
  53. updateGpuBuffer(cgp)
  54. {
  55. if (cgp) this._cgp = cgp;
  56. if (!this._cgp || !this._cgp.device)
  57. {
  58. console.log("no cgp...", this._name, this._cgp);
  59. return;
  60. }
  61.  
  62. this._cgp.pushErrorScope("updateGpuBuffer");
  63. if (!this._gpuBuffer)
  64. {
  65. this._buffCfg = this._buffCfg || {};
  66. this._buffCfg.label = "gpuBuffer-" + this._name;
  67. if (!this._buffCfg.hasOwnProperty("size") && this.floatArr) this._buffCfg.size = this.floatArr.length * 4;
  68. this._buffCfg.usage = this._buffCfg.usage || (GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC);
  69.  
  70. this._gpuBuffer = this._cgp.device.createBuffer(this._buffCfg);
  71. }
  72.  
  73. // if (!isNaN(this.floatArr[0]))console.log("shit", this._name);
  74.  
  75. if (this.floatArr)
  76. this._cgp.device.queue.writeBuffer(
  77. this._gpuBuffer,
  78. 0,
  79. this.floatArr.buffer,
  80. this.floatArr.byteOffset,
  81. this.floatArr.byteLength
  82. );
  83.  
  84. // this._gpuBuffer.unmap();
  85.  
  86. this._cgp.popErrorScope();
  87.  
  88. this.needsUpdate = false;
  89. }
  90.  
  91. get name()
  92. {
  93. return this._name;
  94. }
  95.  
  96. get gpuBuffer()
  97. {
  98. if (!this._gpuBuffer || this.needsUpdate) this.updateGpuBuffer();
  99.  
  100. return this._gpuBuffer;
  101. }
  102.  
  103. get length()
  104. {
  105. return this._length;
  106. }
  107.  
  108. getSizeBytes()
  109. {
  110. return this.floatArr.length * 4;
  111. }
  112.  
  113. dispose()
  114. {
  115. // setTimeout(() =>
  116. // {
  117. // if (this._gpuBuffer) this._gpuBuffer.destroy();
  118. // }, 100);
  119. }
  120. }