当前位置:   article > 正文

Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第七章:在Direct3D中绘制(二)...

introduce to 3d game
原文: Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第七章:在Direct3D中绘制(二)

代码工程地址:

https://github.com/jiabaodan/Direct12BookReadingNotes



学习目标

  1. 理解本章中针对命令队列的更新(不再需要每帧都flush命令队列),提高性能;
  2. 理解其他两种类型的根信号参数类型:根描述和根常量;
  3. 熟悉如何通过程序方法来绘制通用的几何形状:盒子,圆柱体和球体;
  4. 学习如何在CPU做顶点动画,并且通过动态顶点缓冲将顶点数据上传到GPU内存。


1 帧资源

在之前的代码中,我们在每帧结束的时候调用D3DApp::FlushCommandQueue方法来同步CPU和GPU,这个方法可以使用,但是很低效:

  1. 在每帧开始的时候,GPU没有任何命令可以执行,所以它一直在等待,直到CPU提交命令;
  2. 每帧的结尾,CPU需要等待GPU执行完命令。

这个问题的其中一个解决方案是针对CPU更新的资源创建一个环形数组,我们叫它帧资源(frame resources),通常情况下数组中使用3个元素。该方案中,CPU提交资源后,将会获取下一个可使用的资源(GPU没有在执行的)继续数据的更新,使用3个元素可以确保CPU提前2个元素更新,这样就可以保证GPU一直的高效运算。下面的例子是使用在Shape示例中的,因为CPU只需要更新常量缓冲,所以帧数据只包含常量缓冲:

  1. // Stores the resources needed for the CPU to build the command lists
  2. // for a frame. The contents here will vary from app to app based on
  3. // the needed resources.
  4. struct FrameResource
  5. {
  6. public:
  7. FrameResource(ID3D12Device* device, UINT passCount, UINT objectCount);
  8. FrameResource(const FrameResource& rhs) = delete;
  9. FrameResource& operator=(const FrameResource& rhs) = delete;
  10. ˜FrameResource();
  11. // We cannot reset the allocator until the GPU is done processing the
  12. // commands. So each frame needs their own allocator.
  13. Microsoft::WRL::ComPtr<ID3D12CommandAllocator> CmdListAlloc;
  14. // We cannot update a cbuffer until the GPU is done processing the
  15. // commands that reference it. So each frame needs their own cbuffers.
  16. std::unique_ptr<UploadBuffer<PassConstants>> PassCB = nullptr;
  17. std::unique_ptr<UploadBuffer<ObjectConstants>> ObjectCB = nullptr;
  18. // Fence value to mark commands up to this fence point. This lets us
  19. // check if these frame resources are still in use by the GPU.
  20. UINT64 Fence = 0;
  21. };
  22. FrameResource::FrameResource(ID3D12Device* device, UINT passCount, UINT objectCount)
  23. {
  24. ThrowIfFailed(device->CreateCommandAllocator(
  25. D3D12_COMMAND_LIST_TYPE_DIRECT,
  26. IID_PPV_ARGS(CmdListAlloc.GetAddressOf())));
  27. PassCB = std::make_unique<UploadBuffer<PassConstants>> (device, passCount, true);
  28. ObjectCB = std::make_unique<UploadBuffer<ObjectConstants>> (device, objectCount, true);
  29. }
  30. FrameResource::˜ FrameResource()
  31. {
  32. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

在我们的应用中使用Vector来实例化3个资源,并且跟踪当前的资源:

  1. static const int NumFrameResources = 3;
  2. std::vector<std::unique_ptr<FrameResource>> mFrameResources;
  3. FrameResource* mCurrFrameResource = nullptr;
  4. int mCurrFrameResourceIndex = 0;
  5. void ShapesApp::BuildFrameResources()
  6. {
  7. for(int i = 0; i < gNumFrameResources; ++i)
  8. {
  9. mFrameResources.push_back(std::make_unique<FrameResource> (
  10. md3dDevice.Get(), 1,
  11. (UINT)mAllRitems.size()));
  12. }
  13. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

现在对于CPU第N帧,执行算法是:

  1. void ShapesApp::Update(const GameTimer& gt)
  2. {
  3. // Cycle through the circular frame resource array.
  4. mCurrFrameResourceIndex = (mCurrFrameResourceIndex + 1) % NumFrameResources;
  5. mCurrFrameResource = mFrameResources[mCurrFrameResourceIndex];
  6. // Has the GPU finished processing the commands of the current frame
  7. // resource. If not, wait until the GPU has completed commands up to
  8. // this fence point.
  9. if(mCurrFrameResource->Fence != 0
  10. && mCommandQueue->GetLastCompletedFence() < mCurrFrameResource->Fence)
  11. {
  12. HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS);
  13. ThrowIfFailed(mCommandQueue->SetEventOnFenceCompletion(
  14. mCurrFrameResource->Fence, eventHandle));
  15. WaitForSingleObject(eventHandle, INFINITE);
  16. CloseHandle(eventHandle);
  17. }
  18. // […] Update resources in mCurrFrameResource (like cbuffers).
  19. }
  20. void ShapesApp::Draw(const GameTimer& gt)
  21. {
  22. // […] Build and submit command lists for this frame.
  23. // Advance the fence value to mark commands up to this fence point.
  24. mCurrFrameResource->Fence = ++mCurrentFence;
  25. // Add an instruction to the command queue to set a new fence point.
  26. // Because we are on the GPU timeline, the new fence point won’t be
  27. // set until the GPU finishes processing all the commands prior to
  28. // this Signal().
  29. mCommandQueue->Signal(mFence.Get(), mCurrentFence);
  30. // Note that GPU could still be working on commands from previous
  31. // frames, but that is okay, because we are not touching any frame
  32. // resources associated with those frames.
  33. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

这个方案并没有完美解决等待,如果其中一个处理器处理太快,它还是要等待另一个处理器。



2 渲染物体(RENDER ITEMS)

绘制一个物体需要设置大量参数,比如创建顶点和索引缓存,绑定常量缓冲,设置拓扑结构,指定DrawIndexedInstanced参数。如果我们要绘制多个物体,设计和创建一个轻量级结构用来保存上述所有数据就很有用。我们对这一组单个绘制调用需要的所有数据称之为一个渲染物体(render item),当前Demo中,我们RenderItem结构如下:

  1. // Lightweight structure stores parameters to draw a shape. This will
  2. // vary from app-to-app.
  3. struct RenderItem
  4. {
  5. RenderItem() = default;
  6. // World matrix of the shape that describes the object’s local space
  7. // relative to the world space, which defines the position,
  8. // orientation, and scale of the object in the world.
  9. XMFLOAT4X4 World = MathHelper::Identity4x4();
  10. // Dirty flag indicating the object data has changed and we need
  11. // to update the constant buffer. Because we have an object
  12. // cbuffer for each FrameResource, we have to apply the
  13. // update to each FrameResource. Thus, when we modify obect data we
  14. // should set
  15. // NumFramesDirty = gNumFrameResources so that each frame resource
  16. // gets the update.
  17. int NumFramesDirty = gNumFrameResources;
  18. // Index into GPU constant buffer corresponding to the ObjectCB
  19. // for this render item.
  20. UINT ObjCBIndex = -1;
  21. // Geometry associated with this render-item. Note that multiple
  22. // render-items can share the same geometry.
  23. MeshGeometry* Geo = nullptr;
  24. // Primitive topology.
  25. D3D12_PRIMITIVE_TOPOLOGY PrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  26. // DrawIndexedInstanced parameters.
  27. UINT IndexCount = 0;
  28. UINT StartIndexLocation = 0;
  29. int BaseVertexLocation = 0;
  30. };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

我们的应用将包含一个渲染物体列表来表示他们如何渲染;需要不同PSO的物体会放置到不同的列表中:

  1. // List of all the render items.
  2. std::vector<std::unique_ptr<RenderItem>> mAllRitems;
  3. // Render items divided by PSO.
  4. std::vector<RenderItem*> mOpaqueRitems;
  5. std::vector<RenderItem*> mTransparentRitems;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7


3 PASS CONSTANTS

之前的章节中我们介绍了一个新的常量缓冲:

  1. std::unique_ptr<UploadBuffer<PassConstants>> PassCB = nullptr;
  • 1
  • 2

它主要包含一些各个物体通用的常量,比如眼睛位置,透视投影矩阵,屏幕分辨率数据,还包括时间数据等。目前我们的Demo不需要所有这些数据,但是都实现他们会很方便,并且只会消耗很少的额外数据空间。比如我们如果要做一些后期特效,渲染目标尺寸数据就很有用:

  1. cbuffer cbPass : register(b1)
  2. {
  3. float4x4 gView;
  4. float4x4 gInvView;
  5. float4x4 gProj;
  6. float4x4 gInvProj;
  7. float4x4 gViewProj;
  8. float4x4 gInvViewProj;
  9. float3 gEyePosW;
  10. float cbPerObjectPad1;
  11. float2 gRenderTargetSize;
  12. float2 gInvRenderTargetSize;
  13. float gNearZ;
  14. float gFarZ;
  15. float gTotalTime;
  16. float gDeltaTime;
  17. };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

我们也需要修改之和每个物体关联的常量缓冲。目前我们只需要世界变换矩阵:

  1. cbuffer cbPerObject : register(b0)
  2. {
  3. float4x4 gWorld;
  4. };
  • 1
  • 2
  • 3
  • 4
  • 5

这样做的好处是可以将常量缓冲分组进行更新,每一个pass更新的常量缓冲需要每一个渲染Pass的时候更新;物体常量只需要当物体世界矩阵变换的时候更新;静态物体只需要在初始化的时候更新一下。在我们Demo中,实现了下面的方法来更新常量缓冲,它们每帧在Update中调用一次:

  1. void ShapesApp::UpdateObjectCBs(const GameTimer& gt)
  2. {
  3. auto currObjectCB = mCurrFrameResource->ObjectCB.get();
  4. for(auto& e : mAllRitems)
  5. {
  6. // Only update the cbuffer data if the constants have changed.
  7. // This needs to be tracked per frame resource.
  8. if(e->NumFramesDirty > 0)
  9. {
  10. XMMATRIX world = XMLoadFloat4x4(&e->World);
  11. ObjectConstants objConstants;
  12. XMStoreFloat4x4(&objConstants.World, XMMatrixTranspose(world));
  13. currObjectCB->CopyData(e->ObjCBIndex, objConstants);
  14. // Next FrameResource need to be updated too.
  15. e->NumFramesDirty--;
  16. }
  17. }
  18. }
  19. void ShapesApp::UpdateMainPassCB(const GameTimer& gt)
  20. {
  21. XMMATRIX view = XMLoadFloat4x4(&mView);
  22. XMMATRIX proj = XMLoadFloat4x4(&mProj);
  23. XMMATRIX viewProj = XMMatrixMultiply(view, proj);
  24. XMMATRIX invView = XMMatrixInverse(&XMMatrixDeterminant(view), view);
  25. XMMATRIX invProj = XMMatrixInverse(&XMMatrixDeterminant(proj), proj);
  26. XMMATRIX invViewProj = XMMatrixInverse(&XMMatrixDeterminant(viewProj), viewProj);
  27. XMStoreFloat4x4(&mMainPassCB.View, XMMatrixTranspose(view));
  28. XMStoreFloat4x4(&mMainPassCB.InvView, XMMatrixTranspose(invView));
  29. XMStoreFloat4x4(&mMainPassCB.Proj, XMMatrixTranspose(proj));
  30. XMStoreFloat4x4(&mMainPassCB.InvProj, XMMatrixTranspose(invProj));
  31. XMStoreFloat4x4(&mMainPassCB.ViewProj, XMMatrixTranspose(viewProj));
  32. XMStoreFloat4x4(&mMainPassCB.InvViewProj, XMMatrixTranspose(invViewProj));
  33. mMainPassCB.EyePosW = mEyePos;
  34. mMainPassCB.RenderTargetSize = XMFLOAT2((float)mClientWidth, (float)mClientHeight);
  35. mMainPassCB.InvRenderTargetSize = XMFLOAT2(1.0f / mClientWidth, 1.0f / mClientHeight);
  36. mMainPassCB.NearZ = 1.0f;
  37. mMainPassCB.FarZ = 1000.0f;
  38. mMainPassCB.TotalTime = gt.TotalTime();
  39. mMainPassCB.DeltaTime = gt.DeltaTime();
  40. auto currPassCB = mCurrFrameResource->PassCB.get();
  41. currPassCB->CopyData(0, mMainPassCB);
  42. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

我们更新顶点着色器相应的支持这个缓冲变换:

  1. VertexOut VS(VertexIn vin)
  2. {
  3. VertexOut vout;
  4. // Transform to homogeneous clip space.
  5. float4 posW = mul(float4(vin.PosL, 1.0f), gWorld);
  6. vout.PosH = mul(posW, gViewProj);
  7. // Just pass vertex color into the pixel shader.
  8. vout.Color = vin.Color;
  9. return vout;
  10. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这里额外的逐顶点矩阵相乘,在现在强大的GPU上是微不足道的。
着色器需要的资源发生变化,所以需要更新根签名相应的包含两个描述表:

  1. CD3DX12_DESCRIPTOR_RANGE cbvTable0;
  2. cbvTable0.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);
  3. CD3DX12_DESCRIPTOR_RANGE cbvTable1;
  4. cbvTable1.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1);
  5. // Root parameter can be a table, root descriptor or root constants.
  6. CD3DX12_ROOT_PARAMETER slotRootParameter[2];
  7. // Create root CBVs.
  8. slotRootParameter[0].InitAsDescriptorTable(1, &cbvTable0);
  9. slotRootParameter[1].InitAsDescriptorTable(1, &cbvTable1);
  10. // A root signature is an array of root parameters.
  11. CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(2,
  12. slotRootParameter, 0, nullptr,
  13. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT__LAYOUT);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

不要在着色器中使用太多的常量缓冲,为了性能[Thibieroz13]建议保持在5个以下。



4 形状几何

这节将会展示如何创建椭球体,球体,圆柱体和圆锥体。这些形状对于绘制天空示例,Debugging,可视化碰撞检测和延时渲染非常有用。
我们将在程序中创建几何体的代码放在GeometryGenerator(GeometryGenerator.h/.cpp)类中,该类创建的数据保存在内存中,所以我们还需要将它们赋值到顶点/索引缓冲中。MeshData结构是一个内嵌在GeometryGenerator中用来保存顶点和索引列表的简单结构:

  1. class GeometryGenerator
  2. {
  3. public:
  4. using uint16 = std::uint16_t;
  5. using uint32 = std::uint32_t;
  6. struct Vertex
  7. {
  8. Vertex(){}
  9. Vertex(
  10. const DirectX::XMFLOAT3& p,
  11. const DirectX::XMFLOAT3& n,
  12. const DirectX::XMFLOAT3& t,
  13. const DirectX::XMFLOAT2& uv) :
  14. Position(p),
  15. Normal(n),
  16. TangentU(t),
  17. TexC(uv){}
  18. Vertex(
  19. float px, float py, float pz,
  20. float nx, float ny, float nz,
  21. float tx, float ty, float tz,
  22. float u, float v) :
  23. Position(px,py,pz),
  24. Normal(nx,ny,nz),
  25. TangentU(tx, ty, tz),
  26. TexC(u,v){}
  27. DirectX::XMFLOAT3 Position;
  28. DirectX::XMFLOAT3 Normal;
  29. DirectX::XMFLOAT3 TangentU;
  30. DirectX::XMFLOAT2 TexC;
  31. };
  32. struct MeshData
  33. {
  34. std::vector<Vertex> Vertices;
  35. std::vector<uint32> Indices32;
  36. std::vector<uint16>& GetIndices16()
  37. {
  38. if(mIndices16.empty())
  39. {
  40. mIndices16.resize(Indices32.size());
  41. for(size_t i = 0; i < Indices32.size(); ++i)
  42. mIndices16[i] = static_cast<uint16> (Indices32[i]);
  43. }
  44. return mIndices16;
  45. }
  46. private:
  47. std::vector<uint16> mIndices16;
  48. };
  49. };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

4.1 创建圆柱体网格

我们通过定义底面和顶面半径,高度,切片(slice)和堆叠(stack)个数来定义一个圆柱体网格,如下图,我们将圆柱体划分成侧面,底面和顶面:
在这里插入图片描述


4.1.1 圆柱体侧面几何

我们创建的圆柱体中心的原点,平行于Y轴,所有顶点依赖于环(rings)。每个圆柱体有stackCount + 1环,每一环有sliceCount个独立的顶点。每一环半径的变化为(topRadius – bottomRadius)/stackCount;所以基本的创建圆柱体的思路就是遍历每一环创建顶点:

  1. GeometryGenerator::MeshData
  2. GeometryGenerator::CreateCylinder(
  3. float bottomRadius, float topRadius,
  4. float height, uint32 sliceCount, uint32
  5. stackCount)
  6. {
  7. MeshData meshData;
  8. //
  9. // Build Stacks.
  10. //
  11. float stackHeight = height / stackCount;
  12. // Amount to increment radius as we move up each stack level from
  13. // bottom to top.
  14. float radiusStep = (topRadius - bottomRadius) / stackCount;
  15. uint32 ringCount = stackCount+1;
  16. // Compute vertices for each stack ring starting at the bottom and
  17. // moving up.
  18. for(uint32 i = 0; i < ringCount; ++i)
  19. {
  20. float y = -0.5f*height + i*stackHeight;
  21. float r = bottomRadius + i*radiusStep;
  22. // vertices of ring
  23. float dTheta = 2.0f*XM_PI/sliceCount;
  24. for(uint32 j = 0; j <= sliceCount; ++j)
  25. {
  26. Vertex vertex;
  27. float c = cosf(j*dTheta);
  28. float s = sinf(j*dTheta);
  29. vertex.Position = XMFLOAT3(r*c, y, r*s);
  30. vertex.TexC.x = (float)j/sliceCount;
  31. vertex.TexC.y = 1.0f - (float)i/stackCount;
  32. // Cylinder can be parameterized as follows, where we introduce v
  33. // parameter that goes in the same direction as the v tex-coord
  34. // so that the bitangent goes in the same direction as the
  35. // v tex-coord.
  36. // Let r0 be the bottom radius and let r1 be the top radius.
  37. // y(v) = h - hv for v in [0,1].
  38. // r(v) = r1 + (r0-r1)v
  39. //
  40. // x(t, v) = r(v)*cos(t)
  41. // y(t, v) = h - hv
  42. // z(t, v) = r(v)*sin(t)
  43. //
  44. // dx/dt = -r(v)*sin(t)
  45. // dy/dt = 0
  46. // dz/dt = +r(v)*cos(t)
  47. //
  48. // dx/dv = (r0-r1)*cos(t)
  49. // dy/dv = -h
  50. // dz/dv = (r0-r1)*sin(t)
  51. // This is unit length.
  52. vertex.TangentU = XMFLOAT3(-s, 0.0f, c);
  53. float dr = bottomRadius-topRadius;
  54. XMFLOAT3 bitangent(dr*c, -height, dr*s);
  55. XMVECTOR T = XMLoadFloat3(&vertex.TangentU);
  56. XMVECTOR B = XMLoadFloat3(&bitangent);
  57. XMVECTOR N = XMVector3Normalize(XMVector3Cross(T, B));
  58. XMStoreFloat3(&vertex.Normal, N);
  59. meshData.Vertices.push_back(vertex);
  60. }
  61. }
  62. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

侧面的每个四边形中有2个三角形,所以第i层的第j个切片的索引计算如下:
在这里插入图片描述
n是每环中顶点的索引,所以创建索引的思路是遍历每一层的每一个切面,然后应用上面的公式:

  1. // Add one because we duplicate the first and last vertex per ring
  2. // since the texture coordinates are different.
  3. uint32 ringVertexCount = sliceCount+1;
  4. // Compute indices for each stack.
  5. for(uint32 i = 0; i < stackCount; ++i)
  6. {
  7. for(uint32 j = 0; j < sliceCount; ++j)
  8. {
  9. meshData.Indices32.push_back(i*ringVertexCount + j);
  10. meshData.Indices32.push_back((i+1)*ringVertexCount + j);
  11. meshData.Indices32.push_back((i+1)*ringVertexCount + j+1);
  12. meshData.Indices32.push_back(i*ringVertexCount + j);
  13. meshData.Indices32.push_back((i+1)*ringVertexCount + j+1);
  14. meshData.Indices32.push_back(i*ringVertexCount + j+1);
  15. }
  16. }
  17. BuildCylinderTopCap(bottomRadius, topRadius, height, sliceCount, stackCount, meshData);
  18. BuildCylinderBottomCap(bottomRadius, topRadius, height, sliceCount, stackCount, meshData);
  19. return meshData;
  20. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

在这里插入图片描述


4.1.2 上下盖

对顶面和底面通过创建切面数量个三角形模拟出近似的圆:

  1. void GeometryGenerator::BuildCylinderTopCap(
  2. float bottomRadius, float topRadius, float height,
  3. uint32 sliceCount, uint32 stackCount, MeshData& meshData)
  4. {
  5. uint32 baseIndex = (uint32)meshData.Vertices.size();
  6. float y = 0.5f*height;
  7. float dTheta = 2.0f*XM_PI/sliceCount;
  8. // Duplicate cap ring vertices because the texture coordinates and
  9. // normals differ.
  10. for(uint32 i = 0; i <= sliceCount; ++i)
  11. {
  12. float x = topRadius*cosf(i*dTheta);
  13. float z = topRadius*sinf(i*dTheta);
  14. // Scale down by the height to try and make top cap texture coord
  15. // area proportional to base.
  16. float u = x/height + 0.5f;
  17. float v = z/height + 0.5f;
  18. meshData.Vertices.push_back(Vertex(x, y, z, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, u, v) );
  19. }
  20. // Cap center vertex.
  21. meshData.Vertices.push_back( Vertex(0.0f, y, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f) );
  22. // Index of center vertex.
  23. uint32 centerIndex = (uint32)meshData.Vertices.size()-1;
  24. for(uint32 i = 0; i < sliceCount; ++i)
  25. {
  26. meshData.Indices32.push_back(centerIndex);
  27. meshData.Indices32.push_back(baseIndex + i+1);
  28. meshData.Indices32.push_back(baseIndex + i);
  29. }
  30. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

底部代码类似


4.2 创建球体网格

我们通过定义半径,切面和堆叠数来定义一个球体。创建球体的算法和圆柱体的算法非常类似,除了每环半径的变化是非线性的基于三角函数的方程(GeometryGenerator::CreateSphere代码中)。我们可以通过缩放球体来创建椭圆形。
在这里插入图片描述


4.3 创建三角面片球体(Geosphere)网格

上节创建的球体并不具有相同的面积,在某些需求下这是不合需求的。一个三角面片球体使用相同面积和边长的三角形组成近似的球体。

在这里插入图片描述
为了创建它,我们从一个二十面体开始,细分每个三角形然后将顶点映射到给定半径的一个球体上。我们重复这个过程来对三角形细分。
下图展示了如何细分三角形,就是简单的找到每个边的中点。
在这里插入图片描述

  1. GeometryGenerator::MeshData GeometryGenerator::CreateGeosphere(float radius, uint32 numSubdivisions)
  2. {
  3. MeshData meshData;
  4. // Put a cap on the number of subdivisions.
  5. numSubdivisions = std::min<uint32> (numSubdivisions, 6u);
  6. // Approximate a sphere by tessellating an icosahedron.
  7. const float X = 0.525731f;
  8. const float Z = 0.850651f;
  9. XMFLOAT3 pos[12] =
  10. {
  11. XMFLOAT3(-X, 0.0f, Z), XMFLOAT3(X, 0.0f, Z),
  12. XMFLOAT3(-X, 0.0f, -Z), XMFLOAT3(X, 0.0f, - Z),
  13. XMFLOAT3(0.0f, Z, X), XMFLOAT3(0.0f, Z, - X),
  14. XMFLOAT3(0.0f, -Z, X), XMFLOAT3(0.0f, -Z, - X),
  15. XMFLOAT3(Z, X, 0.0f), XMFLOAT3(-Z, X, 0.0f),
  16. XMFLOAT3(Z, -X, 0.0f), XMFLOAT3(-Z, -X, 0.0f)
  17. };
  18. uint32 k[60] =
  19. {
  20. 1,4,0, 4,9,0, 4,5,9, 8,5,4, 1,8,4,
  21. 1,10,8, 10,3,8, 8,3,5, 3,2,5, 3,7,2,
  22. 3,10,7, 10,6,7, 6,11,7, 6,0,11, 6,1,0,
  23. 10,1,6, 11,0,9, 2,11,9, 5,2,9, 11,2,7
  24. };
  25. meshData.Vertices.resize(12);
  26. meshData.Indices32.assign(&k[0], &k[60]);
  27. for(uint32 i = 0; i < 12; ++i)
  28. meshData.Vertices[i].Position = pos[i];
  29. for(uint32 i = 0; i < numSubdivisions; ++i)
  30. Subdivide(meshData);
  31. // Project vertices onto sphere and scale.
  32. for(uint32 i = 0; i < meshData.Vertices.size(); ++i)
  33. {
  34. // Project onto unit sphere.
  35. XMVECTOR n = XMVector3Normalize(XMLoadFloat3(&meshData.Vertices[i].Position));
  36. // Project onto sphere.
  37. XMVECTOR p = radius*n;
  38. XMStoreFloat3(&meshData.Vertices[i].Position, p);
  39. XMStoreFloat3(&meshData.Vertices[i].Normal, n);
  40. // Derive texture coordinates from spherical coordinates.
  41. float theta = atan2f(meshData.Vertices[i].Position.z, meshData.Vertices[i].Position.x);
  42. // Put in [0, 2pi].
  43. if(theta < 0.0f)
  44. theta += XM_2PI;
  45. float phi = acosf(meshData.Vertices[i].Position.y / radius);
  46. meshData.Vertices[i].TexC.x = theta/XM_2PI;
  47. meshData.Vertices[i].TexC.y = phi/XM_PI;
  48. // Partial derivative of P with respect to theta
  49. meshData.Vertices[i].TangentU.x = -radius*sinf(phi)*sinf(theta);
  50. meshData.Vertices[i].TangentU.y = 0.0f;
  51. meshData.Vertices[i].TangentU.z = +radius*sinf(phi)*cosf(theta);
  52. XMVECTOR T = XMLoadFloat3(&meshData.Vertices[i].TangentU);
  53. XMStoreFloat3(&meshData.Vertices[i].TangentU, XMVector3Normalize(T));
  54. }
  55. return meshData;
  56. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67


5 形状示例

为了验证上面的代码,我们实现了这个“Shapes”Demo。另外还会学习多个物体的位置设置,并且将多个物体的数据放到同一个顶点和索引缓冲中。
在这里插入图片描述


5.1 顶点和索引缓冲

示例中,我们只保存一份球体和圆柱体的数据,然后使用不同的世界坐标重新绘制它们多次,这是一个实例化的例子,它可以节约内存。
下面的代码展示了如何创建几何缓冲,如何缓存需要的参数,如何绘制物体:

  1. void ShapesApp::BuildShapeGeometry()
  2. {
  3. GeometryGenerator geoGen;
  4. GeometryGenerator::MeshData box = geoGen.CreateBox(1.5f, 0.5f, 1.5f, 3);
  5. GeometryGenerator::MeshData grid = geoGen.CreateGrid(20.0f, 30.0f, 60, 40);
  6. GeometryGenerator::MeshData sphere = geoGen.CreateSphere(0.5f, 20, 20);
  7. GeometryGenerator::MeshData cylinder = geoGen.CreateCylinder(0.5f, 0.3f, 3.0f, 20, 20);
  8. //
  9. // We are concatenating all the geometry into one big vertex/index
  10. // buffer. So define the regions in the buffer each submesh covers.
  11. //
  12. // Cache the vertex offsets to each object in the concatenated vertex
  13. // buffer.
  14. UINT boxVertexOffset = 0;
  15. UINT gridVertexOffset = (UINT)box.Vertices.size();
  16. UINT sphereVertexOffset = gridVertexOffset + (UINT)grid.Vertices.size();
  17. UINT cylinderVertexOffset = sphereVertexOffset + (UINT)sphere.Vertices.size();
  18. // Cache the starting index for each object in the concatenated index
  19. // buffer.
  20. UINT boxIndexOffset = 0;
  21. UINT gridIndexOffset = (UINT)box.Indices32.size();
  22. UINT sphereIndexOffset = gridIndexOffset + (UINT)grid.Indices32.size();
  23. UINT cylinderIndexOffset = sphereIndexOffset + (UINT)sphere.Indices32.size();
  24. // Define the SubmeshGeometry that cover different
  25. // regions of the vertex/index buffers.
  26. SubmeshGeometry boxSubmesh;
  27. boxSubmesh.IndexCount = (UINT)box.Indices32.size();
  28. boxSubmesh.StartIndexLocation = boxIndexOffset;
  29. boxSubmesh.BaseVertexLocation = boxVertexOffset;
  30. SubmeshGeometry gridSubmesh;
  31. gridSubmesh.IndexCount = (UINT)grid.Indices32.size();
  32. gridSubmesh.StartIndexLocation = gridIndexOffset;
  33. gridSubmesh.BaseVertexLocation = gridVertexOffset;
  34. SubmeshGeometry sphereSubmesh;
  35. sphereSubmesh.IndexCount = (UINT)sphere.Indices32.size();
  36. sphereSubmesh.StartIndexLocation = sphereIndexOffset;
  37. sphereSubmesh.BaseVertexLocation = sphereVertexOffset;
  38. SubmeshGeometry cylinderSubmesh;
  39. cylinderSubmesh.IndexCount = (UINT)cylinder.Indices32.size();
  40. cylinderSubmesh.StartIndexLocation = cylinderIndexOffset;
  41. cylinderSubmesh.BaseVertexLocation = cylinderVertexOffset;
  42. //
  43. // Extract the vertex elements we are interested in and pack the
  44. // vertices of all the meshes into one vertex buffer.
  45. //
  46. auto totalVertexCount = box.Vertices.size() + grid.Vertices.size() + sphere.Vertices.size() + cylinder.Vertices.size();
  47. std::vector<Vertex> vertices(totalVertexCount);
  48. UINT k = 0;
  49. for(size_t i = 0; i < box.Vertices.size(); ++i, ++k)
  50. {
  51. vertices[k].Pos = box.Vertices[i].Position;
  52. vertices[k].Color = XMFLOAT4(DirectX::Colors::DarkGreen);
  53. }
  54. for(size_t i = 0; i < grid.Vertices.size(); ++i, ++k)
  55. {
  56. vertices[k].Pos = grid.Vertices[i].Position;
  57. vertices[k].Color = XMFLOAT4(DirectX::Colors::ForestGreen);
  58. }
  59. for(size_t i = 0; i < sphere.Vertices.size(); ++i, ++k)
  60. {
  61. vertices[k].Pos = sphere.Vertices[i].Position;
  62. vertices[k].Color = XMFLOAT4(DirectX::Colors::Crimson);
  63. }
  64. for(size_t i = 0; i < cylinder.Vertices.size(); ++i, ++k)
  65. {
  66. vertices[k].Pos = cylinder.Vertices[i].Position;
  67. vertices[k].Color = XMFLOAT4(DirectX::Colors::SteelBlue);
  68. }
  69. std::vector<std::uint16_t> indices;
  70. indices.insert(indices.end(), std::begin(box.GetIndices16()), std::end(box.GetIndices16()));
  71. indices.insert(indices.end(), std::begin(grid.GetIndices16()), std::end(grid.GetIndices16()));
  72. indices.insert(indices.end(), std::begin(sphere.GetIndices16()), std::end(sphere.GetIndices16()));
  73. indices.insert(indices.end(), std::begin(cylinder.GetIndices16()), std::end(cylinder.GetIndices16()));
  74. const UINT vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
  75. const UINT ibByteSize = (UINT)indices.size() * sizeof(std::uint16_t);
  76. auto geo = std::make_unique<MeshGeometry>();
  77. geo->Name = "shapeGeo";
  78. ThrowIfFailed(D3DCreateBlob(vbByteSize, &geo->VertexBufferCPU));
  79. CopyMemory(geo->VertexBufferCPU->GetBufferPointer(), vertices.data(), vbByteSize);
  80. ThrowIfFailed(D3DCreateBlob(ibByteSize, &geo->IndexBufferCPU));
  81. CopyMemory(geo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);
  82. geo->VertexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  83. mCommandList.Get(), vertices.data(),
  84. vbByteSize, geo->VertexBufferUploader);
  85. geo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  86. mCommandList.Get(), indices.data(),
  87. ibByteSize, geo->IndexBufferUploader);
  88. geo->VertexByteStride = sizeof(Vertex);
  89. geo->VertexBufferByteSize = vbByteSize;
  90. geo->IndexFormat = DXGI_FORMAT_R16_UINT;
  91. geo->IndexBufferByteSize = ibByteSize;
  92. geo->DrawArgs["box"] = boxSubmesh;
  93. geo->DrawArgs["grid"] = gridSubmesh;
  94. geo->DrawArgs["sphere"] = sphereSubmesh;
  95. geo->DrawArgs["cylinder"] = cylinderSubmesh;
  96. mGeometries[geo->Name] = std::move(geo);
  97. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109

mGeometries变量定义如下:

  1. std::unordered_map<std::string, std::unique_ptr<MeshGeometry>> mGeometries;
  • 1
  • 2

这个模式会在本书中其他地方一直使用,为每个几何体,PSO,纹理和着色器创建一个新的变量名称是非常笨重的,所以我们使用一个unordered maps在固定时间使用名称来查找或者引用对象,下面是一些其他例子:

  1. std::unordered_map<std::string,
  2. std::unique_ptr<MeshGeometry>> mGeometries;
  3. std::unordered_map<std::string, ComPtr<ID3DBlob>> mShaders;
  4. std::unordered_map<std::string, ComPtr<ID3D12PipelineState>> mPSOs;
  • 1
  • 2
  • 3
  • 4
  • 5

5.2 渲染项目

现在我们定义场景中的渲染项目,观察所有渲染项目如何共用一个MeshGeometry,并且如何使用DrawArgs获取DrawIndexedInstanced来绘制子区间的顶点/索引缓冲:

  1. // ShapesApp member variable.
  2. std::vector<std::unique_ptr<RenderItem>> mAllRitems;
  3. std::vector<RenderItem*> mOpaqueRitems;
  4. void ShapesApp::BuildRenderItems()
  5. {
  6. auto boxRitem = std::make_unique<RenderItem>();
  7. XMStoreFloat4x4(&boxRitem->World, XMMatrixScaling(2.0f, 2.0f, 2.0f)*XMMatrixTranslation(0.0f, 0.5f, 0.0f));
  8. boxRitem->ObjCBIndex = 0;
  9. boxRitem->Geo = mGeometries["shapeGeo"].get();
  10. boxRitem->PrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  11. boxRitem->IndexCount = boxRitem->Geo->DrawArgs["box"].IndexCount;
  12. boxRitem->StartIndexLocation = boxRitem->Geo->DrawArgs["box"]. StartIndexLocation;
  13. boxRitem->BaseVertexLocation = boxRitem->Geo->DrawArgs["box"]. BaseVertexLocation;
  14. mAllRitems.push_back(std::move(boxRitem));
  15. auto gridRitem = std::make_unique<RenderItem> ();
  16. gridRitem->World = MathHelper::Identity4x4();
  17. gridRitem->ObjCBIndex = 1;
  18. gridRitem->Geo = mGeometries["shapeGeo"].get();
  19. gridRitem->PrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  20. gridRitem->IndexCount = gridRitem->Geo->DrawArgs["grid"].IndexCount;
  21. gridRitem->StartIndexLocation = gridRitem->Geo->DrawArgs["grid"].StartIndexLocation;
  22. gridRitem->BaseVertexLocation = gridRitem->Geo->DrawArgs["grid"].BaseVertexLocation;
  23. mAllRitems.push_back(std::move(gridRitem));
  24. // Build the columns and spheres in rows as in Figure 7.6.
  25. UINT objCBIndex = 2;
  26. for(int i = 0; i < 5; ++i)
  27. {
  28. auto leftCylRitem = std::make_unique<RenderItem>();
  29. auto rightCylRitem = std::make_unique<RenderItem>();
  30. auto leftSphereRitem = std::make_unique<RenderItem>();
  31. auto rightSphereRitem = std::make_unique<RenderItem>();
  32. XMMATRIX leftCylWorld = XMMatrixTranslation(-5.0f, 1.5f, -10.0f + i*5.0f);
  33. XMMATRIX rightCylWorld = XMMatrixTranslation(+5.0f, 1.5f, -10.0f + i*5.0f);
  34. XMMATRIX leftSphereWorld = XMMatrixTranslation(-5.0f, 3.5f, -10.0f + i*5.0f);
  35. XMMATRIX rightSphereWorld = XMMatrixTranslation(+5.0f, 3.5f, -10.0f + i*5.0f);
  36. XMStoreFloat4x4(&leftCylRitem->World, rightCylWorld);
  37. leftCylRitem->ObjCBIndex = objCBIndex++;
  38. leftCylRitem->Geo = mGeometries["shapeGeo"].get();
  39. leftCylRitem->PrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  40. leftCylRitem->IndexCount = leftCylRitem->Geo->DrawArgs["cylinder"].IndexCount;
  41. leftCylRitem->StartIndexLocation =leftCylRitem->Geo->DrawArgs["cylinder"].StartIndexLocation;
  42. leftCylRitem->BaseVertexLocation =leftCylRitem->Geo->DrawArgs["cylinder"].BaseVertexLocation;
  43. XMStoreFloat4x4(&rightCylRitem->World,leftCylWorld);
  44. rightCylRitem->ObjCBIndex = objCBIndex++;
  45. rightCylRitem->Geo =mGeometries["shapeGeo"].get();
  46. rightCylRitem->PrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  47. rightCylRitem->IndexCount = rightCylRitem-> Geo->DrawArgs["cylinder"].IndexCount;
  48. rightCylRitem->StartIndexLocation = rightCylRitem->Geo->DrawArgs["cylinder"].StartIndexLocation;
  49. rightCylRitem->BaseVertexLocation = rightCylRitem->Geo->DrawArgs["cylinder"].BaseVertexLocation;
  50. XMStoreFloat4x4(&leftSphereRitem->World, leftSphereWorld);
  51. leftSphereRitem->ObjCBIndex = objCBIndex++;
  52. leftSphereRitem->Geo = mGeometries["shapeGeo"].get();
  53. leftSphereRitem->PrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  54. leftSphereRitem->IndexCount = leftSphereRitem->Geo->DrawArgs["sphere"].IndexCount;
  55. leftSphereRitem->StartIndexLocation = leftSphereRitem->Geo->DrawArgs["sphere"].StartIndexLocation;
  56. leftSphereRitem->BaseVertexLocation = leftSphereRitem->Geo->DrawArgs["sphere"].BaseVertexLocation;
  57. XMStoreFloat4x4(&rightSphereRitem->World, rightSphereWorld);
  58. rightSphereRitem->ObjCBIndex = objCBIndex++;
  59. rightSphereRitem->Geo = mGeometries["shapeGeo"].get();
  60. rightSphereRitem->PrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  61. rightSphereRitem->IndexCount = rightSphereRitem->Geo->DrawArgs["sphere"].IndexCount;
  62. rightSphereRitem->StartIndexLocation = rightSphereRitem->Geo->DrawArgs["sphere"].StartIndexLocation;
  63. rightSphereRitem->BaseVertexLocation = rightSphereRitem->Geo->DrawArgs["sphere"].BaseVertexLocation;
  64. mAllRitems.push_back(std::move(leftCylRitem));
  65. mAllRitems.push_back(std::move(rightCylRitem));
  66. mAllRitems.push_back(std::move(leftSphereRitem));
  67. mAllRitems.push_back(std::move(rightSphereRitem));
  68. }
  69. // All the render items are opaque in this demo.
  70. for(auto& e : mAllRitems)
  71. mOpaqueRitems.push_back(e.get());
  72. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82

5.3 帧资源和常量缓冲描述(Constant Buffer Views)

我们有一个vector的FrameResources,然后每一个FrameResources都有一个上传缓冲来为场景中每一个项目保存常量缓冲:

  1. std::unique_ptr<UploadBuffer<PassConstants>> PassCB = nullptr;
  2. std::unique_ptr<UploadBuffer<ObjectConstants>> ObjectCB = nullptr;
  • 1
  • 2
  • 3

如果我们有3个帧资源,和n个渲染项目,那么我们需要3n个物体常量缓冲和3个Pass常量缓冲,所以我们需要3(n+1)constant buffer views (CBVs),所以我们需要修改我们的CBV堆来包含这些东西:

  1. void ShapesApp::BuildDescriptorHeaps()
  2. {
  3. UINT objCount = (UINT)mOpaqueRitems.size();
  4. // Need a CBV descriptor for each object for each frame resource,
  5. // +1 for the perPass CBV for each frame resource.
  6. UINT numDescriptors = (objCount+1) * gNumFrameResources;
  7. // Save an offset to the start of the pass CBVs. These are the last 3 descriptors.
  8. mPassCbvOffset = objCount * gNumFrameResources;
  9. D3D12_DESCRIPTOR_HEAP_DESC cbvHeapDesc;
  10. cbvHeapDesc.NumDescriptors = numDescriptors;
  11. cbvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  12. cbvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  13. cbvHeapDesc.NodeMask = 0;
  14. ThrowIfFailed(md3dDevice->CreateDescriptorHeap(&cbvHeapDesc, IID_PPV_ARGS(&mCbvHeap)));
  15. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

现在我们可以使用下面的代码填充CBV堆。其中0 到 n-1保存第0个帧资源中的物体CBVs,n 到 2n−1保存第1个帧资源中的物体CBVs,2n 到 3n−1保存第2个帧资源中的物体CBVs,然后3n, 3n+1,和 3n+2保存pass CBVs:

  1. void ShapesApp::BuildConstantBufferViews()
  2. {
  3. UINT objCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));
  4. UINT objCount = (UINT)mOpaqueRitems.size();
  5. // Need a CBV descriptor for each object for each frame resource.
  6. for(int frameIndex = 0; frameIndex < gNumFrameResources; ++frameIndex)
  7. {
  8. auto objectCB = mFrameResources[frameIndex]->ObjectCB->Resource();
  9. for(UINT i = 0; i < objCount; ++i)
  10. {
  11. D3D12_GPU_VIRTUAL_ADDRESS cbAddress = objectCB->GetGPUVirtualAddress();
  12. // Offset to the ith object constant buffer in the current buffer.
  13. cbAddress += i*objCBByteSize;
  14. // Offset to the object CBV in the descriptor heap.
  15. int heapIndex = frameIndex*objCount + i;
  16. auto handle = CD3DX12_CPU_DESCRIPTOR_HANDLE( mCbvHeap->GetCPUDescriptorHandleForHeapStart());
  17. handle.Offset(heapIndex, mCbvSrvUavDescriptorSize);
  18. D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc;
  19. cbvDesc.BufferLocation = cbAddress;
  20. cbvDesc.SizeInBytes = objCBByteSize;
  21. md3dDevice- >CreateConstantBufferView(&cbvDesc, handle);
  22. }
  23. }
  24. UINT passCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof (PassConstants));
  25. // Last three descriptors are the pass CBVs for each frame resource.
  26. for(int frameIndex = 0; frameIndex < gNumFrameResources; ++frameIndex)
  27. {
  28. auto passCB = mFrameResources[frameIndex]->PassCB->Resource();
  29. // Pass buffer only stores one cbuffer per frame resource.
  30. D3D12_GPU_VIRTUAL_ADDRESS cbAddress = passCB->GetGPUVirtualAddress();
  31. // Offset to the pass cbv in the descriptor heap.
  32. int heapIndex = mPassCbvOffset + frameIndex;
  33. auto handle = CD3DX12_CPU_DESCRIPTOR_HANDLE(mCbvHeap->GetCPUDescriptorHandleForHeapStart());
  34. handle.Offset(heapIndex, mCbvSrvUavDescriptorSize);
  35. D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc;
  36. cbvDesc.BufferLocation = cbAddress;
  37. cbvDesc.SizeInBytes = passCBByteSize;
  38. md3dDevice->CreateConstantBufferView(&cbvDesc, handle);
  39. }
  40. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

我们可以得到第一个描述的句柄通过ID3D12DescriptorHeap::GetCPUDescriptorHandleForHeapStar方法。但是现在我们堆中有多个描述,所以这个方法并不高效。我们需要在堆中偏移我们的描述,为了实现这个,我们需要知道得到下一个描述需要偏移的大小。这个由硬件定义,所以我们需要从device那里确认这些信息,并且它取决于对类型:

  1. mRtvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  2. mDsvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  3. mCbvSrvUavDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  • 1
  • 2
  • 3
  • 4

当我们知道描述增长的大小后,可以使用2个CD3DX12_CPU_DESCRIPTOR_HANDLE::Offset方法中的一个来偏移到目标描述:

  1. // Specify the number of descriptors to offset times the descriptor
  2. // Offset by n descriptors:
  3. CD3DX12_CPU_DESCRIPTOR_HANDLE handle = mCbvHeap->GetCPUDescriptorHandleForHeapStart();
  4. handle.Offset(n * mCbvSrvDescriptorSize);
  5. // Or equivalently, specify the number of descriptors to offset,
  6. // followed by the descriptor increment size:
  7. CD3DX12_CPU_DESCRIPTOR_HANDLE handle = mCbvHeap->GetCPUDescriptorHandleForHeapStart();
  8. handle.Offset(n, mCbvSrvDescriptorSize);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

其中CD3DX12_GPU_DESCRIPTOR_HANDLE也具有相同的Offset方法。


5.4 绘制场景

最后,我们可以绘制我们的渲染项目了。可能稍微不同一点的地方在于我们需要偏移到对应的CBV:

  1. void ShapesApp::DrawRenderItems(ID3D12GraphicsCommandList* cmdList, const std::vector<RenderItem*>& ritems)
  2. {
  3. UINT objCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));
  4. auto objectCB = mCurrFrameResource->ObjectCB->Resource();
  5. // For each render item…
  6. for(size_t i = 0; i < ritems.size(); ++i)
  7. {
  8. auto ri = ritems[i];
  9. cmdList->IASetVertexBuffers(0, 1, &ri->Geo->VertexBufferView());
  10. cmdList->IASetIndexBuffer(&ri->Geo->IndexBufferView());
  11. cmdList->IASetPrimitiveTopology(ri->PrimitiveType);
  12. // Offset to the CBV in the descriptor heap for this object and
  13. // for this frame resource.
  14. UINT cbvIndex = mCurrFrameResourceIndex* (UINT)mOpaqueRitems.size() + ri->ObjCBIndex;
  15. auto cbvHandle = CD3DX12_GPU_DESCRIPTOR_HANDLE(mCbvHeap->GetGPUDescriptorHandleForHeapStart());
  16. cbvHandle.Offset(cbvIndex, mCbvSrvUavDescriptorSize);
  17. cmdList->SetGraphicsRootDescriptorTable(0, cbvHandle);
  18. cmdList->DrawIndexedInstanced(ri->IndexCount,
  19. 1,
  20. ri->StartIndexLocation, ri- >BaseVertexLocation, 0);
  21. }
  22. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

DrawRenderItems方法在Draw中调用:

  1. void ShapesApp::Draw(const GameTimer& gt)
  2. {
  3. auto cmdListAlloc = mCurrFrameResource->CmdListAlloc;
  4. // Reuse the memory associated with command recording.
  5. // We can only reset when the associated command lists have
  6. // finished execution on the GPU.
  7. ThrowIfFailed(cmdListAlloc->Reset());
  8. // A command list can be reset after it has been added to the
  9. // command queue via ExecuteCommandList.
  10. // Reusing the command list reuses memory.
  11. if(mIsWireframe)
  12. {
  13. ThrowIfFailed(mCommandList->Reset(cmdListAlloc.Get(), mPSOs["opaque_wireframe"].Get()));
  14. }
  15. else
  16. {
  17. ThrowIfFailed(mCommandList->Reset(cmdListAlloc.Get(), mPSOs["opaque"].Get()));
  18. }
  19. mCommandList->RSSetViewports(1, &mScreenViewport);
  20. mCommandList->RSSetScissorRects(1, &mScissorRect);
  21. // Indicate a state transition on the resource usage.
  22. mCommandList->ResourceBarrier(1,
  23. &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
  24. D3D12_RESOURCE_STATE_PRESENT,
  25. D3D12_RESOURCE_STATE_RENDER_TARGET));
  26. // Clear the back buffer and depth buffer.
  27. mCommandList->ClearRenderTargetView(CurrentBackBufferView(),Colors::LightSteelBlue, 0, nullptr);
  28. mCommandList->ClearDepthStencilView(DepthStencilView(),
  29. D3D12_CLEAR_FLAG_DEPTH |
  30. D3D12_CLEAR_FLAG_STENCIL,
  31. 1.0f, 0, 0, nullptr);
  32. // Specify the buffers we are going to render to.
  33. mCommandList->OMSetRenderTargets(1, &CurrentBackBufferView(), true, &DepthStencilView());
  34. ID3D12DescriptorHeap* descriptorHeaps[] = { mCbvHeap.Get() };
  35. mCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
  36. mCommandList->SetGraphicsRootSignature(mRootSignature.Get());
  37. int passCbvIndex = mPassCbvOffset + mCurrFrameResourceIndex;
  38. auto passCbvHandle = CD3DX12_GPU_DESCRIPTOR_HANDLE(mCbvHeap->GetGPUDescriptorHandleForHeapStart());
  39. passCbvHandle.Offset(passCbvIndex, mCbvSrvUavDescriptorSize);
  40. mCommandList->SetGraphicsRootDescriptorTable(1, passCbvHandle);
  41. DrawRenderItems(mCommandList.Get(), mOpaqueRitems);
  42. // Indicate a state transition on the resource usage.
  43. mCommandList->ResourceBarrier(1,
  44. &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(),
  45. D3D12_RESOURCE_STATE_RENDER_TARGET,
  46. D3D12_RESOURCE_STATE_PRESENT));
  47. // Done recording commands.
  48. ThrowIfFailed(mCommandList->Close());
  49. // Add the command list to the queue for execution.
  50. ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
  51. mCommandQueue- >ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
  52. // Swap the back and front buffers
  53. ThrowIfFailed(mSwapChain->Present(0, 0));
  54. mCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;
  55. // Advance the fence value to mark commands up to this fence point.
  56. mCurrFrameResource->Fence = ++mCurrentFence;
  57. // Add an instruction to the command queue to set a new fence point.
  58. // Because we are on the GPU timeline, the new fence point won’t be
  59. // set until the GPU finishes processing all the commands prior to this Signal().
  60. mCommandQueue->Signal(mFence.Get(),
  61. mCurrentFence);
  62. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76


6 更多关于根签名(ROOT SIGNATURES)

在前一小节我们介绍了根签名。一个根签名定义了在设置绘制调用前,那些资源需要绑定到渲染管线和如何映射到着色器程序。当一个PSO创建好后,根签名和着色器程序组合将被验证。


6.1 根参数

一个根签名是由一个根参数数组定义,之前我们只是创建一个根参数来保存一个描述表。然而一个根参数可以拥有下面3中类型:

  1. 描述表(Descriptor Table):绑定在堆中连续范围定义的资源的引用;
  2. 根描述(Root descriptor (inline descriptor)):直接绑定到确定资源的描述;该描述不需要放到堆中。只有针对常量缓冲的CBV和针对缓冲的SRV/UAVs可以绑定到根描述;所以针对贴图的SRV不能绑定到根描述。
  3. 根常量(Root constant):一个32位常量列表直接绑定的值。

为了性能,根签名有一个64DWORDs的数量限制,下面是每种根签名类型占用的空间:

  1. Descriptor Table: 1 DWORD
  2. Root Descriptor: 2 DWORDs
  3. Root Constant: 1 DWORD per 32-bit constant

我们可以创建任意不超过64DWORD的根签名,Root Descriptor非常方便但是会占用更多的空间;比如如果只有一个常量数据:world-viewprojection矩阵,我们使用16个Root Constant来保存它,它可以让我们不用去创建常量缓冲和CBV堆;这些操作会消耗四分之一的开销。在实际游戏应用中,我们需要这三种类型的结合。
在代码中,我们需要为一个CD3DX12_ROOT_PARAMETER结构赋值:

  1. typedef struct D3D12_ROOT_PARAMETER
  2. {
  3. D3D12_ROOT_PARAMETER_TYPE ParameterType;
  4. union
  5. {
  6. D3D12_ROOT_DESCRIPTOR_TABLE DescriptorTable;
  7. D3D12_ROOT_CONSTANTS Constants;
  8. D3D12_ROOT_DESCRIPTOR Descriptor;
  9. };
  10. D3D12_SHADER_VISIBILITY ShaderVisibility;
  11. }D3D12_ROOT_PARAMETER;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  1. ParameterType:下面枚举中的一个类型,定义根参数的类型:
  1. enum D3D12_ROOT_PARAMETER_TYPE
  2. {
  3. D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE = 0,
  4. D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS= 1,
  5. D3D12_ROOT_PARAMETER_TYPE_CBV = 2,
  6. D3D12_ROOT_PARAMETER_TYPE_SRV = 3 ,
  7. D3D12_ROOT_PARAMETER_TYPE_UAV = 4
  8. } D3D12_ROOT_PARAMETER_TYPE;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. DescriptorTable/Constants/Descriptor:描述根参数的结构,根据类型来指定结构类型;
  2. ShaderVisibility:下面枚举中的一个类型,来定义着色器的可见性。本书中我们一般设置为D3D12_SHADER_VISIBILITY_ALL。但是如果我们只希望在像素着色器中使用该资源我们可以设置为D3D12_SHADER_VISIBILITY_PIXEL。限制根参数的可见性可能会提高性能:
  1. enum D3D12_SHADER_VISIBILITY
  2. {
  3. D3D12_SHADER_VISIBILITY_ALL = 0,
  4. D3D12_SHADER_VISIBILITY_VERTEX = 1,
  5. D3D12_SHADER_VISIBILITY_HULL = 2,
  6. D3D12_SHADER_VISIBILITY_DOMAIN = 3,
  7. D3D12_SHADER_VISIBILITY_GEOMETRY = 4,
  8. D3D12_SHADER_VISIBILITY_PIXEL = 5
  9. } D3D12_SHADER_VISIBILITY;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

6.2 描述表(Descriptor Tables)

一个描述表根参数是由赋值一个DescriptorTable的变量D3D12_ROOT_PARAMETER结构来定义的:

  1. typedef struct D3D12_ROOT_DESCRIPTOR_TABLE
  2. {
  3. UINT NumDescriptorRanges;
  4. const D3D12_DESCRIPTOR_RANGE *pDescriptorRanges;
  5. } D3D12_ROOT_DESCRIPTOR_TABLE;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

它简单定义一个D3D12_DESCRIPTOR_RANGEs数据和数组中范围的数量。
D3D12_DESCRIPTOR_RANGE结构定义如下:

  1. typedef struct D3D12_DESCRIPTOR_RANGE
  2. {
  3. D3D12_DESCRIPTOR_RANGE_TYPE RangeType;
  4. UINT NumDescriptors;
  5. UINT BaseShaderRegister;
  6. UINT RegisterSpace;
  7. UINT OffsetInDescriptorsFromTableStart;
  8. } D3D12_DESCRIPTOR_RANGE;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. RangeType:下面枚举类型来指定当前范围的描述类型:
  1. enum D3D12_DESCRIPTOR_RANGE_TYPE
  2. {
  3. D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0,
  4. D3D12_DESCRIPTOR_RANGE_TYPE_UAV = 1,
  5. D3D12_DESCRIPTOR_RANGE_TYPE_CBV = 2 ,
  6. D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = 3
  7. } D3D12_DESCRIPTOR_RANGE_TYPE;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. NumDescriptors:该范围中描述的数量;
  2. BaseShaderRegister:绑定的基本着色器寄存器参数。比如如果你设置NumDescriptors为3,BaseShaderRegister为1,并且类型为CBV。那么你将绑定到寄存器到HLSL:
  1. cbuffer cbA : register(b1) {…};
  2. cbuffer cbB : register(b2) {…};
  3. cbuffer cbC : register(b3) {…};
  • 1
  • 2
  • 3
  • 4
  1. RegisterSpace:这个属性给予你另一个维度来定义着色器寄存器。比如下面2个寄存器看起来是重叠的,但是它们是不同的因为它们有不同的空间:
  1. Texture2D gDiffuseMap : register(t0, space0);
  2. Texture2D gNormalMap : register(t0, space1);
  • 1
  • 2
  • 3

如果着色器程序中没有指定空间,那么它默认为space0。通常情况下我们都使用space0,但是对于一个资源数据,它就比较有用了,并且如果资源的大小无法确定是,它就很有必要。

  1. OffsetInDescriptorsFromTableStart:该描述范围从表开始位置的偏移量。

一个槽的根参数通过一个D3D12_DESCRIPTOR_RANGE实例数组来初始化为描述表是因为我们可以混合多种类型的描述在一个表中。假设我们定义一个下面三种类型,拥有6个描述的一个表:两个CBV,三个SRV,和一个UAV。那么这个表应该这么定义:

  1. // Create a table with 2 CBVs, 3 SRVs and 1 UAV.
  2. CD3DX12_DESCRIPTOR_RANGE descRange[3];
  3. descRange[0].Init(
  4. D3D12_DESCRIPTOR_RANGE_TYPE_CBV, // descriptor type
  5. 2, // descriptor count
  6. 0, // base shader register arguments are bound to for this root
  7. // parameter
  8. 0, // register space
  9. 0);// offset from start of table
  10. descRange[1].Init(
  11. D3D12_DESCRIPTOR_RANGE_TYPE_SRV, // descriptor type
  12. 3, // descriptor count
  13. 0, // base shader register arguments are bound to for this root
  14. // parameter
  15. 0, // register space
  16. 2);// offset from start of table
  17. descRange[2].Init(
  18. D3D12_DESCRIPTOR_RANGE_TYPE_UAV, // descriptor
  19. type
  20. 1, // descriptor count
  21. 0, // base shader register arguments are bound to for this root
  22. // parameter
  23. 0, // register space
  24. 5);// offset from start of table
  25. slotRootParameter[0].InitAsDescriptorTable(3, descRange, D3D12_SHADER_VISIBILITY_ALL);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

CD3DX12_DESCRIPTOR_RANGE是继承自D3D12_DESCRIPTOR_RANGE的结构,我们使用下面的初始化方法:

  1. void CD3DX12_DESCRIPTOR_RANGE::Init(
  2. D3D12_DESCRIPTOR_RANGE_TYPE rangeType,
  3. UINT numDescriptors,
  4. UINT baseShaderRegister,
  5. UINT registerSpace = 0,
  6. UINT offsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

该表包含6个描述,每个类型寄存器都从0开始,它们是不重复的,因为不同类型拥有不同寄存器类型。我们可以通过制定D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND让D3D计算offsetInDescriptorsFromTableStart;该命令Direct3D使用之前描述范围个数来计算偏移。CD3DX12_DESCRIPTOR_RANGE::Init方法寄存器空间默认是0并且OffsetInDescriptorsFromTableStart为D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND。


6.3 根描述(Root Descriptors)

一个根描述根参数通过进一步定义Descriptor的D3D12_ROOT_PARAMETER变量来定义:

  1. typedef struct D3D12_ROOT_DESCRIPTOR
  2. {
  3. UINT ShaderRegister;
  4. UINT RegisterSpace;
  5. }D3D12_ROOT_DESCRIPTOR;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  1. ShaderRegister:描述需要绑定的寄存器。
  2. RegisterSpace:如上述space。

和描述表不同,我们只需要简单的直接把虚拟位置绑定到资源:

  1. UINT objCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));
  2. D3D12_GPU_VIRTUAL_ADDRESS objCBAddress = objectCB->GetGPUVirtualAddress();
  3. // Offset to the constants for this object in the buffer.
  4. objCBAddress += ri->ObjCBIndex*objCBByteSize;
  5. cmdList->SetGraphicsRootConstantBufferView(
  6. 0, // root parameter index
  7. objCBAddress);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

6.4 根常量(Root Constants)

需要进一步定义D3D12_ROOT_PARAMETER:

  1. typedef struct D3D12_ROOT_CONSTANTS
  2. {
  3. UINT ShaderRegister;
  4. UINT RegisterSpace;
  5. UINT Num32BitValues;
  6. } D3D12_ROOT_CONSTANTS;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

下面是一个使用的例子:

  1. // Application code: Root signature definition.
  2. CD3DX12_ROOT_PARAMETER slotRootParameter[1];
  3. slotRootParameter[0].InitAsConstants(12, 0);
  4. // A root signature is an array of root parameters.
  5. CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(1,
  6. slotRootParameter,
  7. 0, nullptr,
  8. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  9. // Application code: to set the constants to register b0.
  10. auto weights = CalcGaussWeights(2.5f);
  11. int blurRadius = (int)weights.size() / 2;
  12. cmdList->SetGraphicsRoot32BitConstants(0, 1, &blurRadius, 0);
  13. cmdList->SetGraphicsRoot32BitConstants(0, (UINT)weights.size(), weights.data(), 1);
  14. // HLSL code.
  15. cbuffer cbSettings : register(b0)
  16. {
  17. // We cannot have an array entry in a constant buffer that gets
  18. // mapped onto root constants, so list each element.
  19. int gBlurRadius;
  20. // Support up to 11 blur weights.
  21. float w0;
  22. float w1;
  23. float w2;
  24. float w3;
  25. float w4;
  26. float w5;
  27. float w6;
  28. float w7;
  29. float w8;
  30. float w9;
  31. float w10;
  32. };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

ID3D12GraphicsCommandList::SetGraphicsRoot32BitConstant参数如下:

  1. void ID3D12GraphicsCommandList::SetGraphicsRoot32BitConstants(
  2. UINT RootParameterIndex,
  3. UINT Num32BitValuesToSet,
  4. const void *pSrcData,
  5. UINT DestOffsetIn32BitValues);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

6.5 更复杂的根信号例子

假设着色器程序希望获得下面资源:

  1. Texture2D gDiffuseMap : register(t0);
  2. cbuffer cbPerObject : register(b0)
  3. {
  4. float4x4 gWorld;
  5. float4x4 gTexTransform;
  6. };
  7. cbuffer cbPass : register(b1)
  8. {
  9. float4x4 gView;
  10. float4x4 gInvView;
  11. float4x4 gProj;
  12. float4x4 gInvProj;
  13. float4x4 gViewProj;
  14. float4x4 gInvViewProj;
  15. float3 gEyePosW;
  16. float cbPerObjectPad1;
  17. float2 gRenderTargetSize;
  18. float2 gInvRenderTargetSize;
  19. float gNearZ;
  20. float gFarZ;
  21. float gTotalTime;
  22. float gDeltaTime;
  23. float4 gAmbientLight;
  24. Light gLights[MaxLights];
  25. };
  26. cbuffer cbMaterial : register(b2)
  27. {
  28. float4 gDiffuseAlbedo;
  29. float3 gFresnelR0;
  30. float gRoughness;
  31. float4x4 gMatTransform;
  32. };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

那么根签名描述如下:

  1. CD3DX12_DESCRIPTOR_RANGE texTable;
  2. texTable.Init(
  3. D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
  4. 1, // number of descriptors
  5. 0); // register t0
  6. // Root parameter can be a table, root descriptor or root constants.
  7. CD3DX12_ROOT_PARAMETER slotRootParameter[4];
  8. // Perfomance TIP: Order from most frequent to least frequent.
  9. slotRootParameter[0].InitAsDescriptorTable(1, &texTable, D3D12_SHADER_VISIBILITY_PIXEL);
  10. slotRootParameter[1].InitAsConstantBufferView(0);
  11. // register b0
  12. slotRootParameter[2].InitAsConstantBufferView(1);
  13. // register b1
  14. slotRootParameter[3].InitAsConstantBufferView(2);
  15. // register b2
  16. // A root signature is an array of root parameters.
  17. CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4,
  18. slotRootParameter,
  19. 0, nullptr,
  20. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

6.6 根参数的版本管理

根参数对象(Root arguments)我们传递的根参数中的实际数据,考虑下面的代码,我们每一个绘制调用都改变了根参数对象:

  1. for(size_t i = 0; i < mRitems.size(); ++i)
  2. {
  3. const auto& ri = mRitems[i];
  4. // Offset to the CBV for this frame and this render item.
  5. int cbvOffset = mCurrFrameResourceIndex*(int)mRitems.size();
  6. cbvOffset += ri.CbIndex;
  7. cbvHandle.Offset(cbvOffset, mCbvSrvDescriptorSize);
  8. // Identify descriptors to use for this draw call.
  9. cmdList->SetGraphicsRootDescriptorTable(0, cbvHandle);
  10. cmdList->DrawIndexedInstanced(
  11. ri.IndexCount, 1,
  12. ri.StartIndexLocation,
  13. ri.BaseVertexLocation, 0);
  14. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

每一个绘制调用都会以当前设置的根参数对象状态来执行。这样可以正常执行,因为硬件会为每一个绘制调用自动保存一份根参数对象的snapshot。也就是说根参数对象会在每次绘制调用中自动进行版本管理。
一个根签名可以提供比着色器使用的更多的字段。
为了性能优化,我们应该尽可能让根签名更小,其中一个原因是每个绘制调用中对根参数对象的自动版本管理,根签名越大,需要的开销就越大。更进一步,SDK文档建议跟参数应该根据改变的频率来排序(从高到低),并且尽可能减少根签名的切换。所以在多个PSO中共享一个根签名是一个不错的主意。所以创建一个“super”根签名在多个着色器程序中共享,即使部分参数在部分着色器中不需要使用,也可以优化性能。但是如果这个“super”根签名太大就会让减少切换获得的好处变小。



7 陆地和波浪示例

在这里插入图片描述
该图是一个基于实数方程y = f(x, z)的平面,我们可以通过生成一个xz平面(每个方格由2个三角形组成),然后再将每个顶点套入上述方程后近似得到。
在这里插入图片描述


7.1 创建网格顶点

一个m × n的网格包含(m – 1) × (n – 1)个四边形,每个四边形包含2个三角形,所以总共就有2 (m – 1) × (n – 1)个三角形。如果网格的宽度是w,深度是d,那么每个四边形在x轴方向的长度是dx = w/(n – 1),在z轴方向就是dz = d/(m − 1)。所以我们从左上角开始创建,那么第ijth个顶点的坐标就是:
在这里插入图片描述
在这里插入图片描述
其创建代码如下:

  1. GeometryGenerator::MeshData GeometryGenerator::CreateGrid(float width, float depth, uint32 m, uint32 n)
  2. {
  3. MeshData meshData;
  4. uint32 vertexCount = m*n;
  5. uint32 faceCount = (m-1)*(n-1)*2;
  6. float halfWidth = 0.5f*width;
  7. float halfDepth = 0.5f*depth;
  8. float dx = width / (n-1);
  9. float dz = depth / (m-1);
  10. float du = 1.0f / (n-1);
  11. float dv = 1.0f / (m-1);
  12. meshData.Vertices.resize(vertexCount);
  13. for(uint32 i = 0; i < m; ++i)
  14. {
  15. float z = halfDepth - i*dz;
  16. for(uint32 j = 0; j < n; ++j)
  17. {
  18. float x = -halfWidth + j*dx;
  19. meshData.Vertices[i*n+j].Position = XMFLOAT3(x, 0.0f, z);
  20. meshData.Vertices[i*n+j].Normal = XMFLOAT3(0.0f, 1.0f, 0.0f);
  21. meshData.Vertices[i*n+j].TangentU = XMFLOAT3(1.0f, 0.0f, 0.0f);
  22. // Stretch texture over grid.
  23. meshData.Vertices[i*n+j].TexC.x = j*du;
  24. meshData.Vertices[i*n+j].TexC.y = i*dv;
  25. }
  26. }
  27. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

7.2 创建网格索引

从左上角开始遍历每个四边形,用索引生成2个三角形:
在这里插入图片描述
在这里插入图片描述
生成索引的代码如下:

  1. meshData.Indices32.resize(faceCount*3); // 3 indices per face
  2. // Iterate over each quad and compute indices.
  3. uint32 k = 0;
  4. for(uint32 i = 0; i < m-1; ++i)
  5. {
  6. for(uint32 j = 0; j < n-1; ++j)
  7. {
  8. meshData.Indices32[k] = i*n+j;
  9. meshData.Indices32[k+1] = i*n+j+1;
  10. meshData.Indices32[k+2] = (i+1)*n+j;
  11. meshData.Indices32[k+3] = (i+1)*n+j;
  12. meshData.Indices32[k+4] = i*n+j+1;
  13. meshData.Indices32[k+5] = (i+1)*n+j+1;
  14. k += 6; // next quad
  15. }
  16. }
  17. return meshData;
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

7.3 应用高度计算方程

创建好网格后,我们可以从MeshData中提取出顶点数据,转换成高度不同的表面来表示山脉,然后再根据高度赋予不同的颜色:

  1. // Not to be confused with GeometryGenerator::Vertex.
  2. struct Vertex
  3. {
  4. XMFLOAT3 Pos;
  5. XMFLOAT4 Color;
  6. };
  7. void LandAndWavesApp::BuildLandGeometry()
  8. {
  9. GeometryGenerator geoGen;
  10. GeometryGenerator::MeshData grid = geoGen.CreateGrid(160.0f, 160.0f, 50, 50);
  11. //
  12. // Extract the vertex elements we are interested and apply the height
  13. // function to each vertex. In addition, color the vertices based on
  14. // their height so we have sandy looking beaches, grassy low hills,
  15. // and snow mountain peaks.
  16. //
  17. std::vector<Vertex> vertices(grid.Vertices.size());
  18. for(size_t i = 0; i < grid.Vertices.size(); ++i)
  19. {
  20. auto& p = grid.Vertices[i].Position;
  21. vertices[i].Pos = p;
  22. vertices[i].Pos.y = GetHillsHeight(p.x, p.z);
  23. // Color the vertex based on its height.
  24. if(vertices[i].Pos.y < -10.0f)
  25. {
  26. // Sandy beach color.
  27. vertices[i].Color = XMFLOAT4(1.0f, 0.96f, 0.62f, 1.0f);
  28. }
  29. else if(vertices[i].Pos.y < 5.0f)
  30. {
  31. // Light yellow-green.
  32. vertices[i].Color = XMFLOAT4(0.48f, 0.77f, 0.46f, 1.0f);
  33. }
  34. else if(vertices[i].Pos.y < 12.0f)
  35. {
  36. // Dark yellow-green.
  37. vertices[i].Color = XMFLOAT4(0.1f, 0.48f, 0.19f, 1.0f);
  38. }
  39. else if(vertices[i].Pos.y < 20.0f)
  40. {
  41. // Dark brown.
  42. vertices[i].Color = XMFLOAT4(0.45f, 0.39f, 0.34f, 1.0f);
  43. }
  44. else
  45. {
  46. // White snow.
  47. vertices[i].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
  48. }
  49. }
  50. const UINT vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
  51. std::vector<std::uint16_t> indices = grid.GetIndices16();
  52. const UINT ibByteSize = (UINT)indices.size() * sizeof(std::uint16_t);
  53. auto geo = std::make_unique<MeshGeometry>();
  54. geo->Name = "landGeo";
  55. ThrowIfFailed(D3DCreateBlob(vbByteSize, &geo->VertexBufferCPU));
  56. CopyMemory(geo->VertexBufferCPU->GetBufferPointer(), vertices.data(), vbByteSize);
  57. ThrowIfFailed(D3DCreateBlob(ibByteSize, &geo->IndexBufferCPU));
  58. CopyMemory(geo->IndexBufferCPU->GetBufferPointer(), indices.data(), ibByteSize);
  59. geo->VertexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  60. mCommandList.Get(), vertices.data(),
  61. vbByteSize, geo->VertexBufferUploader);
  62. geo->IndexBufferGPU = d3dUtil::CreateDefaultBuffer(md3dDevice.Get(),
  63. mCommandList.Get(), indices.data(),
  64. ibByteSize, geo->IndexBufferUploader);
  65. geo->VertexByteStride = sizeof(Vertex);
  66. geo->VertexBufferByteSize = vbByteSize;
  67. geo->IndexFormat = DXGI_FORMAT_R16_UINT;
  68. geo->IndexBufferByteSize = ibByteSize;
  69. SubmeshGeometry submesh;
  70. submesh.IndexCount = (UINT)indices.size();
  71. submesh.StartIndexLocation = 0;
  72. submesh.BaseVertexLocation = 0;
  73. geo->DrawArgs["grid"] = submesh;
  74. mGeometries["landGeo"] = std::move(geo);
  75. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85

本Demo中的函数f(x, z)实现如下:

  1. float LandAndWavesApp::GetHeight(float x, float z)const
  2. {
  3. return 0.3f*(z*sinf(0.1f*x) + x*cosf(0.1f*z));
  4. }
  • 1
  • 2
  • 3
  • 4
  • 5

7.4 根CBVs

另一个和Shape Demo不同的地方在于,我们使用根描述所以CBV可以直接绑定而不需要描述堆:

  1. 根签名需要2个根CBV而不是两个描述表;
  2. 不需要描述堆;
  3. 新的语法来绑定根描述。
  1. // Root parameter can be a table, root descriptor or root constants.
  2. CD3DX12_ROOT_PARAMETER slotRootParameter[2];
  3. // Create root CBV.
  4. slotRootParameter[0].InitAsConstantBufferView(0);
  5. // per-object CBV
  6. slotRootParameter[1].InitAsConstantBufferView(1);
  7. // per-pass CBV
  8. // A root signature is an array of root parameters.
  9. CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(2,
  10. slotRootParameter, 0,
  11. nullptr,
  12. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

InitAsConstantBufferView方法参数是寄存器序号。
现在我们使用下面的方法来以参数的形式绑定CBV到根描述:

  1. void ID3D12GraphicsCommandList::SetGraphicsRootConstantBufferView(
  2. UINT RootParameterIndex,
  3. D3D12_GPU_VIRTUAL_ADDRESS BufferLocation);
  • 1
  • 2
  • 3
  • 4
  1. RootParameterIndex:绑定的根参数的索引;
  2. BufferLocation:常量缓冲资源的虚拟地址。

修改后,我们的绘制代码如下:

  1. void LandAndWavesApp::Draw(const GameTimer& gt)
  2. {
  3. […]
  4. // Bind per-pass constant buffer. We only need to do this once per-pass.
  5. auto passCB = mCurrFrameResource->PassCB->Resource();
  6. mCommandList->SetGraphicsRootConstantBufferView(1, passCB->GetGPUVirtualAddress());
  7. DrawRenderItems(mCommandList.Get(), mRitemLayer[(int)RenderLayer::Opaque]);
  8. […]
  9. }
  10. void LandAndWavesApp::DrawRenderItems(
  11. ID3D12GraphicsCommandList* cmdList,
  12. const std::vector<RenderItem*>& ritems)
  13. {
  14. UINT objCBByteSize = d3dUtil::CalcConstantBufferByteSize(sizeof(ObjectConstants));
  15. auto objectCB = mCurrFrameResource->ObjectCB->Resource();
  16. // For each render item…
  17. for(size_t i = 0; i < ritems.size(); ++i)
  18. {
  19. auto ri = ritems[i];
  20. cmdList->IASetVertexBuffers(0, 1, &ri->Geo->VertexBufferView());
  21. cmdList->IASetIndexBuffer(&ri->Geo->IndexBufferView());
  22. cmdList->IASetPrimitiveTopology(ri->PrimitiveType);
  23. D3D12_GPU_VIRTUAL_ADDRESS objCBAddress = objectCB->GetGPUVirtualAddress();
  24. objCBAddress += ri->ObjCBIndex*objCBByteSize;
  25. cmdList->SetGraphicsRootConstantBufferView(0, objCBAddress);
  26. cmdList->DrawIndexedInstanced(ri->IndexCount,
  27. 1,
  28. ri->StartIndexLocation, ri->BaseVertexLocation, 0);
  29. }
  30. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

7.5 动态顶点缓冲

我们之前已经使用过每帧从CPU上传常量缓冲数据到GPU,我们可以使用UploadBuffer类利用同样的技术上传顶点数组,来动态模拟水面:

  1. std::unique_ptr<UploadBuffer<Vertex>> WavesVB = nullptr;
  2. WavesVB = std::make_unique<UploadBuffer<Vertex>>(device, waveVertCount, false);
  • 1
  • 2
  • 3

因为我们每帧需要从CPU上传新的顶点缓冲,所以它需要成为一个帧资源。否则我们可能会改写GPU没有执行到的数据。
每一帧我们执行播放模拟和更新的顶点缓冲代码如下:

  1. void LandAndWavesApp::UpdateWaves(const GameTimer& gt)
  2. {
  3. // Every quarter second, generate a random wave.
  4. static float t_base = 0.0f;
  5. if((mTimer.TotalTime() - t_base) >= 0.25f)
  6. {
  7. t_base += 0.25f;
  8. int i = MathHelper::Rand(4, mWaves->RowCount() - 5);
  9. int j = MathHelper::Rand(4, mWaves->ColumnCount() - 5);
  10. float r = MathHelper::RandF(0.2f, 0.5f);
  11. mWaves->Disturb(i, j, r);
  12. }
  13. // Update the wave simulation.
  14. mWaves->Update(gt.DeltaTime());
  15. // Update the wave vertex buffer with the new solution.
  16. auto currWavesVB = mCurrFrameResource->WavesVB.get();
  17. for(int i = 0; i < mWaves->VertexCount(); ++i)
  18. {
  19. Vertex v;
  20. v.Pos = mWaves->Position(i);
  21. v.Color = XMFLOAT4(DirectX::Colors::Blue);
  22. currWavesVB->CopyData(i, v);
  23. }
  24. // Set the dynamic VB of the wave renderitem to the current frame VB.
  25. mWavesRitem->Geo->VertexBufferGPU = currWavesVB->Resource();
  26. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

使用动态缓冲会有一些额外开销,因为新数据需要从CPU不断上传到GPU。所以静态缓冲比动态缓冲更好。前一个版本的D3D介绍了一些新特征来减少动态缓冲的使用:

  1. 简单的动画使用顶点着色器实现;
  2. 如果可以的话通过渲染到贴图、计算着色器、和顶点贴图获取功能来实现波浪模拟;让这些运算完全在GPU上执行;
  3. 几何着色器可以实现在GPU上创建或者销毁基元(没有它的时候这些任务只能在CPU上实现);
  4. 曲面细分阶段可以在GPU细分曲面(没有它的时候这些任务只能在CPU上实现)。

索引缓冲也可以使用动态缓冲,因为本Demo中拓扑结构不变,所以不需要。
本书并不对波浪的实现算法进行细入分析(可以看[Lengyel02]),但是会更多的描述动态缓冲:在CPU动态模拟然后使用上传缓冲上传到GPU。



8 总结

  1. 等待GPU执行完所有命令是一个很低效的事情,因为GPU和CPU都会产生等待的时间;一个更高效的方法是创建帧资源(frame resources)------一个环形数组的资源,CPU需要修改所有资源。这样CPU不需要再等待GPU执行完毕,可以直接修改下一个可修改的资源。但是如果CPU一直执行过快,CPU还是可能产生等到GPU的时间;不过大部分情况下这是值得的,因为首先可以保证GPU满负荷运转,CPU空余出来的时候可以进行其它模块的计算,比如AI、物理和游戏逻辑等。
  2. 我们可以通过下面的函数获取描述堆中第一个的句柄ID3D12DescriptorHeap::GetCPUDescriptorHandleForHeapStart;然后可以通过下面的方法获取描述的大小:ID3D12Device::GetDescriptorHandleIncrementSize(DescriptorHeapType type)。然后通过下面的方法来偏移到我们需要的描述位置:CD3DX12_CPU_DESCRIPTOR_HANDLE::Offset:
  1. // Specify the number of descriptors to offset times the descriptor
  2. // increment size:
  3. D3D12_CPU_DESCRIPTOR_HANDLE handle = mCbvHeap->GetCPUDescriptorHandleForHeapStart();
  4. handle.Offset(n * mCbvSrvDescriptorSize);
  5. // Or equivalently, specify the number of descriptors to offset,
  6. // followed by the descriptor increment size:
  7. D3D12_CPU_DESCRIPTOR_HANDLE handle = mCbvHeap->GetCPUDescriptorHandleForHeapStart();
  8. handle.Offset(n, mCbvSrvDescriptorSize);
  9. //The CD3DX12_GPU_DESCRIPTOR_HANDLE type has the same Offset methods.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  1. 根签名定义了在一个绘制调用前那些资源要被绑定到渲染管线和这些资源是如何被绑定到着色器寄存器中的。哪些资源会被绑定取决于着色器程序的预期。当PSO被创建时,根签名和着色器程序组合会被验证。一个根签名由一组根参数来定义。一个根参数可以是描述表,根描述或者根常量。一个描述表定义了一段在描述堆中连续的范围;根描述用以直接绑定一个描述到根签名;根常量用以直接绑定常量数据到根签名。为了性能,根签名最多只能放64 DWORDs的上限,描述表占用1DWORD;根描述占用2DWORD;根常量每32位占用1DWORD。在每个绘制调用时,硬件自动为每个根参数对象保存快照(版本管理),所以我们需要尽可能减少根签名的大小来节约内存占用。
  2. 动态顶点缓冲用来当常量顶点缓冲需要频繁更新和上传的时候。我们可以使用UploadBuffer来视线动态顶点缓冲。因为我们需要上传新内容到GPU,所以动态顶点缓冲需要放到帧资源中。使用动态顶点缓冲时会有一些新的开销,因为需要将数据从CPU传到GPU。静态顶点缓冲比动态的更实用,前一个版本的D3D提供了一些新特性来减少使用动态缓冲。


9 练习

1. 修改“Shape” Demo,使用GeometryGenerator::CreateGeosphere代替GeometryGenerator::CreateSphere,并尝试0、1、2、3细分等级;
代码在 https://github.com/jiabaodan/Direct12BookReadingNotes 中的 Chapter7_Exercises_1_Geosphere 工程
在这里插入图片描述
替换创建函数即可

2. 修改“Shape” Demo,使用16个根常量替换描述表来设置每个物体的世界坐标变换矩阵;
代码在 https://github.com/jiabaodan/Direct12BookReadingNotes 中的 Chapter7_Exercises_2_RootConstants 工程
在这里插入图片描述
修改为使用Root Constant即可

  1. CD3DX12_ROOT_PARAMETER slotRootParameter[2];
  2. slotRootParameter[0].InitAsConstants(16, 0);
  3. // 设置Root Constant's values
  4. DirectX::XMFLOAT4X4 WorldTest = MathHelper::Identity4x4();
  5. XMStoreFloat4x4(&WorldTest,
  6. XMMatrixTranslation(0.0f, 2.0f, 0.0f) *
  7. XMMatrixRotationX(0.f) *
  8. XMMatrixScaling(2.0f, 1.0f, 2.0f));
  9. mCommandList->SetGraphicsRoot32BitConstants(0, 16, WorldTest.m, 0);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

但是这样做后会有2个问题:1、没办法针对每个物体设置值;2、进行位移设置后,物体会显示错误
在这里插入图片描述
针对上面的问题和BUG目前没有找到解决方案,如果有大佬看到的话希望指点下,谢谢哈~

3. 在本书的光盘中有一个Models/Skull.txt文件,它包含了一个骷髅头模型所需要的顶点和索引列表数据。使用文本编辑器来学习这个文件然后修改“Shape” Demo来加载骷髅头网格。
代码在 https://github.com/jiabaodan/Direct12BookReadingNotes 中的Chapter7_Exercises_3_Skull
在这里插入图片描述

posted on 2019-05-05 23:31 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/10817146.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/883746
推荐阅读
  

闽ICP备14008679号