import { ExtensionType } from '../../../extensions/Extensions.mjs';

class BindGroupSystem {
  constructor(renderer) {
    this._hash = /* @__PURE__ */ Object.create(null);
    this._renderer = renderer;
  }
  contextChange(gpu) {
    this._gpu = gpu;
  }
  getBindGroup(bindGroup, program, groupIndex) {
    bindGroup.updateKey();
    const gpuBindGroup = this._hash[bindGroup.key] || this._createBindGroup(bindGroup, program, groupIndex);
    return gpuBindGroup;
  }
  _createBindGroup(group, program, groupIndex) {
    const device = this._gpu.device;
    const groupLayout = program.layout[groupIndex];
    const entries = [];
    for (const j in groupLayout) {
      const resource = group.resources[j] ?? group.resources[groupLayout[j]];
      let gpuResource;
      if (resource.resourceType === "uniformGroup") {
        const uniformGroup = resource;
        this._renderer.uniformBuffer.updateUniformGroup(uniformGroup);
        const buffer = uniformGroup.buffer;
        gpuResource = {
          buffer: this._renderer.buffer.getGPUBuffer(buffer),
          offset: 0,
          size: buffer.descriptor.size
        };
      } else if (resource.resourceType === "buffer") {
        const buffer = resource;
        gpuResource = {
          buffer: this._renderer.buffer.getGPUBuffer(buffer),
          offset: 0,
          size: buffer.descriptor.size
        };
      } else if (resource.resourceType === "bufferResource") {
        const bufferResource = resource;
        gpuResource = {
          buffer: this._renderer.buffer.getGPUBuffer(bufferResource.buffer),
          offset: bufferResource.offset,
          size: bufferResource.size
        };
      } else if (resource.resourceType === "textureSampler") {
        const sampler = resource;
        gpuResource = this._renderer.texture.getGpuSampler(sampler);
      } else if (resource.resourceType === "textureSource") {
        const texture = resource;
        gpuResource = this._renderer.texture.getGpuSource(texture).createView({});
      }
      entries.push({
        binding: groupLayout[j],
        resource: gpuResource
      });
    }
    const gpuBindGroup = device.createBindGroup({
      layout: program._gpuLayout.bindGroups[groupIndex],
      entries
    });
    this._hash[group.key] = gpuBindGroup;
    return gpuBindGroup;
  }
  destroy() {
    for (const key of Object.keys(this._hash)) {
      this._hash[key] = null;
    }
    this._hash = null;
    const writeable = this;
    writeable._renderer = null;
  }
}
/** @ignore */
BindGroupSystem.extension = {
  type: [
    ExtensionType.WebGPUSystem
  ],
  name: "bindGroup"
};

export { BindGroupSystem };
//# sourceMappingURL=BindGroupSystem.mjs.map
