#include "dx_texture_pipeline.h"

#include "backend/dx/dx_renderer.h"
#include "backend/dx/dx_texture.h"

bool dx_texture_pipeline::init() {
    texture_pipeline::init();
    const auto d3d_device = aorii::get_renderer<dx_renderer>()->get_d3d_device();

    D3D11_SAMPLER_DESC sampler_desc = {};
    sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampler_desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sampler_desc.MinLOD = 0;
    sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;
    d3d_device->CreateSamplerState(&sampler_desc, &sampler_state);

    return loader.load("aorii_texture_vertex_main", "aorii_texture_pixel_main");
}

void dx_texture_pipeline::use() {
    loader.use();
}

void dx_texture_pipeline::draw(uint32_t in_index_count) {
    if (!texture) return;
    const auto d3d_context = aorii::get_renderer<dx_renderer>()->get_d3d_context();

    // 设置顶点缓冲区
    constexpr UINT stride = sizeof(aorii_vertex);
    constexpr UINT offset = 0;
    auto* v_buffer = static_cast<ID3D11Buffer*>(vertex_buffer->get_native_handle());
    auto* i_buffer = static_cast<ID3D11Buffer*>(index_buffer->get_native_handle());
    auto* c_buffer = static_cast<ID3D11Buffer*>(param_buffer->get_native_handle());
    auto* srv = (ID3D11ShaderResourceView*)texture->get_shader_resource_view();
    d3d_context->IASetVertexBuffers(0, 1, &v_buffer, &stride, &offset);
    d3d_context->IASetIndexBuffer(i_buffer, DXGI_FORMAT_R32_UINT, 0);
    d3d_context->PSSetSamplers(0, 1, &sampler_state);
    d3d_context->VSSetConstantBuffers(0, 1, &c_buffer);
    d3d_context->PSSetShaderResources(0, 1, &srv);

    // 设置图元拓扑
    d3d_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    // 绘制矩形
    d3d_context->DrawIndexed(in_index_count, 0, 0);
}
