package net.vulkanmod.render.engine;

import com.mojang.blaze3d.opengl.GlStateManager;
import net.minecraft.class_9848;
import net.vulkanmod.gl.VkGlFramebuffer;
import net.vulkanmod.vulkan.Renderer;
import net.vulkanmod.vulkan.VRenderSystem;

public class VkFbo {
   final int glId = GlStateManager.glGenFramebuffers();
   final VkGpuTexture colorAttachment;
   final VkGpuTexture depthAttachment;

   protected VkFbo(VkGpuTexture colorAttachment, VkGpuTexture depthAttachment) {
      this.colorAttachment = colorAttachment;
      this.depthAttachment = depthAttachment;
      VkGlFramebuffer fbo = VkGlFramebuffer.getFramebuffer(this.glId);
      fbo.setAttachmentTexture(36064, colorAttachment.id);
      if (depthAttachment != null) {
         fbo.setAttachmentTexture(36096, depthAttachment.id);
      }

   }

   public void bind() {
      VkGlFramebuffer.bindFramebuffer(36160, this.glId);
      this.clearAttachments();
   }

   protected void clearAttachments() {
      int clear = 0;
      if (this.colorAttachment.needsClear()) {
         clear |= 16384;
         int clearColor = this.colorAttachment.clearColor;
         VRenderSystem.setClearColor(class_9848.method_65101(clearColor), class_9848.method_65102(clearColor), class_9848.method_65103(clearColor), class_9848.method_65100(clearColor));
         this.colorAttachment.needsClear = false;
      }

      if (this.depthAttachment != null && this.depthAttachment.needsClear()) {
         clear |= 256;
         float clearDepth = this.depthAttachment.depthClearValue;
         VRenderSystem.clearDepth((double)clearDepth);
         this.depthAttachment.needsClear = false;
      }

      if (clear != 0) {
         Renderer.clearAttachments(clear);
      }

   }

   protected void close() {
      VkGlFramebuffer.deleteFramebuffer(this.glId);
   }

   public boolean needsClear() {
      return this.colorAttachment.needsClear() || this.depthAttachment != null && this.depthAttachment.needsClear();
   }
}
