索引结构体gs_index_buffer
2024-06-19
15
0
对应于顶点结构体,也有一个索引结构体gs_index_buffer.
struct DataPtr {
void *data;
inline DataPtr(void *data) : data(data) {}
inline ~DataPtr() { bfree(data); }
};
struct gs_index_buffer : gs_obj {
ComPtr<ID3D11Buffer> indexBuffer; //索引缓冲区指针
bool dynamic; //与CPU访问相关
gs_index_type type; //short 还是 long
size_t indexSize; //2字节的还是4字节的索引
size_t num; // 索引点个数
DataPtr indices; //索引点指针
D3D11_BUFFER_DESC bd = {};
D3D11_SUBRESOURCE_DATA srd = {};
void InitBuffer();
void Rebuild(ID3D11Device *dev);
inline void Release() { indexBuffer.Release(); }
gs_index_buffer(gs_device_t *device, enum gs_index_type type,void *indices, size_t num, uint32_t flags);
};
构造函数如下:
gs_index_buffer::gs_index_buffer(gs_device_t *device, enum gs_index_type type,
void *indices, size_t num, uint32_t flags)
: gs_obj(device, gs_type::gs_index_buffer),
dynamic((flags & GS_DYNAMIC) != 0),
type(type),
num(num),
indices(indices)
{
switch (type) {
case GS_UNSIGNED_SHORT:
indexSize = 2;
break;
case GS_UNSIGNED_LONG:
indexSize = 4;
break;
}
InitBuffer();
}
使用成员函数InitBuffer创建缓冲区。
void gs_index_buffer::InitBuffer()
{
HRESULT hr;
memset(&bd, 0, sizeof(bd));
memset(&srd, 0, sizeof(srd));
bd.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
bd.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
bd.BindFlags = D3D11_BIND_INDEX_BUFFER; //绑定到索引缓冲区
bd.ByteWidth = UINT(indexSize * num);
srd.pSysMem = indices.data;
hr = device->device->CreateBuffer(&bd, &srd, indexBuffer.Assign());
if (FAILED(hr))
throw HRError("Failed to create buffer", hr);
}
重新构造:
void gs_index_buffer::Rebuild(ID3D11Device *dev)
{
HRESULT hr = dev->CreateBuffer(&bd, &srd, &indexBuffer);
if (FAILED(hr))
throw HRError("Failed to create buffer", hr);
}