UNPKG

p5

Version:

[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)

3,290 lines • 125 kB
import { B as EXCLUSION, Bt as REMOVE, Ht as REPLACE, O as DARKEST, Vt as REPEAT, W as FLOAT, bn as WEBGPU, ht as MIRROR, lt as LIGHTEST, pn as UNSIGNED_BYTE, qt as SCREEN, t as ADD, tn as SUBTRACT, u as BLEND, ut as LINEAR, vt as MULTIPLY, y as CLAMP, yt as NEAREST } from "../constants-DA50zLWL.js";
import { getStrokeDefs } from "../webgl/enums.js";
import { warnExperimental } from "../core/experimental.js";
import { DataType } from "../strands/ir_types.js";
import { wgslBackend } from "./strands_wgslBackend.js";
import { colorFragmentShader, colorVertexShader } from "./shaders/color.js";
import { lineFragmentShader, lineVertexShader } from "./shaders/line.js";
import { materialFragmentShader, materialVertexShader } from "./shaders/material.js";
import { fontFragmentShader, fontVertexShader } from "./shaders/font.js";
import { blitFragmentShader, blitVertexShader } from "./shaders/blit.js";
import { baseFilterFragmentShader, baseFilterVertexShader } from "./shaders/filters/base.js";
import { imageLightDiffusedFragmentShader, imageLightSpecularFragmentShader, imageLightVertexShader } from "./shaders/imageLight.js";
import { baseComputeShader } from "./shaders/compute.js";
//#region src/webgpu/p5.RendererWebGPU.js
/**
* @module 3D
* @submodule p5.strands
* @for p5
*/
const FRAME_STATE = {
	PENDING: 0,
	UNPROMOTED: 1,
	PROMOTED: 2
};
function rendererWebGPU(p5, fn) {
	const { lineDefs } = getStrokeDefs((n, v, t) => `const ${n}: ${t} = ${v};\n`);
	const { Renderer3D, Shader, Texture, MipmapTexture, Image, Camera, RGBA } = p5;
	const STORAGE_ARRAY_TYPES = {
		f32: Float32Array,
		u32: Uint32Array,
		i32: Int32Array
	};
	class StorageBuffer {
		constructor(buffer, size, renderer, schema = null, arrayType = Float32Array, length = null) {
			this._isStorageBuffer = true;
			this.buffer = buffer;
			this.size = size;
			this.length = length;
			this._renderer = renderer;
			this._schema = schema;
			this._arrayType = schema !== null ? Float32Array : arrayType;
			this._checkedArrayType = void 0;
		}
		/**
		* Updates the data in the buffer with new values. The new data must be in
		* the same format as the data originally passed to
		* <a href="#/p5/createStorage">`createStorage()`</a>.
		*
		* ```js example
		* let particles;
		* let computeShader;
		* let displayShader;
		* const numParticles = 100;
		*
		* async function setup() {
		*   await createCanvas(100, 100, WEBGPU);
		*   particles = createStorage(makeParticles(width / 2, height / 2));
		*   computeShader = buildComputeShader(simulate);
		*   displayShader = buildMaterialShader(display);
		*   describe('100 orange particles shooting outward.');
		* }
		*
		* function makeParticles(x, y) {
		*   let data = [];
		*   for (let i = 0; i < numParticles; i++) {
		*     let angle = (i / numParticles) * TWO_PI;
		*     let speed = random(0.5, 2);
		*     data.push({
		*       position: createVector(x, y),
		*       velocity: createVector(cos(angle) * speed, sin(angle) * speed),
		*     });
		*   }
		*   return data;
		* }
		*
		* function simulate() {
		*   let data = uniformStorage(particles);
		*   let idx = index.x;
		*   data[idx].position = data[idx].position + data[idx].velocity;
		* }
		*
		* function display() {
		*   let data = uniformStorage(particles);
		*   worldInputs.begin();
		*   let pos = data[instanceIndex].position;
		*   worldInputs.position.xy += pos - [width / 2, height / 2];
		*   worldInputs.end();
		* }
		*
		* function draw() {
		*   background(30);
		*   if (frameCount % 60 === 0) {
		*     particles.update(makeParticles(random(width), random(height)));
		*   }
		*   compute(computeShader, numParticles);
		*   noStroke();
		*   fill(255, 200, 50);
		*   shader(displayShader);
		*   instances(numParticles).sphere(2);
		* }
		* ```
		*
		* @method update
		* @for p5.StorageBuffer
		* @beta
		* @webgpu
		* @webgpuOnly
		* @param {Number[]|Float32Array|Uint32Array|Int32Array|Object[]} data The new data to write into the buffer.
		*/
		update(data) {
			const device = this._renderer.device;
			if (this._schema !== null) {
				if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== "object" || Array.isArray(data[0])) throw new Error("update() expects an array of objects matching the original struct format");
				const newSchema = this._renderer._inferStructSchema(data[0]);
				if (newSchema.structBody !== this._schema.structBody) throw new Error(`update() data structure doesn't match the original.\n  Expected: ${this._schema.structBody}\n  Got:      ${newSchema.structBody}`);
				const packed = this._renderer._packStructArray(data, this._schema);
				if (packed.byteLength > this.size) throw new Error(`update() data (${packed.byteLength} bytes) exceeds buffer size (${this.size} bytes)`);
				device.queue.writeBuffer(this.buffer, 0, packed);
			} else {
				const ArrayType = this._arrayType;
				let typedData;
				if (data instanceof ArrayType) typedData = data;
				else if (Array.isArray(data)) typedData = new ArrayType(data);
				else throw new Error(`update() expects a ${ArrayType.name} or array of numbers for this buffer`);
				if (typedData.byteLength > this.size) throw new Error(`update() data (${typedData.byteLength} bytes) exceeds buffer size (${this.size} bytes)`);
				device.queue.writeBuffer(this.buffer, 0, typedData);
			}
		}
		/**
		* Reads data from a storage buffer back into JavaScript.
		*
		* Copies data from the GPU to the CPU using a temporary buffer,
		* so it must be awaited. Returns a typed array (such as `Float32Array` or
		* `Uint32Array`) for number buffers, or an array of plain objects for
		* struct buffers.
		*
		* Note: This is a GPU -> CPU read, so calling it often (like every frame)
		* can be slow.
		*
		* ```js example
		* let data;
		* let computeShader;
		*
		* async function setup() {
		*   await createCanvas(100, 100, WEBGPU);
		*
		*   data = createStorage(new Float32Array([1, 2, 3, 4]));
		*   computeShader = buildComputeShader(doubleValues);
		*   compute(computeShader, 4);
		*
		*   let result = await data.read();
		*   // result is Float32Array [2, 4, 6, 8]
		*   for (let i = 0; i < result.length; i++) {
		*     print(result[i]);
		*   }
		*   describe('Prints the values 2, 4, 6, 8 to the console.');
		* }
		*
		* function doubleValues() {
		*   let d = uniformStorage(data);
		*   let idx = index.x;
		*   d[idx] = d[idx] * 2;
		* }
		* ```
		*
		* While p5.strands is still growing, there may be WGSL features it doesn't
		* cover yet. You can still reach for them by writing WGSL directly, and the
		* buffer will read back as the right kind of typed array. Atomics are one
		* example: WGSL only allows them on `u32` and `i32`, so a buffer used as
		* `array<atomic<u32>>` should be created with a `Uint32Array`.
		*
		* ```js example
		* let data;
		* let computeShader;
		*
		* async function setup() {
		*   await createCanvas(100, 100, WEBGPU);
		*
		*   data = createStorage(new Uint32Array([10, 20, 30, 40]));
		*   computeShader = buildComputeShader({
		*     computeDeclarations: `
		*       @group(0) @binding(1) var<storage, read_write> counts: array<atomic<u32>>;
		*     `,
		*     'void iteration': `(index: vec3<i32>) {
		*       let idx = index.x;
		*       atomicAdd(&counts[idx], 5u);
		*     }`
		*   });
		*   computeShader.setUniform('counts', data);
		*   compute(computeShader, 4);
		*
		*   let result = await data.read();
		*   // result is Uint32Array [15, 25, 35, 45]
		*   for (let i = 0; i < result.length; i++) {
		*     print(result[i]);
		*   }
		*   describe('Prints the values 15, 25, 35, 45 to the console.');
		* }
		* ```
		*
		* @method read
		* @for p5.StorageBuffer
		* @beta
		* @webgpu
		* @webgpuOnly
		* @returns {Promise<Float32Array|Uint32Array|Int32Array|Object[]>}
		*/
		async read() {
			const device = this._renderer.device;
			this._renderer.flushDraw();
			const stagingBuffer = device.createBuffer({
				size: this.size,
				usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
			});
			const commandEncoder = device.createCommandEncoder();
			commandEncoder.copyBufferToBuffer(this.buffer, 0, stagingBuffer, 0, this.size);
			device.queue.submit([commandEncoder.finish()]);
			await stagingBuffer.mapAsync(GPUMapMode.READ, 0, this.size);
			const mappedRange = stagingBuffer.getMappedRange(0, this.size);
			const ArrayType = this._arrayType;
			const rawCopy = new ArrayType(mappedRange.byteLength / ArrayType.BYTES_PER_ELEMENT);
			rawCopy.set(new ArrayType(mappedRange));
			stagingBuffer.unmap();
			stagingBuffer.destroy();
			if (this._schema !== null) return this._renderer._unpackStructArray(rawCopy, this._schema);
			return rawCopy;
		}
		/**
		* Updates a single element in the buffer at a given index. Use this
		* when only a small number of elements need to change. If you need to
		* replace all the data at once, use
		* <a href="#/p5.StorageBuffer/update">`update()`</a> instead.
		*
		* ```js
		* let buf;
		*
		* async function setup() {
		*   await createCanvas(100, 100, WEBGPU);
		*
		*   // Float buffer: update one value by index
		*   buf = createStorage(new Float32Array([1, 2, 3, 4]));
		*   buf.set(2, 9.5); // only index 2 changes → [1, 2, 9.5, 4]
		*
		*   let result = await buf.read();
		*   print(result[2]); // 9.5
		*   describe('Prints 9.5 to the console.');
		* }
		* ```
		*
		* ```js
		* let particles;
		* const numParticles = 100;
		*
		* async function setup() {
		*   await createCanvas(100, 100, WEBGPU);
		*   particles = createStorage(makeParticles());
		*
		*   // Replace particle 42 without touching the others
		*   particles.set(42, {
		*     position: createVector(0, 0),
		*     velocity: createVector(1, 0),
		*   });
		*
		*   // Read back to confirm the update
		*   let result = await particles.read();
		*   print(result[42].position.x, result[42].position.y); // 0, 0
		*   describe('Prints the position of particle 42 after updating it.');
		* }
		*
		* function makeParticles() {
		*   let data = [];
		*   for (let i = 0; i < numParticles; i++) {
		*     data.push({
		*       position: createVector(random(width), random(height)),
		*       velocity: createVector(random(-1, 1), random(-1, 1)),
		*     });
		*   }
		*   return data;
		* }
		* ```
		*
		* @method set
		* @for p5.StorageBuffer
		* @beta
		* @webgpu
		* @webgpuOnly
		* @param {Number} index The zero-based index of the element to update.
		* @param {Number|Object} value The new value. Pass a number for float
		*   buffers, or a plain object matching the original struct layout for
		*   struct buffers.
		*/
		set(index, value) {
			const device = this._renderer.device;
			if (this._schema !== null) {
				if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("set() expects a plain object matching the original struct format for this buffer");
				const { stride } = this._schema;
				const byteOffset = index * stride;
				if (byteOffset + stride > this.size) throw new Error(`set() index ${index} is out of bounds for this buffer (buffer holds ${Math.floor(this.size / stride)} elements)`);
				const packed = this._renderer._packStructArray([value], this._schema);
				device.queue.writeBuffer(this.buffer, byteOffset, packed.buffer, 0, stride);
			} else {
				if (typeof value !== "number") throw new Error("set() expects a number for this float buffer");
				const byteOffset = index * 4;
				if (byteOffset + 4 > this.size) throw new Error(`set() index ${index} is out of bounds for this buffer (buffer holds ${Math.floor(this.size / 4)} floats)`);
				device.queue.writeBuffer(this.buffer, byteOffset, new Float32Array([value]));
			}
		}
	}
	/**
	* A block of data that shaders can read from, and compute shaders can also
	* write to. This is only available in WebGPU mode.
	*
	* Note: <a href="#/p5/createStorage">`createStorage()`</a> is the recommended
	* way to create an instance of this class.
	*
	* @class p5.StorageBuffer
	* @beta
	* @webgpu
	* @webgpuOnly
	*/
	p5.StorageBuffer = StorageBuffer;
	class StorageList {
		constructor(buffer, lengthOffset, maxCapacity, renderer, schema = null, initialCount = 0) {
			this._isStorageList = true;
			this.buffer = buffer;
			this._lengthOffset = lengthOffset;
			this.maxCapacity = maxCapacity;
			this._renderer = renderer;
			this._schema = schema;
			this._stride = schema ? schema.stride : 4;
			this._cpuLength = initialCount;
		}
		/**
		* Empties the list.
		*
		* @method clear
		* @for p5.StorageList
		* @beta
		* @webgpu
		* @webgpuOnly
		*/
		clear() {
			this._cpuLength = 0;
			const encoder = this._renderer.device.createCommandEncoder();
			encoder.clearBuffer(this.buffer, this._lengthOffset, 4);
			this._renderer._pendingCommandEncoders.push(encoder.finish());
			this._renderer._hasPendingDraws = true;
		}
		/**
		* Appends one element to the list. This can be called from your sketch's
		* JavaScript or from within a <a href="#/p5/buildComputeShader">compute shader.</a> Use this to seed a list
		* before any compute shaders run. Calling `push()` after a GPU compute pass
		* that has already modified the list will produce undefined ordering.
		*
		* For a float list, pass a number. For a struct list, pass a plain object
		* whose properties match the schema.
		*
		* ```js example
		* let positions;
		* let drawShader;
		* const COUNT = 5;
		*
		* async function setup() {
		*   await createCanvas(200, 200, WEBGPU);
		*
		*   positions = createStorageList(COUNT, { pos: createVector(0, 0) });
		*   for (let i = 0; i < COUNT; i++) {
		*     positions.push({
		*       pos: createVector(
		*         random(-1, 1) * width / 2,
		*         random(-1, 1) * height / 2
		*       )
		*     });
		*   }
		*
		*   drawShader = buildMaterialShader(() => {
		*     let data = uniformStorage(positions);
		*     worldInputs.begin();
		*     worldInputs.position.xy += data[instanceIndex].pos;
		*     worldInputs.end();
		*   });
		*
		*   describe('Five circles placed at random positions.');
		* }
		*
		* function draw() {
		*   background(220);
		*   noStroke();
		*   shader(drawShader);
		*   instances(positions).circle(0, 0, 20);
		* }
		* ```
		*
		* You can also use `push()` from compute shaders. This approach can often
		* be faster as no data needs to transfer from the CPU to the GPU.
		*
		* ```js example
		* let particles, nextParticles;
		* let removeOld, emitNew;
		* let drawParticles;
		* const MAX_PARTICLES = 300;
		*
		* async function setup() {
		*   await createCanvas(200, 200, WEBGPU);
		*
		*   const schema = { position: createVector(0, 0), velocity: createVector(0, 0), life: 0 };
		*   particles = createStorageList(MAX_PARTICLES, schema);
		*   nextParticles = createStorageList(MAX_PARTICLES, schema);
		*
		*   // Seed an initial burst from JavaScript so something is visible on frame 1.
		*   for (let i = 0; i < 20; i++) {
		*     let angle = random(TWO_PI);
		*     particles.push({
		*       position: createVector(0, 0),
		*       velocity: createVector(cos(angle) * 2, sin(angle) * 2 - 2.5),
		*       life: random(0.5, 1.0)
		*     });
		*   }
		*
		*   removeOld = buildComputeShader(() => {
		*     let src = uniformStorage(() => particles);
		*     let dst = uniformStorage(() => nextParticles);
		*     if (index.x < src.length) {
		*       let p = src[index.x];
		*       p.velocity.y += 0.08;
		*       p.position += p.velocity;
		*       p.life -= 0.02;
		*       if (p.life > 0) {
		*         dst.push(p);
		*       }
		*     }
		*   });
		*
		*   emitNew = buildComputeShader(() => {
		*     let dst = uniformStorage(() => nextParticles);
		*     let angle = random() * TWO_PI;
		*     dst.push({
		*       position: [mouseX, mouseY] - [width, height] / 2,
		*       velocity: [cos(angle), sin(angle) - 2.5],
		*       life: 1.0
		*     });
		*   });
		*
		*   drawParticles = buildMaterialShader(() => {
		*     let particleData = uniformStorage(() => particles);
		*     let p = particleData[instanceIndex];
		*     worldInputs.begin();
		*     worldInputs.position.xy += p.position;
		*     worldInputs.end();
		*     finalColor.begin();
		*     finalColor.set([1, p.life * 0.4, 0, p.life]);
		*     finalColor.end();
		*   });
		*
		*   describe('Orange particles emitting from the cursor, falling with gravity.');
		* }
		*
		* function draw() {
		*   background(0);
		*   noStroke();
		*
		*   nextParticles.clear();
		*   compute(removeOld, MAX_PARTICLES);
		*   compute(emitNew, 5);
		*   [particles, nextParticles] = [nextParticles, particles];
		*
		*   shader(drawParticles);
		*   blendMode(ADD);
		*   instances(particles).circle(0, 0, 4);
		* }
		* ```
		*
		* @method push
		* @for p5.StorageList
		* @beta
		* @webgpu
		* @webgpuOnly
		* @param {Number|Object} element A number for float lists, or a plain object
		*   matching the list's schema for struct lists.
		*/
		push(element) {
			if (this._cpuLength >= this.maxCapacity) throw new Error(`StorageList is full (maxCapacity: ${this.maxCapacity})`);
			const device = this._renderer.device;
			let packed;
			if (this._schema) packed = this._renderer._packStructArray([element], this._schema);
			else {
				if (typeof element !== "number") throw new Error("Float StorageList.push() expects a number");
				packed = new Float32Array([element]);
			}
			device.queue.writeBuffer(this.buffer, this._cpuLength * this._stride, packed);
			this._cpuLength++;
			device.queue.writeBuffer(this.buffer, this._lengthOffset, new Int32Array([this._cpuLength]));
		}
		/**
		* Replaces the contents of the list with new data from JavaScript,
		* updating the element count to match.
		*
		* For a list of numbers, `update` takes in an array of numbers (or
		* a `Float32Array`.) For a list of objects, pass an array of plain
		* objects with the same properties present as when you created the list.
		*
		* @method update
		* @for p5.StorageList
		* @beta
		* @webgpu
		* @webgpuOnly
		* @param {Number[]|Float32Array|Object[]} data The new data to write.
		*/
		update(data) {
			if (this._schema) {
				if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== "object") throw new Error("update() expects an array of objects matching the list schema");
				if (data.length > this.maxCapacity) throw new Error(`update() data length ${data.length} exceeds maxCapacity ${this.maxCapacity}`);
				const packed = this._renderer._packStructArray(data, this._schema);
				this._renderer.device.queue.writeBuffer(this.buffer, 0, packed);
			} else {
				let typedData = data instanceof Float32Array ? data : new Float32Array(data);
				if (typedData.length > this.maxCapacity) throw new Error(`update() data length ${typedData.length} exceeds maxCapacity ${this.maxCapacity}`);
				this._renderer.device.queue.writeBuffer(this.buffer, 0, typedData);
			}
			this._cpuLength = data.length;
			this._renderer.device.queue.writeBuffer(this.buffer, this._lengthOffset, new Int32Array([this._cpuLength]));
		}
		/**
		* Reads the current contents of the list back to JavaScript.
		*
		* It returns a `Float32Array` for float lists, or an array of plain objects
		* for struct lists.
		*
		* Note: This is a GPU-to-CPU read. Calling it frequently can be slow.
		*
		* @method read
		* @for p5.StorageList
		* @beta
		* @webgpu
		* @webgpuOnly
		* @returns {Promise<Float32Array|Object[]>}
		*/
		async read() {
			const device = this._renderer.device;
			this._renderer.flushDraw();
			const totalSize = this.buffer.size;
			const stagingBuffer = device.createBuffer({
				size: totalSize,
				usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
			});
			const encoder = device.createCommandEncoder();
			encoder.copyBufferToBuffer(this.buffer, 0, stagingBuffer, 0, totalSize);
			device.queue.submit([encoder.finish()]);
			await stagingBuffer.mapAsync(GPUMapMode.READ);
			const mapped = stagingBuffer.getMappedRange();
			const length = Math.min(new DataView(mapped).getInt32(this._lengthOffset, true), this.maxCapacity);
			let result;
			const stride = this._schema ? this._schema.stride : 4;
			if (this._schema) {
				const byteLen = length * stride;
				const rawCopy = new Float32Array(byteLen / 4);
				if (byteLen > 0) rawCopy.set(new Float32Array(mapped, 0, byteLen / 4));
				result = this._renderer._unpackStructArray(rawCopy, this._schema);
			} else {
				const rawCopy = new Float32Array(length);
				if (length > 0) rawCopy.set(new Float32Array(mapped, 0, length));
				result = rawCopy;
			}
			stagingBuffer.unmap();
			stagingBuffer.destroy();
			return result;
		}
	}
	/**
	* A variable-length buffer that compute can push to and pop from, like
	* a JavaScript array.
	*
	* This is only available in WebGPU mode.
	*
	* Note: <a href="#/p5/createStorageList">`createStorageList()`</a> is the
	* recommended way to create an instance of this class.
	*
	* @class p5.StorageList
	* @beta
	* @webgpu
	* @webgpuOnly
	*/
	p5.StorageList = StorageList;
	class RendererWebGPU extends Renderer3D {
		constructor(pInst, w, h, isMainCanvas, elt) {
			super(pInst, w, h, isMainCanvas, elt);
			this.rendererType = WEBGPU;
			this._pInst.rendererType = this.rendererType;
			warnExperimental(p5, pInst, "webgpu");
			this.activeRenderPass = null;
			this.activeRenderPassEncoder = null;
			this.activeShaderOptions = null;
			this.activeShader = null;
			this.samplers = /* @__PURE__ */ new Map();
			this.uniformBufferAlignment = 256;
			this.activeUniformBuffers = [];
			this.currentUniformBuffer = void 0;
			this.uniformBufferPool = [];
			this.resettingUniformBuffers = [];
			this.dynamicEntryOffsets = /* @__PURE__ */ new Uint32Array(64);
			this.currentCanvasColorTexture = null;
			this.currentCanvasColorTextureView = null;
			this.pixelReadBuffer = null;
			this.pixelReadBufferSize = 0;
			this.strandsBackend = wgslBackend;
			this._shadersWithPools = [];
			this._geometriesWithPools = [];
			this._hasPendingDraws = false;
			this._pendingCommandEncoders = [];
			this._postSubmitCallbacks = [];
			this._retiredBuffers = [];
			this._storageBuffers = /* @__PURE__ */ new Set();
			this._tempBuffers = [];
			this._pixelReadCanvas = null;
			this._pixelReadCtx = null;
			this.mainFramebuffer = null;
			this._frameState = FRAME_STATE.PENDING;
			this.finalCamera = new Camera(this);
			this.finalCamera._computeCameraDefaultSettings();
			this.finalCamera._setDefaultCamera();
			this.depthFormat = "depth24plus-stencil8";
			this.depthTexture = null;
			this.depthTextureView = null;
		}
		async setupContext() {
			this._setAttributeDefaults(this._pInst);
			await this._initContext();
		}
		_setAttributeDefaults(pInst) {
			const defaults = {
				forceFallbackAdapter: false,
				powerPreference: "high-performance"
			};
			if (pInst._webgpuAttributes === null) pInst._webgpuAttributes = defaults;
			else pInst._webgpuAttributes = Object.assign(defaults, pInst._webgpuAttributes);
		}
		async _initContext() {
			if (!navigator.gpu) throw new Error("WebGPU is not supported by this browser.");
			this.adapter = await navigator.gpu.requestAdapter(this._webgpuAttributes);
			if (!this.adapter) throw new Error("No compatible GPU could be found for WebGPU on this device.");
			this.device = await this.adapter.requestDevice({ requiredFeatures: ["depth32float-stencil8"] }).catch(() => null);
			if (!this.device) throw new Error("WebGPU is available, but a WebGPU device could not be created on this system.");
			this.drawingContext = this.canvas.getContext("webgpu");
			if (!this.drawingContext) throw new Error("WebGPU is available, but the drawing context could not be created for this canvas.");
			this.queue = this.device.queue;
			this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
			this.drawingContext.configure({
				device: this.device,
				format: this.presentationFormat,
				usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
				alphaMode: "premultiplied"
			});
			this.mainFramebuffer = this.createFramebuffer({ _useCanvasFormat: true });
			this._updateSize();
			this._update();
			this.flushDraw();
		}
		async _setAttributes(key, value) {
			if (typeof this._pInst._webgpuAttributes === "undefined") {
				console.log("You are trying to use setAttributes on a p5.Graphics object that does not use a WebGPU renderer.");
				return;
			}
			let unchanged = true;
			if (typeof value !== "undefined") {
				if (this._pInst._webgpuAttributes === null) this._pInst._webgpuAttributes = {};
				if (this._pInst._webgpuAttributes[key] !== value) {
					this._pInst._webgpuAttributes[key] = value;
					unchanged = false;
				}
			} else if (key instanceof Object) {
				if (this._pInst._webgpuAttributes !== key) {
					this._pInst._webgpuAttributes = key;
					unchanged = false;
				}
			}
			if (!this.isP3D || unchanged) return;
			if (!this._pInst._setupDone) {
				if (this.geometryBufferCache.numCached() > 0) {
					p5.FES.log`Sorry, Could not set the attributes, you need to call setAttributes() before calling the other drawing methods in setup()`();
					return;
				}
			}
			await this._resetContext(null, null, RendererWebGPU);
			if (this.states.curCamera) this.states.curCamera._renderer = this._renderer;
		}
		_updateSize() {
			if (!this.device || !this.depthFormat) return;
			if (this.depthTexture && this.depthTexture.destroy) {
				this.flushDraw();
				const textureToDestroy = this.depthTexture;
				this._postSubmitCallbacks.push(() => textureToDestroy.destroy());
				this.depthTextureView = null;
			}
			this.depthTexture = this.device.createTexture({
				size: {
					width: Math.ceil(this.width * this._pixelDensity),
					height: Math.ceil(this.height * this._pixelDensity),
					depthOrArrayLayers: 1
				},
				format: this.depthFormat,
				usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
			});
			this.depthTextureView = this.depthTexture.createView();
			this.clear();
		}
		_getCanvasColorTextureView() {
			const canvasTexture = this.drawingContext.getCurrentTexture();
			if (this.currentCanvasColorTexture !== canvasTexture) {
				this.currentCanvasColorTexture = canvasTexture;
				this.currentCanvasColorTextureView = canvasTexture.createView();
			}
			return this.currentCanvasColorTextureView;
		}
		_beginActiveRenderPass() {
			if (this.activeRenderPass) return;
			const activeFramebuffer = this.activeFramebuffer();
			const colorAttachment = {
				view: activeFramebuffer ? activeFramebuffer.aaColorTexture ? activeFramebuffer.aaColorTextureView : activeFramebuffer.colorTextureView : this._getCanvasColorTextureView(),
				loadOp: "load",
				storeOp: "store",
				resolveTarget: activeFramebuffer && activeFramebuffer.aaColorTexture ? activeFramebuffer.colorTextureView : void 0
			};
			const depthTextureView = activeFramebuffer ? activeFramebuffer.aaDepthTexture ? activeFramebuffer.aaDepthTextureView : activeFramebuffer.depthTextureView : this.depthTextureView;
			const renderPassDescriptor = {
				colorAttachments: [colorAttachment],
				depthStencilAttachment: depthTextureView ? {
					view: depthTextureView,
					depthLoadOp: "load",
					depthStoreOp: "store",
					depthClearValue: 1,
					stencilLoadOp: "load",
					stencilStoreOp: "store",
					depthReadOnly: false,
					stencilReadOnly: false
				} : void 0
			};
			const commandEncoder = this.device.createCommandEncoder();
			const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
			this.activeRenderPassEncoder = commandEncoder;
			this.activeRenderPass = passEncoder;
		}
		_finishActiveRenderPass() {
			if (!this.activeRenderPass) return;
			const commandEncoder = this.activeRenderPassEncoder;
			this.activeRenderPass.end();
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this.activeRenderPassEncoder = null;
			this.activeRenderPass = null;
			this.activeShader = null;
			this.activeShaderOptions = null;
		}
		clear(...args) {
			if (!this.device || !this.drawingContext) return;
			const _r = args[0] || 0;
			const _g = args[1] || 0;
			const _b = args[2] || 0;
			const _a = args[3] || 0;
			if (this._frameState !== FRAME_STATE.PROMOTED && !this.activeFramebuffer()) {
				if (this._pInst.frameCount > 0) this._frameState = FRAME_STATE.UNPROMOTED;
				else this._promoteToFramebufferWithoutCopy();
			}
			this._finishActiveRenderPass();
			const commandEncoder = this.device.createCommandEncoder();
			const activeFramebuffer = this.activeFramebuffer();
			const colorAttachment = {
				view: activeFramebuffer ? activeFramebuffer.aaColorTexture ? activeFramebuffer.aaColorTextureView : activeFramebuffer.colorTextureView : this._getCanvasColorTextureView(),
				clearValue: {
					r: _r * _a,
					g: _g * _a,
					b: _b * _a,
					a: _a
				},
				loadOp: "clear",
				storeOp: "store",
				resolveTarget: activeFramebuffer && activeFramebuffer.aaColorTexture ? activeFramebuffer.colorTextureView : void 0
			};
			const depthTextureView = activeFramebuffer ? activeFramebuffer.aaDepthTexture ? activeFramebuffer.aaDepthTextureView : activeFramebuffer.depthTextureView : this.depthTextureView;
			const depthAttachment = depthTextureView ? {
				view: depthTextureView,
				depthClearValue: 1,
				depthLoadOp: "clear",
				depthStoreOp: "store",
				stencilLoadOp: "load",
				stencilStoreOp: "store"
			} : void 0;
			const renderPassDescriptor = {
				colorAttachments: [colorAttachment],
				...depthAttachment ? { depthStencilAttachment: depthAttachment } : {}
			};
			commandEncoder.beginRenderPass(renderPassDescriptor).end();
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this._hasPendingDraws = true;
		}
		/**
		* Resets all depth information so that nothing previously drawn will
		* occlude anything subsequently drawn.
		*/
		clearDepth(depth = 1) {
			if (!this.device || !this.depthTextureView) return;
			this._finishActiveRenderPass();
			const commandEncoder = this.device.createCommandEncoder();
			const activeFramebuffer = this.activeFramebuffer();
			const depthTextureView = activeFramebuffer ? activeFramebuffer.aaDepthTexture ? activeFramebuffer.aaDepthTextureView : activeFramebuffer.depthTextureView : this.depthTextureView;
			if (!depthTextureView) return;
			const renderPassDescriptor = {
				colorAttachments: [],
				depthStencilAttachment: {
					view: depthTextureView,
					depthClearValue: depth,
					depthLoadOp: "clear",
					depthStoreOp: "store",
					stencilLoadOp: "load",
					stencilStoreOp: "store"
				}
			};
			commandEncoder.beginRenderPass(renderPassDescriptor).end();
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this._hasPendingDraws = true;
		}
		_prepareBuffer(renderBuffer, geometry, shader) {
			const attr = shader.attributes[renderBuffer.attr];
			if (!attr) return;
			const { src, dst, size, map } = renderBuffer;
			const device = this.device;
			const buffers = this._getOrMakeCachedBuffers(geometry);
			let srcData = geometry[src];
			if (!srcData || srcData.length === 0) {
				if (renderBuffer.default) {
					srcData = geometry[src] = renderBuffer.default(geometry);
					srcData.isDefault = true;
				} else return;
			}
			if (!buffers[dst] || geometry.dirtyFlags[src] !== false) {
				const raw = map ? map(srcData) : srcData;
				const typed = this._normalizeBufferData(raw, Float32Array);
				const pooledBufferInfo = this._getVertexBufferFromPool(geometry, dst, typed.byteLength);
				const dataCopy = new typed.constructor(typed);
				pooledBufferInfo.dataCopy = dataCopy;
				device.queue.writeBuffer(pooledBufferInfo.buffer, 0, dataCopy);
				buffers[dst] = pooledBufferInfo.buffer;
				geometry.dirtyFlags[src] = false;
			}
			shader.enableAttrib(attr, size);
		}
		_disableRemainingAttributes(shader) {}
		_enableAttrib(attr) {
			const loc = attr.location;
			if (!this.registerEnabled.has(loc)) this.registerEnabled.add(loc);
		}
		_ensureGeometryBuffers(buffers, indices, indexType) {
			if (!indices) return;
			const buffer = this.device.createBuffer({
				size: Math.ceil(indices.length * indexType.BYTES_PER_ELEMENT / 4) * 4,
				usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
				mappedAtCreation: true
			});
			new indexType(buffer.getMappedRange()).set(indices);
			buffer.unmap();
			buffers.indexBuffer = buffer;
			buffers.indexBufferType = indexType === Uint32Array ? "uint32" : "uint16";
		}
		_freeBuffers(buffers) {
			const destroyIfExists = (buf) => {
				if (buf && buf.destroy) buf.destroy();
			};
			destroyIfExists(buffers.indexBuffer);
			const freeDefs = (defs) => {
				for (const def of defs) {
					destroyIfExists(buffers[def.dst]);
					buffers[def.dst] = null;
				}
			};
			freeDefs(this.buffers.stroke);
			freeDefs(this.buffers.fill);
			freeDefs(this.buffers.user);
		}
		_getValidSampleCount(requestedCount) {
			if (requestedCount <= 1) return 1;
			if (requestedCount <= 4) return 4;
			return 4;
		}
		_shaderOptions({ mode, compute, workgroupSize }) {
			if (compute) return {
				compute: true,
				workgroupSize
			};
			const activeFramebuffer = this.activeFramebuffer();
			const format = activeFramebuffer ? this._getWebGPUColorFormat(activeFramebuffer) : this.presentationFormat;
			const requestedSampleCount = activeFramebuffer ? activeFramebuffer.antialias ? activeFramebuffer.antialiasSamples : 1 : 1;
			const sampleCount = this._getValidSampleCount(requestedSampleCount);
			const depthFormat = activeFramebuffer ? activeFramebuffer.useDepth ? this._getWebGPUDepthFormat(activeFramebuffer) : void 0 : this.depthFormat;
			const drawTarget = this.drawTarget();
			const clipping = this._clipping;
			const clipApplied = drawTarget._isClipApplied;
			return {
				topology: mode === 5 ? "triangle-strip" : "triangle-list",
				blendMode: this.states.curBlendMode,
				sampleCount,
				format,
				depthFormat,
				clipping,
				clipApplied
			};
		}
		_shaderOptionsDifferent(newOptions) {
			if (!this.activeShaderOptions) return true;
			for (const key in this.activeShaderOptions) if (this.activeShaderOptions[key] !== newOptions[key]) return true;
			return false;
		}
		_initShader(shader) {
			const device = this.device;
			if (shader.shaderType === "compute") {
				shader.computeModule = device.createShaderModule({ code: shader.computeSrc() });
				shader._computePipelineCache = null;
				shader._workgroupSize = null;
				shader.getPipeline = ({ workgroupSize }) => {
					if (!shader._computePipelineCache) {
						shader._computePipelineCache = device.createComputePipeline({
							layout: shader._pipelineLayout,
							compute: {
								module: shader.computeModule,
								entryPoint: "main"
							}
						});
						shader._workgroupSize = workgroupSize;
					}
					return shader._computePipelineCache;
				};
				return;
			}
			shader.vertModule = device.createShaderModule({ code: shader.vertSrc() });
			shader.fragModule = device.createShaderModule({ code: shader.fragSrc() });
			shader._pipelineCache = /* @__PURE__ */ new Map();
			shader.getPipeline = ({ topology, blendMode, sampleCount, format, depthFormat, clipping, clipApplied }) => {
				const key = `${topology}_${blendMode}_${sampleCount}_${format}_${depthFormat}_${clipping}_${clipApplied}`;
				if (!shader._pipelineCache.has(key)) {
					const pipeline = device.createRenderPipeline({
						layout: shader._pipelineLayout,
						vertex: {
							module: shader.vertModule,
							entryPoint: "main",
							buffers: this._getVertexLayout(shader)
						},
						fragment: {
							module: shader.fragModule,
							entryPoint: "main",
							targets: [{
								format,
								blend: this._getBlendState(blendMode)
							}]
						},
						primitive: { topology },
						multisample: { count: sampleCount },
						...depthFormat ? { depthStencil: {
							format: depthFormat,
							depthWriteEnabled: !clipping,
							depthCompare: "less-equal",
							stencilFront: {
								compare: clipping ? "always" : clipApplied ? "not-equal" : "always",
								failOp: "keep",
								depthFailOp: "keep",
								passOp: clipping ? "replace" : "keep"
							},
							stencilBack: {
								compare: clipping ? "always" : clipApplied ? "not-equal" : "always",
								failOp: "keep",
								depthFailOp: "keep",
								passOp: clipping ? "replace" : "keep"
							},
							stencilReadMask: 255,
							stencilWriteMask: clipping ? 255 : 0
						} } : {}
					});
					shader._pipelineCache.set(key, pipeline);
				}
				return shader._pipelineCache.get(key);
			};
		}
		_finalizeShader(shader) {
			shader._uniformBufferGroups = [];
			shader.buffersDirty = /* @__PURE__ */ new Set();
			for (const group of shader._uniformGroups) {
				const groupUniforms = Object.values(group.uniforms);
				const rawSize = Math.max(0, ...groupUniforms.map((u) => u.offsetEnd));
				const alignedSize = Math.ceil(rawSize / 16) * 16;
				shader._uniformBufferGroups.push({
					group: group.group,
					binding: group.binding,
					cacheKey: group.group * 1e3 + group.binding,
					varName: group.varName,
					structType: group.structType,
					uniforms: groupUniforms,
					size: alignedSize,
					bufferPool: [],
					nextBufferPool: [],
					dynamic: groupUniforms.some((u) => u.name.startsWith("uModel")),
					buffersInUse: /* @__PURE__ */ new Set(),
					currentBuffer: null
				});
			}
			this._shadersWithPools.push(shader);
			const bindGroupLayouts = /* @__PURE__ */ new Map();
			const groupEntries = /* @__PURE__ */ new Map();
			const structEntries = /* @__PURE__ */ new Map();
			for (const bufferGroup of shader._uniformBufferGroups) {
				const entries = structEntries.get(bufferGroup.group) || [];
				entries.push({
					bufferGroup,
					binding: bufferGroup.binding,
					visibility: shader.shaderType === "compute" ? GPUShaderStage.COMPUTE : GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
					buffer: {
						type: "uniform",
						hasDynamicOffset: bufferGroup.dynamic
					}
				});
				structEntries.set(bufferGroup.group, entries);
			}
			for (const [group, entries] of structEntries.entries()) {
				entries.sort((a, b) => a.binding - b.binding);
				groupEntries.set(group, entries);
			}
			for (const sampler of shader.samplers) {
				const group = sampler.group;
				const entries = groupEntries.get(group) || [];
				if (!["sampler", "texture_2d<f32>"].includes(sampler.type)) throw new Error(`Unsupported texture type: ${sampler.type}`);
				entries.push({
					binding: sampler.binding,
					visibility: sampler.visibility,
					sampler: sampler.type === "sampler" ? { type: "filtering" } : void 0,
					texture: sampler.type === "texture_2d<f32>" ? {
						sampleType: "float",
						viewDimension: "2d"
					} : void 0,
					uniform: sampler
				});
				entries.sort((a, b) => a.binding - b.binding);
				groupEntries.set(group, entries);
			}
			for (const storage of shader._storageBuffers || []) {
				const group = storage.group;
				const entries = groupEntries.get(group) || [];
				entries.push({
					binding: storage.binding,
					visibility: storage.visibility,
					buffer: { type: storage.accessMode === "read" ? "read-only-storage" : "storage" },
					storage
				});
				entries.sort((a, b) => a.binding - b.binding);
				groupEntries.set(group, entries);
			}
			const groupEntriesArr = [];
			for (const [group, entries] of groupEntries) {
				const layout = this.device.createBindGroupLayout({ entries });
				bindGroupLayouts.set(group, layout);
				groupEntriesArr.push([group, entries]);
			}
			shader._groupEntries = groupEntriesArr;
			shader._bindGroupLayouts = [...bindGroupLayouts.values()];
			shader._cachedBindGroup = {};
			shader._lastDynamicBuffer = {};
			shader._pipelineLayout = this.device.createPipelineLayout({ bindGroupLayouts: shader._bindGroupLayouts });
			shader._compiled = true;
		}
		_getBlendState(mode) {
			switch (mode) {
				case BLEND: return {
					color: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one-minus-src-alpha"
					},
					alpha: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one-minus-src-alpha"
					}
				};
				case ADD: return {
					color: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one"
					},
					alpha: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one"
					}
				};
				case REMOVE: return {
					color: {
						operation: "add",
						srcFactor: "zero",
						dstFactor: "one-minus-src-alpha"
					},
					alpha: {
						operation: "add",
						srcFactor: "zero",
						dstFactor: "one-minus-src-alpha"
					}
				};
				case MULTIPLY: return {
					color: {
						operation: "add",
						srcFactor: "dst-color",
						dstFactor: "one-minus-src-alpha"
					},
					alpha: {
						operation: "add",
						srcFactor: "dst-alpha",
						dstFactor: "one-minus-src-alpha"
					}
				};
				case SCREEN: return {
					color: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one-minus-src-color"
					},
					alpha: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one-minus-src-alpha"
					}
				};
				case EXCLUSION: return {
					color: {
						operation: "add",
						srcFactor: "one-minus-dst-color",
						dstFactor: "one-minus-src-color"
					},
					alpha: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one"
					}
				};
				case REPLACE: return {
					color: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "zero"
					},
					alpha: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "zero"
					}
				};
				case SUBTRACT: return {
					color: {
						operation: "reverse-subtract",
						srcFactor: "one",
						dstFactor: "one"
					},
					alpha: {
						operation: "add",
						srcFactor: "one",
						dstFactor: "one-minus-src-alpha"
					}
				};
				case DARKEST: return {
					color: {
						operation: "min",
						srcFactor: "one",
						dstFactor: "one"
					},
					alpha: {
						operation: "min",
						srcFactor: "one",
						dstFactor: "one"
					}
				};
				case LIGHTEST: return {
					color: {
						operation: "max",
						srcFactor: "one",
						dstFactor: "one"
					},
					alpha: {
						operation: "max",
						srcFactor: "one",
						dstFactor: "one"
					}
				};
				default:
					console.warn(`Unsupported blend mode: ${mode}`);
					return;
			}
		}
		_applyColorBlend() {}
		_getVertexLayout(shader) {
			const layouts = [];
			for (const attrName in shader.attributes) {
				const attr = shader.attributes[attrName];
				if (!attr || attr.location === -1) continue;
				const renderBuffer = this.buffers[shader.shaderType].find((buf) => buf.attr === attrName) || this.buffers.user.find((buf) => buf.attr === attrName);
				if (!renderBuffer) continue;
				const { size } = renderBuffer;
				const format = this._getFormatFromSize(size);
				layouts.push({
					arrayStride: size * 4,
					stepMode: "vertex",
					attributes: [{
						shaderLocation: attr.location,
						offset: 0,
						format
					}]
				});
			}
			return layouts;
		}
		_getVertexBuffers(shader) {
			if (!shader._vertexBuffers) {
				const buffers = [];
				for (const attrName in shader.attributes) {
					const attr = shader.attributes[attrName];
					if (!attr || attr.location === -1) continue;
					const renderBuffer = this.buffers[shader.shaderType].find((buf) => buf.attr === attrName) || this.buffers.user.find((buf) => buf.attr === attrName);
					if (!renderBuffer) continue;
					buffers.push(renderBuffer);
				}
				shader._vertexBuffers = buffers;
			}
			return shader._vertexBuffers;
		}
		_getFormatFromSize(size) {
			switch (size) {
				case 1: return "float32";
				case 2: return "float32x2";
				case 3: return "float32x3";
				case 4: return "float32x4";
				default: throw new Error(`Unsupported attribute size: ${size}`);
			}
		}
		_useShader(shader, options) {}
		_updateViewport() {
			this._origViewport = {
				width: this.width,
				height: this.height
			};
			this._viewport = [
				0,
				0,
				this.width,
				this.height
			];
		}
		_createPixelsArray() {
			this.pixels = new Uint8Array(this.width * this.pixelDensity() * this.height * this.pixelDensity() * 4);
		}
		supportsTriangleFan() {
			return false;
		}
		supportsVideoUpload() {
			return this._supportsVideoUpload !== false;
		}
		textureNeedsRecreating(texture) {
			if (texture.isFramebufferTexture) return false;
			const gpuTexture = texture.textureHandle.gpuTexture;
			const data = texture._getTextureDataFromSource();
			if (!data || !data.width || !data.height) return false;
			return data.width !== gpuTexture.width || data.height !== gpuTexture.height;
		}
		viewport() {}
		zClipRange() {
			return [0, 1];
		}
		defaultNearScale() {
			return .01;
		}
		defaultFarScale() {
			return 100;
		}
		_resetBuffersBeforeDraw() {
			this._finishActiveRenderPass();
			if (this._pInst.frameCount > 0) this._frameState = FRAME_STATE.PENDING;
			const activeFramebuffer = this.activeFramebuffer();
			const commandEncoder = this.device.createCommandEncoder();
			const depthTextureView = activeFramebuffer ? activeFramebuffer.aaDepthTexture ? activeFramebuffer.aaDepthTextureView : activeFramebuffer.depthTextureView : this.depthTextureView;
			if (depthTextureView) {
				const renderPassDescriptor = {
					colorAttachments: [],
					depthStencilAttachment: {
						view: depthTextureView,
						depthClearValue: 1,
						depthLoadOp: "clear",
						depthStoreOp: "store",
						stencilLoadOp: "load",
						stencilStoreOp: "store"
					}
				};
				commandEncoder.beginRenderPass(renderPassDescriptor).end();
				this._pendingCommandEncoders.push(commandEncoder.finish());
				this._hasPendingDraws = true;
			}
		}
		/**
		* Promotes the current frame to use mainFramebuffer.
		* Copies current canvas content to mainFramebuffer, then switches to rendering there.
		* @private
		*/
		_promoteToFramebuffer() {
			if (this._frameState === FRAME_STATE.PROMOTED) return;
			if (this.activeFramebuffer()) return;
			this.flushDraw();
			this._frameState = FRAME_STATE.PROMOTED;
			const canvasTexture = this.drawingContext.getCurrentTexture();
			if (this.mainFramebuffer.width !== this.width || this.mainFramebuffer.height !== this.height) this.mainFramebuffer.resize(this.width, this.height);
			const commandEncoder = this.device.createCommandEncoder();
			commandEncoder.copyTextureToTexture({
				texture: canvasTexture,
				origin: {
					x: 0,
					y: 0,
					z: 0
				},
				mipLevel: 0
			}, {
				texture: this.mainFramebuffer.colorTexture,
				origin: {
					x: 0,
					y: 0,
					z: 0
				},
				mipLevel: 0
			}, {
				width: Math.ceil(this.width * this._pixelDensity),
				height: Math.ceil(this.height * this._pixelDensity),
				depthOrArrayLayers: 1
			});
			commandEncoder.copyTextureToTexture({
				texture: this.depthTexture,
				origin: {
					x: 0,
					y: 0,
					z: 0
				},
				mipLevel: 0
			}, {
				texture: this.mainFramebuffer.depthTexture,
				origin: {
					x: 0,
					y: 0,
					z: 0
				},
				mipLevel: 0
			}, {
				width: Math.ceil(this.width * this._pixelDensity),
				height: Math.ceil(this.height * this._pixelDensity),
				depthOrArrayLayers: 1
			});
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this._hasPendingDraws = true;
			const savedModelMatrix = this.states.uModelMatrix.copy();
			this.states.uModelMatrix.set(this.states.uModelMatrix.copy());
			this.states.uModelMatrix.reset();
			this.mainFramebuffer.defaultCamera.set(this.states.curCamera);
			this.mainFramebuffer.begin();
			this.states.uModelMatrix.set(savedModelMatrix);
		}
		_promoteToFramebufferWithoutCopy() {
			if (this._frameState === FRAME_STATE.PROMOTED) return;
			if (this.mainFramebuffer.width !== this.width || this.mainFramebuffer.height !== this.height) this.mainFramebuffer.resize(this.width, this.height);
			this._frameState = FRAME_STATE.PROMOTED;
			this.flushDraw();
			const savedModelMatrix = this.states.uModelMatrix.copy();
			this.states.uModelMatrix.set(this.states.uModelMatrix.copy());
			this.states.uModelMatrix.reset();
			this.mainFramebuffer.defaultCamera.set(this.states.curCamera);
			this.mainFramebuffer.begin();
			this.states.uModelMatrix.set(savedModelMatrix);
		}
		_initializeGeometryBufferPools(geometry) {
			if (geometry._vertexBufferPools) return;
			geometry._vertexBufferPools = {};
			geometry._vertexBuffersInUse = {};
			geometry._vertexBuffersToReturn = {};
			this._geometriesWithPools.push(geometry);
		}
		_getVertexBufferFromPool(geometry, dst, size) {
			this._initializeGeometryBufferPools(geometry);
			if (!geometry._vertexBufferPools[dst]) geometry._vertexBufferPools[dst] = [];
			if (!geometry._vertexBuffersInUse[dst]) geometry._vertexBuffersInUse[dst] = [];
			if (!geometry._vertexBuffersToReturn[dst]) geometry._vertexBuffersToReturn[dst] = [];
			const pool = geometry._vertexBufferPools[dst];
			if (pool.length > 0) {
				const bufferInfo = pool.pop();
				if (bufferInfo.buffer.size >= size) {
					geometry._vertexBuffersInUse[dst].push(bufferInfo);
					return bufferInfo;
				} else this._retiredBuffers.push(bufferInfo.buffer);
			}
			const bufferInfo = {
				buffer: this.device.createBuffer({
					size,
					usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
				}),
				size,
				dataCopy: null
			};
			geometry._vertexBuffersInUse[dst].push(bufferInfo);
			return bufferInfo;
		}
		_returnVertexBuffersToPool() {
			for (const geometry of this._geometriesWithPools) if (geometry._vertexBuffersToReturn) {
				for (const [dst, buffersToReturn] of Object.entries(geometry._vertexBuffersToReturn)) if (buffersToReturn.length > 0) {
					const pool = geometry._vertexBufferPools[dst] || [];
					while (buffersToReturn.length > 0) {
						const bufferInfo = buffersToReturn.pop();
						bufferInfo.dataCopy = null;
						pool.push(bufferInfo);
					}
					geometry._vertexBufferPools[dst] = pool;
				}
			}
		}
		onReset(geometry) {
			this._markGeometryBuffersForReturn(geometry);
		}
		_markGeometryBuffersForReturn(geometry) {
			if (geometry._vertexBuffersInUse && geometry._vertexBuffersToReturn) {
				for (const [dst, buffersInUse] of Object.entries(geometry._vertexBuffersInUse)) if (buffersInUse.length > 0) {
					const buffersToReturn = geometry._vertexBuffersToReturn[dst] || [];
					while (buffersInUse.length > 0) {
						const bufferInfo = buffersInUse.pop();
						buffersToReturn.push(bufferInfo);
					}
					geometry._vertexBuffersToReturn[dst] = buffersToReturn;
				}
			}
		}
		_getUniformBufferFromPool(bufferGroup) {
			if (bufferGroup.bufferPool.length > 0) {
				const bufferInfo = bufferGroup.bufferPool.pop();
				bufferGroup.buffersInUse.add(bufferInfo);
				return bufferInfo;
			}
			const newBuffer = this.device.createBuffer({
				size: bufferGroup.size,
				usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
			});
			const newData = new Float32Array(bufferGroup.size / 4);
			const bufferInfo = {
				buffer: newBuffer,
				data: newData,
				dataView: new DataView(newData.buffer)
			};
			bufferGroup.buffersInUse.add(bufferInfo);
			return bufferInfo;
		}
		_getDynamicUniformBufferFromPool(bufferGroup) {
			let buffer;
			if (this.currentUniformBuffer && this.currentUniformBuffer.offset + bufferGroup.size < this.currentUniformBuffer.size) buffer = this.currentUniformBuffer;
			else if (this.uniformBufferPool.length > 0) {
				buffer = this.uniformBufferPool.pop();
				this.activeUniformBuffers.push(buffer);
			} else {
				const size = 10240;
				buffer = {
					dynamic: true,
					lastOffset: 0,
					offset: 0,
					size,
					buffer: this.device.createBuffer({
						size,
						usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC,
						mappedAtCreation: true
					}),
					uniformBuffer: this.device.createBuffer({
						size,
						usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
					})
				};
				buffer.data = new Float32Array(buffer.buffer.getMappedRange());
				buffer.dataView = new DataView(buffer.data.buffer);
				this.activeUniformBuffers.push(buffer);
			}
			this.currentUniformBuffer = buffer;
			return buffer;
		}
		_returnUniformBuffersToPool() {
			for (const shader of this._shadersWithPools) this._returnShaderBuffersToPool(shader);
		}
		_returnShaderBuffersToPool(shader) {
			if (shader._uniformBufferGroups) for (const bufferGroup of shader._uniformBufferGroups) {
				while (bufferGroup.nextBufferPool.length > 0) bufferGroup.bufferPool.push(bufferGroup.nextBufferPool.pop());
				for (const bufferInfo of bufferGroup.buffersInUse.keys()) if (bufferInfo !== bufferGroup.currentBuffer) bufferGroup.nextBufferPool.push(bufferInfo);
				bufferGroup.buffersInUse.clear();
				if (bufferGroup.currentBuffer) bufferGroup.buffersInUse.add(bufferGroup.currentBuffer);
			}
		}
		flushDraw() {
			this._finishActiveRenderPass();
			if (this._hasPendingDraws) {
				const commandsToSubmit = this._pendingCommandEncoders;
				this._pendingCommandEncoders = [];
				this._hasPendingDraws = false;
				if (this.activeUniformBuffers.length > 0) {
					const encoder = this.device.createCommandEncoder();
					for (const bufferInfo of this.activeUniformBuffers) {
						bufferInfo.buffer.unmap();
						encoder.copyBufferToBuffer(bufferInfo.buffer, bufferInfo.uniformBuffer);
					}
					commandsToSubmit.unshift(encoder.finish());
				}
				this.queue.submit(commandsToSubmit);
				const tempBuffers = this._tempBuffers;
				this._tempBuffers = [];
				if (tempBuffers.length > 0) this._postSubmitCallbacks.push(() => {
					for (const buf of tempBuffers) buf.destroy();
				});
				for (const buf of this.activeUniformBuffers) {
					buf.offset = 0;
					buf.lastOffset = 0;
					buf.buffer.mapAsync(GPUMapMode.WRITE).then(() => {
						buf.data = new Float32Array(buf.buffer.getMappedRange());
						buf.dataView = new DataView(buf.data.buffer);
						this.uniformBufferPool.push(buf);
						return buf;
					});
				}
				this.activeUniformBuffers = [];
				this.currentUniformBuffer = void 0;
				if (this._postSubmitCallbacks.length > 0) {
					const callbacks = this._postSubmitCallbacks;
					this._postSubmitCallbacks = [];
					this.device.queue.onSubmittedWorkDone().then(() => {
						for (const callback of callbacks) callback();
					});
				}
				this.currentCanvasColorTexture = null;
				this.currentCanvasColorTextureView = null;
			}
		}
		_ensurePixelReadCanvas(width, height) {
			if (!this._pixelReadCanvas) {
				this._pixelReadCanvas = document.createElement("canvas");
				this._pixelReadCtx = this._pixelReadCanvas.getContext("2d");
			}
			if (this._pixelReadCanvas.width !== width || this._pixelReadCanvas.height !== height) {
				this._pixelReadCanvas.width = width;
				this._pixelReadCanvas.height = height;
			}
			return {
				canvas: this._pixelReadCanvas,
				ctx: this._pixelReadCtx
			};
		}
		resize(w, h) {
			super.resize(w, h);
			this._hasPendingDraws = true;
			this.flushDraw();
		}
		async finishDraw() {
			this.flushDraw();
			const states = [];
			if (this._frameState === FRAME_STATE.PROMOTED) {
				while (this.activeFramebuffers.length > 0) {
					const fbo = this.activeFramebuffers.pop();
					states.unshift({
						fbo,
						diff: { ...this.states }
					});
				}
				this.flushDraw();
				this._pInst.push();
				this.states.setValue("enableLighting", false);
				this.states.setValue("activeImageLight", null);
				this._pInst.setCamera(this.finalCamera);
				this._pInst.shader(this._getBlitShader());
				this._pInst.resetMatrix();
				this._pInst.imageMode(this._pInst.CENTER);
				this._pInst.image(this.mainFramebuffer, 0, 0);
				this._pInst.pop();
				this.flushDraw();
			}
			this._returnUniformBuffersToPool();
			for (const geometry of this._geometriesWithPools) this._markGeometryBuffersForReturn(geometry);
			this.resettingUniformBuffers = [];
			this._returnVertexBuffersToPool();
			const retired = this._retiredBuffers;
			this._postSubmitCallbacks.push(() => {
				for (const buffer of retired) if (buffer && buffer.destroy) buffer.destroy();
			});
			this._retiredBuffers = [];
			if (this._frameState === FRAME_STATE.PROMOTED) for (const { fbo, diff } of states) {
				if (fbo !== this.mainFramebuffer || this._frameState !== FRAME_STATE.PROMOTED) fbo.begin();
				for (const key in diff) this.states.setValue(key, diff[key]);
			}
		}
		_drawBuffers(geometry, { mode = 4, count = 1 }) {
			const buffers = this.geometryBufferCache.getCached(geometry);
			if (!buffers) return;
			if (this._frameState === FRAME_STATE.PENDING && !this.activeFramebuffer()) this._promoteToFramebufferWithoutCopy();
			const currentShader = this._curShader;
			const instanceList = this._instanceList;
			if (instanceList) {
				this._drawBuffersIndirect(geometry, buffers, currentShader, mode, instanceList);
				return;
			}
			this._beginActiveRenderPass();
			const passEncoder = this.activeRenderPass;
			this.setupShaderBindGroups(currentShader, passEncoder, {
				mode,
				buffers
			});
			for (const buffer of currentShader._vertexBuffers || this._getVertexBuffers(currentShader)) {
				const location = currentShader.attributes[buffer.attr].location;
				const gpuBuffer = buffers[buffer.dst];
				passEncoder.setVertexBuffer(location, gpuBuffer, 0);
			}
			if (currentShader.shaderType === "fill") {
				if (buffers.indexBuffer) {
					const indexFormat = buffers.indexFormat || "uint16";
					passEncoder.setIndexBuffer(buffers.indexBuffer, indexFormat);
					passEncoder.drawIndexed(geometry.faces.length * 3, count, 0, 0, 0);
				} else passEncoder.draw(geometry.vertices.length, count, 0, 0);
			} else if (currentShader.shaderType === "text") {
				if (!buffers.indexBuffer) throw new Error("Text geometry must have an index buffer");
				const indexFormat = buffers.indexFormat || "uint16";
				passEncoder.setIndexBuffer(buffers.indexBuffer, indexFormat);
				passEncoder.drawIndexed(geometry.faces.length * 3, count, 0, 0, 0);
			}
			if (buffers.lineVerticesBuffer && currentShader.shaderType === "stroke") passEncoder.draw(geometry.lineVertices.length / 3, count, 0, 0);
			this._hasPendingDraws = true;
		}
		_drawBuffersIndirect(geometry, buffers, currentShader, mode, instanceList) {
			this._finishActiveRenderPass();
			const isIndexed = !!buffers.indexBuffer && currentShader.shaderType !== "stroke";
			const indirectBuffer = this.device.createBuffer({
				size: 20,
				usage: GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST,
				mappedAtCreation: true
			});
			const indirectInit = new Uint32Array(indirectBuffer.getMappedRange());
			if (currentShader.shaderType === "stroke") indirectInit[0] = geometry.lineVertices ? geometry.lineVertices.length / 3 : 0;
			else if (isIndexed) indirectInit[0] = geometry.faces.length * 3;
			else indirectInit[0] = geometry.vertices.length;
			indirectBuffer.unmap();
			this._tempBuffers.push(indirectBuffer);
			const copyEncoder = this.device.createCommandEncoder();
			copyEncoder.copyBufferToBuffer(instanceList.buffer, instanceList._lengthOffset, indirectBuffer, 4, 4);
			this._pendingCommandEncoders.push(copyEncoder.finish());
			this._beginActiveRenderPass();
			const passEncoder = this.activeRenderPass;
			this.setupShaderBindGroups(currentShader, passEncoder, {
				mode,
				buffers
			});
			for (const buffer of currentShader._vertexBuffers || this._getVertexBuffers(currentShader)) {
				const location = currentShader.attributes[buffer.attr].location;
				const gpuBuffer = buffers[buffer.dst];
				passEncoder.setVertexBuffer(location, gpuBuffer, 0);
			}
			if (currentShader.shaderType === "fill") {
				if (isIndexed) {
					passEncoder.setIndexBuffer(buffers.indexBuffer, buffers.indexFormat || "uint16");
					passEncoder.drawIndexedIndirect(indirectBuffer, 0);
				} else passEncoder.drawIndirect(indirectBuffer, 0);
			} else if (currentShader.shaderType === "stroke") {
				if (buffers.lineVerticesBuffer) passEncoder.drawIndirect(indirectBuffer, 0);
			} else if (currentShader.shaderType === "text") {
				if (buffers.indexBuffer) {
					passEncoder.setIndexBuffer(buffers.indexBuffer, buffers.indexFormat || "uint16");
					passEncoder.drawIndexedIndirect(indirectBuffer, 0);
				}
			}
			this._hasPendingDraws = true;
		}
		setupShaderBindGroups(currentShader, passEncoder, shaderOptionsParams) {
			const shaderOptions = this._shaderOptions(shaderOptionsParams);
			if (shaderOptions.compute || this.activeShader !== currentShader || this._shaderOptionsDifferent(shaderOptions)) passEncoder.setPipeline(currentShader.getPipeline(shaderOptions));
			if (!shaderOptions.compute) {
				this.activeShader = currentShader;
				this.activeShaderOptions = shaderOptions;
				if (this.drawTarget()._isClipApplied && !this._clipping) passEncoder.setStencilReference(0);
				else if (this._clipping) passEncoder.setStencilReference(1);
			}
			for (const bufferGroup of currentShader._uniformBufferGroups) if (bufferGroup.dynamic) {
				const uniformBufferInfo = this._getDynamicUniformBufferFromPool(bufferGroup);
				if (currentShader._lastDynamicBuffer[bufferGroup.cacheKey] !== uniformBufferInfo) {
					currentShader._cachedBindGroup[bufferGroup.group] = void 0;
					currentShader._lastDynamicBuffer[bufferGroup.cacheKey] = uniformBufferInfo;
				}
				this._packUniformGroup(currentShader, bufferGroup.uniforms, uniformBufferInfo);
				uniformBufferInfo.lastOffset = uniformBufferInfo.offset;
				uniformBufferInfo.offset += Math.ceil(bufferGroup.size / this.uniformBufferAlignment) * this.uniformBufferAlignment;
				bufferGroup.currentDynamicBuffer = uniformBufferInfo;
				bufferGroup.lastOffset = uniformBufferInfo.lastOffset;
			} else {
				let bufferInfo;
				if (!this._hasGroupDataChanged(currentShader, bufferGroup) && bufferGroup.currentBuffer) {
					bufferInfo = bufferGroup.currentBuffer;
					bufferGroup.buffersInUse.add(bufferInfo);
				} else {
					bufferInfo = this._getUniformBufferFromPool(bufferGroup);
					this._packUniformGroup(currentShader, bufferGroup.uniforms, bufferInfo);
					this.device.queue.writeBuffer(bufferInfo.buffer, 0, bufferInfo.data.buffer, bufferInfo.data.byteOffset, bufferInfo.data.byteLength);
					currentShader.buffersDirty.delete(bufferGroup.group * 1e3 + bufferGroup.binding);
					currentShader._cachedBindGroup[bufferGroup.group] = void 0;
					bufferGroup.currentBuffer = bufferInfo;
				}
			}
			for (const sampler of currentShader.samplers) {
				const key = sampler.group * 1e3 + sampler.binding;
				if (currentShader.buffersDirty.has(key)) {
					currentShader._cachedBindGroup[sampler.group] = void 0;
					currentShader.buffersDirty.delete(key);
				}
			}
			for (const storage of currentShader._storageBuffers || []) {
				const key = storage.group * 1e3 + storage.binding;
				if (currentShader.buffersDirty.has(key)) {
					currentShader._cachedBindGroup[storage.group] = void 0;
					currentShader.buffersDirty.delete(key);
				}
			}
			for (const iter of currentShader._groupEntries) {
				const group = iter[0];
				const entries = iter[1];
				let dynamicOffsetIdx = 0;
				const bgEntries = [];
				let bindGroup = currentShader._cachedBindGroup[group];
				for (const entry of entries) {
					const bufferGroup = entry.bufferGroup;
					const uniformBufferInfo = bufferGroup?.currentBuffer || bufferGroup?.currentDynamicBuffer;
					if (uniformBufferInfo) {
						if (bufferGroup.dynamic) this.dynamicEntryOffsets[dynamicOffsetIdx++] = bufferGroup.lastOffset;
						if (!bindGroup) bgEntries.push({
							binding: entry.binding,
							resource: bufferGroup.dynamic ? {
								buffer: uniformBufferInfo.uniformBuffer,
								offset: 0,
								size: Math.ceil(bufferGroup.size / this.uniformBufferAlignment) * this.uniformBufferAlignment
							} : { buffer: uniformBufferInfo.buffer }
						});
					} else if (entry.storage && !bindGroup) {
						const uniform = currentShader.uniforms[entry.storage.name];
						if (!uniform || !uniform._cachedData || !uniform._cachedData._isStorageBuffer && !uniform._cachedData._isStorageList) throw new Error(`Storage buffer "${entry.storage.name}" not set. Use shader.setUniform("${entry.storage.name}", storageBuffer)`);
						this._checkStorageElementType(entry.storage, uniform._cachedData);
						bgEntries.push({
							binding: entry.binding,
							resource: { buffer: uniform._cachedData.buffer }
						});
					} else if (!bindGroup) bgEntries.push({
						binding: entry.binding,
						resource: entry.uniform.type === "sampler" ? (entry.uniform.textureSource.texture || this._getEmptyTexture()).getSampler() : (entry.uniform.texture || this._getEmptyTexture()).textureHandle.view
					});
				}
				const layout = currentShader._bindGroupLayouts[group];
				if (!bindGroup) bindGroup = this.device.createBindGroup({
					layout,
					entries: bgEntries
				});
				currentShader._cachedBindGroup[group] = bindGroup;
				if (dynamicOffsetIdx === 0) passEncoder.setBindGroup(group, bindGroup);
				else passEncoder.setBindGroup(group, bindGroup, this.dynamicEntryOffsets, 0, dynamicOffsetIdx);
			}
			return passEncoder;
		}
		_packField(field, value, floatView, dataView, baseOffset) {
			if (value === void 0) return;
			if (value?.isVector) value = value.values.length !== value.dimensions ? value.values.slice(0, value.dimensions) : value.values;
			else if (value?.isColor) value = value._getRGBA([
				1,
				1,
				1,
				1
			]);
			const byteOffset = baseOffset + field.offset;
			if (field.baseType === "u32") {
				if (field.size === 4) dataView.setUint32(byteOffset, value, true);
				else for (let i = 0; i < value.length; i++) dataView.setUint32(byteOffset + i * 4, value[i], true);
			} else if (field.baseType === "i32") {
				if (field.size === 4) dataView.setInt32(byteOffset, value, true);
				else for (let i = 0; i < value.length; i++) dataView.setInt32(byteOffset + i * 4, value[i], true);
			} else if (field.packInPlace) {
				const base = byteOffset / 4;
				floatView[base + 0] = value[0];
				floatView[base + 1] = value[1];
				floatView[base + 2] = value[2];
				floatView[base + 4] = value[3];
				floatView[base + 5] = value[4];
				floatView[base + 6] = value[5];
				floatView[base + 8] = value[6];
				floatView[base + 9] = value[7];
				floatView[base + 10] = value[8];
			} else if (field.size === 4) floatView.set([value], byteOffset / 4);
			else floatView.set(value, byteOffset / 4);
		}
		_packUniformGroup(shader, groupUniforms, bufferInfo) {
			const data = bufferInfo.data;
			const dataView = bufferInfo.dataView;
			const offset = bufferInfo.offset || 0;
			for (const uniform of groupUniforms) {
				const fullUniform = shader.uniforms[uniform.name];
				if (!fullUniform || fullUniform.isSampler) continue;
				this._packField(fullUniform, fullUniform._mappedData, data, dataView, offset);
			}
		}
		_hasGroupDataChanged(shader, bufferGroup) {
			if (!bufferGroup.currentBuffer) return true;
			return shader.buffersDirty.has(bufferGroup.group * 1e3 + bufferGroup.binding);
		}
		_parseStruct(shaderSource, structName) {
			const structMatch = shaderSource.match(new RegExp(`struct\\s+${structName}\\s*\\{([^\\}]+)\\}`));
			if (!structMatch) throw new Error(`Can't find a struct definition for ${structName}`);
			const structBody = structMatch[1];
			const elements = {};
			let match;
			let index = 0;
			let offset = 0;
			const elementRegex = /(?:@location\((\d+)\)\s+)?(\w+):\s*([^\n]+?),?\n/g;
			const baseAlignAndSize = (type) => {
				if ([
					"f32",
					"i32",
					"u32",
					"bool"
				].includes(type)) return {
					align: 4,
					size: 4,
					items: 1,
					baseType: type
				};
				if (/^vec[2-4](<f32>|f)$/.test(type)) {
					const n = parseInt(type.match(/^vec([2-4])/)[1]);
					const size = 4 * n;
					return {
						align: n === 2 ? 8 : 16,
						size,
						items: n,
						baseType: "f32"
					};
				}
				if (/^vec[2-4]<(i32|u32)>$/.test(type)) {
					const n = parseInt(type.match(/^vec([2-4])/)[1]);
					const baseType = type.match(/^vec[2-4]<(i32|u32)>$/)[1];
					const size = 4 * n;
					return {
						align: n === 2 ? 8 : 16,
						size,
						items: n,
						baseType
					};
				}
				if (/^mat[2-4](?:x[2-4])?(<f32>|f)$/.test(type)) {
					if (type[4] === "x" && type[3] !== type[5]) throw new Error("Non-square matrices not implemented yet");
					const dim = parseInt(type[3]);
					const align = dim === 2 ? 8 : 16;
					return {
						align,
						size: Math.ceil(dim * 4 / align) * align * dim,
						pack: dim === 3 ? (data) => [
							...data.slice(0, 3),
							...data.slice(3, 6),
							...data.slice(6, 9)
						] : void 0,
						packInPlace: dim === 3,
						items: dim * dim,
						baseType: "f32"
					};
				}
				if (/^array<.+>$/.test(type)) {
					const [, subtype, rawLength] = type.match(/^array<(.+),\s*(\d+)>/);
					const length = parseInt(rawLength);
					const { align: elemAlign, size: elemSize, items: elemItems, pack: elemPack = (data) => [...data], baseType: elemBaseType } = baseAlignAndSize(subtype);
					const stride = Math.ceil(elemSize / elemAlign) * elemAlign;
					const pack = (data) => {
						const result = [];
						for (let i = 0; i < data.length; i += elemItems) {
							const elemData = elemPack(data.slice(i, elemItems));
							result.push(...elemData);
							for (let j = 0; j < stride / 4 - elemData.length; j++) result.push(0);
						}
						return result;
					};
					return {
						align: elemAlign,
						size: stride * length,
						items: elemItems * length,
						pack,
						baseType: elemBaseType
					};
				}
				throw new Error(`Unknown type in WGSL struct: ${type}`);
			};
			while ((match = elementRegex.exec(structBody)) !== null) {
				const [, location, name, type] = match;
				const { size, align, pack, packInPlace, baseType } = baseAlignAndSize(type);
				offset = Math.ceil(offset / align) * align;
				const offsetEnd = offset + size;
				elements[name] = {
					name,
					location: location ? parseInt(location) : void 0,
					index,
					type,
					size,
					offset,
					offsetEnd,
					pack,
					packInPlace,
					baseType
				};
				index++;
				offset = offsetEnd;
			}
			return elements;
		}
		_mapUniformData(uniform, data) {
			if (uniform.pack) return uniform.pack(data);
			return data;
		}
		_getShaderAttributes(shader) {
			const mainMatch = /fn main\(.+:\s*([^\s)]+)/.exec(shader._vertSrc);
			if (!mainMatch) throw new Error("Can't find `fn main` in vertex shader source");
			const inputType = mainMatch[1];
			return this._parseStruct(shader.vertSrc(), inputType);
		}
		getUniformMetadata(shader) {
			const uniformGroups = [];
			const uniformVarRegex = /@group\((\d+)\)\s+@binding\((\d+)\)\s+var<uniform>\s+(\w+)\s*:\s*(\w+);/g;
			let match;
			const src = shader.shaderType === "compute" ? shader.computeSrc() : shader.vertSrc();
			while ((match = uniformVarRegex.exec(src)) !== null) {
				const [, groupNum, binding, varName, structType] = match;
				const bindingIndex = parseInt(binding);
				const uniforms = this._parseStruct(src, structType);
				uniformGroups.push({
					group: parseInt(groupNum),
					binding: bindingIndex,
					varName,
					structType,
					uniforms
				});
			}
			if (uniformGroups.length === 0 && shader.shaderType !== "compute") throw new Error("Expected at least one uniform struct bound to @group(0)");
			const allUniforms = {};
			for (const group of uniformGroups) for (const [uniformName, uniformData] of Object.entries(group.uniforms)) allUniforms[uniformName] = {
				...uniformData,
				group: group.group,
				binding: group.binding,
				varName: group.varName
			};
			shader._uniformGroups = uniformGroups;
			const samplers = {};
			const samplerRegex = /@group\((\d+)\)\s*@binding\((\d+)\)\s*var\s+(\w+)\s*:\s*(texture_2d<f32>|sampler);/g;
			const storageBuffers = {};
			const storageRegex = /@group\((\d+)\)\s*@binding\((\d+)\)\s*var<storage,\s*(read|read_write)>\s+(\w+)\s*:\s*(array<[\w<>, ]+>|atomic<\w+>|\w+)/g;
			const structUniformBindings = {};
			for (const g of uniformGroups) structUniformBindings[g.group + "," + g.binding] = true;
			for (const [src, visibility] of [
				[shader.vertSrc(), GPUShaderStage.VERTEX],
				[shader.fragSrc(), GPUShaderStage.FRAGMENT],
				[shader.computeSrc ? shader.computeSrc() : null, GPUShaderStage.COMPUTE]
			]) {
				if (!src) continue;
				let match;
				while ((match = samplerRegex.exec(src)) !== null) {
					const [, group, binding, name, type] = match;
					const groupIndex = parseInt(group);
					const bindingIndex = parseInt(binding);
					if (structUniformBindings[groupIndex + "," + bindingIndex]) continue;
					const key = `${groupIndex},${bindingIndex}`;
					samplers[key] = {
						visibility: (samplers[key]?.visibility || 0) | visibility,
						group: groupIndex,
						binding: bindingIndex,
						name,
						type,
						isSampler: true,
						noData: type === "sampler"
					};
				}
				for (const sampler of Object.values(samplers)) if (sampler.type.startsWith("texture")) {
					const samplerName = sampler.name + "_sampler";
					const samplerNode = Object.values(samplers).find((s) => s.name === samplerName);
					if (!samplerNode) throw new Error(`Every shader texture needs an accompanying sampler. Could not find sampler ${samplerName} for texture ${sampler.name}`);
					samplerNode.textureSource = sampler;
				}
				while ((match = storageRegex.exec(src)) !== null) {
					const [, group, binding, accessMode, name, bindingType] = match;
					const elementType = bindingType.match(/^array<(.+?)(?:,\s*\d+)?>$/)?.[1] ?? bindingType;
					const groupIndex = parseInt(group);
					const bindingIndex = parseInt(binding);
					const key = `${groupIndex},${bindingIndex}`;
					const existing = storageBuffers[key];
					const finalAccessMode = existing?.accessMode === "read_write" || accessMode === "read_write" ? "read_write" : accessMode;
					storageBuffers[key] = {
						visibility: (existing?.visibility || 0) | visibility,
						group: groupIndex,
						binding: bindingIndex,
						name,
						accessMode: finalAccessMode,
						isStorage: true,
						type: "storage",
						elementType,
						expectedArrayType: this._storageArrayTypeFor(elementType)
					};
				}
			}
			shader._storageBuffers = Object.values(storageBuffers);
			shader._storageBuffersByName = {};
			for (const storage of shader._storageBuffers) shader._storageBuffersByName[storage.name] = storage;
			return [
				...Object.values(allUniforms).sort((a, b) => a.index - b.index),
				...Object.values(samplers),
				...Object.values(storageBuffers)
			];
		}
		getNextBindingIndex({ vert, frag, compute }, group = 0) {
			const bindingRegex = /@group\((\d+)\)\s*@binding\((\d+)\)/g;
			let maxBindingIndex = -1;
			const sources = [];
			if (vert) sources.push([vert, GPUShaderStage.VERTEX]);
			if (frag) sources.push([frag, GPUShaderStage.FRAGMENT]);
			if (compute) sources.push([compute, GPUShaderStage.COMPUTE]);
			for (const [src] of sources) {
				let match;
				while ((match = bindingRegex.exec(src)) !== null) {
					const [, groupIndex, bindingIndex] = match;
					if (parseInt(groupIndex) === group) maxBindingIndex = Math.max(maxBindingIndex, parseInt(bindingIndex));
				}
			}
			return maxBindingIndex + 1;
		}
		updateUniformValue(shader, uniform, data) {
			if (uniform.isSampler) uniform.texture = data instanceof Texture ? data : this.getTexture(data);
			else if (!data?._isStorageBuffer) uniform._mappedData = this._mapUniformData(uniform, uniform._cachedData);
			else if (shader._storageBuffersByName) this._checkStorageElementType(shader._storageBuffersByName[uniform.name], data);
			shader.buffersDirty.add(uniform.group * 1e3 + uniform.binding);
		}
		_updateTexture(uniform, tex, shader) {
			if (this.textureNeedsRecreating(tex)) {
				tex = this.getTexture(tex.src);
				uniform.texture = tex;
				shader.buffersDirty.add(uniform.group * 1e3 + uniform.binding);
			}
			tex.update();
		}
		bindTexture(tex) {}
		unbindTexture(tex) {}
		_unbindFramebufferTexture(uniform) {}
		createTexture({ width, height, format = "rgba8unorm", usage }) {
			const gpuTexture = this.device.createTexture({
				size: [Math.max(1, width), Math.max(1, height)],
				format,
				usage: usage || GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
			});
			return {
				gpuTexture,
				view: gpuTexture.createView()
			};
		}
		uploadTextureFromSource({ gpuTexture }, source) {
			const isVideo = source instanceof HTMLVideoElement;
			if (isVideo && source.readyState < 2) return;
			try {
				this.queue.copyExternalImageToTexture({ source }, { texture: gpuTexture }, [source.videoWidth || source.width, source.videoHeight || source.height]);
			} catch (e) {
				if (isVideo && e instanceof TypeError) {
					this._supportsVideoUpload = false;
					return;
				}
				throw e;
			}
			this._hasPendingDraws = true;
			this.flushDraw();
		}
		uploadTextureFromData({ gpuTexture }, data, width, height) {
			this.queue.writeTexture({ texture: gpuTexture }, data, {
				bytesPerRow: width * 4,
				rowsPerImage: height
			}, {
				width,
				height,
				depthOrArrayLayers: 1
			});
			this._hasPendingDraws = true;
			this.flushDraw();
		}
		setTextureParams(_texture) {}
		getSampler(texture) {
			const key = `${texture.minFilter}_${texture.magFilter}_${texture.wrapS}_${texture.wrapT}`;
			if (this.samplers.has(key)) return this.samplers.get(key);
			const constantMapping = {
				[NEAREST]: "nearest",
				[LINEAR]: "linear",
				[CLAMP]: "clamp-to-edge",
				[REPEAT]: "repeat",
				[MIRROR]: "mirror-repeat"
			};
			const sampler = this.device.createSampler({
				magFilter: constantMapping[texture.magFilter],
				minFilter: constantMapping[texture.minFilter],
				addressModeU: constantMapping[texture.wrapS],
				addressModeV: constantMapping[texture.wrapT]
			});
			this.samplers.set(key, sampler);
			return sampler;
		}
		bindTextureToShader(_texture, _sampler, _uniformName, _unit) {}
		deleteTexture({ gpuTexture }) {
			this._postSubmitCallbacks.push(() => gpuTexture.destroy());
		}
		_getLightShader(useTextureMaps = false) {
			const cacheKey = useTextureMaps ? "_defaultLightShaderWithMaps" : "_defaultLightShader";
			if (!this[cacheKey]) this[cacheKey] = new Shader(this, materialVertexShader({ useTextureMaps }), materialFragmentShader({ useTextureMaps }), {
				vertex: {
					"void beforeVertex": "() {}",
					"Vertex getObjectInputs": "(inputs: Vertex) { return inputs; }",
					"Vertex getWorldInputs": "(inputs: Vertex) { return inputs; }",
					"Vertex getCameraInputs": "(inputs: Vertex) { return inputs; }",
					"void afterVertex": "() {}"
				},
				fragment: {
					"void beforeFragment": "() {}",
					"Inputs getPixelInputs": "(inputs: Inputs) { return inputs; }",
					"vec4f combineColors": `(components: ColorComponents) {
                var rgb = vec3<f32>(0.0);
                rgb += components.diffuse * components.baseColor;
                rgb += components.ambient * components.ambientColor;
                rgb += components.specular * components.specularColor;
                rgb += components.emissive;
                return vec4<f32>(rgb, components.opacity);
              }`,
					"vec4f getFinalColor": "(color: vec4<f32>, texCoord: vec2<f32>) { return color; }",
					"void afterFragment": "() {}"
				}
			});
			return this[cacheKey];
		}
		_getColorShader() {
			if (!this._defaultColorShader) this._defaultColorShader = new Shader(this, colorVertexShader, colorFragmentShader, {
				vertex: {
					"void beforeVertex": "() {}",
					"Vertex getObjectInputs": "(inputs: Vertex) { return inputs; }",
					"Vertex getWorldInputs": "(inputs: Vertex) { return inputs; }",
					"Vertex getCameraInputs": "(inputs: Vertex) { return inputs; }",
					"void afterVertex": "() {}"
				},
				fragment: {
					"void beforeFragment": "() {}",
					"vec4<f32> getFinalColor": "(color: vec4<f32>, texCoord: vec2<f32>) { return color; }",
					"void afterFragment": "() {}"
				}
			});
			return this._defaultColorShader;
		}
		_getLineShader() {
			if (!this._defaultLineShader) this._defaultLineShader = new Shader(this, lineDefs + lineVertexShader, lineDefs + lineFragmentShader, {
				vertex: {
					"void beforeVertex": "() {}",
					"StrokeVertex getObjectInputs": "(inputs: StrokeVertex) { return inputs; }",
					"StrokeVertex getWorldInputs": "(inputs: StrokeVertex) { return inputs; }",
					"StrokeVertex getCameraInputs": "(inputs: StrokeVertex) { return inputs; }",
					"void afterVertex": "() {}"
				},
				fragment: {
					"void beforeFragment": "() {}",
					"Inputs getPixelInputs": "(inputs: Inputs) { return inputs; }",
					"vec4<f32> getFinalColor": "(color: vec4<f32>, texCoord: vec2<f32>) { return color; }",
					"bool shouldDiscard": "(outside: bool) { return outside; };",
					"void afterFragment": "() {}"
				}
			});
			return this._defaultLineShader;
		}
		_getFontShader() {
			if (!this._defaultFontShader) this._defaultFontShader = new Shader(this, fontVertexShader, fontFragmentShader);
			return this._defaultFontShader;
		}
		_getBlitShader() {
			if (!this._defaultBlitShader) this._defaultBlitShader = new Shader(this, blitVertexShader, blitFragmentShader);
			return this._defaultBlitShader;
		}
		_adjustDimensions(width, height) {
			return {
				adjustedWidth: width,
				adjustedHeight: height
			};
		}
		_applyClip() {
			const commandEncoder = this.device.createCommandEncoder();
			const activeFramebuffer = this.activeFramebuffer();
			const depthTextureView = activeFramebuffer ? activeFramebuffer.aaDepthTexture ? activeFramebuffer.aaDepthTextureView : activeFramebuffer.depthTextureView : this.depthTextureView;
			if (!depthTextureView) return;
			const renderPassDescriptor = {
				colorAttachments: [],
				depthStencilAttachment: {
					view: depthTextureView,
					stencilLoadOp: "clear",
					stencilStoreOp: "store",
					stencilClearValue: 0,
					depthReadOnly: true,
					stencilReadOnly: false
				}
			};
			commandEncoder.beginRenderPass(renderPassDescriptor).end();
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this._hasPendingDraws = true;
		}
		_unapplyClip() {}
		_clearClipBuffer() {
			this._finishActiveRenderPass();
			const commandEncoder = this.device.createCommandEncoder();
			const activeFramebuffer = this.activeFramebuffer();
			const depthTextureView = activeFramebuffer ? activeFramebuffer.aaDepthTexture ? activeFramebuffer.aaDepthTextureView : activeFramebuffer.depthTextureView : this.depthTextureView;
			if (!depthTextureView) return;
			const renderPassDescriptor = {
				colorAttachments: [],
				depthStencilAttachment: {
					view: depthTextureView,
					stencilLoadOp: "clear",
					stencilStoreOp: "store",
					stencilClearValue: 1,
					depthReadOnly: true,
					stencilReadOnly: false
				}
			};
			commandEncoder.beginRenderPass(renderPassDescriptor).end();
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this._hasPendingDraws = true;
		}
		_applyStencilTestIfClipping() {}
		uniformNameFromHookKey(key) {
			return key.slice(0, key.indexOf(":"));
		}
		populateHooks(shader, src, shaderType) {
			if (!src.includes("fn main")) return src;
			src = src.replace(/\/\/ @p5 (ifdef|ifndef) (\w+)\s+(\w+)\n((?:(?!\/\/ @p5)(?:.|\n))*)\/\/ @p5 endif/g, (_, condition, hookType, hookName, body) => {
				const target = condition === "ifdef";
				if ((!!shader.hooks.modified.vertex[`${hookType} ${hookName}`] || !!shader.hooks.modified.fragment[`${hookType} ${hookName}`]) === target) return body;
				else return "";
			});
			let [preMain, main, postMain] = src.split(/((?:@(?:vertex|fragment|compute)\s*(?:@workgroup_size\([^)]+\)\s*)?)?fn main[^{]+\{)/);
			const getBuiltinParamName = (mainSrc, builtinName) => {
				const match = new RegExp(`@builtin\\s*\\(\\s*${builtinName}\\s*\\)\\s*(\\w+)\\s*:`).exec(mainSrc);
				return match ? match[1] : null;
			};
			const ensureBuiltinParam = (mainSrc, builtinName, fallbackName, typeName) => {
				const existingName = getBuiltinParamName(mainSrc, builtinName);
				if (existingName) return {
					mainSrc,
					argName: existingName
				};
				const hasParams = /\(\s*\S/.test(mainSrc);
				return {
					mainSrc: mainSrc.replace(/\)\s*(->|\{)/, `${hasParams ? ", " : ""}@builtin(${builtinName}) ${fallbackName}: ${typeName}) $1`),
					argName: fallbackName
				};
			};
			const getMainStructParameter = (mainSrc) => {
				const match = /fn main\s*\(\s*(\w+)\s*:\s*(\w+)/.exec(mainSrc);
				if (!match) return null;
				return {
					inputName: match[1],
					structName: match[2]
				};
			};
			const getStructBuiltinFieldName = (structName, builtinName) => {
				const structMatch = new RegExp(`struct\\s+${structName}\\s*\\{([^}]*)\\}`, "s").exec(preMain);
				if (!structMatch) return null;
				const fieldMatch = new RegExp(`@builtin\\s*\\(\\s*${builtinName}\\s*\\)\\s*(\\w+)\\s*:`, "s").exec(structMatch[1]);
				return fieldMatch ? fieldMatch[1] : null;
			};
			const appendHookParams = (params, additionalParams) => {
				if (additionalParams.length === 0) return params;
				const hasParams = !/^\(\s*\)$/.test(params);
				return `${params.slice(0, -1)}${hasParams ? ", " : ""}${additionalParams.join(", ")})`;
			};
			let hookExtraParams = [];
			let hookExtraArgs = [];
			if (shaderType === "vertex") {
				const ensuredInstance = ensureBuiltinParam(main, "instance_index", "instanceID", "u32");
				main = ensuredInstance.mainSrc;
				const ensuredVertex = ensureBuiltinParam(main, "vertex_index", "_p5VertexId", "u32");
				main = ensuredVertex.mainSrc;
				hookExtraParams = ["instanceID: u32", "_p5VertexId: u32"];
				hookExtraArgs = [ensuredInstance.argName, ensuredVertex.argName];
			} else if (shaderType === "fragment") {
				let fragmentPositionArg = getBuiltinParamName(main, "position");
				if (!fragmentPositionArg) {
					const mainStructParam = getMainStructParameter(main);
					if (mainStructParam) {
						const positionField = getStructBuiltinFieldName(mainStructParam.structName, "position");
						if (positionField) fragmentPositionArg = `${mainStructParam.inputName}.${positionField}`;
					}
				}
				if (!fragmentPositionArg) {
					const ensuredPosition = ensureBuiltinParam(main, "position", "_p5FragPos", "vec4<f32>");
					main = ensuredPosition.mainSrc;
					fragmentPositionArg = ensuredPosition.argName;
				}
				hookExtraParams = ["_p5FragPos: vec4<f32>"];
				hookExtraArgs = [fragmentPositionArg];
			} else if (shaderType === "compute") {
				const ensuredGlobalId = ensureBuiltinParam(main, "global_invocation_id", "_p5GlobalId", "vec3<u32>");
				main = ensuredGlobalId.mainSrc;
				hookExtraParams = ["_p5GlobalId: vec3<u32>"];
				hookExtraArgs = [ensuredGlobalId.argName];
			}
			let hookUniformFields = "";
			for (const key in shader.hooks.uniforms) {
				if (key.endsWith(": sampler2D")) continue;
				hookUniformFields += `  ${key},\n`;
			}
			if (hookUniformFields) {
				const nextBinding = this.getNextBindingIndex({
					vert: shaderType === "vertex" ? preMain + (shader.hooks.vertex?.declarations ?? "") + shader.hooks.declarations : shader._vertSrc,
					frag: shaderType === "fragment" ? preMain + (shader.hooks.fragment?.declarations ?? "") + shader.hooks.declarations : shader._fragSrc,
					compute: shaderType === "compute" ? preMain + (shader.hooks.compute?.declarations ?? "") + shader.hooks.declarations : shader._computeSrc
				}, 0);
				const hookUniformsDecl = `
// Hook Uniforms (from .modify())
struct HookUniforms {
${hookUniformFields}}

@group(0) @binding(${nextBinding}) var<uniform> hooks: HookUniforms;
`;
				const replaced = preMain.replace(/(@group\(0\)\s+@binding)/, `${hookUniformsDecl}\n$1`);
				if (replaced === preMain) preMain = preMain + "\n" + hookUniformsDecl;
				else preMain = replaced;
			}
			if (shader.hooks.varyingVariables && shader.hooks.varyingVariables.length > 0) {
				let nextLocationIndex = this._getNextAvailableLocation(preMain, shaderType);
				let varyingMembers = "";
				for (const varyingVar of shader.hooks.varyingVariables) {
					const member = `@location(${nextLocationIndex++}) ${varyingVar},`;
					varyingMembers += member + "\n";
				}
				if (shaderType === "vertex") preMain = preMain.replace(/struct\s+VertexOutput\s+\{([^}]*)\}/, (match, body) => `struct VertexOutput {${body}\n${varyingMembers}}`);
				else if (shaderType === "fragment") preMain = preMain.replace(/struct\s+FragmentInput\s+\{([^}]*)\}/, (match, body) => `struct FragmentInput {${body}\n${varyingMembers}}`);
			}
			if (shader.hooks.varyingVariables && shader.hooks.varyingVariables.length > 0) {
				let varyingDeclarations = "";
				for (const varyingVar of shader.hooks.varyingVariables) {
					const [varName, varType] = varyingVar.split(":").map((s) => s.trim());
					varyingDeclarations += `var<private> ${varName}: ${varType};\n`;
				}
				preMain += varyingDeclarations;
				if (shaderType === "vertex") {
					let copyStatements = "";
					for (const varyingVar of shader.hooks.varyingVariables) {
						const [varName] = varyingVar.split(":").map((s) => s.trim());
						copyStatements += `  OUTPUT_VAR.${varName} = ${varName};\n`;
					}
					const returnMatch = postMain.match(/return\s+(\w+)\s*;/);
					if (returnMatch) {
						const outputVarName = returnMatch[1];
						copyStatements = copyStatements.replace(/OUTPUT_VAR/g, outputVarName);
						postMain = postMain.replace(/(return\s+\w+\s*;)/g, `${copyStatements}  $1`);
					}
				} else if (shaderType === "fragment") {
					let initStatements = "";
					for (const varyingVar of shader.hooks.varyingVariables) {
						const [varName] = varyingVar.split(":").map((s) => s.trim());
						initStatements += `  ${varName} = INPUT_VAR.${varName};\n`;
					}
					const mainStructParam = getMainStructParameter(main);
					if (mainStructParam) {
						const inputVarName = mainStructParam.inputName;
						initStatements = initStatements.replace(/INPUT_VAR/g, inputVarName);
						postMain = initStatements + postMain;
					}
				}
			}
			if (shader.hooks.instanceIDVarying) {
				const { declaration, source, interpolation } = shader.hooks.instanceIDVarying;
				const nextLocIndex = this._getNextAvailableLocation(preMain, shaderType);
				const interpAttr = interpolation ? ` @interpolate(${interpolation})` : "";
				const [varName] = declaration.split(":").map((s) => s.trim());
				const structMember = `@location(${nextLocIndex})${interpAttr} ${declaration},`;
				if (shaderType === "vertex") {
					preMain = preMain.replace(/struct\s+VertexOutput\s+\{([^}]*)\}/, (match, body) => `struct VertexOutput {${body}\n${structMember}}`);
					preMain += `var<private> ${declaration};\n`;
					postMain = `\n  ${varName} = ${source};\n` + postMain;
					const returnMatch = postMain.match(/return\s+(\w+)\s*;/);
					if (returnMatch) {
						const outputVarName = returnMatch[1];
						postMain = postMain.replace(/(return\s+\w+\s*;)/g, `${outputVarName}.${varName} = ${varName};\n  $1`);
					}
				} else if (shaderType === "fragment") {
					preMain = preMain.replace(/struct\s+FragmentInput\s+\{([^}]*)\}/, (match, body) => `struct FragmentInput {${body}\n${structMember}}`);
					preMain += `var<private> ${declaration};\n`;
					const mainStructParam = getMainStructParameter(main);
					if (mainStructParam) postMain = `\n  ${varName} = ${mainStructParam.inputName}.${varName};\n` + postMain;
				}
			}
			let hooks = "";
			let defines = "";
			if (shader.hooks.declarations) hooks += shader.hooks.declarations + "\n";
			if (shader.hooks[shaderType] && shader.hooks[shaderType].declarations) hooks += shader.hooks[shaderType].declarations + "\n";
			for (const hookDef in shader.hooks.helpers) {
				const [hookType, hookName] = hookDef.split(" ");
				const [, params, body] = /^(\([^)]*\))((?:.|\n)*)$/.exec(shader.hooks.helpers[hookDef]);
				if (hookType === "void") hooks += `fn ${hookName}${params}${body}\n`;
				else hooks += `fn ${hookName}${params} -> ${hookType}${body}\n`;
			}
			for (const hookDef in shader.hooks[shaderType]) {
				if (hookDef === "declarations") continue;
				const [hookType, hookName] = hookDef.split(" ");
				defines += `const AUGMENTED_HOOK_${hookName} = ${shader.hooks.modified[shaderType][hookDef] ? "true" : "false"};\n`;
				let [, params, body] = /^(\([^)]*\))((?:.|\n)*)$/.exec(shader.hooks[shaderType][hookDef]);
				params = appendHookParams(params, hookExtraParams);
				if (hookType === "void") hooks += `fn HOOK_${hookName}${params}${body}\n`;
				else hooks += `fn HOOK_${hookName}${params} -> ${hookType}${body}\n`;
			}
			if (hookExtraArgs.length > 0) {
				const addHookArgs = (src) => {
					const insertions = [];
					let searchIdx = 0;
					let m;
					while ((m = /HOOK_\w+\(/.exec(src.slice(searchIdx))) !== null) {
						const openParen = searchIdx + m.index + m[0].length - 1;
						let pos = openParen + 1;
						let nesting = 1;
						let hasParams = false;
						while (pos < src.length && nesting > 0) {
							if (src[pos] === "(") nesting++;
							else if (src[pos] === ")") {
								nesting--;
								if (nesting === 0) break;
							} else if (/\S/.test(src[pos])) hasParams = true;
							pos++;
						}
						insertions.push({
							pos,
							hasParams
						});
						searchIdx = openParen + 1;
					}
					insertions.sort((a, b) => b.pos - a.pos);
					let result = src;
					for (const { pos, hasParams } of insertions) {
						const insertion = (hasParams ? ", " : "") + hookExtraArgs.join(", ");
						result = result.slice(0, pos) + insertion + result.slice(pos);
					}
					return result;
				};
				preMain = addHookArgs(preMain);
				postMain = addHookArgs(postMain);
			}
			return preMain + "\n" + defines + hooks + main + postMain;
		}
		_getNextAvailableLocation(shaderSource, shaderType) {
			let maxLocation = -1;
			const structName = shaderType === "vertex" ? "VertexOutput" : "FragmentInput";
			const structMatch = shaderSource.match(new RegExp(`struct\\s+${structName}\\s*\\{([^}]*)\\}`, "s"));
			if (structMatch) {
				const locationMatches = structMatch[1].matchAll(/@location\((\d+)\)/g);
				for (const match of locationMatches) {
					const locationNum = parseInt(match[1]);
					if (locationNum > maxLocation) maxLocation = locationNum;
				}
			}
			return maxLocation + 1;
		}
		getShaderHookTypes(shader, hookName) {
			const wgslToDataType = {
				f32: DataType.float1,
				"vec2<f32>": DataType.float2,
				"vec3<f32>": DataType.float3,
				"vec4<f32>": DataType.float4,
				vec2f: DataType.float2,
				vec3f: DataType.float3,
				vec4f: DataType.float4,
				i32: DataType.int1,
				"vec2<i32>": DataType.int2,
				"vec3<i32>": DataType.int3,
				"vec4<i32>": DataType.int4,
				bool: DataType.bool1,
				"vec2<bool>": DataType.bool2,
				"vec3<bool>": DataType.bool3,
				"vec4<bool>": DataType.bool4,
				"mat2x2<f32>": DataType.mat2,
				"mat3x3<f32>": DataType.mat3,
				"mat4x4<f32>": DataType.mat4,
				"texture_2d<f32>": DataType.sampler2D
			};
			let fullSrc = shader._vertSrc;
			let body = shader.hooks.vertex[hookName];
			if (!body) {
				body = shader.hooks.fragment[hookName];
				fullSrc = shader._fragSrc;
			}
			if (!body) {
				body = shader.hooks.compute[hookName];
				fullSrc = shader._computeSrc;
			}
			if (!body) throw new Error(`Can't find hook ${hookName}!`);
			const nameParts = hookName.split(/\s+/g);
			const functionName = nameParts.pop();
			const returnType = nameParts.pop();
			const returnQualifiers = [...nameParts];
			const parameterMatch = /\(([^)]*)\)/.exec(body);
			if (!parameterMatch) throw new Error(`Couldn't find function parameters in hook body:\n${body}`);
			const structProperties = (structName) => {
				const structDefMatch = new RegExp(`struct\\s+${structName}\\s*{([^}]*)}`).exec(fullSrc);
				if (!structDefMatch) return void 0;
				const properties = [];
				for (const fieldSrc of structDefMatch[1].split(",")) {
					const trimmed = fieldSrc.trim();
					if (!trimmed) continue;
					const fieldMatch = /(?:@location\([^)]*\)\s*)?(\w+)\s*:\s*([^,\s]+)/.exec(trimmed);
					if (!fieldMatch) continue;
					const name = fieldMatch[1];
					let typeName = fieldMatch[2];
					const dataType = wgslToDataType[typeName] || null;
					const typeProperties = structProperties(typeName);
					properties.push({
						name,
						type: {
							typeName,
							qualifiers: [],
							properties: typeProperties,
							dataType
						}
					});
				}
				return properties;
			};
			const parameters = parameterMatch[1].split(",").map((paramString) => {
				const trimmed = paramString.trim();
				if (!trimmed) return null;
				const parts = trimmed.split(":").map((s) => s.trim());
				if (parts.length !== 2) return null;
				const name = parts[0];
				let typeName = parts[1];
				if (typeName.includes("texture_2d")) typeName = "texture_2d<f32>";
				const dataType = wgslToDataType[typeName] || null;
				const properties = structProperties(typeName);
				return {
					name,
					type: {
						typeName,
						qualifiers: [],
						properties,
						dataType
					}
				};
			}).filter(Boolean);
			const returnDataType = wgslToDataType[returnType] || null;
			return {
				name: functionName,
				returnType: {
					typeName: returnType,
					qualifiers: returnQualifiers,
					properties: structProperties(returnType),
					dataType: returnDataType
				},
				parameters
			};
		}
		_ensurePixelReadBuffer(requiredSize) {
			if (!this.pixelReadBuffer || this.pixelReadBufferSize < requiredSize) {
				if (this.pixelReadBuffer) {
					this.flushDraw();
					this.pixelReadBuffer.destroy();
				}
				const bufferSize = Math.max(requiredSize, this.pixelReadBufferSize * 2);
				this.pixelReadBuffer = this.device.createBuffer({
					size: bufferSize,
					usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
				});
				this.pixelReadBufferSize = bufferSize;
			}
			return this.pixelReadBuffer;
		}
		_alignBytesPerRow(bytesPerRow) {
			return Math.ceil(bytesPerRow / 256) * 256;
		}
		defaultFramebufferAlpha() {
			return true;
		}
		defaultFramebufferAntialias() {
			return this._pInst._webgpuAttributes?.antialias !== false;
		}
		supportsFramebufferAntialias() {
			return true;
		}
		createFramebufferResources(framebuffer) {}
		validateFramebufferFormats(framebuffer) {
			if (![
				"unsigned-byte",
				"float",
				"half-float"
			].includes(framebuffer.format)) {
				console.warn("Unknown Framebuffer format. Please use UNSIGNED_BYTE, FLOAT, or HALF_FLOAT. Defaulting to UNSIGNED_BYTE.");
				framebuffer.format = UNSIGNED_BYTE;
			}
			if (framebuffer.useDepth && !["unsigned-int", "float"].includes(framebuffer.depthFormat)) {
				console.warn("Unknown Framebuffer depth format. Please use UNSIGNED_INT or FLOAT. Defaulting to FLOAT.");
				framebuffer.depthFormat = FLOAT;
			}
		}
		recreateFramebufferTextures(framebuffer) {
			this.flushDraw();
			if (framebuffer.colorTexture && framebuffer.colorTexture.destroy) {
				const tex = framebuffer.colorTexture;
				this._postSubmitCallbacks.push(() => tex.destroy());
				framebuffer.colorTextureView = null;
			}
			if (framebuffer.aaColorTexture && framebuffer.aaColorTexture.destroy) {
				const tex = framebuffer.aaColorTexture;
				this._postSubmitCallbacks.push(() => tex.destroy());
				framebuffer.aaColorTextureView = null;
			}
			if (framebuffer.depthTexture && framebuffer.depthTexture.destroy) {
				const tex = framebuffer.depthTexture;
				this._postSubmitCallbacks.push(() => tex.destroy());
				framebuffer.depthTextureView = null;
			}
			if (framebuffer.aaDepthTexture && framebuffer.aaDepthTexture.destroy) {
				const tex = framebuffer.aaDepthTexture;
				this._postSubmitCallbacks.push(() => tex.destroy());
				framebuffer.aaDepthTextureView = null;
			}
			const baseDescriptor = {
				size: {
					width: framebuffer.width * framebuffer.density,
					height: framebuffer.height * framebuffer.density,
					depthOrArrayLayers: 1
				},
				format: this._getWebGPUColorFormat(framebuffer)
			};
			const colorTextureDescriptor = {
				...baseDescriptor,
				usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | (framebuffer._useCanvasFormat ? GPUTextureUsage.COPY_DST : 0),
				sampleCount: 1
			};
			framebuffer.colorTexture = this.device.createTexture(colorTextureDescriptor);
			framebuffer.colorTextureView = framebuffer.colorTexture.createView();
			if (framebuffer.antialias) {
				const aaColorTextureDescriptor = {
					...baseDescriptor,
					usage: GPUTextureUsage.RENDER_ATTACHMENT,
					sampleCount: this._getValidSampleCount(framebuffer.antialiasSamples)
				};
				framebuffer.aaColorTexture = this.device.createTexture(aaColorTextureDescriptor);
				framebuffer.aaColorTextureView = framebuffer.aaColorTexture.createView();
			}
			if (framebuffer.useDepth) {
				const depthBaseDescriptor = {
					size: {
						width: framebuffer.width * framebuffer.density,
						height: framebuffer.height * framebuffer.density,
						depthOrArrayLayers: 1
					},
					format: this._getWebGPUDepthFormat(framebuffer)
				};
				const depthTextureDescriptor = {
					...depthBaseDescriptor,
					usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | (framebuffer._useCanvasFormat ? GPUTextureUsage.COPY_DST : 0),
					sampleCount: 1
				};
				framebuffer.depthTexture = this.device.createTexture(depthTextureDescriptor);
				framebuffer.depthTextureView = framebuffer.depthTexture.createView();
				if (framebuffer.antialias) {
					const aaDepthTextureDescriptor = {
						...depthBaseDescriptor,
						usage: GPUTextureUsage.RENDER_ATTACHMENT,
						sampleCount: this._getValidSampleCount(framebuffer.antialiasSamples)
					};
					framebuffer.aaDepthTexture = this.device.createTexture(aaDepthTextureDescriptor);
					framebuffer.aaDepthTextureView = framebuffer.aaDepthTexture.createView();
				}
			}
			this._clearFramebufferTextures(framebuffer);
		}
		_clearFramebufferTextures(framebuffer) {
			this._finishActiveRenderPass();
			const commandEncoder = this.device.createCommandEncoder();
			const colorAttachment = {
				view: framebuffer.aaColorTexture ? framebuffer.aaColorTextureView : framebuffer.colorTextureView,
				loadOp: "clear",
				storeOp: "store",
				clearValue: {
					r: 0,
					g: 0,
					b: 0,
					a: 0
				},
				resolveTarget: framebuffer.aaColorTexture ? framebuffer.colorTextureView : void 0
			};
			const depthStencilAttachment = framebuffer.aaDepthTexture || framebuffer.depthTexture ? {
				view: framebuffer.aaDepthTexture ? framebuffer.aaDepthTextureView : framebuffer.depthTextureView,
				depthLoadOp: "clear",
				depthStoreOp: "store",
				depthClearValue: 1,
				stencilLoadOp: "clear",
				stencilStoreOp: "store",
				depthReadOnly: false,
				stencilReadOnly: false
			} : void 0;
			const renderPassDescriptor = {
				colorAttachments: [colorAttachment],
				depthStencilAttachment
			};
			commandEncoder.beginRenderPass(renderPassDescriptor).end();
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this._hasPendingDraws = true;
		}
		_getFramebufferColorTextureView(framebuffer) {
			if (framebuffer.colorTexture) return framebuffer.colorTextureView;
			return null;
		}
		createFramebufferTextureHandle(framebufferTexture) {
			const src = framebufferTexture;
			let renderer = this;
			return {
				get view() {
					return renderer._getFramebufferColorTextureView(src.framebuffer);
				},
				get gpuTexture() {
					return src.framebuffer.colorTexture;
				}
			};
		}
		_jsValueToWgslType(value) {
			if (typeof value === "number") return "f32";
			if (value?.isVector) {
				if (value.dimensions === 2) return "vec2f";
				if (value.dimensions === 3) return "vec3f";
				if (value.dimensions === 4) return "vec4f";
				throw new Error(`Unsupported vector dimension ${value.dimensions} for struct storage field`);
			}
			if (value?.isColor) return "vec4f";
			if (Array.isArray(value)) {
				if (value.length === 2) return "vec2f";
				if (value.length === 3) return "vec3f";
				if (value.length === 4) return "vec4f";
				throw new Error(`Unsupported array length ${value.length} for struct storage field`);
			}
			throw new Error(`Unsupported value type ${typeof value} for struct storage field`);
		}
		_inferStructSchema(firstElement) {
			const entries = Object.entries(firstElement);
			if (!p5.disableFriendlyErrors) {
				for (const [name, value] of entries) if (value !== null && typeof value === "object" && !Array.isArray(value) && !value?.isVector && !value?.isColor) p5._friendlyError(`The "${name}" property in your storage data contains a nested object. Make sure you only use properties with numbers, arrays of numbers, or p5.Vector.`, "createStorage");
			}
			const structBody = `{\n${entries.map(([name, value]) => `  ${name}: ${this._jsValueToWgslType(value)},`).join("\n")}\n}`;
			const elements = this._parseStruct(`struct _Tmp ${structBody}`, "_Tmp");
			let maxEnd = 0;
			let maxAlign = 1;
			return {
				fields: entries.map(([name, value]) => {
					const el = elements[name];
					maxEnd = Math.max(maxEnd, el.offsetEnd);
					const align = el.size <= 4 ? 4 : el.size <= 8 ? 8 : 16;
					maxAlign = Math.max(maxAlign, align);
					const kind = value?.isVector ? "vector" : value?.isColor ? "color" : void 0;
					return {
						name,
						baseType: el.baseType,
						size: el.size,
						offset: el.offset,
						packInPlace: el.packInPlace ?? false,
						dim: el.size / 4,
						kind
					};
				}),
				stride: Math.ceil(maxEnd / maxAlign) * maxAlign,
				structBody
			};
		}
		_packStructArray(data, schema) {
			const { fields, stride } = schema;
			const totalBytes = Math.max(data.length * stride, 16);
			const alignedBytes = Math.ceil(totalBytes / 16) * 16;
			const buffer = new ArrayBuffer(alignedBytes);
			const floatView = new Float32Array(buffer);
			const dataView = new DataView(buffer);
			for (let i = 0; i < data.length; i++) {
				const item = data[i];
				const baseOffset = i * stride;
				for (const field of fields) this._packField(field, item[field.name], floatView, dataView, baseOffset);
			}
			return floatView;
		}
		_unpackStructArray(floatView, schema) {
			const { fields, stride } = schema;
			const dataView = new DataView(floatView.buffer);
			const count = Math.floor(floatView.byteLength / stride);
			const result = [];
			for (let i = 0; i < count; i++) {
				const item = {};
				const baseOffset = i * stride;
				for (const field of fields) {
					const byteOffset = baseOffset + field.offset;
					const n = field.size / 4;
					if (field.baseType === "u32") {
						if (n === 1) item[field.name] = dataView.getUint32(byteOffset, true);
						else item[field.name] = Array.from({ length: n }, (_, j) => dataView.getUint32(byteOffset + j * 4, true));
					} else if (field.baseType === "i32") {
						if (n === 1) item[field.name] = dataView.getInt32(byteOffset, true);
						else item[field.name] = Array.from({ length: n }, (_, j) => dataView.getInt32(byteOffset + j * 4, true));
					} else {
						const idx = byteOffset / 4;
						if (n === 1) item[field.name] = floatView[idx];
						else {
							const values = Array.from(floatView.slice(idx, idx + n));
							if (field.kind === "vector") item[field.name] = this._pInst.createVector(...values);
							else if (field.kind === "color") {
								const maxes = this.states.colorMaxes[this.states.colorMode];
								item[field.name] = this._pInst.color(values[0] * maxes[0], values[1] * maxes[1], values[2] * maxes[2], values[3] * maxes[3]);
							} else item[field.name] = values;
						}
					}
				}
				result.push(item);
			}
			return result;
		}
		/**
		* Resolves the WGSL element type a shader declares for a storage buffer
		* into the typed array that reads it back correctly, unwrapping
		* `atomic<T>` to `T`. Returns undefined for types we can't check.
		* @private
		*/
		_storageArrayTypeFor(elementType) {
			if (!elementType) return void 0;
			return STORAGE_ARRAY_TYPES[elementType.replace(/^atomic<(\w+)>$/, "$1")];
		}
		/**
		* Warns when the typed array a storage buffer was created with doesn't
		* match the element type the shader declares for it, since the bytes
		* would otherwise be silently reinterpreted.
		*
		* Both call sites run every frame, so the result is cached on the buffer:
		* after the first check this costs a property read and a comparison, and
		* any warning is only ever logged once.
		* @private
		*/
		_checkStorageElementType(parsedStorage, storageBuffer) {
			if (p5.disableFriendlyErrors) return;
			const expected = parsedStorage?.expectedArrayType;
			if (!expected) return;
			if (storageBuffer._isStorageList) return;
			if (storageBuffer._checkedArrayType === expected) return;
			storageBuffer._checkedArrayType = expected;
			if (storageBuffer._schema !== null) return;
			if (storageBuffer._arrayType === expected) return;
			p5._friendlyError(`The storage buffer "${parsedStorage.name}" is declared as array<${parsedStorage.elementType}> in the shader, but it was created with a ${storageBuffer._arrayType.name}. Create it with a ${expected.name} instead so the values are read back correctly.`, "createStorage");
		}
		createStorage(dataOrCount) {
			const device = this.device;
			if (Array.isArray(dataOrCount) && dataOrCount.length > 0 && typeof dataOrCount[0] === "object" && !Array.isArray(dataOrCount[0])) {
				if (!p5.disableFriendlyErrors && dataOrCount.length > 1) {
					const firstKeys = Object.keys(dataOrCount[0]);
					let warned = false;
					for (let i = 1; i < dataOrCount.length; i++) {
						const el = dataOrCount[i];
						const elKeys = Object.keys(el);
						if (!(firstKeys.length === elKeys.length && firstKeys.every((k, j) => k === elKeys[j]))) {
							p5._friendlyError(`Element ${i} has different fields than element 0. All elements should have the same properties.`, "createStorage");
							break;
						}
						for (const key of firstKeys) {
							const firstType = this._jsValueToWgslType(dataOrCount[0][key]);
							const elType = this._jsValueToWgslType(el[key]);
							if (firstType !== elType) {
								p5._friendlyError(`The "${key}" property of element ${i} has type ${elType} but element 0 has type ${firstType}. Proporties should have the same type across all elements.`, "createStorage");
								warned = true;
								break;
							}
						}
						if (warned) break;
					}
				}
				const schema = this._inferStructSchema(dataOrCount[0]);
				const packed = this._packStructArray(dataOrCount, schema);
				const size = packed.byteLength;
				const buffer = device.createBuffer({
					size,
					usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
					mappedAtCreation: true
				});
				new Float32Array(buffer.getMappedRange()).set(packed);
				buffer.unmap();
				const storageBuffer = new StorageBuffer(buffer, size, this, schema, Float32Array, dataOrCount.length);
				this._storageBuffers.add(storageBuffer);
				return storageBuffer;
			}
			let size, initialData;
			if (typeof dataOrCount === "number") {
				size = dataOrCount * 4;
				initialData = new Float32Array(dataOrCount);
			} else {
				if (ArrayBuffer.isView(dataOrCount) && !(dataOrCount instanceof DataView)) initialData = dataOrCount;
				else if (Array.isArray(dataOrCount)) initialData = new Float32Array(dataOrCount);
				else throw new Error("createStorage expects a number or array/TypedArray");
				size = initialData.byteLength;
			}
			const ArrayType = initialData.constructor;
			size = Math.ceil(size / 16) * 16;
			const buffer = device.createBuffer({
				size,
				usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
				mappedAtCreation: initialData.length > 0
			});
			if (initialData.length > 0) {
				new ArrayType(buffer.getMappedRange()).set(initialData);
				buffer.unmap();
			}
			const storageBuffer = new StorageBuffer(buffer, size, this, null, ArrayType, initialData.length);
			this._storageBuffers.add(storageBuffer);
			return storageBuffer;
		}
		createStorageList(maxCapacity, schemaOrData) {
			const device = this.device;
			let schema = null;
			let initialCount = 0;
			let initialDataPacked = null;
			if (Array.isArray(schemaOrData) && schemaOrData.length > 0 && typeof schemaOrData[0] === "object" && !Array.isArray(schemaOrData[0])) {
				schema = this._inferStructSchema(schemaOrData[0]);
				initialDataPacked = this._packStructArray(schemaOrData, schema);
				initialCount = schemaOrData.length;
			} else if (schemaOrData !== void 0 && typeof schemaOrData === "object" && !Array.isArray(schemaOrData)) schema = this._inferStructSchema(schemaOrData);
			const lengthOffset = maxCapacity * (schema ? schema.stride : 4);
			const totalSize = Math.max(Math.ceil((lengthOffset + 4) / 16) * 16, 16);
			const buffer = device.createBuffer({
				size: totalSize,
				usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
				mappedAtCreation: true
			});
			const mapped = buffer.getMappedRange();
			if (initialDataPacked !== null) new Float32Array(mapped).set(initialDataPacked);
			new Int32Array(mapped, lengthOffset, 1).set([initialCount]);
			buffer.unmap();
			const storageList = new StorageList(buffer, lengthOffset, maxCapacity, this, schema, initialCount);
			this._storageBuffers.add(storageList);
			return storageList;
		}
		_getWebGPUColorFormat(framebuffer) {
			if (framebuffer.format === "float") return framebuffer.channels === RGBA ? "rgba32float" : "rgba32float";
			else if (framebuffer.format === "half-float") return framebuffer.channels === RGBA ? "rgba16float" : "rgba16float";
			else {
				if (framebuffer._useCanvasFormat) return this.presentationFormat;
				return framebuffer.channels === RGBA ? "rgba8unorm" : "rgba8unorm";
			}
		}
		_getWebGPUDepthFormat(framebuffer) {
			if (framebuffer._useCanvasFormat) return this.depthFormat;
			if (framebuffer.useStencil) return framebuffer.depthFormat === "float" ? "depth32float-stencil8" : "depth24plus-stencil8";
			else return framebuffer.depthFormat === "float" ? "depth32float" : "depth24plus";
		}
		_deleteFramebufferTexture(texture) {
			this.flushDraw();
			const handle = texture.rawTexture();
			if (handle.texture && handle.texture.destroy) {
				const tex = handle.texture;
				this._postSubmitCallbacks.push(() => tex.destroy());
			}
			this.textures.delete(texture);
		}
		deleteFramebufferTextures(framebuffer) {
			this._deleteFramebufferTexture(framebuffer.color);
			if (framebuffer.depth) this._deleteFramebufferTexture(framebuffer.depth);
		}
		deleteFramebufferResources(framebuffer) {
			this.flushDraw();
			if (framebuffer.colorTexture && framebuffer.colorTexture.destroy) {
				const tex = framebuffer.colorTexture;
				this._postSubmitCallbacks.push(() => tex.destroy());
			}
			if (framebuffer.depthTexture && framebuffer.depthTexture.destroy) {
				const tex = framebuffer.depthTexture;
				this._postSubmitCallbacks.push(() => tex.destroy());
			}
			if (framebuffer.aaDepthTexture && framebuffer.aaDepthTexture.destroy) {
				const tex = framebuffer.aaDepthTexture;
				this._postSubmitCallbacks.push(() => tex.destroy());
			}
		}
		getFramebufferToBind(framebuffer) {}
		updateFramebufferTexture(framebuffer, property) {}
		bindFramebuffer(framebuffer) {}
		framebufferYScale() {
			return 1;
		}
		async readFramebufferPixels(framebuffer) {
			this.flushDraw();
			const width = framebuffer.width * framebuffer.density;
			const height = framebuffer.height * framebuffer.density;
			const bytesPerPixel = 4;
			const unalignedBytesPerRow = width * bytesPerPixel;
			const alignedBytesPerRow = this._alignBytesPerRow(unalignedBytesPerRow);
			const bufferSize = alignedBytesPerRow * height;
			const stagingBuffer = this.device.createBuffer({
				size: bufferSize,
				usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
			});
			const commandEncoder = this.device.createCommandEncoder();
			commandEncoder.copyTextureToBuffer({
				texture: framebuffer.colorTexture,
				origin: {
					x: 0,
					y: 0,
					z: 0
				},
				mipLevel: 0,
				aspect: "all"
			}, {
				buffer: stagingBuffer,
				bytesPerRow: alignedBytesPerRow,
				rowsPerImage: height
			}, {
				width,
				height,
				depthOrArrayLayers: 1
			});
			this.device.queue.submit([commandEncoder.finish()]);
			await stagingBuffer.mapAsync(GPUMapMode.READ, 0, bufferSize);
			const mappedRange = stagingBuffer.getMappedRange(0, bufferSize);
			let result;
			if (alignedBytesPerRow === unalignedBytesPerRow) {
				result = new Uint8Array(mappedRange.slice(0, width * height * bytesPerPixel));
				stagingBuffer.unmap();
			} else {
				result = new Uint8Array(width * height * bytesPerPixel);
				const mappedData = new Uint8Array(mappedRange);
				for (let y = 0; y < height; y++) {
					const srcOffset = y * alignedBytesPerRow;
					const dstOffset = y * unalignedBytesPerRow;
					result.set(mappedData.subarray(srcOffset, srcOffset + unalignedBytesPerRow), dstOffset);
				}
				stagingBuffer.unmap();
			}
			this._ensurePixelsAreRGBA(framebuffer, result);
			return result;
		}
		async readFramebufferPixel(framebuffer, x, y) {
			this.flushDraw();
			const alignedBytesPerRow = this._alignBytesPerRow(4);
			const bufferSize = alignedBytesPerRow;
			const stagingBuffer = this._ensurePixelReadBuffer(bufferSize);
			const commandEncoder = this.device.createCommandEncoder();
			commandEncoder.copyTextureToBuffer({
				texture: framebuffer.colorTexture,
				origin: {
					x,
					y,
					z: 0
				}
			}, {
				buffer: stagingBuffer,
				bytesPerRow: alignedBytesPerRow
			}, {
				width: 1,
				height: 1,
				depthOrArrayLayers: 1
			});
			this.device.queue.submit([commandEncoder.finish()]);
			await stagingBuffer.mapAsync(GPUMapMode.READ, 0, bufferSize);
			const mappedRange = stagingBuffer.getMappedRange(0, bufferSize);
			const pixelData = new Uint8Array(mappedRange);
			const result = [
				pixelData[0],
				pixelData[1],
				pixelData[2],
				pixelData[3]
			];
			this._ensurePixelsAreRGBA(framebuffer, result);
			stagingBuffer.unmap();
			return result;
		}
		async readFramebufferRegion(framebuffer, x, y, w, h) {
			this.flushDraw();
			const width = w * framebuffer.density;
			const height = h * framebuffer.density;
			const bytesPerPixel = 4;
			const unalignedBytesPerRow = width * bytesPerPixel;
			const alignedBytesPerRow = this._alignBytesPerRow(unalignedBytesPerRow);
			const bufferSize = alignedBytesPerRow * height;
			const stagingBuffer = this._ensurePixelReadBuffer(bufferSize);
			const commandEncoder = this.device.createCommandEncoder();
			commandEncoder.copyTextureToBuffer({
				texture: framebuffer.colorTexture,
				mipLevel: 0,
				origin: {
					x: x * framebuffer.density,
					y: y * framebuffer.density,
					z: 0
				}
			}, {
				buffer: stagingBuffer,
				bytesPerRow: alignedBytesPerRow
			}, {
				width,
				height,
				depthOrArrayLayers: 1
			});
			this.device.queue.submit([commandEncoder.finish()]);
			await stagingBuffer.mapAsync(GPUMapMode.READ, 0, bufferSize);
			const mappedRange = stagingBuffer.getMappedRange(0, bufferSize);
			let pixelData;
			if (alignedBytesPerRow === unalignedBytesPerRow) pixelData = new Uint8Array(mappedRange.slice(0, width * height * bytesPerPixel));
			else {
				pixelData = new Uint8Array(width * height * bytesPerPixel);
				const mappedData = new Uint8Array(mappedRange);
				for (let y = 0; y < height; y++) {
					const srcOffset = y * alignedBytesPerRow;
					const dstOffset = y * unalignedBytesPerRow;
					pixelData.set(mappedData.subarray(srcOffset, srcOffset + unalignedBytesPerRow), dstOffset);
				}
			}
			this._ensurePixelsAreRGBA(framebuffer, pixelData);
			const region = new Image(width, height);
			region.imageData = region.canvas.getContext("2d").createImageData(width, height);
			region.imageData.data.set(pixelData);
			region.pixels = region.imageData.data;
			region.updatePixels();
			if (framebuffer.density !== 1) region.pixelDensity(framebuffer.density);
			stagingBuffer.unmap();
			return region;
		}
		updateFramebufferPixels(framebuffer) {
			const width = framebuffer.width * framebuffer.density;
			const height = framebuffer.height * framebuffer.density;
			const bytesPerPixel = 4;
			const expectedLength = width * height * bytesPerPixel;
			if (!framebuffer.pixels || framebuffer.pixels.length !== expectedLength) throw new Error("The pixels array has not been set correctly. Please call loadPixels() before updatePixels().");
			this.device.queue.writeTexture({ texture: framebuffer.colorTexture }, framebuffer.pixels, {
				bytesPerRow: width * bytesPerPixel,
				rowsPerImage: height
			}, {
				width,
				height,
				depthOrArrayLayers: 1
			});
		}
		_ensurePixelsAreRGBA(framebuffer, result) {
			if (framebuffer._useCanvasFormat && this.presentationFormat === "bgra8unorm") this._convertBGRtoRGB(result);
		}
		_convertBGRtoRGB(pixelData) {
			for (let i = 0; i < pixelData.length; i += 4) {
				const temp = pixelData[i];
				pixelData[i] = pixelData[i + 2];
				pixelData[i + 2] = temp;
			}
		}
		async loadPixels() {
			this._promoteToFramebuffer();
			await this.mainFramebuffer.loadPixels();
			this.pixels = this.mainFramebuffer.pixels.slice();
		}
		async get(x, y, w, h) {
			this._promoteToFramebuffer();
			return this.mainFramebuffer.get(x, y, w, h);
		}
		filter(...args) {
			if (!this.activeFramebuffer()) this._promoteToFramebuffer();
			return super.filter(...args);
		}
		baseFilterShader() {
			if (!this._baseFilterShader) this._baseFilterShader = new Shader(this, baseFilterVertexShader, baseFilterFragmentShader, {
				vertex: {},
				fragment: { "vec4<f32> getColor": `(inputs: FilterInputs, canvasContent: texture_2d<f32>, canvasContent_sampler: sampler) -> vec4<f32> {
                return textureSample(tex, tex_sampler, inputs.texCoord);
              }` },
				hookAliases: { getColor: ["filterColor"] }
			});
			return this._baseFilterShader;
		}
		baseComputeShader() {
			if (!this._baseComputeShader) this._baseComputeShader = new Shader(this, baseComputeShader, { compute: { "void iteration": "(index: vec3<i32>) {}" } });
			return this._baseComputeShader;
		}
		_createImageLightShader(type) {
			if (type === "diffused") return this._pInst.createShader(imageLightVertexShader, imageLightDiffusedFragmentShader);
			else if (type === "specular") return this._pInst.createShader(imageLightVertexShader, imageLightSpecularFragmentShader);
			throw new Error(`Unknown imageLight shader type: ${type}`);
		}
		_createMipmapTexture(levels) {
			return new MipmapTexture(this, levels, {});
		}
		_prepareMipmapData(size, mipLevels) {
			const textureDescriptor = {
				size: {
					width: size,
					height: size,
					depthOrArrayLayers: 1
				},
				mipLevelCount: mipLevels,
				format: "rgba8unorm",
				usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
			};
			return {
				gpuTexture: this.device.createTexture(textureDescriptor),
				size,
				mipLevels,
				format: "rgba8unorm"
			};
		}
		_accumulateMipLevel(framebuffer, mipmapData, mipLevel, width, height) {
			this.flushDraw();
			const commandEncoder = this.device.createCommandEncoder();
			const sourceTexture = framebuffer.color.rawTexture().texture;
			commandEncoder.copyTextureToTexture({
				texture: sourceTexture,
				origin: {
					x: 0,
					y: 0,
					z: 0
				}
			}, {
				texture: mipmapData.gpuTexture,
				mipLevel,
				origin: {
					x: 0,
					y: 0,
					z: 0
				}
			}, {
				width,
				height,
				depthOrArrayLayers: 1
			});
			this.device.queue.submit([commandEncoder.finish()]);
		}
		_finalizeMipmapTexture(mipmapData) {
			return new MipmapTexture(this, mipmapData, {});
		}
		createMipmapTextureHandle({ gpuTexture, format, dataType, width, height }) {
			return {
				texture: gpuTexture,
				view: gpuTexture.createView(),
				glFormat: format || "rgba8unorm",
				glDataType: dataType || "uint8"
			};
		}
		compute(shader, x, y = 1, z = 1) {
			if (shader.shaderType !== "compute") throw new Error("compute() can only be called with a compute shader");
			this._finishActiveRenderPass();
			if (!shader._compiled) shader.init();
			shader.setDefaultUniforms();
			shader.setUniform("uTotalCount", [
				x,
				y,
				z
			]);
			const WORKGROUP_SIZE_X = 8;
			const WORKGROUP_SIZE_Y = 8;
			const WORKGROUP_SIZE_Z = 1;
			const totalIterations = x * y * z;
			const MAX_THREADS_PER_DIM = 524280;
			let px = x;
			let py = y;
			let pz = z;
			if (x > MAX_THREADS_PER_DIM || y > MAX_THREADS_PER_DIM || z > MAX_THREADS_PER_DIM || totalIterations > 1024 && y === 1 && z === 1) {
				px = Math.ceil(Math.sqrt(totalIterations));
				py = Math.ceil(totalIterations / px);
				pz = 1;
			}
			const workgroupCountX = Math.ceil(px / WORKGROUP_SIZE_X);
			const workgroupCountY = Math.ceil(py / WORKGROUP_SIZE_Y);
			const workgroupCountZ = Math.ceil(pz / WORKGROUP_SIZE_Z);
			shader.setUniform("uPhysicalCount", [
				workgroupCountX * WORKGROUP_SIZE_X,
				workgroupCountY * WORKGROUP_SIZE_Y,
				workgroupCountZ * WORKGROUP_SIZE_Z
			]);
			const commandEncoder = this.device.createCommandEncoder();
			const passEncoder = commandEncoder.beginComputePass();
			this.setupShaderBindGroups(shader, passEncoder, {
				compute: true,
				workgroupSize: [
					WORKGROUP_SIZE_X,
					WORKGROUP_SIZE_Y,
					WORKGROUP_SIZE_Z
				]
			});
			passEncoder.dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ);
			passEncoder.end();
			this._pendingCommandEncoders.push(commandEncoder.finish());
			this._hasPendingDraws = true;
		}
	}
	p5.RendererWebGPU = RendererWebGPU;
	p5.renderers[WEBGPU] = p5.RendererWebGPU;
	fn.setAttributes = async function(key, value) {
		return this._renderer._setAttributes(key, value);
	};
}
if (typeof p5 !== "undefined") rendererWebGPU(p5, p5.prototype);
//#endregion
export { rendererWebGPU as default };