playcanvas
Version:
Open-source WebGL/WebGPU 3D engine for the web
68 lines (67 loc) • 2.31 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { DynamicBuffer } from "../dynamic-buffer.js";
class WebglDynamicBuffer extends DynamicBuffer {
/**
* @param {WebglGraphicsDevice} device - The graphics device.
* @param {number} size - The byte size of the buffer.
*/
constructor(device, size) {
super(device);
/**
* The GL buffer object (mirrors WebgpuDynamicBuffer.buffer). Created lazily on the first
* upload, so it is also recreated automatically after a context loss nulls it.
*
* @type {WebGLBuffer|null}
*/
__publicField(this, "bufferId", null);
/**
* CPU-side backing for the whole buffer, written to during the uniform buffer update and
* uploaded by {@link upload}.
*
* @type {Int32Array}
*/
__publicField(this, "storage");
/**
* Byte size of the buffer.
*
* @type {number}
*/
__publicField(this, "size");
this.size = size;
this.storage = new Int32Array(size / 4);
device._vram.ub += size;
}
destroy(device) {
if (this.bufferId) {
device.gl.deleteBuffer(this.bufferId);
this.bufferId = null;
}
device._vram.ub -= this.size;
}
/**
* Called when the rendering context is lost. The GL buffer is gone with the context, so drop
* the handle; the next upload recreates it. The CPU storage and pooling are preserved.
*/
loseContext() {
this.bufferId = null;
}
/**
* Upload the CPU backing to the GL buffer, creating the buffer on first use (or after a context
* loss). Uses `bufferData` (full respecify) so the driver orphans the previous storage - this
* avoids a pipeline stall when the buffer is reused while the previous frame's draws may still
* be reading it.
*/
upload() {
const gl = this.device.gl;
if (!this.bufferId) {
this.bufferId = gl.createBuffer();
}
gl.bindBuffer(gl.UNIFORM_BUFFER, this.bufferId);
gl.bufferData(gl.UNIFORM_BUFFER, this.storage, gl.STREAM_DRAW);
}
}
export {
WebglDynamicBuffer
};