{"id":1575,"date":"2018-06-05T18:13:00","date_gmt":"2018-06-05T18:13:00","guid":{"rendered":"https:\/\/xplicity.com\/?p=1575"},"modified":"2025-01-03T14:44:20","modified_gmt":"2025-01-03T11:44:20","slug":"3d-maze-of-voices","status":"publish","type":"post","link":"https:\/\/xplicity.com\/3d-maze-of-voices\/","title":{"rendered":"3D Maze of Voices"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The article covers the creation of a 3D Direct3D rendered maze for UWP (so that it could be run on any of Microsoft\u2019s platforms \u2013 Windows 10, Windows Phone (Windows 10 Mobile), Xbox One or HoloLens) and it is navigable with voice commands.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application starts with the player\u2019s avatar positioned on the starting tile indicated by a black \u2018S\u2019 letter. The user uses voice commands (or the corresponding directional inputs with arrow keys): \u201cup\u201d, \u201cdown,\u201d \u201cleft\u201d or \u201cright\u201d to guide the avatar through the maze to the finish tile indicated by a white \u2018F\u2019 letter. After reaching the finish, a short winning animation is played, through which everything is reset back to the start state for another round.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is an update of my previous article titled \u201cWriting a 3D DirectX maze that\u2019s navigable with speech commands\u201d which was written in commemoration to the arrival of Windows Phone 8. In addition to many new features brought in by the platform update developers then were provided with the ability to write and run native applications on WP8 devices. The article targeted DirectX 11 for Windows Phone 8 platform.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This current article updates the technologies used in the original article to their latest counterparts. The accompanying code sample is also structured in a way that in my opinion would be the best starting point for easy customization and building of your own engine\\game.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, buckle up and let me take you on a bumpy journey to the shallow parts of the deep oceans of DirectX.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">REQUIREMENTS<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To run the sample, you need a Windows PC running Windows 10 with a DirectX 12 ready GPU.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a comfortable reading experience, you need to have a working knowledge of C++.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Previous DirectX knowledge will ease the process a lot, but it is not a must.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I strongly recommend&nbsp;<a href=\"https:\/\/marketplace.visualstudio.com\/items?itemName=TimGJones.HLSLToolsforVisualStudio\" target=\"_blank\" rel=\"noreferrer noopener\">downloading HLSL Tools<\/a>&nbsp;by Tim Jones. This will significantly enhance the experience when dealing with shader code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">RUNNING THE SAMPLE<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The first step would be to try out the application in action.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"655\" height=\"328\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/Screenshot_2.png\" alt=\"\" class=\"wp-image-1601\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/Screenshot_2.png 655w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/Screenshot_2-300x150.png 300w\" sizes=\"auto, (max-width: 655px) 100vw, 655px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">During the first run of the application, you will be prompted to allow the application to access the microphone. Select \u2018YES\u2019, so that the application would be able to initialize speech recognition engine and you would be able to navigate the maze by shouting commands into your computer\u2019s microphone \\ camera.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae2ff45a46.png\" alt=\"\" class=\"wp-image-1602\" width=\"600\" height=\"192\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae2ff45a46.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae2ff45a46-300x96.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>In the Windows prompt, please allow the use of the microphone for voice input<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Here you can see the application in action:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"325\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae32f15a2b.png\" alt=\"\" class=\"wp-image-1603\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae32f15a2b.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae32f15a2b-300x163.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>App in action<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">1. DIRECT3D 12<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The subset of DirectX 12 API known as&nbsp;<strong>Direct3D 12<\/strong>&nbsp;is used to deal with 3D rendering.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The thing with Direct3D 12 is that it is really different from all the other recent releases of D3D. Many of the things that used to be handled for you by the driver is now your responsibility. Now you can optimize for far better performance by having more control over multithreading and the possibility to offset more work onto GPU. This, in turn, will free the CPU for other tasks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sadly, it comes at a price of hugely increased complexity. DirectX had always carried the reputation of being a hard and involved API to work with. With DirectX 12, even developers, who already had previous run-ins with D3D, might be shockedby the difference in the approach of D3D12. I can only imagine how it is for complete newcomers (or actually, those guys might be at an advantage as they will not need to&nbsp;<em>\u201cunlearn\u201d&nbsp;<\/em>the previous knowledge). The removal of immediate drawing and emphasis on indirect drawing via command lists, descriptor tables, pipeline state objects, etc. have changed the rules of the game a lot. One might even find that correctly initializing the state of the device for a simple drawing operation might prove to be a challenge. This also means you will have to adjust the architecture of your project accordingly to get the most of the new API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I had quite a struggle and was questioning pretty much every decision Microsoft has made with this new version of Direct3D. The Direct3D 12 brings in breaking changes, especially when you compare the two architectures that you would end up with when employing this and the earlier versions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The thing to remember here though is that this was all done for the greater benefit. If you press forward regardless of how hard and frustrating it gets, eventually you will reach a point where you will feel comfortable with the codebase again, and at this point, you will have made the foundation that is much more performant and flexible than any previous version would have allowed it to be.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I have tried to do my best to allow the sample project to be a launchpad, a mini(micro(nano)))-engine of sorts, that would let my readers understand how certain common things are achieved in DirectX12 and build upon that newly found knowledge by extending the sample to their needs. You might be surprised, but by creatively using the building blocks that currently reside in the sample project, you could create a working game even though it would be missing some parts like, e.g., shadow casting.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. STARTING UP<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We will be starting with C++ DirectX 12 UWP project template structure. If you select DirectX 12 App from templates when creating a new project in Visual Studio, you will get a project that is exactly that.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"178\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae33ca3437.png\" alt=\"\" class=\"wp-image-1604\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae33ca3437.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae33ca3437-300x89.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Select the \u201cDirectX 12 App (Universal Windows)\u201d template for a fresh DirectX enabled starting point<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">It already provides us with a gritty, low-level initialization and operation functions. We already get basic things like graphics device selection and initialization, swap chain setup, depth buffer creation, resource fencing, frame buffering, etc.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">And if you just run it, you will get a fully working DirectX app: the state is initialized, geometry is rendered and also update calls are made. Just by doing that you get a signature spinning \u201crainbow cube\u201d on a \u201ccornflower blue\u201d background. As per tradition.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"465\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae3464e2bd.png\" alt=\"\" class=\"wp-image-1605\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae3464e2bd.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae3464e2bd-300x233.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Running the template project already provides you with a rendering \u201crainbow cube\u201d<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Now to start things off \u2013 we will immediately remove random stuff left and right. No, on a serious note, all of the \u201cgame\u201d logic, when starting with the template, is contained within\u00a0<strong>Sample3DSceneRenderer<\/strong>\u00a0class. And I mean all kinds of things \u2013 game specific initialization, transformations, projections, game (update) logic, rendering, you name it. It\u2019s a mess, albeit, it\u2019s an example that you are supposed to rewrite it anyway. I would like to propose more structure and explicit responsibility bounds so that the project is easier to navigate and maintain.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"439\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae35445923.png\" alt=\"\" class=\"wp-image-1606\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae35445923.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae35445923-300x220.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>The screenshot indicates which parts were removed from the template<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The idea is as follows: the&nbsp;<strong>Sample3DSceneRenderer<\/strong>&nbsp;class was removed and the contents (or their enhanced counterparts) were all moved to various classes within&nbsp;<em>VoiceMaze<\/em>&nbsp;folder.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Camera&nbsp;<\/strong>class accommodates the view transformations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Renderer3DBase<\/strong>&nbsp;takes most of the initialization logic and provides a generalized game loop (this class is expected to be extended by another class with concrete implementation for the particular game logic, as in this case is&nbsp;<strong>VoiceMazeRenderer<\/strong>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>RenderableObject<\/strong>&nbsp;is a base where the setup of the renderable object (the \u201crainbow cube,\u201d for example) happens.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>GLOBALSETTINGS<\/strong>&nbsp;is just that \u2013 global project settings like GPU adapter skip index or content base directory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I tried to keep the&nbsp;<strong>DeviceResources<\/strong>&nbsp;file as much intact as possible. It only has minor adjustments for the GPU adapter skip regarding the problem that was mentioned earlier.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For more details look at the\u00a0<a href=\"https:\/\/www.xplicity.com\/blog\/3d-maze-of-voices\/#generalStructure\">General code\\engine structure<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">3. BASIC 3D DEVELOPMENT CRASH COURSE<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this section, I will do a quick general introduction to DirectX and 3D development principles before moving to the sample application \u2013 Voice Maze.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, if we start with the template application, there are a few essential things that are happening already. Namely:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>the content is being initialized<\/li>\n\n\n\n<li>the game loop is being run<\/li>\n\n\n\n<li>certain transformations are being applied every frame<\/li>\n\n\n\n<li>shaders are being executed<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3.1 Initialization<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">One of the nice things that&nbsp;<strong>DeviceResources<\/strong>&nbsp;already supplies us with is the graphics adapter initialization. There is, of course, the selection of the correct hardware (since most of the computers nowadays have both processor integrated and a dedicated graphics card). But it does not stop there.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It also creates other essential elements: it initializes descriptor heaps that are later used for&nbsp;<strong>the render target<\/strong>&nbsp;and&nbsp;<strong>depth stencil<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The synchronization objects, also known as&nbsp;<strong>fences<\/strong>, are initialized here too. This together with&nbsp;<strong>resource barriers&nbsp;<\/strong>binds to the multithreading management of DirectX 12. Fences mark when specific work has been finished by GPU or CPU so that they could be synchronized.&nbsp;<strong>Resource barriers<\/strong>&nbsp;add commands to perform conversions between resource types (for example from a render target to a resource).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After that, we perform the&nbsp;<strong>swap chain<\/strong>&nbsp;initialization. The main purpose of the&nbsp;<strong>swap chain<\/strong>&nbsp;is to provide a safe way of updating the data that is currently being displayed on the user\u2019s monitor. If, say, the application was to send all its render output straight to the monitor, the user would see a lot of drawing artifacts because of the out of sync update rates. For example, if the update rate of the monitor is 60Hz and your application on this particular machine manages to output 100 frames every second, this means that there is quite a high possibility that a single display refresh will consist of the data from 1.6 frames. This happens because once half of the image gets displayed on the screen the data of the new frame arrives and monitor immediately starts pulling the rest of the image from this new, replaced data. This ends up in visible artifacts. Depending on how fast the visuals change on the screen and the disjoint between monitor refresh rate and FPS, the effects range from barely noticeable to quite distracting. One of the most familiar ones that you might have encountered is&nbsp;<strong>screen tearing<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To mitigate this, we use the&nbsp;<strong>swap chain<\/strong>: we write to an invisible buffer and as soon as that one is filled, we swap it with the one being displayed.&nbsp;&nbsp;We can use double or even triple buffering for this. And all that functionality is already provided inside the&nbsp;<strong>DeviceResources<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then we create the&nbsp;<strong>render target views<\/strong>. These are the actual draw surfaces we will be using to render to, and they will get swapped around by the swap chain.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Lastly, we are provided with the&nbsp;<strong>depth stencil<\/strong>. The&nbsp;<strong>depth stencil<\/strong>&nbsp;has a very specific role in 3D development. This buffer is used to sample if a specific geometry is in front or if it is actually being blocked by other geometry when viewed by a virtual camera. If the depth stencil is not used properly, the geometry might not sit quite right or render completely weirdly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.2 The initialization code<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now we will look at the main parts of the code that was moved from&nbsp;<strong>Sample3DSceneRenderer<\/strong>&nbsp;to other classes. Most of the initialization was moved to&nbsp;<strong>Renderer3DBase<\/strong>&nbsp;class. This class is supposed to be extended by a concrete&nbsp;<strong>Renderer&nbsp;<\/strong>implementation that executes all the game-specific logic.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.1 Root signature<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The first big one is&nbsp;<strong>root signature<\/strong>. A&nbsp;<strong>root signature<\/strong>&nbsp;is a descriptor that the app fills in, and it links to the resources that the app will use in the shaders. Root signature can contain three parameter types:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>root constants<\/strong>&nbsp;\u2013 for small rapidly accessed data. They are limited in number<\/li>\n\n\n\n<li><strong>root descriptors<\/strong>&nbsp;\u2013 these are again for often accessed resources and are limited to CBV (constant buffer view), SRV (shader resource view), UAV (Unordered Access view). We will be using these for per-frame and per-object constant buffers.<\/li>\n\n\n\n<li><strong>descriptor tables<\/strong>&nbsp;\u2013 which have two indirections so are a bit slower but are unlimited albeit a bit more complicated to use. We will use it for texture descriptors.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>D3D12_ROOT_DESCRIPTOR rootCBVDescriptor;\nrootCBVDescriptor.RegisterSpace = 0;\nrootCBVDescriptor.ShaderRegister = 0;\n\nCD3DX12_ROOT_PARAMETER rootParameters&#91;3];\n{\n\tCD3DX12_DESCRIPTOR_RANGE range;\n\n\trange.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);\n\trootParameters&#91;0].InitAsDescriptorTable(1, &amp;range, D3D12_SHADER_VISIBILITY_VERTEX);\n}\n\n{\n\tCD3DX12_DESCRIPTOR_RANGE range;\n\n\trange.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1);\n\t\/\/in some cases like normal maps the constant buffer data might be needed in pixel shader calculations too. So: visibility-ALL\n\trootParameters&#91;1].InitAsDescriptorTable(1, &amp;range, D3D12_SHADER_VISIBILITY_ALL);\n}\n\n{\n\tCD3DX12_DESCRIPTOR_RANGE range;\n\trange.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);\n\n\tD3D12_ROOT_DESCRIPTOR_TABLE descriptorTable;\n\tdescriptorTable.NumDescriptorRanges = 1; \/\/ we only have one range\n\tdescriptorTable.pDescriptorRanges = &amp;range; \/\/ the pointer to the beginning of our ranges array\n\n\trootParameters&#91;2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; \/\/ this is a descriptor table\n\trootParameters&#91;2].DescriptorTable = descriptorTable; \/\/ this is our descriptor table for this root parameter\n\trootParameters&#91;2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; \/\/ our pixel shader will be the only shader accessing this parameter for now\n}\n\n\/\/ create a static sampler\nD3D12_STATIC_SAMPLER_DESC sampler = {};\nsampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;\nsampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;\nsampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;\nsampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;\nsampler.MipLODBias = 0;\nsampler.MaxAnisotropy = 0;\nsampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;\nsampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;\nsampler.MinLOD = 0.0f;\nsampler.MaxLOD = D3D12_FLOAT32_MAX;\nsampler.ShaderRegister = 0;\nsampler.RegisterSpace = 0;\nsampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;\n\nD3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =\n\tD3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | \/\/ Only the input assembler stage needs access to the constant buffer.\n\tD3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |\n\tD3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |\n\tD3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;\n\nCD3DX12_ROOT_SIGNATURE_DESC descRootSignature;\ndescRootSignature.Init(_countof(rootParameters), rootParameters, 1, &amp;sampler, rootSignatureFlags);\n\nComPtr pSignature;\nComPtr pError;\nDX::ThrowIfFailed(D3D12SerializeRootSignature(&amp;descRootSignature, D3D_ROOT_SIGNATURE_VERSION_1, pSignature.GetAddressOf(), pError.GetAddressOf()));\nDX::ThrowIfFailed(d3dDevice-&gt;CreateRootSignature(0, pSignature-&gt;GetBufferPointer(), pSignature-&gt;GetBufferSize(), IID_PPV_ARGS(&amp;m_rootSignature)));\nNAME_D3D12_OBJECT(m_rootSignature);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The created root parameter slots will be used as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The first slot will contain per-object constant buffer data.&nbsp;For example,&nbsp;<strong>transformations<\/strong>.<\/li>\n\n\n\n<li>Second slot will be used as a per-frame constant buffer that will keep data like&nbsp;<strong>lighting direction, light color<\/strong>, etc.<\/li>\n\n\n\n<li>The third will be used to indicate the texture used when rendering geometry.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.2 Shader loading<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we will be doing&nbsp;<strong>shader loading<\/strong>. For this, we will reuse functionality provided in&nbsp;<em>DirectXHelper.h<\/em>&nbsp;\u2013 it\u2019s as simple as reading in the data from a file and then supplying&nbsp;<strong>PSO (Pipeline State Object)<\/strong>&nbsp;with that data so that it gets transferred to the GPU for execution. That is actually it with shader loading \u2013 pretty simple, pretty straightforward.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.3 Pipeline State Object<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">After the loading is done we create a&nbsp;<strong>PSO (Pipeline State Object)<\/strong>. We use pipeline state descriptor to configure the GPU, so that it is ready to interpret and render the input data we supply.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To do that we will use various objects&nbsp;we created \u2013 like the previously loaded shaders,&nbsp;<strong>input layout<\/strong>&nbsp;(more on that later),&nbsp;<strong>blend states, topology<\/strong>&nbsp;\u2013 in this case triangle-based etc.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D3D12_GRAPHICS_PIPELINE_STATE_DESC state = {};\nstate.InputLayout = inputLayoutDesc;\nstate.pRootSignature = m_rootSignature.Get();\nstate.VS = CD3DX12_SHADER_BYTECODE(&amp;m_vertexShader&#91;0], m_vertexShader.size());\nstate.PS = CD3DX12_SHADER_BYTECODE(&amp;m_pixelShader&#91;0], m_pixelShader.size());\nstate.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;\nstate.RTVFormats&#91;0] = m_deviceResources-&gt;GetBackBufferFormat();\nstate.SampleDesc.Count = 1;\nstate.SampleMask = UINT_MAX;\nstate.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);\nstate.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);\nstate.NumRenderTargets = 1;\nstate.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);\nstate.DSVFormat = m_deviceResources-&gt;GetDepthBufferFormat();\n\nDX::ThrowIfFailed(m_deviceResources-&gt;GetD3DDevice()-&gt;CreateGraphicsPipelineState(&amp;state, IID_PPV_ARGS(&amp;m_pipelineState)));<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.4 Input layout \\ Vertex data structure<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>input layout<\/strong>&nbsp;describes the way the data should be read from memory or, in other words, the way it is expected to arrive in the shader. This is done, because you might want to vary and optimize the way the data is being sent in \u2013 it will differ depending on texturing, material data, lines\\full geometry, lighting data etc.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The original app template has this input layout:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static const D3D12_INPUT_ELEMENT_DESC inputLayout&#91;] =\n{\n\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t{ \"COLOR\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This pretty much means that for every vertex \\ corner of the cube (8 in total) we will be sending in<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u201e<strong>POSITION<\/strong>\u201c values in 3 coordinates of XYZ (or alternatively \u2013 reuse RGB color notation).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u201e<strong>COLOR<\/strong>\u201c associated with it, also defined in RGB and offset by 12 bytes (3 previous values by 4 bytes each).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Cube vertices. Each vertex has a position and a color.\nVertexPositionColor cubeVertices&#91;] =\n{\n\t{ XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f) },\n\t{ XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,  0.5f,  0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f) },\n\t{ XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f, -0.5f,  0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f) },\n\t{ XMFLOAT3(0.5f,  0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f,  0.5f,  0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f) },\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now it might be a bit clearer how we get this \u201erainbow cube:\u201c each of the vertices have a set hard color value \u2013 red, green, blue, and hard mixes in between (yellow, orange etc.), so in essence 1.0s or 0.0s. When the GPU renders the geometry and needs to draw a pixel that is in between the vertices, it&nbsp;<strong>interpolates<\/strong>&nbsp;(it calculates the gradient). It calculates how much of each of the color component it has to set for the resulting pixel when the distance to the vertexes with set values are taken into account.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The input layout itself arrives from the&nbsp;<em>GetInputLayoutDescriptor<\/em>&nbsp;method in your&nbsp;<strong>Renderer3DBase<\/strong>&nbsp;extending class. This way you can&nbsp;adjust the expected input layout a lot easier to suit your project\u2019s needs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We will be modifying this vertex data structure throughout the article to adjust to the new techniques we come across later.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.5 Command list<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">After all that was done, we create a&nbsp;<strong>Command List<\/strong>&nbsp;with a simple&nbsp;<em>CreateCommandList<\/em>&nbsp;command (pardon the puns). As you can see, it extends the creation chain we have been using to get to this point:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>DX::ThrowIfFailed(d3dDevice-&gt;CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_deviceResources-&gt;GetCommandAllocator(), m_pipelineState.Get(), IID_PPV_ARGS(&amp;m_commandList)));<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The purpose of the command list, though, is not as humble as its creation via a single code line.&nbsp; Command list is a sequence of GPU commands that are \u201crecorded\u201d (or&nbsp;composed) throughout a single execution pass of the application. We will use command lists to upload data to the GPU, perform render calls, and change parameters and states for the rendering pipeline.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After the command list was composed with all the steps you want for the render, you call the list to be executed by the GPU. This is probably the part of DirectX 12 that gives the most potential for the optimization. Since you provide the GPU with a definitive list of what is going to happen, you are giving it the ability to batch and optimize execution calls.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.3 3D Geometry<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The sample had some simple geometry in it \u2013 a cube. A lot of the geometry initialization happened inside the&nbsp;<strong>Sample3DSceneRenderer&nbsp;<\/strong>class. We will have a separate class to deal with objects that can be rendered \u2013&nbsp;<strong>RenderableObject<\/strong>. This object will contain pointers to the data that is necessary to render it out \u2013&nbsp;<strong>vertex buffer, index buffer, textures, constant buffers<\/strong>, and&nbsp;<strong>transformations&nbsp;<\/strong>(we will cover the last three in the next few sections); together with methods for initialization and draw calls. So, essentially some of the code with heavy alterations have been moved out and into this new class.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3.3.1 Vertex and index buffers<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We define 3D geometry using vertex and index buffers. If it helps, you can imagine them as the \u201cConnect the dots\u201d puzzle from your childhood. The vertex buffer defines a list of points or\u00a0<strong>vectors\u00a0<\/strong>in space, using cartesian 3D coordinates \u2013 X, Y, and Z. Direct 3D uses a coordinate system, also known as the\u00a0<strong>left-handed<\/strong>\u00a0coordinate system (as opposed to OpenGL which uses right-handed, hence the inverted Z-axis):<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"450\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae367714a7.png\" alt=\"\" class=\"wp-image-1577\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae367714a7.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae367714a7-300x225.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Direct3D uses left-handed coordinate system<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So, every single vertex in the&nbsp;<strong>vertex buffer<\/strong>&nbsp;is defining a position. Of course, that is not enough to display anything as a point does not define a volume all by itself.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Index buffer<\/strong>&nbsp;defines the order in which the vertices are to be connected, much like the numbers in the \u201cConnect the dots.\u201d The major difference here is that two index values do not directly define a line going between the two vertexes. Indices, depending on the selected primitive topology, define a primitive. In simpler terms, it is interpreted as what you asked it to be at the draw time. The most popular choice being \u2013 three indices define a triangle. And from a whole lot of triangles, you can construct just about anything you can imagine. There&nbsp;are other primitive types: lines, triangle strips, triangle-fans, etc. But again, the most used form is the triangle list, in which every triplet of indices defines a single triangle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the case of the sample cube, we have eight vertices in the vertex buffer. Those are used by the index buffer to create\u00a0<strong>faces<\/strong>. When you define a surface by three indices, you end up with a face. Each side of the cube is composed of two faces \u2013 two pairs of triangles.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"400\" height=\"393\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae372f2520.png\" alt=\"\" class=\"wp-image-1578\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae372f2520.png 400w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae372f2520-300x295.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Triangles composing two faces on a single side of the cube<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So, we end up with 6 sides, each having 2 faces (triangles) \u2013 a cube that is composed of 12 triangles. This, of course, translates into 36 indices in the index buffer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There is a little catch in all of this though \u2013 we run into a phenomenon known as\u00a0<strong>vertex winding order<\/strong>. Well, it\u2019s not a phenomenon as much as an optimization technique. When we define a face, we are not telling it which way it is looking at, are we?<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"311\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae38700447.png\" alt=\"\" class=\"wp-image-1579\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae38700447.png 300w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daae38700447-289x300.png 289w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Which side is the \u2018face\u2019 side in this triangle?<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Is the triangle visible from our side or from the back of the monitor? The easiest way would be to say, that it is visible either way \u2013 once a triangle is defined you should always see its face, regardless of the direction: it works that way in the real world \u2013 there are two sides for anything you are looking at. But with 3D graphics, you want to optimize as much as possible and not throw extra unnecessary work onto the processors. It does not make sense to process and draw triangles that cannot be seen. In case of a single triangle, you would be drawing two times even though the other side is hidden by the one you see at that instance. And in the case of a cube, you would never even see the faces that are on the inner walls of the cube. It might not sound like that big of a deal, and it isn\u2019t\u2026 when we are talking about our little cube with only 6 polygons. But now imagine a model with millions of polygons, which if not<strong>&nbsp;back-face culled<\/strong>&nbsp;(that is what the process of eliminating unseen triangles is called) would, in turn, double the amount of data that needs to be processed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That is where the vertex winding order comes into play. A face is considered to be facing the viewer when the vertices that compose it are in a clockwise order. So, we can see a triangle if the indices define the \u201cconnect the dots\u201d order in a clockwise order. It does not matter which of the vertices within that triangle you start and end with, as long as the winding is done in a clockwise order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once again for comparison, since OpenGL is using right-handed coordinates, their winding order is also, by default, counter-clockwise.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"500\" height=\"492\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf1e14fed8.png\" alt=\"\" class=\"wp-image-1580\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf1e14fed8.png 500w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf1e14fed8-300x295.png 300w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Winding in Direct3D must be done in a clockwise order.<br>The two triangles would then be defined as {v0, v1, v2} and {v0, v2, v3}<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The creation of the buffers is done inside the&nbsp;<strong>RenderableObject&nbsp;<\/strong>class in&nbsp;<em>CreateVertexBuffer&nbsp;<\/em>and&nbsp;<em>CreateIndexBuffer&nbsp;<\/em>methods. It\u2019s pretty self-explanatory \u2013 you take the data, create the&nbsp;<strong>upload buffer&nbsp;<\/strong>and the&nbsp;<strong>usage<\/strong>&nbsp;<strong>buffer&nbsp;<\/strong>from the descriptors, and send the data over to the GPU. One thing to note here is that you&nbsp;<strong>must&nbsp;<\/strong>keep the buffer variables created with the&nbsp;<em>CreateCommietedResource&nbsp;<\/em>alive for as long as the data is being transferred over to the GPU. If you remove the descriptor too early, the object might not render at all.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>DX::ThrowIfFailed(d3dDevice-&gt;CreateCommittedResource(\n\t&amp;uploadHeapProperties,\n\tD3D12_HEAP_FLAG_NONE,\n\t&amp;vertexBufferDesc,\n\tD3D12_RESOURCE_STATE_GENERIC_READ,\n\tnullptr,\n\tIID_PPV_ARGS(&amp;m_vertexBufferUpload)));<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3.4 Transformations<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The original sample was already performing some transformations, but it was only doing it for one singular object. It is a whole different story when you need to draw more than one. And let\u2019s be honest, you will most definitely want more than one object on the screen. Luckily, we already did some ground work with constant buffer initialization, so we only need to build upon that.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What exactly are&nbsp;<strong>Transformations<\/strong>, you ask? Well, in the simplest sense, a transformation is a way to alter an object so that it gets manipulated in space without modifying the underlying structure of the object itself. What does that mean exactly? Let me illustrate with an example.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Say we have a player avatar in our virtual world. You will most probably want it to be a non-stationary object. That means you want to have a way to move it around, rotate it to face the enemies etc. Transformations will help you with that.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Going even further, you have defined everything in your virtual world in 3D, right? You have your X, Y and Z axes, yes? But your monitor is not 3D. It\u2019s pretty much a glorified two-dimensional piece of paper that can quickly change its contents. You only work with X and Y when dealing with monitor space. So how do you translate your 3D character to 2D space? You have guessed it right \u2013 transformations got you covered here too.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Transformations are defined by a&nbsp;<strong>4\u00d74 matrix<\/strong>. If you remember your math, a matrix is a two-dimensional array of numbers. The interesting thing with them is that they can do most of the usual mathematical operations. Another interesting thing is that if you multiply a matrix by a vector, that vector gets transformed by said matrix. Since transformations (matrices) work on per vertex (vector) base this turns out to be a match made in heaven.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3.4.1 Transformation Pipeline<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s take a quick look at the&nbsp;<strong>transformation pipeline<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The untransformed vertices within the geometry of the object inside a game must go through the strict transformation pipeline so that they correctly map to their final counterparts that could then be viewed on the monitor. The whole pipeline looks like this:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"169\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf1fe370ca.png\" alt=\"\" class=\"wp-image-1581\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf1fe370ca.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf1fe370ca-300x85.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Transformation pipeline<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The untransformed vertices that are part of your object, start in the&nbsp;<strong>Model Space<\/strong>. This means their positions are defined only in regard to each other.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we take vertices that are in&nbsp;<strong>Model Space<\/strong>&nbsp;and apply&nbsp;<strong>World Transformations<\/strong>&nbsp;which changes their coordinates to&nbsp;<strong>World Space<\/strong>. This means that their positions are now defined in regard to vertices that are part of other objects within the world.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then these vertices are once again transformed by the&nbsp;<strong>View Transformation<\/strong>. This aligns the object within the world to the&nbsp;<strong>Virtual Camera<\/strong>&nbsp;and flattens them for the 2D space.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Lastly the&nbsp;<strong>Projection Transformation<\/strong>&nbsp;gives the perspective to the vertices, so that the objects that are further away taper nicely, thus giving the illusion of depth. Now the vertices are in their final coordinates \u2013 the&nbsp;<strong>Screen Space<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s quickly run through the most common transformations so we can make sense of all this.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">3.4.1.1 Translation<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To move an object to a specific position within the world we perform a&nbsp;<strong>Translation<\/strong>&nbsp;transformation. All you need to do to get the transformation matrix is call&nbsp;<em>XMMatrixTranslation<\/em>&nbsp;method and supply it with the end coordinates.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>auto translation = XMMatrixTranslation(position.x, position.y, position.z);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Translation is part of&nbsp;<strong>World Transformations.<\/strong><\/p>\n\n\n\n<h5 class=\"wp-block-heading\">3.4.1.2 Rotation<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To rotate an object around any or all the axes we perform a&nbsp;<strong>Rotation<\/strong>&nbsp;transformation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are quite a few choices here depending on your personal taste or the way the rotation data is stored in your application. The transformation matrix can be retrieved by calling:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>any of the&nbsp;<em>XMMatrixRotationX, XMMatrixRotationY or XMMatrixRotationZ<\/em>&nbsp;and supplying it with the angle in radians to rotate around a specific axis.<code>auto rotation = XMMatrixRotationY(3.14f);<\/code>&nbsp;<\/li>\n\n\n\n<li>use the Roll-Pitch-Yaw notation with the&nbsp;<em>XMMatrixRotationRollPitchYaw<\/em>&nbsp;method and providing the appropriate values<code>auto rpyRotation = XMMatrixRotationRollPitchYaw(0, 0, 3.14f);<\/code>&nbsp;<\/li>\n\n\n\n<li><em>XMMatrixRotationAxis<\/em>&nbsp;and supplying it with a vector which acts as an arbitrary axis around which the rotation will be performed by a provided amount.<code>auto axisRotation = XMMatrixRotationAxis(XMVECTOR(0, 1, 0), 3.14f);<\/code>&nbsp;<\/li>\n\n\n\n<li><em>XMMatrixRotationQuaternion<\/em>&nbsp;and providing a quaternion value which describes a rotation.<code>auto quaternion = XMQuaternionRotationAxis({ 0, 1, 0 }, 3.14f); auto quatRotation = XMMatrixRotationQuaternion(quaternion);<\/code>&nbsp;<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">All the above rotations will result in the same matrix that rotates an object around the Y axis by 180\u00b0.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Rotation is part of&nbsp;<strong>World Transformations.<\/strong><\/p>\n\n\n\n<h5 class=\"wp-block-heading\">3.4.1.3 Scale<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To change the size of the object without adjusting its structural vector positions one can use&nbsp;<strong>Scaling<\/strong>&nbsp;transformation. The object can be enlarged or shrunken and not necessarily uniformly \u2013 meaning you can, if you want, only scale it only in Y axis to make it tall. Or use any other combination for that matter. Scale matrix is retrieved by calling&nbsp;<em>XMMatrixScaling<\/em>&nbsp;and supplying it with scale ratios for each axis. The ratio of 1.0 indicates no change, 2.0 would be doubling in size and 0.5 \u2013 shrunkenin half.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>auto scale = XMMatrixScaling(2, 2, 2);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Scaling is part of&nbsp;<strong>World Transformations.<\/strong><\/p>\n\n\n\n<h5 class=\"wp-block-heading\">3.4.1.4 View<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Since the virtual camera is a free moving object, it can end up in any place in the 3D world, rotated or even upside-down. This means that to properly render the object, we must first align the direction of the coordinate system to be in line with the virtual camera. The\u00a0<strong>View Transformation\u00a0<\/strong>does exactly that \u2013 it adjusts the 3D coordinates of all the vertices so that it is now aligned. The coordinates at this point enter the\u00a0<strong>Camera Space<\/strong>\u00a0(or\u00a0<strong>View Space<\/strong>).<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"311\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf20f3a690.png\" alt=\"\" class=\"wp-image-1582\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf20f3a690.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf20f3a690-300x156.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>Aligning axes to camera: left \u2013 unaligned, right \u2013 camera-space aligned<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">To retrieve the view transformation matrix, we simply call\u00a0<em>XMMatrixLookAtLH<\/em>\u00a0method. Here LH stands for left-handed, so be careful not to confuse it with the very similar method ending with RH. The method should be supplied with\u00a0<strong>EyePosition<\/strong>\u00a0which is the location where the camera is,\u00a0<strong>FocusPosition<\/strong>\u00a0which is the point where the camera is looking at and the\u00a0<strong>cameraUp<\/strong>\u00a0which is the vector that describes which direction is considered \u201cup\u201d.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"248\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2303272c.png\" alt=\"\" class=\"wp-image-1583\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2303272c.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2303272c-300x124.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>XMMatrixLookAtLH parameter representation in relation to camera<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>auto view = XMMatrixLookAtLH(XMVECTOR{ 0, 3, -10 }, XMVECTOR{ 0, 0, 0 }, XMVECTOR{ 0, 1, 0 });<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this case we get a camera that is looking at the dead center of the world and is a bit away and elevated.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">3.4.1.5 Projection<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>Projection Transformation<\/strong>&nbsp;transforms the coordinates that are in View Space to their final coordinates in the&nbsp;<strong>Screen Space<\/strong>. By applying the projection transformation, we also obtain the illusion of depth with further objects starting to appear smaller in the final render. Or the lack of it, if using orthographic projection (via&nbsp;<em>XMMatrixOrthographicLH<\/em>&nbsp;method). This is mostly employed when doing 2D games that use sprites and don\u2019t need any depth.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We would retrieve the projection transformation matrix by calling&nbsp;<em>XMMatrixPerspectiveFovLH<\/em>&nbsp;method. It should be provided with the&nbsp;<strong>fieldOfView<\/strong>&nbsp;value (pretty much all that the famous&nbsp;<strong>FOV slider<\/strong>&nbsp;in mainstream games do is just adjust this value),&nbsp;<strong>aspectRatio<\/strong>&nbsp;which is the dimension ratio of the rendering surface,&nbsp;<strong>nearClippingPlane<\/strong>anda<strong>farClippingPlane<\/strong>&nbsp;which are the minimal and maximal distances at which the objects are still expected to be drawn.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">View-plane clipping is done for performance reasons \u2013 the infamous\u00a0<strong>Draw Distance<\/strong>\u00a0limits the drawing of object that are far away and also prevents an object that is practically clipping the camera from covering the whole screen.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"270\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf24216a9a.png\" alt=\"\" class=\"wp-image-1584\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf24216a9a.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf24216a9a-300x135.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>XMMatrixPerspectiveFovLH parameter representation in relation to camera<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>auto projection = XMMatrixPerspectiveFovLH(XM_PIDIV4, screenSize.Width \/ screenSize.Height, 1, 100);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This code line would get us a projection matrix with a standard FOV angle, a ratio that is the ratio of the screen (since the back buffer is most of the time&nbsp; the dimensions of the screen), and objects will only get drawn if they are further than distance of 1 and less than 100 away from the camera.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">3.4.1.6 Combining transformations<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">While reading through these last sections one question might have popped into your mind \u2013 what if I want to move the object AND give it a rotation too? Well the answer is pretty simple \u2013 multiplication. The only thing you need to do to combine one or more transformations expressed through matrices is to multiply them. The following line would result in a matrix that would transform vertices by rotating an object by its Y and X axis and would also move the object deeper into the screen:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>auto rotateAndMove = XMMatrixRotationY(-3.14f \/ 2) * XMMatrixRotationX(0.001f) * XMMatrixTranslation(0, 0, 20);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It is really simple except for one caveat \u2013 multiplication order. Unlike simple scalar values, the multiplication order with matrices do matter.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"300\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf25719396.png\" alt=\"\" class=\"wp-image-1585\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf25719396.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf25719396-300x150.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\"><em><strong>A result by rotating and then moving with transformations = matRotateY * matTranslate<\/strong><\/em><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"300\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf265c8286.png\" alt=\"\" class=\"wp-image-1586\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf265c8286.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf265c8286-300x150.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>A result by moving before rotating with transformations = matTranslate * matRotateY<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">This is nothing groundbreaking, but really helps to have it in mind to prevent unexpected behavior when applying transformations. The default multiplication order for transformations is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>auto transformations = matRotationX * matRotationY * matRotationZ * matScale * matTranslate * matView * matProjection;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">3.4.2 Camera<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Since there is quite a bit of functionality regarding virtual camera it would be handy to have all the related functionality encapsulated in a class. For this purpose, we have a&nbsp;<strong>Camera<\/strong>&nbsp;class in&nbsp;<em>VoiceMaze\\<\/em>CommonElements. The functionality from&nbsp;<strong>Sample3DSceneRenderer<\/strong>&nbsp;related to dealing with perspective and view transformations were moved to this new class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The class can be used to get view and projection matrices, scissor rectangle, and the camera view vector that will come in handy when dealing with effects in later chapters.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3.4.3 Transformation data<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Among other things the newly added&nbsp;<strong>RenderableObject<\/strong>&nbsp;base class has the responsibility of maintaining the information about its spatial positioning, scale and rotations. When rendering, this data is converted to the appropriate transformations which are then passed to an appropriate&nbsp;<strong>constant buffer<\/strong>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3.4.4 Constant buffers<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In its essence, the job of a&nbsp;<strong>Constant Buffer<\/strong>&nbsp;is to carry the information from the main application to the shader subroutine.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You must first declare and initialize a&nbsp;<strong>descriptor<\/strong>. For this purpose, we have a&nbsp;<strong>BufferDescriptor<\/strong>&nbsp;class. It creates a CBV in the descriptor heap, also considering the frame buffering amount to version the constant buffer data for shaders.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A popular approach is to separate the constant buffers into at least two categories. We will have a buffer that changes only once every frame \u2013 the camera-based data, lighting data, etc. We will call this one&nbsp;<strong>PerFrameConstantBuffer<\/strong>. And then we will have a buffer that changes many times per frame \u2013 it will be different for every object that is rendered: a single object has different transformations, maybe some additional lighting data, etc. This will be called&nbsp;<strong>PerObjectConstantBuffer<\/strong>. This is done for performance reasons, because by updating only the buffers that are actually changing you would be saving on memory bandwidth. Sometimes you might encounter static constant buffers. These are often run time defined constants for shader that rarely, if ever, change during the operation of the application (like, f.e. screen size).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The data structure resides in&nbsp;<em>BaseClasses\\ShaderStructures.h<\/em>. It looks something like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>struct PerObjectConstantBuffer\n{\n\tDirectX::XMFLOAT4X4 Transformations;\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There are two camps when passing transformation data to the shader: some people like to pass all transformations separately \u2013 world, view and projection and then perform the multiplication in the shader itself. I like to pass the transformations already premultiplied to save doing the same operation for every single vertex in the object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To update the descriptor itself, we will use&nbsp;<strong>BufferDescriptor<\/strong>\u2019s&nbsp;<em>UpdateBuffer<\/em>&nbsp;method and it will copy the data over. For the shader and in turn \u2013 GPU to access.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.5 Game Loop<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If you would look at the contents of the&nbsp;<em>App.cpp<\/em>&nbsp;file, you would come across its&nbsp;<em>Run<\/em>&nbsp;method. Within it we have a structure that is called a&nbsp;<strong>Game Loop<\/strong>. Inside we have a while loop that runs for as long as the application window is not closed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ This method is called after the window becomes active.\nvoid App::Run()\n{\n\twhile (!m_windowClosed)\n\t{\n\t\tif (m_windowVisible)\n\t\t{\n\t\t\tCoreWindow::GetForCurrentThread()-&gt;Dispatcher-&gt;ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);\n\n\t\t\tauto commandQueue = GetDeviceResources()-&gt;GetCommandQueue();\n\t\t\tPIXBeginEvent(commandQueue, 0, L\"Update\");\n\t\t\t{\n\t\t\t\tm_main-&gt;Update();\n\t\t\t}\n\t\t\tPIXEndEvent(commandQueue);\n\n\t\t\tPIXBeginEvent(commandQueue, 0, L\"Render\");\n\t\t\t{\n\t\t\t\tif (m_main-&gt;Render())\n\t\t\t\t{\n\t\t\t\t\tGetDeviceResources()-&gt;Present();\n\t\t\t\t}\n\t\t\t}\n\t\t\tPIXEndEvent(commandQueue);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCoreWindow::GetForCurrentThread()-&gt;Dispatcher-&gt;ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);\n\t\t}\n\t}\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">What it does is: it processes all the events that arrive to the window, like close, minimize events and so on. This part used to be known as the&nbsp;<strong>Message Pump<\/strong>. If the window is visible it performs two critical parts that form the basis for all games currently in existence:&nbsp;<em>Update<\/em>&nbsp;and&nbsp;<em>Render<\/em>&nbsp;methods. After that, the rendered data is presented on screen and the same process starts again: events, update, render. Rinse and repeat.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This happens up to 60 or even 120 times a second. In theory you could go even further provided your system is powerful enough and the rendered scenes are not overly complex. Going over 120 FPS is pointless though as the visual perception of a human eye is limited. Remember \u2013 even movies are only played in 24 FPS. More frames result in a smoother looking motion: 60 FPS seems to be the sweet spot, 120 often has a&nbsp;<em>panacea<\/em>&nbsp;effect and anything above that is pretty much just a wear on the hardware and a waste of electricity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Update<\/em>&nbsp;method updates the state of the game world. You can imagine it as the action phase \u2013 projectiles are moved, player avatar reacts to input, camera adapts to the best possible position, physics are applied, etc. Usually a small timeframe \u2013&nbsp;<strong>time delta<\/strong>&nbsp;is used which defines how much time passed since the last update and the objects can be manipulated according to that \u2013 just like with physics formulas (and those are actually often reused in the virtual world) in the real world.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Render<\/em>\u00a0method, on the other hand, is (or at the very least\u00a0<em>should be<\/em>) like a still photography \u2013 all the objects that were previously positioned, are now being exposed to the camera, their vertices transformed from 3D to 2D, shaders run, various effects are applied and, in this implementation, if it completes successfully, the resulting contents are presented to the player on the monitor.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"135\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf27660ec2.png\" alt=\"\" class=\"wp-image-1587\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf27660ec2.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf27660ec2-300x68.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>This is how the game loop performing classes are related in VoiceMaze structure<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In Voice Maze, we have a&nbsp;<strong>VoiceMazeDX12UWPMain<\/strong>&nbsp;class that has a&nbsp;<strong>StepTimer<\/strong>&nbsp;instance, so it can retrieve the time delta. It also has a reference to a scene renderer, namely,&nbsp;<strong>Renderer3DBase\u2019s<\/strong>&nbsp;concrete implementation \u2013&nbsp;<strong>VoiceMazeRenderer<\/strong>. When an&nbsp;<em>Update<\/em>&nbsp;is called on&nbsp;<strong>VoiceMazeDX12UWPMain<\/strong>&nbsp;from&nbsp;<em>App.cpp<\/em>game loop, it subsequently calls&nbsp;<em>Update<\/em>&nbsp;on the&nbsp;<strong>Renderer3DBase<\/strong>&nbsp;and provides a reference to the&nbsp;<strong>timer<\/strong>. Inside it performs a call to the concrete implementation\u2019s&nbsp;<em>InternalUpdateSteps<\/em>&nbsp;method which does the actual, application-specific update, also supplying it with the&nbsp;<strong>time delta<\/strong>&nbsp;value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Render wise, it goes similarly: when a&nbsp;<em>Render<\/em>&nbsp;is called on&nbsp;<strong>VoiceMazeDX12UWPMain<\/strong>&nbsp;from&nbsp;<em>App.cpp<\/em>, it calls&nbsp;<em>Render<\/em>&nbsp;on the&nbsp;<strong>Renderer3DBase<\/strong>. Within this method a lot of common basic rendering setup is performed and after that the&nbsp;<em>InternalRenderSteps<\/em>&nbsp;is called which performs application specific rendering commands.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.6 Content Manager<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For the sake of completion, I will do a short detour and say a few words about&nbsp;<strong>ContentManager<\/strong>&nbsp;class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The purpose of the content manager in our little framework is that we would have a central place through which we would be loading content \u2013 textures, meshes, sounds (not in this project) and so on. It helps to have a common way of loading those files so that you don\u2019t litter your codebase with loading calls in every place this functionality is needed. Also, in case you happen to use the same resource in multiple places, you could reuse the already loaded instance (that the content manager saves a reference to) and save on some processor cycles and memory. And, last but not least, once application decides to free the resources you will have one and only one place where you can do exactly that.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The content manager is initialized inside the&nbsp;<strong>GameBase<\/strong>&nbsp;class which is extended by&nbsp;<strong>VoiceMazeDX12UWPMain.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.7 Shaders<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Shaders<\/strong>. You probably have heard this word over and over whenever computer graphics related topic comes along. And there is a reason for that \u2013 shaders are a big thing. So, what exactly are they then?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A shader is a subroutine in your application that runs on the GPU and allows you to control the programmable GPU rendering pipeline. Simply said, they run every time you perform a render operation and they are the final frontier that do the final vertex transformations, rasterizations, polygon coloring ant post processing effects. The result that comes out is displayed on the screen afterwards.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The biggest thing about a shader is that their operations are run&nbsp;<strong>in parallel<\/strong>. This is where the greatest performance boost happens. Imagine if calculation for every pixel on your screen is calculated on its own dedicated CUDA core in the GPU (<em>not entirely true, but helps to paint the overall picture<\/em>), as opposed to doing one by one in a linear fashion.&nbsp;<em>Mythbusters<\/em>&nbsp;actually did a really nice job explaining this difference. Just google \u201cmythbusters cpu vs gpu\u201d.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Current day and age graphical pipeline is extremely configurable and programmable. In turn there are quite a few different shader stages, like Hull shader, Domain shader, Compute shader, etc. We will only bother ourselves with two main ones:&nbsp;<strong>Vertex Shader<\/strong>&nbsp;and&nbsp;<strong>Pixel Shader<\/strong>&nbsp;(in other circles known as the&nbsp;<strong>Fragment Shader<\/strong>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Vertex Shader<\/strong>&nbsp;runs on every vertex that you render. Here you would typically perform transformations, do lighting calculations and pass on coloring data to further stages. The shader code is in&nbsp;<em>Content\\SampleVertexShader.hlsl<\/em>&nbsp;file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Pixel Shader<\/strong>, as a rule of thumb, runs for every pixel that is going to be rendered. Though to be more specific, it runs for each pixel that is covered by a primitive. And there are many other factors that might interfere with this notion too \u2013 like multiple primitives with alpha transparency covering the same pixel, so, in turn running multiple times, etc. Considering this, I like the name of \u201cFragment Shader\u201d more, from the standpoint of the meaning of this stage, but for this article we will keep calling it a \u201cPixel Shader\u201d as DirectX refers to it with this name. Pixel shaders calculate the final color of the pixel, taking into account material colors, lighting, textures, etc. You can even go commando mode here and implement per-pixel lighting calculations and post-processing effects in a Pixel Shader. The shader code is in&nbsp;<em>Content\\SamplePixelShader.hlsl<\/em>&nbsp;file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The shaders themselves are written in&nbsp;<strong>HLSL<\/strong>&nbsp;(High-Level Shading language) or its similar cousin&nbsp;<strong>GLSL<\/strong>&nbsp;(OpenGL Shading Language). Nice thing is that both are very similar, and if you find a particular code on the internet you like, you can port one to the other quite easily.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When working with shaders in Visual Studio I would highly recommend downloading HLSL Tools for Visual Studio. It provides you with highlighting, syntax checking and makes the coding a much more enjoyable experience.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To shed light on the subject, let\u2019s run through a rendering sample and get our heads around what is actually happening in one Rendering pass. Please note, that the code is a bit different in the final version of the code as there will be quite a few new parts added to this and the code is refactored to make it more self-sufficient, but this is much clearer and straight to the point.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bool VoiceMazeRenderer::InternalRenderSteps()\n{\n\t\/\/ update camera\n\tXMFLOAT4X4 viewProjection;\n\tXMFLOAT4X4 orientation = m_deviceResources-&gt;GetOrientationTransform3D();\n\tauto viewProjectionMatrix = m_camera-&gt;CalculateViewMat() * m_camera-&gt;CalculateProjectionMat(orientation);\n\tXMStoreFloat4x4(&amp;viewProjection, viewProjectionMatrix);\n\n\t\/\/ Record drawing commands.\n\tD3D12_CPU_DESCRIPTOR_HANDLE renderTargetView = m_deviceResources-&gt;GetRenderTargetView();\n\tD3D12_CPU_DESCRIPTOR_HANDLE depthStencilView = m_deviceResources-&gt;GetDepthStencilView();\n\tm_commandList-&gt;ClearRenderTargetView(renderTargetView, DirectX::Colors::CornflowerBlue, 0, nullptr);\n\tm_commandList-&gt;ClearDepthStencilView(depthStencilView, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);\n\n\tm_commandList-&gt;OMSetRenderTargets(1, &amp;renderTargetView, false, &amp;depthStencilView);\n\n\t{\n\t\tauto frameIndex = m_deviceResources-&gt;GetCurrentFrameIndex();\n\n\t\tm_mazeElement-&gt;Render(m_commandList, frameIndex, viewProjection);\n\t\tm_mazeElement2-&gt;Render(m_commandList, frameIndex, viewProjection);\n\t\tm_mazeElement3-&gt;Render(m_commandList, frameIndex, viewProjection);\n\t}\n\n\n\treturn true;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first few lines in the&nbsp;<strong>VoiceMazeRenderer<\/strong>&nbsp;implementation should be familiar to you from the Camera section. It just takes the various transformations and combines them into&nbsp;<strong>view * projection<\/strong>&nbsp;matrix.&nbsp;<em>XMStoreFloat<\/em>&nbsp;just copies the matrix into a&nbsp;<strong>FLOAT4X4<\/strong>&nbsp;structure which is a lot easier to pass around. After that we get handles to two important entities for the drawing \u2013 the&nbsp;<strong>renderTargetView<\/strong>&nbsp;\u2013 which is our drawing surface and the&nbsp;<strong>depthStencilView<\/strong>&nbsp;which is our depth buffer. Next, we wipe away any data that is currently on the draw surface with the&nbsp;<em>ClearRenderTargetView<\/em>&nbsp;command and also while we are at it we give it a familiar uniform blue color. We also perform a similar operation on the depth stencil. Then we indicate that these two buffers will be used in the drawing operations with the&nbsp;<em>OMSetRenderTargets<\/em>&nbsp;command.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now we come to the drawing of individual objects. This happens in the&nbsp;<em>Render<\/em>&nbsp;method of the&nbsp;<strong>RenderableObject<\/strong>&nbsp;class<strong>:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void RenderableObject::Render(const Microsoft::WRL::ComPtr &amp;commandList, UINT8 frameIndex, XMFLOAT4X4 transformations)\n{\n\t\/\/ Update constant buffers\n\tID3D12DescriptorHeap* ppHeaps&#91;] = { m_cbvHeap.Get() };\n\tcommandList-&gt;SetDescriptorHeaps(_countof(ppHeaps), ppHeaps);\n\n\t\/\/ Bind the current frame's constant buffer to the pipeline.\n\tCD3DX12_GPU_DESCRIPTOR_HANDLE gpuHandle(m_cbvHeap-&gt;GetGPUDescriptorHandleForHeapStart(), frameIndex, m_cbvDescriptorSize);\n\tcommandList-&gt;SetGraphicsRootDescriptorTable(0, gpuHandle);\n\n\tauto worldTransform = GetTransformations();\n\tauto transformationsMatrix = worldTransform * XMLoadFloat4x4(&amp;transformations);\n\n\tXMStoreFloat4x4(&amp;m_constantBufferData.transformations, XMMatrixTranspose(transformationsMatrix));\n\t\/\/ Update the constant buffer resource.\n\tUINT8* destination = m_mappedConstantBuffer + (frameIndex * c_alignedConstantBufferSize);\n\tmemcpy(destination, &amp;m_constantBufferData, sizeof(m_constantBufferData));\n\n\tcommandList-&gt;IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\tcommandList-&gt;IASetVertexBuffers(0, 1, &amp;m_vertexBufferView);\n\tcommandList-&gt;IASetIndexBuffer(&amp;m_indexBufferView);\n\tcommandList-&gt;DrawIndexedInstanced(m_indexCount, 1, 0, 0, 0);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We start by getting the address of the constant buffer of this particular renderable object and indicating that this constant buffer will be used for the following operations. After we finish up with this initialization we move onto the fun part that is getting the transformations of this object and copying those over onto the constant buffer struct. Since constant buffers must be stored at 256 byte offsets from the resource heap beginning before the final&nbsp;<em>memcpy<\/em>, we align the addresses to do exactly that.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The last few operations are actual drawing of the primitives. We indicate the most common topology that our current render object uses \u2013 a Triangle list. Then we indicate the GPU which vertex buffer and index buffer will be used for this operation with&nbsp;<em>IASetVertexBuffers<\/em>&nbsp;and&nbsp;<em>IASetIndexBuffer<\/em>&nbsp;commands respectively. Lastly, we ask the GPU to draw the primitive by using the data we just configured by calling the&nbsp;<em>DrawIndexedInstanced<\/em>&nbsp;method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, once this next line of code in&nbsp;<strong>Renderer3DBase<\/strong>&nbsp;is executed, all the provided data will be picked up and processed by the shader code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>m_deviceResources-&gt;GetCommandQueue()-&gt;ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Template default Vertex Shader code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ A constant buffer that stores the three basic column-major matrices for composing geometry combined in one.\ncbuffer ModelViewProjectionConstantBuffer : register(b0)\n{\n\tmatrix transformations;\n};\n\n\/\/ Per-vertex data used as input to the vertex shader.\nstruct VertexShaderInput\n{\n\tfloat4 pos : POSITION;\n\tfloat4 color : COLOR0;\n};\n\n\/\/ Per-pixel color data passed through the pixel shader.\nstruct VertexShaderOutput\n{\n\tfloat4 pos : SV_POSITION;\n\tfloat4 color : COLOR0;\n};\n\n\/\/ Simple shader to do vertex processing on the GPU.\nVertexShaderOutput main(VertexShaderInput input)\n{\n\tVertexShaderOutput output;\n\n\toutput.pos = mul(input.pos, transformations);\n\toutput.color = input.color;\n\n\treturn output;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So, the&nbsp;<strong>Vertex<\/strong>&nbsp;shader will be picking up the vertex data and running the main&nbsp;<em>method<\/em>&nbsp;once for every one of them.&nbsp; The constant buffer data arrives into the&nbsp;<strong>transformations<\/strong>&nbsp;variable and position &amp; color value of each of the vertices will be in the&nbsp;<strong>input<\/strong>&nbsp;variable that is of the conveniently placed&nbsp;<strong>VerexShaderInput<\/strong>type. In the main method we just want to fill in the&nbsp;<strong>output<\/strong>&nbsp;variable&nbsp;<strong>which will be the input<\/strong>&nbsp;for the Pixel shader. We do this by transforming the vertex positions through all the hoops of the transformations straight to the screen space. The color value just gets passed through.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Template default Pixel Shader code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Per-pixel color data passed through the pixel shader.\nstruct PixelShaderInput\n{\n\tfloat4 pos : SV_POSITION;\n\tfloat3 color : COLOR0;\n};\n\n\/\/ A pass-through function for the (interpolated) color data.\nfloat4 main(PixelShaderInput input) : SV_TARGET\n{\n\treturn float4(input.color, 1.0f);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The job of the&nbsp;<strong>Pixel<\/strong>&nbsp;shader is just to output the final pixel color \u2013 so we get the information that was sent in by the&nbsp;<strong>Vertex<\/strong>&nbsp;shader and just return that. The intermediate values between two vertices are all interpolated by the GPU for us.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The easiest way to get to know the shaders is to try and construct a few of them. To learn more about shaders I strongly suggest taking some shader centered tutorial and trying it out at the&nbsp;<a href=\"https:\/\/www.shadertoy.com\/\">shadertoy.com<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, after all this we get this onto the screen:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"468\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf29918d46.png\" alt=\"\" class=\"wp-image-1588\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf29918d46.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf29918d46-300x234.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>These are all 1x1x1 cubes that have had their shape, position and rotation<br>changed by the transformations<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">4. ADDITIONAL ESSENTIAL 3D ELEMENTS<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">4.1 Texturing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First off, we will be adding textures. Textures add more life to rendered scene as you can only go so far with just color-coded vertices as was in the template.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Texture<\/strong>&nbsp;is an image that is applied to the surface of a shape. Every vertex in a ploygon is assigned a texture coordinate (which is also known as a&nbsp;<strong>UV coordinate<\/strong>). So, to build one side of a box you would have 4 vertices that contain UV coordinates of the assigned texture. You\u2019d arrange those vertices in a certain order to produce two triangles that make the final face of a box.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">UV coordinates are a bit special. Since the image that is loaded in memory is in screen coordinates (i.e. point [0,0] is top-left), UV coordinates start in the top left and range from 0 to 1 (floating point values). Please see the image below for illustration. OpenGL, as per usual, has the V coordinate axis inverted.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"250\" height=\"250\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2a8f1c31.png\" alt=\"\" class=\"wp-image-1589\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2a8f1c31.png 250w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2a8f1c31-150x150.png 150w\" sizes=\"auto, (max-width: 250px) 100vw, 250px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>UV coordinates<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Now to load the textures into the memory, apply and render them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The image loading itself is done via&nbsp;<strong>ContentManager<\/strong>. By calling its&nbsp;<em>Load<\/em>&nbsp;method and supplying it with the relative path to the image, we receive a&nbsp;<strong>Texture<\/strong>object, which encapsulates the creation of the descriptor heap and which we pass to the objects that need it. The image loading and conversion happens inside the&nbsp;<strong>ImageLoader<\/strong>&nbsp;class. You can find the URL to the page describing the loading procedure in detail in the Links section.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To accommodate these changes, we will make changes to the vertex structure, constant buffer and the shaders. First off \u2013 a new vertex structure:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static D3D12_INPUT_ELEMENT_DESC layout&#91;] =\n{\n\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The Color component was removed in place of a texture coordinate \u2013 a 2D vector. Now each vertex will carry with it the UV coordinates that will map that corner to a position within the texture. A complication that is brought about by it is that we will not be able to make do with only 8 vertices. Once we move to texturing a cube, each vertex might need to describe 3 different UV coordinates for each of the faces while the position is shared. It was fine for a color cube, as we only defined a color and it was then gradually changed to another. If you try and use the same approach for the textures, you might find that some of the faces get garbled, since we are using a full texture that stretches full UV values over one face. This increase in number of vertices means that we will now have duplicate data (actually, 3 times as much, as every shared corner will now have a set of 3 vertices). The good news is that we would need to do this for the lighting chapter anyway. So, now the definition of the cube would look something like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Cube vertices. Each vertex has a position and a texture coordinate.\nstd::vector cubeVertices =\n{\n\t\/\/top\n\t{ XMFLOAT3(-0.5f,\t0.5f,\t-0.5f),\t\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(-0.5f,\t0.5f,\t 0.5f),\t\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3( 0.5f ,\t0.5f,\t 0.5f),\t\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3( 0.5f ,\t0.5f,\t-0.5f),\t\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/left\n\t{ XMFLOAT3(-0.5f,\t-0.5f,\t 0.5f),\t\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(-0.5f,\t 0.5f,\t 0.5f),\t\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,\t 0.5f,\t-0.5f),\t\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,\t-0.5f,\t-0.5f),\t\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/back\n\t{ XMFLOAT3( 0.5f,\t-0.5f,\t 0.5f),\t\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3( 0.5f,\t 0.5f,\t 0.5f),\t\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,\t 0.5f,\t 0.5f),\t\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,\t-0.5f,\t 0.5f),\t\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/right\n\t{ XMFLOAT3( 0.5f,\t-0.5f,\t-0.5f),\t\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3( 0.5f,\t 0.5f,\t-0.5f),\t\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3( 0.5f,\t 0.5f,\t 0.5f),\t\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3( 0.5f,\t-0.5f,\t 0.5f),\t\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/front\n\t{ XMFLOAT3(-0.5f,\t-0.5f,\t-0.5f),\t\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(-0.5f,\t 0.5f,\t-0.5f),\t\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3( 0.5f,\t 0.5f,\t-0.5f),\t\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3( 0.5f,\t-0.5f,\t-0.5f),\t\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/bottom\n\t{ XMFLOAT3( 0.5f,\t-0.5f,\t-0.5f),\t\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3( 0.5f,\t-0.5f,\t 0.5f),\t\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,\t-0.5f,\t 0.5f),\t\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,\t-0.5f,\t-0.5f),\t\tXMFLOAT2(0.0f, 1.0f) },\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Where the first parameter indicates the vertex position and second \u2013 the UV coordinates. As you can see we have 24 value sets instead of previous 8.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now we will need to indicate which texture to use via constant buffer. A&nbsp;<strong>RenderableObject<\/strong>&nbsp;now has a member that stores the texture \u2013&nbsp;<strong>m_texture<\/strong>. If you remember we created 3 slots in the initialization, so now we will set the root parameter with the index 2 to point to this texture so that it could be used by the pixel shader.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n\t\/\/ Update texture\n\tID3D12DescriptorHeap* ppHeaps2&#91;] = { m_texture-&gt;GetTextureDescriptor() };\n\tcommandList-&gt;SetDescriptorHeaps(_countof(ppHeaps2), ppHeaps2);\n\n\tcommandList-&gt;SetGraphicsRootDescriptorTable(2, m_texture-&gt;GetTextureDescriptor()-&gt;GetGPUDescriptorHandleForHeapStart());\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The shaders get a facelift too.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ A constant buffer that stores the three basic column-major matrices for composing geometry pre-multiplied.\ncbuffer PerObjectConstantBuffer : register(b0)\n{\n\tmatrix transformations;\n};\n\ncbuffer PerFrameConstantBuffer : register(b1)\n{\n};\n\n\/\/ Per-vertex data used as input to the vertex shader.\nstruct VertexShaderInput\n{\n    float4 pos : POSITION;\n    float2 texCoord : TEXCOORD;\n};\n\n\/\/ Per-pixel color data passed through to the pixel shader.\nstruct VertexShaderOutput\n{\n\tfloat4 pos : SV_POSITION;\n    float2 texCoord : TEXCOORD;\n};\n\n\/\/ Simple shader to do vertex processing on the GPU.\nVertexShaderOutput main(VertexShaderInput input)\n{\n    VertexShaderOutput output;\n\n    output.pos = mul(input.pos, transformations);\n    output.texCoord = input.texCoord;\n\n    return output;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, the vertex shader now has a new&nbsp;<strong>texCoord<\/strong>&nbsp;input parameter, which mimics the new incoming texture coordinate data. This information is just passed through to the Pixel Shader (and it will be interpolated by the GPU for the points in the middle, to get the in-between texture values for each fragment).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Per-pixel color data passed through the pixel shader.\nTexture2D tex : register(t0);\nSamplerState samplerState : register(s0);\n\nstruct PixelShaderInput\n{\n\tfloat4 pos : SV_POSITION;\n    float2 texCoord : TEXCOORD;\n};\n\n\/\/ Pixel shader processing.\nfloat4 main(PixelShaderInput input) : SV_TARGET\n{\n    return tex.Sample(samplerState, input.texCoord);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The Pixel Shader accepts the\u00a0<strong>texCoord<\/strong>\u00a0parameter and feeds it to the texture sampler \u2013 the way the shaders access textures \u2013 which in turn spews out a color to be used.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"465\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2c27bf65.png\" alt=\"\" class=\"wp-image-1590\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2c27bf65.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2c27bf65-300x233.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>When we run the modified code, we get the textured cube on the right<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">4.2 Basic Lighting<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Next is the lighting. When we talk about lighting in 3D graphics, we talk about\u00a0<strong>normals<\/strong>. A\u00a0<strong>normal<\/strong>\u00a0is a vector that is perpendicular to the face that the light falls onto. As the surface tilts farther away from the angle of the light, the normal vector becomes more exposed to the light, or in mathematical terms \u2013 the light direction vector has a bigger projection onto the surface normal. Direct3D compares the angle of the normal to the angle of the light to determine how brightly lit the surface should be. The surface is brighter the closer these two angles are to each other.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"300\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2d231327.png\" alt=\"\" class=\"wp-image-1591\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2d231327.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2d231327-300x150.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>The amount of light that hits the surface is calculated with the aid of surface normals<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">This physical phenomenon can easily be replicated at home \u2013 just take a piece of white paper and fold it in half. If you fully unfold it, it will be all the same color. Now if you fold it halfway, so that it makes an \u2018L\u2019 shape, observe the two points that are really close to the crease \u2013 one on the bottom part and one facing upwards: even though they are the same material that is the same color, they appear to be different because of the lighting angle. We want the same behavior in our rendering process.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Lighting rendering is often composed of three separate lighting stages:&nbsp;<strong>Ambient<\/strong>,&nbsp;<strong>Diffuse<\/strong>&nbsp;and&nbsp;<strong>Specular<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Ambient light<\/strong>&nbsp;is the light that could be associated with the scattered daylight. As the light shines onto a surface it is reflected to the other surfaces, that is reflected again to other surfaces and so on. The ambient lighting allows us to simulate this indirect lighting without doing absurd levels of reflecting light calculations. This way even the dark parts of the scene can be made somewhat visible.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Diffuse light<\/strong>&nbsp;is the directional light that illuminates the surface. The full normal calculations are performed for this step, so the object reacts naturally to the light as it is being rotated and moved around.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Specular light<\/strong>&nbsp;is the highlights on the surface which are the result of a glossy surface reflecting the light directly into the viewers eye. They are usually small, high intensity patches of very bright color that appear on the surface of the object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To prepare for all this, we update the input structure once more.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static const D3D12_INPUT_ELEMENT_DESC inputLayout&#91;] =\n{\n\t{ \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t{ \"NORMAL\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },\n\t{ \"TEXCOORD\", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In addition to the two parameters you are already familiar with, we add an additional one \u2013 a 3D vector that represents the surface normal. Since we already bumped up the vertex count in the texturing chapter, we will only be adding one more parameter in the initialization of each vertex.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One more note on the tripling of the vertex data for the lighting. Even though there was a possibility to manage the texturing with only 8 vertices by carefully planning the texture input image layout and the UV textures, there is no way we could pull off the same magic here. As all the faces on all the corners are perpendicular to each other \u2013 their normals are also perpendicular to each other. So, we will need 3 separate component vertices to get the desired results.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Cube vertices. Each vertex has a position, a normal and a texcoord.\nstd::vector cubeVertices =\n{\n\t\/\/top\n\t{ XMFLOAT3(-0.5f, 0.5f, -0.5f),\t\tXMFLOAT3(0, 1, 0),\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(-0.5f, 0.5f,  0.5f),\t\tXMFLOAT3(0, 1, 0),\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f, 0.5f,  0.5f),\t\tXMFLOAT3(0, 1, 0),\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f, 0.5f, -0.5f),\t\tXMFLOAT3(0, 1, 0),\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/left\n\t{ XMFLOAT3(-0.5f, -0.5f,  0.5f),\tXMFLOAT3(-1, 0, 0),\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(-0.5f,  0.5f,  0.5f),\tXMFLOAT3(-1, 0, 0),\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,  0.5f, -0.5f),\tXMFLOAT3(-1, 0, 0),\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f, -0.5f, -0.5f),\tXMFLOAT3(-1, 0, 0),\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/back\n\t{ XMFLOAT3(0.5f, -0.5f, 0.5f),\t\tXMFLOAT3(0, 0, 1),\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(0.5f,  0.5f, 0.5f),\t\tXMFLOAT3(0, 0, 1),\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f, 0.5f, 0.5f),\t\tXMFLOAT3(0, 0, 1),\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f,-0.5f, 0.5f),\t\tXMFLOAT3(0, 0, 1),\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/right\n\t{ XMFLOAT3(0.5f, -0.5f, -0.5f),\t\tXMFLOAT3(1, 0, 0),\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(0.5f,  0.5f, -0.5f),\t\tXMFLOAT3(1, 0, 0),\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f,  0.5f,  0.5f),\t\tXMFLOAT3(1, 0, 0),\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f, -0.5f,  0.5f),\t\tXMFLOAT3(1, 0, 0),\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/front\n\t{ XMFLOAT3(-0.5f, -0.5f, -0.5f),\tXMFLOAT3(0, 0, -1),\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(-0.5f,  0.5f, -0.5f),\tXMFLOAT3(0, 0, -1),\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f,   0.5f, -0.5f),\tXMFLOAT3(0, 0, -1),\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(0.5f,  -0.5f, -0.5f),\tXMFLOAT3(0, 0, -1),\tXMFLOAT2(0.0f, 1.0f) },\n\n\t\/\/bottom\n\t{ XMFLOAT3(0.5f,  -0.5f, -0.5f),\tXMFLOAT3(0, -1, 0),\tXMFLOAT2(1.0f, 1.0f) },\n\t{ XMFLOAT3(0.5f,  -0.5f,  0.5f),\tXMFLOAT3(0, -1, 0),\tXMFLOAT2(1.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f, -0.5f,  0.5f),\tXMFLOAT3(0, -1, 0),\tXMFLOAT2(0.0f, 0.0f) },\n\t{ XMFLOAT3(-0.5f, -0.5f, -0.5f),\tXMFLOAT3(0, -1, 0),\tXMFLOAT2(0.0f, 1.0f) },\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We will also need to send in some additional data via constant buffers. Per-object buffers will have two additional parameters:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>WorldInverseTranspose<\/strong>&nbsp;which will store the inverse of the world matrix. We need it so that we would be able to transform normals for the lighting calculations. The actual data is retrieved by calling&nbsp;<em>XMMatrixInverse<\/em>&nbsp;with the world transformations matrix.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>PremultipliedViewVector<\/strong>&nbsp;which is the vector that indicates the direction the camera or the \u2018eye\u2019 is looking in. Since specular lighting highlights depends on where the viewer is, this data will come in handy. We pre-multiply it by the world matrix so that it saves a few cycles in the shader code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>auto viewVector = XMLoadFloat4(&amp;camera-&gt;GetViewVector());\nauto premultipliedViewVector = XMVector4Normalize(XMVector4Transform(XMVector4Normalize(viewVector), XMMatrixTranspose(worldTransform)));\n\nauto perObjectData = PerObjectConstantBuffer();\nXMStoreFloat4x4(&amp;perObjectData.Transformations, XMMatrixTranspose(transformationsMatrix));\nXMStoreFloat4x4(&amp;perObjectData.WorldInverseTranspose, XMMatrixInverse(nullptr, worldTransform));\nXMStoreFloat4(&amp;perObjectData.PremultipliedViewVector, premultipliedViewVector);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The per-frame constant buffer will get a ton of new variables, though to be fair, it didn\u2019t have any to begin with.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>DiffuseLightDirection<\/strong>&nbsp;\u2013 the vector indicating the direction the light will be shining in;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>DiffuseLightColor<\/strong>&nbsp;\u2013 the color that the diffuse light will tint the objects in;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>AmbientLightColor<\/strong>&nbsp;\u2013 same as above, just with ambient lighting;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>SpecularLightColor<\/strong>&nbsp;\u2013 the color of specular highlights. This is often set to a near-white color, as this is supposed to be the light that is reflected to your eyes from a shiny surface;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>DiffuseLightIntensity<\/strong>&nbsp;\u2013 the factor of the diffuse color brightness;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>AmbientLightIntensity<\/strong>&nbsp;\u2013 the factor for the brightness of ambient light;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>SpecularLightIntensity<\/strong>&nbsp;\u2013 indicates how much light will be reflected by the surface;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Shininess<\/strong>&nbsp;\u2013 indicates how shiny the surface is. The lower values will produce broad highlights and the higher it goes the sharper and pin-pointed the highlights become.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Most of the parameters are pre-set and do not change while the game is running (although they very well could).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>struct PerFrameConstantBuffer\n{\n\tDirectX::XMFLOAT4 DiffuseLightDirection;\n\tDirectX::XMFLOAT4 DiffuseLightColor;\n\n\tDirectX::XMFLOAT4 AmbientLightColor = DirectX::XMFLOAT4(1, 1, 1, 1);\n\tDirectX::XMFLOAT4 SpecularLightColor = DirectX::XMFLOAT4(1, 1, 1, 1);\n\n\tfloat DiffuseLightIntensity = 1.0;\n\tfloat AmbientLightIntensity = 0.1;\n\tfloat Shininess = 200;\n\tfloat SpecularLightIntensity = 1.0;\n};<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The rest of the data, related to the diffuse light comes from the&nbsp;<strong>LightSource<\/strong>&nbsp;object and is set by&nbsp;<strong>VoiceMazeRenderer<\/strong>&nbsp;in every render operation<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>PerFrameConstantBuffer perFrameData = PerFrameConstantBuffer();\nperFrameData.DiffuseLightColor = m_lightSource.GetColor();\nperFrameData.DiffuseLightDirection = m_lightSource.GetDirection();\n\nm_perFrameCB.UpdateBuffer(perFrameData, frameIndex, 1, m_commandList);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The only part that\u2019s left is to update the shaders to include the lighting computation logic.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ A constant buffer that stores the three basic column-major matrices for composing geometry pre-multiplied\ncbuffer PerObjectConstantBuffer : register(b0)\n{\n\tmatrix Transformations;\n    matrix WorldInverseTranspose;\n    float4 PremultipliedViewVector;\n};\n\ncbuffer PerFrameConstantBuffer : register(b1)\n{\n    float4 DiffuseLightDirection;\n\n    float4 DiffuseLightColor;\n    float4 AmbientLightColor;\n    float4 SpecularLightColor;\n\n    float DiffuseLightIntensity;\n    float AmbientLightIntensity;\n    float Shininess;\n    float SpecularLightIntensity;\n};\n\n\/\/ Per-vertex data used as input to the vertex shader.\nstruct VertexShaderInput\n{\n    float4 Position : POSITION;\n    float4 Normal: NORMAL;\n    float2 TexCoord : TEXCOORD;\n};\n\n\/\/ Per-pixel data that is passed through to the pixel shader.\nstruct VertexShaderOutput\n{\n    float4 Position : SV_POSITION;\n    float4 Normal : NORMAL;\n    float4 Color : COLOR;\n    float4 PremultipliedViewVector : NORMAL1;\n    float2 TexCoord : TEXCOORD;\n};\n\n\/\/ Vertex processing and preliminary vertex dependent lighting calculations.\nVertexShaderOutput main(VertexShaderInput input)\n{\n    VertexShaderOutput output;\n\n    output.Position = mul(input.Position, Transformations);\n\n    float4 normal = normalize(mul(input.Normal, WorldInverseTranspose));\n    float lightIntensity = dot(normal, DiffuseLightDirection);\n    output.Color = saturate(DiffuseLightColor * DiffuseLightIntensity * lightIntensity);\n\n    output.Normal = normal;\n    output.TexCoord = input.TexCoord;\n    output.PremultipliedViewVector = PremultipliedViewVector;\n\n    return output;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The code is pretty similar to the one in the texturing chapter with some additional calculations involving normal and light directions. We first transform the normal of the vertex with the&nbsp;<strong>worldInverseTranspose<\/strong>&nbsp;matrix. Then we get a dot product which in essence is the projection of the light onto the normal. This will get us the amount of light that reaches the surface. Finally, we output the color for this vertex to the other shading stage by including the calculated amount ratio and the predefined intensity values. The&nbsp;<em>saturate<\/em>&nbsp;method just clamps the resulting value to the range of 0 to 1.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Data passed through to the pixel shader.\nTexture2D Texture : register(t0);\nSamplerState Sampler : register(s0);\n\ncbuffer PerFrameConstantBuffer : register(b1)\n{\n    float4 DiffuseLightDirection;\n\n    float4 DiffuseLightColor;\n    float4 AmbientLightColor;\n    float4 SpecularLightColor;\n\n    float DiffuseLightIntensity;\n    float AmbientLightIntensity;\n    float Shininess;\n    float SpecularLightIntensity;\n};\n\nstruct PixelShaderInput\n{\n    float4 Position : SV_POSITION;\n    float4 Normal : NORMAL;\n    float4 Color : COLOR;\n    float4 PremultipliedViewVector: NORMAL1;\n    float2 TexCoord : TEXCOORD;\n};\n\n\/\/ Main lighting and texturing calculations outputting the final color of the fragment.\nfloat4 main(PixelShaderInput input) : SV_TARGET\n{\n    float4 light = normalize(DiffuseLightDirection);\n    float4 normal = normalize(input.Normal);\n    float4 r = normalize(2 * dot(light, normal) * normal - light);\n    float dotProduct = dot(r, input.PremultipliedViewVector);\n\n    float4 specular = SpecularLightIntensity * SpecularLightColor * max(pow(dotProduct, Shininess), 0) * length(input.Color);\n\n    float4 textureColor = Texture.Sample(Sampler, input.TexCoord);\n\n    return saturate(textureColor * (input.Color + AmbientLightColor * AmbientLightIntensity) + specular);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In pixel shader we employ some heavy math that takes into account all the beforementioned lighting types. The most involved being the specular color which calculates a reflection vector from light direction and the surface normal. This is used in the final specular amount calculation which is also dimmed down by the input color, so that the lower light areas also have a dimmed highlight. At the end we just output the texture color that is brightened or dimmed depending on light angle, ambient light intensity, and in the case of a direct reflection \u2013 overridden by the specular highlight.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"400\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2eff128a.png\" alt=\"\" class=\"wp-image-1592\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2eff128a.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2eff128a-300x200.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>When we run the modified code, we get the properly lit cube on the right<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">4.3 Mesh Loading<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">As you have already seen, coding in every single vertex, their normal data and texture coordinates can get a bit tedious. Now imagine you want to construct something like a car model or a human avatar. Unless you are Minecraft, simple rectangular boxes just will not cut. The models might have hundreds if not tens of thousands of vertices. Populating this much data by hand would take too much time and would just be unreasonable. And top that off, the game artists are usually lazy enough to not know any coding at all.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To create a model, you would employ an external 3D modelling application: 3D Studio Max, Maya or something like Blender if you need open source. They help you mold a model in 3D rapidly. After you have completed this process you would then export it to a file that could later be loaded into your application as a&nbsp;<strong>Mesh<\/strong>. A&nbsp;<strong>Mesh<\/strong>&nbsp;is essentially any imported model with all the connected data \u2013 vertices, indices, normals, texture coordinates, materials, etc.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When exporting there is quite a selection when it comes to file formats. In our case we will be using one of the simpler ones \u2013&nbsp;<strong>.OBJ&nbsp;<\/strong>files. This one is very easy to parse and is supported by most 3D modelling applications. It has the ability to store vertex positions, normals, indexes and texture coordinates \u2013 all that we need. You can read more about .obj file format here:&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Wavefront_.obj_file\">https:\/\/en.wikipedia.org\/wiki\/Wavefront_.obj_file<\/a>&nbsp;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The loading will be done through our&nbsp;<strong>ContentManager<\/strong>. We would just pass the&nbsp;<strong>filePath<\/strong>&nbsp;to its&nbsp;<em>Load<\/em>&nbsp;method and we would get the&nbsp;<strong>MeshObject<\/strong>&nbsp;in return. The heavy-lifting of the loading is done by the&nbsp;<strong>MeshLoader<\/strong>&nbsp;class. In short, it parses the file and creates vertex and index buffers, populates them with data. This data is then used to create the&nbsp;<strong>MeshObject<\/strong>&nbsp;which is then rendered the same way as if we have hard-coded it vertex-by-vertex.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The only object in Voice Maze what uses mesh loading is the player avatar.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"468\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2fc02de3.png\" alt=\"\" class=\"wp-image-1593\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2fc02de3.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf2fc02de3-300x234.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>We will be using this crown model as a player avatar.<br>It was created and exported from 3D Studio Max<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">5. VOICE MAZE<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this section we will go through parts that I would consider part of a concrete application implementation \u2013 in this case \u2013 the idea behind the Voice Maze.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5.1 Maze construction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First step is the maze itself. The easiest way to achieve the construction is to have a 2D array of integers that represents the composition of the maze. Certain numeric values represent certain maze elements:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">[0] is an empty space<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">[1] is a wall<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">[-1] is the starting field<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">[-2] is the finish field<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The construction of the maze is the responsibility of the&nbsp;<strong>Maze<\/strong>&nbsp;class. In its&nbsp;<em>Initialize<\/em>&nbsp;method we have the array representation of the maze and we populate the&nbsp;<strong>MazeElements<\/strong>&nbsp;array based on that data. Every single maze element is a specifically textured cube. The walls are raised by half the size of the cube so to give the illusion that the path of the maze is enclosed by the walls. We also have a failsafe inside the&nbsp;<em>Initialize<\/em>&nbsp;that checks if the provided data forms a closed maze \u2013 i.e. the maze cannot be walked out ant into nothingness by reaching certain outer elements. If this turns out to be the case, additional surrounding wall border is added.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void Maze::Initialize(ID3D12Device *d3dDevice, const Microsoft::WRL::ComPtr &amp;commandList, ContentManager *contentManager)\n{\n\t\/\/maze array representation\n\tconst int KMazeData&#91;] =\n\t{\n\t\t0,0,0,0,0,-1,\n\t\t0,1,1,0,1,1,\n\t\t1,0,1,0,0,0,\n\t\t0,0,0,1,1,0,\n\t\t0,1,0,0,1,0,\n\t\t-2,1,0,0,0,0\n\t};\n\tint numCols = 6;\n\tint numRows = 6;\n\n\t\/\/create the maze\n\tbool enclosed = CheckIfEnclosed(KMazeData, numRows, numCols);\n\tif (!enclosed)\n\t{\n\t\tm_mazeElementTypes.resize(numRows + 2);\n\t\tfor (int i = 0; i &lt; numRows + 2; i++)\n\t\t\tm_mazeElementTypes&#91;i].resize(numCols + 2);\n\n\t\tfor (unsigned int i = 0; i &lt; m_mazeElementTypes.size(); i++)\n\t\t\tfor (unsigned int j = 0; j &lt; m_mazeElementTypes&#91;i].size(); j++)\n\t\t\t{\n\t\t\t\tif (i == 0 || i == m_mazeElementTypes.size() - 1 || j == 0 || j == m_mazeElementTypes&#91;i].size() - 1)\n\t\t\t\t\tm_mazeElementTypes&#91;i]&#91;j] = 1;\/\/set to a wall\n\t\t\t\telse m_mazeElementTypes&#91;i]&#91;j] = KMazeData&#91;(numRows-i )*numCols + j - 1];\n\t\t\t}\n\t}\n\telse\n\t{\n\t\tm_mazeElementTypes.resize(numRows);\n\t\tfor (int i = 0; i &lt; numRows; i++)\n\t\t\tm_mazeElementTypes&#91;i].resize(numCols);\n\n\t\tfor (unsigned int i = 0; i &lt; m_mazeElementTypes.size(); i++)\n\t\t\tfor (unsigned int j = 0; j &lt; m_mazeElementTypes&#91;i].size(); j++)\n\t\t\t\tm_mazeElementTypes&#91;i]&#91;j] = KMazeData&#91;(numRows-i-1)*numCols + (j)];\n\t}\n\n\n\t\/\/create graphical elements\n\tm_mazeElementInstances.resize(m_mazeElementTypes.size());\n\tfor (unsigned int i = 0; i &lt; m_mazeElementTypes.size(); i++)\n\t\tm_mazeElementInstances&#91;i].resize(m_mazeElementTypes&#91;i].size());\n\n\tauto wallTexture = contentManager-&gt;Load(L\"Textures\\\\walltex.png\", commandList.Get());\n\tauto floorTexture = contentManager-&gt;Load(L\"Textures\\\\floortex.png\", commandList.Get());\n\tauto floorTextureS = contentManager-&gt;Load(L\"Textures\\\\floortexS.png\", commandList.Get());\n\tauto floorTextureF = contentManager-&gt;Load(L\"Textures\\\\floortexF.png\", commandList.Get());\n\tTexture* textures&#91;] = { floorTextureF, floorTextureS, floorTexture, wallTexture};\n\n\tfor (unsigned int i = 0; i &lt; m_mazeElementInstances.size(); i++)\n\t\tfor (unsigned int j = 0; j &lt; m_mazeElementInstances&#91;i].size(); j++)\n\t\t{\n\t\t\tauto type = m_mazeElementTypes&#91;i]&#91;j];\n\t\t\tauto element = new MazeElement(d3dDevice, commandList, textures&#91;type +2]);\n\t\t\tif (type == 1)\n\t\t\t\telement-&gt;SetPosition(DirectX::XMFLOAT3(j, 0.5f, i));\n\t\t\telse element-&gt;SetPosition(DirectX::XMFLOAT3(j, 0, i));\n\t\t\tm_mazeElementInstances&#91;i]&#91;j] = element;\n\n\t\t\tif (type == -1)\/\/start position\n\t\t\t\tm_startPosition = DirectX::XMFLOAT2(j, i);\n\t\t}\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now every render pass, all the elements in the array are run through and rendered forming the final maze.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"416\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf3096787f.png\" alt=\"\" class=\"wp-image-1594\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf3096787f.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf3096787f-300x208.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><em><strong>A simple maze being rendered<\/strong><\/em><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">5.2 Game Logic<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When the game is started or once the maze is being formed, to be precise, the starting position in the maze is recorded and player\u2019s position is set to that value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the&nbsp;<strong>VoiceMaze<\/strong>&nbsp;in the&nbsp;<em>Update<\/em>&nbsp;method, once the input arrives an input sanitation is performed. We check the intended position against the integer values of the 2D array. If the input would result in avatar going into a space with a wall, we simply ignore it and wait for another command.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void Maze::ProcessInput(EInput input, PlayerAvatar *playerAvatar)\n{\n\tif (playerAvatar-&gt;IsMoving())\n\t\treturn;\n\n\tauto currPos = playerAvatar-&gt;GetCurrentPositionIndex();\n\tauto avatarY = playerAvatar-&gt;GetCurrentPosition().y;\n\n\tswitch (input)\n\t{\n\tcase EInput::EInput_DOWN:\/\/up down might seem inverted, this happens because of the way it's stored in the array\n\t\tif (currPos.y&gt; 1)\n\t\t\tif (m_mazeElementTypes&#91;currPos.y - 1]&#91;currPos.x] != 1)\n\t\t\t\tplayerAvatar-&gt;MoveAvatar(DirectX::XMFLOAT3(currPos.x, avatarY, currPos.y - 1));\n\t\tbreak;\n\n\tcase EInput::EInput_UP:\/\/up down might seem inverted, this happens because of the way it's stored in the array\n\t\tif (currPos.y &lt; (int)m_mazeElementTypes.size() - 2)\n\t\t\tif (m_mazeElementTypes&#91;currPos.y + 1]&#91;currPos.x] != 1)\n\t\t\t\tplayerAvatar-&gt;MoveAvatar(DirectX::XMFLOAT3(currPos.x, avatarY, currPos.y + 1));\n\t\tbreak;\n\n\tcase EInput::EInput_LEFT:\n\t\tif (currPos.x &gt; 1)\n\t\t\tif (m_mazeElementTypes&#91;currPos.y]&#91;currPos.x - 1] != 1)\n\t\t\t\tplayerAvatar-&gt;MoveAvatar(DirectX::XMFLOAT3(currPos.x - 1, avatarY, currPos.y));\n\t\tbreak;\n\n\tcase EInput::EInput_RIGHT:\n\t\tif (currPos.x &lt; (int)m_mazeElementTypes&#91;0].size() - 2)\n\t\t\tif (m_mazeElementTypes&#91;currPos.y]&#91;currPos.x + 1] != 1)\n\t\t\t\tplayerAvatar-&gt;MoveAvatar(DirectX::XMFLOAT3(currPos.x + 1, avatarY, currPos.y));\n\t\tbreak;\n\t}\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">After each movement completes we check if the current position is the finish space. If that is the case, we start the win sequence and reset the game. Otherwise the game continues on.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5.3 Movement and Animation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">One closely related aspect to input and movement is the&nbsp;<strong>animation<\/strong>. Once the input is registered and the space to move into is valid one, we don\u2019t immediately reposition the avatar to that spot. Instead, we start the transition animation which gradually moves the avatar to a new place in about 1 second.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This has two positive aspects. First, since we ignore any new input if the avatar is in move animation, we don\u2019t need to add input delay. Without it a keypress would result in the model flying through the whole corridor to the nearest wall in the fraction of a second, because every update cycle the model would get repositioned to the next available spot that is indicated by the input direction. Another bonus is that the animated movement just looks nice to the human eye \u2013 if the objects are just jerking around from space to space it looks unnatural and plain weird.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In case the player reaches the final space a&nbsp;<em>PlayEndAnimation<\/em>&nbsp;method is called on the&nbsp;<strong>PlayerAvatar<\/strong>&nbsp;object. This plays a small animation by calling&nbsp;<em>WinAnimationUpdate<\/em>&nbsp;instead of the normal&nbsp;<em>Update<\/em>&nbsp;method on the&nbsp;<strong>PlayerAvatar<\/strong>. In essence the mesh is risen by a certain amount on the Y axis at the same time shrinking it to zero in scale. Then the mesh travels to the starting location and once over it, plays the same animation in reverse \u2013 scales it back to a normal size and lowers it on the Y axis. Since the camera is always following the player we get this nice, simple transition between a win state and a new game.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5.4 Input<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Input is your actual interaction with the application. Without it you would not be able to control anything that is happening on the screen. Even though there are applications that don\u2019t need any actual input \u2013 like a 3D demonstration or benchmark tools, most of the time you would want to give the user the ability to interact with your game\\application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Voice Maze we have two options for user input \u2013 speech recognition and keyboard input. Both of them are encapsulated by the&nbsp;<strong>MazeInput<\/strong>&nbsp;class, which will first try to get the input from speech recognition and then fall back to keyboard if nothing was recognized.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">5.4.1 Voice input<\/h4>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"655\" height=\"312\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/Screenshot_1.png\" alt=\"\" class=\"wp-image-1599\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/Screenshot_1.png 655w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/Screenshot_1-300x143.png 300w\" sizes=\"auto, (max-width: 655px) 100vw, 655px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">We will be using&nbsp;<strong>VoiceInput<\/strong>&nbsp;class to process the input data and provide us a unified movement direction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When initializing, we supply it with the dictionary of words we would like our application to react on. These are called the&nbsp;<strong>Input Constraints<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>VoiceInput::VoiceInput()\n{\n\tm_recognitionConstraints = ref new Vector();\n\n\tIVector ^directions = ref new Vector;\/\/array of voice commands to listen for\n\n\tdirections-&gt;Append(\"up\");\n\tdirections-&gt;Append(\"down\");\n\tdirections-&gt;Append(\"left\");\n\tdirections-&gt;Append(\"right\");\n\n\tSetInputConstraints(directions);\n}\nvoid VoiceInput::Start()\n{\n\tm_isActive = true;\n\tm_lastReadingValue = L\"\";\n\n\tm_speechRecognizer = ref new SpeechRecognizer();\n\tauto listConstraint = ref new SpeechRecognitionListConstraint(m_recognitionConstraints, L\"TextTagIdWhatever\");\n\n\tm_speechRecognizer-&gt;Constraints-&gt;Append(listConstraint);\n\n\tauto constraintsCompilationTask = create_task(m_speechRecognizer-&gt;CompileConstraintsAsync());\n\n\tconstraintsCompilationTask.\n\t\tthen( &#91;this](SpeechRecognitionCompilationResult ^compilationResult)\n\t\t{\n\t\t\tStartRecognitionInstance();\n\t\t}\n\t);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The actual recognition is done asynchronously on another thread. When&nbsp;<em>VoiceInput::Start<\/em>&nbsp;is called, we first initialize a new&nbsp;<strong>SpeechRecognizer<\/strong>&nbsp;and also create a&nbsp;<strong>SpeechRecognitionListConstraint<\/strong>&nbsp;object from our constraint dictionary which is then supplied to the&nbsp;<strong>SpeechRecognizer<\/strong>&nbsp;instance. This data is then prepared for the recognition with the&nbsp;<em>CompileConstraintsAsync<\/em>&nbsp;task. Once it completes, we are ready to start the recognition itself.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void VoiceInput::StartRecognitionInstance()\n{\n\tauto recognitionTask = create_task(m_speechRecognizer-&gt;RecognizeAsync());\n\trecognitionTask.then(&#91;this](SpeechRecognitionResult ^recognitionResult)\n\t{\n\t\tauto newValue = recognitionResult-&gt;Text;\n\t\tm_lastReadingValue = newValue;\n\t\tif (IsActive())\n\t\t\tStartRecognitionInstance();\n\t});\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When we call&nbsp;<em>VoiceInput::StartRecognitionInstance&nbsp;<\/em>a new task is started which will gather live input sound from the microphone and will try to make sense of that data by matching it with the<strong>&nbsp;Input Constraints<\/strong>. The result will be stored in&nbsp;<strong>SpeechRecognitionResult<\/strong>&nbsp;<strong>Text<\/strong>&nbsp;member. After one recognition cycle completes, we immediately start a new one by calling&nbsp;<em>StartRecognitionInstance&nbsp;<\/em>again.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Platform::String^ VoiceInput::GetLastReading(bool clearValue)\n{\n\tauto readingValue = m_lastReadingValue;\n\tif (clearValue)\n\t\tm_lastReadingValue = L\"\";\n\n\treturn readingValue;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Every Update cycle in the main&nbsp;<em>VoiceMazeRenderer::Update<\/em>&nbsp;method we will ask the&nbsp;<strong>VoiceInput<\/strong>&nbsp;instance whether or not it has some new data for us. When we call&nbsp;<em>GetLastReading,<\/em>&nbsp;the last recorded and recognized input text will be provided and the data will be cleared. We can compare the string to the expected values and move the avatar accordingly. In case no new data arrived, the method will return an empty string and no action will take place.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bool MazeInput::ProcessVoiceInput()\n{\n\tbool inputReceived = false;\n\n\tauto lastVoiceCommand = m_voiceInput.GetLastReading(true);\n\tif (lastVoiceCommand-&gt;Equals(\"up\"))\n\t{\n\t\tm_lastInput = EInput::EInput_UP;\n\t\tinputReceived = true;\n\t}\n\telse if (lastVoiceCommand-&gt;Equals(\"down\"))\n\t{\n\t\tm_lastInput = EInput::EInput_DOWN;\n\t\tinputReceived = true;\n\t}\n\telse if (lastVoiceCommand-&gt;Equals(\"left\"))\n\t{\n\t\tm_lastInput = EInput::EInput_LEFT;\n\t\tinputReceived = true;\n\t}\n\telse if (lastVoiceCommand-&gt;Equals(\"right\"))\n\t{\n\t\tm_lastInput = EInput::EInput_RIGHT;\n\t\tinputReceived = true;\n\t}\n\telse m_lastInput = EInput::EInput_NONE;\n\n\treturn inputReceived;\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">5.4.2 Keyboard input<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Keyboard input is quite simple if compared to the Speech recognition. The low-level state is handled inside the&nbsp;<strong>GameInput<\/strong>&nbsp;class. We will only be reacting to key presses that happen on the game\u2019s window. So we get the main window instance:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>m_coreWindow = Windows::ApplicationModel::Core::CoreApplication::GetCurrentView()-&gt;CoreWindow;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Once the Update phase arrives, we poll each key we are interested in: in our case up, down, left and right arrow keys and check their statuses.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bool GameInput::IsKeyPressed(Windows::System::VirtualKey key)\n{\n\n\tauto result = m_coreWindow-&gt;GetKeyState(key);\n\treturn (int)result &amp; (int)Windows::UI::Core::CoreVirtualKeyStates::Down;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If any of them are pressed down, well we react as was the case with the voice input.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void MazeInput::ProcessKeyboardInput()\n{\n\tif (m_gameInput.IsKeyPressed(Windows::System::VirtualKey::Up))\n\t\tm_lastInput = EInput::EInput_UP;\n\telse if (m_gameInput.IsKeyPressed(Windows::System::VirtualKey::Down))\n\t\tm_lastInput = EInput::EInput_DOWN;\n\telse if (m_gameInput.IsKeyPressed(Windows::System::VirtualKey::Left))\n\t\tm_lastInput = EInput::EInput_LEFT;\n\telse if (m_gameInput.IsKeyPressed(Windows::System::VirtualKey::Right))\n\t\tm_lastInput = EInput::EInput_RIGHT;\n\telse m_lastInput = EInput::EInput_NONE;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">GENERAL CODE\\ENGINE STRUCTURE<\/h2>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"277\" src=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf32a67821.png\" alt=\"\" class=\"wp-image-1597\" srcset=\"https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf32a67821.png 600w, https:\/\/xplicity.com\/wp-content\/uploads\/2023\/07\/img_5daaf32a67821-300x139.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong><em>Diagram indicates the overall structure of the project and the component relations<\/em><\/strong><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">CONSIDERATIONS, FURTHER STEPS<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There are quite a few areas of improvement as far as this project goes. From my standpoint, I would start with&nbsp;<strong>Shadow Maps<\/strong>,&nbsp;<strong>Instancing<\/strong>&nbsp;and overall base structure optimization.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Shadow Maps<\/strong>&nbsp;is the current&nbsp;<em>de facto<\/em>&nbsp;standard when it comes to shadow rendering. You might have noticed that the project might feel a bit weird \u2013 the objects react to the light naturally, their sides get darker or brighter depending on the source of the light, but one crucial part is missing. No object is casting shadows on other objects.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The shadows are a natural part of our world. We take them for granted. But when there are no shadows we instantly feel that something is not right with the picture. We might not be able to put our finger on it, but it really bothers us. This is because shadows carry a very important information \u2013 they tell you how objects are sitting in space in relation to each other. If an object is right on the surface \u2013 it casts a really strong but small shadow. As it starts moving towards the light source \u2013 the shadow starts to get bigger and blurrier. That is how we perceive it, even without ever noticing it consciously.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is especially noticeable in our application when the crown mesh starts to rise and shrink. If you know what is supposed to happen you can sort of feel it. But to others it looks really weird, and some people might not even be able to tell what is going on exactly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Shadow maps, in short, render the whole scene from the perspective of the light source. Only the depths are rendered into a separate buffer. Once this is completed \u2013 a normal rendering pass from the point of the camera takes place. When the shader runs, every pixel that is about to be rendered is checked against the rendered depth texture. If we calculate that the pixel-to-be-rendered is blocked from the light source by some other geometry, we color it darker \u2013 it is in shadow. This way we simulate shadows without too much overhead. Most of the games and applications today employ shadow maps for their needs in one form or the other \u2013 the algorithms might be a lot more complex, but the general idea behind it is the same. You can find more info about shadow maps in the links section.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Instancing<\/strong>&nbsp;is another optimization technique. Currently, all maze elements are actual 3D objects with their own geometry that is uploaded to the GPU even though the textures are shared. One of the ways we could save on some memory and processing is by reusing the same geometry for all the elements of the maze \u2013 just transforming to required positions and applying the necessary texture. The way the constant buffer data is sent in and versioned would need to be refactored but would be a more \u201cenvironment friendly\u201d approach.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Structure optimization is pretty straightforward. As you move on creating your game \u2013 the needs and therefore the base structure will change. Even for this demo project the initial architecture changed a couple of times and when doing the structure diagram, I noticed quite a few points of improvement: for example, the shared&nbsp;<strong>ContentManager<\/strong>&nbsp;reference immediately catches the attention as it is doing something not entirely right. So, when you are coding your project, don\u2019t be afraid and refactor often \u2013 things change rapidly from the first time you encounter them, that is just the way it is.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">LINKS \\ FURTHER READING<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"http:\/\/rbwhitaker.wikidot.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">RB Whitaker\u2019s Wiki<\/a>. I really think this guy does not get enough credit as he is such a mentor to a lot of us out there. Especially good starting point if you do XNA \\ MonoGame development<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/social.technet.microsoft.com\/wiki\/contents\/articles\/27204.windows-phone-writing-a-3d-directx-maze-that-s-navigable-with-speech-commands.aspx\" target=\"_blank\" rel=\"noreferrer noopener\">My old article<\/a>&nbsp;if you are interested (targets DirectX 10 \u2013 11):<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/marketplace.visualstudio.com\/items?itemName=TimGJones.HLSLToolsforVisualStudio\" target=\"_blank\" rel=\"noreferrer noopener\">HLSL Tools for VS<\/a>&nbsp;by Tim G. Jones, if you\u2019ve missed it before:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/dn899200(v=vs.85).aspx#direct3d_12_graphics_pipeline\" target=\"_blank\" rel=\"noreferrer noopener\">Direct 3D pipeline diagram<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"http:\/\/www.opengl-tutorial.org\/intermediate-tutorials\/tutorial-16-shadow-mapping\/\" target=\"_blank\" rel=\"noreferrer noopener\">Shadow maps<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Albeit a bit outdated (DirectX 11.2 is the latest one covered), this page it still is a good read to get&nbsp;<a href=\"http:\/\/directxtutorial.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">introduced to DirectX<\/a>. Provides great examples and is really easy to follow. And, heck, even though DirectX 12 is the hot topic right now, it does not mean the older versions are no longer supported.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A really&nbsp;<a href=\"https:\/\/www.3dgep.com\/learning-directx-12-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">nice tutorial page<\/a>. A shame I found it a bit too late.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/www.braynzarsoft.net\/viewtutorial\/q16390-directx-12-textures-from-file\" target=\"_blank\" rel=\"noreferrer noopener\">ImageLoading<\/a>&nbsp;process described in detail and many other goodies.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A different take on UWP DirectX application albeit in DirectX 11 can be found&nbsp;<a href=\"https:\/\/docs.microsoft.com\/en-us\/windows\/uwp\/gaming\/tutorial--create-your-first-uwp-directx-game\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s an outstanding&nbsp;<a href=\"https:\/\/github.com\/Microsoft\/DirectX-Graphics-Samples\" target=\"_blank\" rel=\"noreferrer noopener\">D3D12 project from Microsoft<\/a>, a really nice and noteworthy to look through.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">THANKS<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">I would like to thank my long-time collaborator Martynas Pikiotas for the nice hand coordinates and the lightbulb illustrations.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">CONCLUSION<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This article showed you how to initialize devices, set up the environment and start drawing 3D objects on screen. Furthermore we learned about the 3D basics, how to texture, add lighting and load 3D model files. In the end we had a project that was drawing a maze that could be navigated using speech commands or your good old keyboard. The project should provide you an idea of what a game engine is and how you would go about creating one on your own.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Even though this example project is a far cry from a decent engine, it should serve as a good starting point to creating your small DirectX 12 enabled project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">SOURCE<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The project source can be found&nbsp;<a href=\"https:\/\/gitlab.com\/viktorasb\/VoiceMaze\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The article covers the creation of a 3D Direct3D rendered maze for UWP (so that it could be run on any of Microsoft\u2019s platforms \u2013 Windows 10, Windows Phone (Windows 10 Mobile), Xbox One or HoloLens) and it is navigable with voice commands. The application starts with the player\u2019s avatar positioned on the starting tile [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1576,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-1575","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog"],"acf":[],"_links":{"self":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts\/1575","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/comments?post=1575"}],"version-history":[{"count":4,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts\/1575\/revisions"}],"predecessor-version":[{"id":1607,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/posts\/1575\/revisions\/1607"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/media\/1576"}],"wp:attachment":[{"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/media?parent=1575"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/categories?post=1575"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/xplicity.com\/wp-json\/wp\/v2\/tags?post=1575"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}