diff --git a/Nuake/Engine.cpp b/Nuake/Engine.cpp index e5beceac..3c659a44 100644 --- a/Nuake/Engine.cpp +++ b/Nuake/Engine.cpp @@ -207,6 +207,8 @@ namespace Nuake // Draw scene Window::Get()->Draw(); + + glfwPollEvents(); } void Engine::EndDraw() diff --git a/Nuake/dependencies/dxc/LICENSE-LLVM.txt b/Nuake/dependencies/dxc/LICENSE-LLVM.txt new file mode 100644 index 00000000..d2edb2f0 --- /dev/null +++ b/Nuake/dependencies/dxc/LICENSE-LLVM.txt @@ -0,0 +1,43 @@ +============================================================================== +LLVM Release License +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2003-2015 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. diff --git a/Nuake/dependencies/dxc/LICENSE-MIT.txt b/Nuake/dependencies/dxc/LICENSE-MIT.txt new file mode 100644 index 00000000..63447fd8 --- /dev/null +++ b/Nuake/dependencies/dxc/LICENSE-MIT.txt @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/Nuake/dependencies/dxc/LICENSE-MS.txt b/Nuake/dependencies/dxc/LICENSE-MS.txt new file mode 100644 index 00000000..6c9c3c67 --- /dev/null +++ b/Nuake/dependencies/dxc/LICENSE-MS.txt @@ -0,0 +1,158 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT DIRECTX SHADER COMPILER + +These license terms are an agreement between you and Microsoft +Corporation (or one of its affiliates). They apply to the software named +above and any Microsoft services or software updates (except to the +extent such services or updates are accompanied by new or additional +terms, in which case those different terms apply prospectively and do +not alter your or Microsoft’s rights relating to pre-updated software or +services). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS +BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. + +INSTALLATION AND USE RIGHTS. + +General. Subject to the terms of this agreement, you may install and use any number of copies of the software, and solely for use on Windows. + +Included Microsoft Applications. The software may include other Microsoft applications. These license terms apply to those included applications, if any, unless other license terms are provided with the other Microsoft applications. + +Microsoft Platforms. The software may include components from Microsoft Windows. These components are governed by separate agreements and their own product support policies, as described in the license terms found in the installation directory for that component or in the “Licenses” folder accompanying the software. + +Third Party Components. The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file(s) accompanying the software. + +DATA. + +Data Collection. The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may opt-out of many of these scenarios, but not all, as described in the product documentation.  There are also some features in the software that may enable you to collect data from users of your applications. If you use these features to enable data collection in your applications, you must comply with applicable law, including providing appropriate notices to users of your applications. You can learn more about data collection and use in the help documentation and the privacy statement at https://aka.ms/privacy. Your use of the software operates as your consent to these practices. + +Processing of Personal Data. To the extent Microsoft is a processor or subprocessor of personal data in connection with the software, Microsoft makes the commitments in the European Union General Data Protection Regulation Terms of the Online Services Terms to all customers effective May 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr. + +DISTRIBUTABLE CODE. The software may contain code you are permitted to distribute (i.e. make available for third parties) in applications you develop, as described in this Section. + +Distribution Rights. The code and test files described below are distributable if included with the software. + +Distributables. You may copy and distribute the object code form of the software listed in the distributables file list in the software; and + +Third Party Distribution. You may permit distributors of your applications to copy and distribute any of this distributable code you elect to distribute with your applications. + +Distribution Requirements. For any code you distribute, you must: + +add significant primary functionality to it in your applications; + +i. require distributors and external end users to agree to terms that protect it and Microsoft at least as much as this agreement; and + +ii. indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your applications, except to the extent that any claim is based solely on the unmodified distributable code. + +Distribution Restrictions. You may not: + +use Microsoft’s trademarks or trade dress in your application in any way that suggests your application comes from or is endorsed by Microsoft; or modify or distribute the source code of any distributable code so that any part of it becomes subject to any license that requires that the distributable code, any other part of the software, or any of Microsoft’s other intellectual property be disclosed or distributed in source code form, or that others have the right to modify it. + +SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you will not (and have no right to): + +work around any technical limitations in the software that only allow you to use it in certain ways; + +reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source code for the software, except and to the extent required by third party licensing terms governing use of certain open source components that may be included in the software; + +remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software; + +use the software in any way that is against the law or to create or propagate malware; or + +share, publish, distribute, or lease the software (except for any distributable code, subject to the terms above), provide the software as a stand-alone offering for others to use, or transfer the software or this agreement to any third party. + +EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit https://aka.ms/exporting. + +SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for the software. Any support provided is “as is”, “with all faults”, and without warranty of any kind. + +UPDATES. The software may periodically check for updates, and download and install them for you. You may obtain updates only from Microsoft or authorized sources. Microsoft may need to update your system to provide you with updates. You agree to receive these automatic updates without any additional notice. Updates may not include or support all existing software features, services, or peripheral devices. + +ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software. + +APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United States or Canada, the laws of the state or province where you live (or, if a business, where your principal place of business is located) govern the interpretation of this agreement, claims for its breach, and all other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of laws principles. If you acquired the software in any other country, its laws apply. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court. If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court. + +CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you: + +a. Australia. You have statutory guarantees under the Australian + Consumer Law and nothing in this agreement is intended to affect + those rights. + +b. Canada. If you acquired this software in Canada, you may stop + receiving updates by turning off the automatic update feature, + disconnecting your device from the Internet (if and when you + re-connect to the Internet, however, the software will resume + checking for and installing updates), or uninstalling the software. + The product documentation, if any, may also specify how to turn off + updates for your specific device or software. + +c. Germany and Austria. + + i. Warranty. The properly licensed software will perform substantially + as described in any Microsoft materials that accompany the software. + However, Microsoft gives no contractual guarantee in relation to the + licensed software. + + ii. Limitation of Liability. In case of intentional conduct, gross + negligence, claims based on the Product Liability Act, as well as, in + case of death or personal or physical injury, Microsoft is liable + according to the statutory law. + +Subject to the foregoing clause ii., Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of slight negligence, Microsoft will not be liable for slight negligence. + +DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. + +LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT, OR INCIDENTAL DAMAGES. + +This limitation applies to (a) anything related to the software, +services, content (including code) on third party Internet sites, or +third party applications; and (b) claims for breach of contract, +warranty, guarantee, or condition; strict liability, negligence, or +other tort; or any other claim; in each case to the extent permitted by +applicable law. + +It also applies even if Microsoft knew or should have known about the +possibility of the damages. The above limitation or exclusion may not +apply to you because your state, province, or country may not allow the +exclusion or limitation of incidental, consequential, or other damages. + +Please note: As this software is distributed in Canada, some of the +clauses in this agreement are provided below in French. + +Remarque: Ce logiciel étant distribué au Canada, certaines des clauses +dans ce contrat sont fournies ci-dessous en français. + +EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « +tel quel ». Toute utilisation de ce logiciel est à votre seule risque et +péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez +bénéficier de droits additionnels en vertu du droit local sur la +protection des consommateurs, que ce contrat ne peut modifier. La ou +elles sont permises par le droit locale, les garanties implicites de +qualité marchande, d’adéquation à un usage particulier et d’absence de +contrefaçon sont exclues. + +LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES +DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une +indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ +US. Vous ne pouvez prétendre à aucune indemnisation pour les autres +dommages, y compris les dommages spéciaux, indirects ou accessoires et +pertes de bénéfices. + +Cette limitation concerne: + +• tout ce qui est relié au logiciel, aux services ou au contenu (y +compris le code) figurant sur des sites Internet tiers ou dans des +programmes tiers; et + +• les réclamations au titre de violation de contrat ou de garantie, ou +au titre de responsabilité stricte, de négligence ou d’une autre faute +dans la limite autorisée par la loi en vigueur. + +Elle s’applique également, même si Microsoft connaissait ou devrait +connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas +l’exclusion ou la limitation de responsabilité pour les dommages +indirects, accessoires ou de quelque nature que ce soit, il se peut que +la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre +égard. + +EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. +Vous pourriez avoir d’autres droits prévus par les lois de votre pays. +Le présent contrat ne modifie pas les droits que vous confèrent les lois +de votre pays si celles-ci ne le permettent pas. diff --git a/Nuake/dependencies/dxc/inc/d3d12shader.h b/Nuake/dependencies/dxc/inc/d3d12shader.h new file mode 100644 index 00000000..749e9339 --- /dev/null +++ b/Nuake/dependencies/dxc/inc/d3d12shader.h @@ -0,0 +1,487 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// File: D3D12Shader.h +// Content: D3D12 Shader Types and APIs +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef __D3D12SHADER_H__ +#define __D3D12SHADER_H__ + +#include "d3dcommon.h" + +typedef enum D3D12_SHADER_VERSION_TYPE +{ + D3D12_SHVER_PIXEL_SHADER = 0, + D3D12_SHVER_VERTEX_SHADER = 1, + D3D12_SHVER_GEOMETRY_SHADER = 2, + + // D3D11 Shaders + D3D12_SHVER_HULL_SHADER = 3, + D3D12_SHVER_DOMAIN_SHADER = 4, + D3D12_SHVER_COMPUTE_SHADER = 5, + + // D3D12 Shaders + D3D12_SHVER_LIBRARY = 6, + + D3D12_SHVER_RAY_GENERATION_SHADER = 7, + D3D12_SHVER_INTERSECTION_SHADER = 8, + D3D12_SHVER_ANY_HIT_SHADER = 9, + D3D12_SHVER_CLOSEST_HIT_SHADER = 10, + D3D12_SHVER_MISS_SHADER = 11, + D3D12_SHVER_CALLABLE_SHADER = 12, + + D3D12_SHVER_MESH_SHADER = 13, + D3D12_SHVER_AMPLIFICATION_SHADER = 14, + + D3D12_SHVER_RESERVED0 = 0xFFF0, +} D3D12_SHADER_VERSION_TYPE; + +#define D3D12_SHVER_GET_TYPE(_Version) \ + (((_Version) >> 16) & 0xffff) +#define D3D12_SHVER_GET_MAJOR(_Version) \ + (((_Version) >> 4) & 0xf) +#define D3D12_SHVER_GET_MINOR(_Version) \ + (((_Version) >> 0) & 0xf) + +// Slot ID for library function return +#define D3D_RETURN_PARAMETER_INDEX (-1) + +typedef D3D_RESOURCE_RETURN_TYPE D3D12_RESOURCE_RETURN_TYPE; + +typedef D3D_CBUFFER_TYPE D3D12_CBUFFER_TYPE; + + +typedef struct _D3D12_SIGNATURE_PARAMETER_DESC +{ + LPCSTR SemanticName; // Name of the semantic + UINT SemanticIndex; // Index of the semantic + UINT Register; // Number of member variables + D3D_NAME SystemValueType;// A predefined system value, or D3D_NAME_UNDEFINED if not applicable + D3D_REGISTER_COMPONENT_TYPE ComponentType; // Scalar type (e.g. uint, float, etc.) + BYTE Mask; // Mask to indicate which components of the register + // are used (combination of D3D10_COMPONENT_MASK values) + BYTE ReadWriteMask; // Mask to indicate whether a given component is + // never written (if this is an output signature) or + // always read (if this is an input signature). + // (combination of D3D_MASK_* values) + UINT Stream; // Stream index + D3D_MIN_PRECISION MinPrecision; // Minimum desired interpolation precision +} D3D12_SIGNATURE_PARAMETER_DESC; + +typedef struct _D3D12_SHADER_BUFFER_DESC +{ + LPCSTR Name; // Name of the constant buffer + D3D_CBUFFER_TYPE Type; // Indicates type of buffer content + UINT Variables; // Number of member variables + UINT Size; // Size of CB (in bytes) + UINT uFlags; // Buffer description flags +} D3D12_SHADER_BUFFER_DESC; + +typedef struct _D3D12_SHADER_VARIABLE_DESC +{ + LPCSTR Name; // Name of the variable + UINT StartOffset; // Offset in constant buffer's backing store + UINT Size; // Size of variable (in bytes) + UINT uFlags; // Variable flags + LPVOID DefaultValue; // Raw pointer to default value + UINT StartTexture; // First texture index (or -1 if no textures used) + UINT TextureSize; // Number of texture slots possibly used. + UINT StartSampler; // First sampler index (or -1 if no textures used) + UINT SamplerSize; // Number of sampler slots possibly used. +} D3D12_SHADER_VARIABLE_DESC; + +typedef struct _D3D12_SHADER_TYPE_DESC +{ + D3D_SHADER_VARIABLE_CLASS Class; // Variable class (e.g. object, matrix, etc.) + D3D_SHADER_VARIABLE_TYPE Type; // Variable type (e.g. float, sampler, etc.) + UINT Rows; // Number of rows (for matrices, 1 for other numeric, 0 if not applicable) + UINT Columns; // Number of columns (for vectors & matrices, 1 for other numeric, 0 if not applicable) + UINT Elements; // Number of elements (0 if not an array) + UINT Members; // Number of members (0 if not a structure) + UINT Offset; // Offset from the start of structure (0 if not a structure member) + LPCSTR Name; // Name of type, can be NULL +} D3D12_SHADER_TYPE_DESC; + +typedef D3D_TESSELLATOR_DOMAIN D3D12_TESSELLATOR_DOMAIN; + +typedef D3D_TESSELLATOR_PARTITIONING D3D12_TESSELLATOR_PARTITIONING; + +typedef D3D_TESSELLATOR_OUTPUT_PRIMITIVE D3D12_TESSELLATOR_OUTPUT_PRIMITIVE; + +typedef struct _D3D12_SHADER_DESC +{ + UINT Version; // Shader version + LPCSTR Creator; // Creator string + UINT Flags; // Shader compilation/parse flags + + UINT ConstantBuffers; // Number of constant buffers + UINT BoundResources; // Number of bound resources + UINT InputParameters; // Number of parameters in the input signature + UINT OutputParameters; // Number of parameters in the output signature + + UINT InstructionCount; // Number of emitted instructions + UINT TempRegisterCount; // Number of temporary registers used + UINT TempArrayCount; // Number of temporary arrays used + UINT DefCount; // Number of constant defines + UINT DclCount; // Number of declarations (input + output) + UINT TextureNormalInstructions; // Number of non-categorized texture instructions + UINT TextureLoadInstructions; // Number of texture load instructions + UINT TextureCompInstructions; // Number of texture comparison instructions + UINT TextureBiasInstructions; // Number of texture bias instructions + UINT TextureGradientInstructions; // Number of texture gradient instructions + UINT FloatInstructionCount; // Number of floating point arithmetic instructions used + UINT IntInstructionCount; // Number of signed integer arithmetic instructions used + UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used + UINT StaticFlowControlCount; // Number of static flow control instructions used + UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used + UINT MacroInstructionCount; // Number of macro instructions used + UINT ArrayInstructionCount; // Number of array instructions used + UINT CutInstructionCount; // Number of cut instructions used + UINT EmitInstructionCount; // Number of emit instructions used + D3D_PRIMITIVE_TOPOLOGY GSOutputTopology; // Geometry shader output topology + UINT GSMaxOutputVertexCount; // Geometry shader maximum output vertex count + D3D_PRIMITIVE InputPrimitive; // GS/HS input primitive + UINT PatchConstantParameters; // Number of parameters in the patch constant signature + UINT cGSInstanceCount; // Number of Geometry shader instances + UINT cControlPoints; // Number of control points in the HS->DS stage + D3D_TESSELLATOR_OUTPUT_PRIMITIVE HSOutputPrimitive; // Primitive output by the tessellator + D3D_TESSELLATOR_PARTITIONING HSPartitioning; // Partitioning mode of the tessellator + D3D_TESSELLATOR_DOMAIN TessellatorDomain; // Domain of the tessellator (quad, tri, isoline) + // instruction counts + UINT cBarrierInstructions; // Number of barrier instructions in a compute shader + UINT cInterlockedInstructions; // Number of interlocked instructions + UINT cTextureStoreInstructions; // Number of texture writes +} D3D12_SHADER_DESC; + +typedef struct _D3D12_SHADER_INPUT_BIND_DESC +{ + LPCSTR Name; // Name of the resource + D3D_SHADER_INPUT_TYPE Type; // Type of resource (e.g. texture, cbuffer, etc.) + UINT BindPoint; // Starting bind point + UINT BindCount; // Number of contiguous bind points (for arrays) + + UINT uFlags; // Input binding flags + D3D_RESOURCE_RETURN_TYPE ReturnType; // Return type (if texture) + D3D_SRV_DIMENSION Dimension; // Dimension (if texture) + UINT NumSamples; // Number of samples (0 if not MS texture) + UINT Space; // Register space + UINT uID; // Range ID in the bytecode +} D3D12_SHADER_INPUT_BIND_DESC; + +#define D3D_SHADER_REQUIRES_DOUBLES 0x00000001 +#define D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL 0x00000002 +#define D3D_SHADER_REQUIRES_UAVS_AT_EVERY_STAGE 0x00000004 +#define D3D_SHADER_REQUIRES_64_UAVS 0x00000008 +#define D3D_SHADER_REQUIRES_MINIMUM_PRECISION 0x00000010 +#define D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS 0x00000020 +#define D3D_SHADER_REQUIRES_11_1_SHADER_EXTENSIONS 0x00000040 +#define D3D_SHADER_REQUIRES_LEVEL_9_COMPARISON_FILTERING 0x00000080 +#define D3D_SHADER_REQUIRES_TILED_RESOURCES 0x00000100 +#define D3D_SHADER_REQUIRES_STENCIL_REF 0x00000200 +#define D3D_SHADER_REQUIRES_INNER_COVERAGE 0x00000400 +#define D3D_SHADER_REQUIRES_TYPED_UAV_LOAD_ADDITIONAL_FORMATS 0x00000800 +#define D3D_SHADER_REQUIRES_ROVS 0x00001000 +#define D3D_SHADER_REQUIRES_VIEWPORT_AND_RT_ARRAY_INDEX_FROM_ANY_SHADER_FEEDING_RASTERIZER 0x00002000 +#define D3D_SHADER_REQUIRES_WAVE_OPS 0x00004000 +#define D3D_SHADER_REQUIRES_INT64_OPS 0x00008000 +#define D3D_SHADER_REQUIRES_VIEW_ID 0x00010000 +#define D3D_SHADER_REQUIRES_BARYCENTRICS 0x00020000 +#define D3D_SHADER_REQUIRES_NATIVE_16BIT_OPS 0x00040000 +#define D3D_SHADER_REQUIRES_SHADING_RATE 0x00080000 +#define D3D_SHADER_REQUIRES_RAYTRACING_TIER_1_1 0x00100000 +#define D3D_SHADER_REQUIRES_SAMPLER_FEEDBACK 0x00200000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_TYPED_RESOURCE 0x00400000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_GROUP_SHARED 0x00800000 +#define D3D_SHADER_REQUIRES_DERIVATIVES_IN_MESH_AND_AMPLIFICATION_SHADERS 0x01000000 +#define D3D_SHADER_REQUIRES_RESOURCE_DESCRIPTOR_HEAP_INDEXING 0x02000000 +#define D3D_SHADER_REQUIRES_SAMPLER_DESCRIPTOR_HEAP_INDEXING 0x04000000 +#define D3D_SHADER_REQUIRES_WAVE_MMA 0x08000000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE 0x10000000 + +typedef struct _D3D12_LIBRARY_DESC +{ + LPCSTR Creator; // The name of the originator of the library. + UINT Flags; // Compilation flags. + UINT FunctionCount; // Number of functions exported from the library. +} D3D12_LIBRARY_DESC; + +typedef struct _D3D12_FUNCTION_DESC +{ + UINT Version; // Shader version + LPCSTR Creator; // Creator string + UINT Flags; // Shader compilation/parse flags + + UINT ConstantBuffers; // Number of constant buffers + UINT BoundResources; // Number of bound resources + + UINT InstructionCount; // Number of emitted instructions + UINT TempRegisterCount; // Number of temporary registers used + UINT TempArrayCount; // Number of temporary arrays used + UINT DefCount; // Number of constant defines + UINT DclCount; // Number of declarations (input + output) + UINT TextureNormalInstructions; // Number of non-categorized texture instructions + UINT TextureLoadInstructions; // Number of texture load instructions + UINT TextureCompInstructions; // Number of texture comparison instructions + UINT TextureBiasInstructions; // Number of texture bias instructions + UINT TextureGradientInstructions; // Number of texture gradient instructions + UINT FloatInstructionCount; // Number of floating point arithmetic instructions used + UINT IntInstructionCount; // Number of signed integer arithmetic instructions used + UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used + UINT StaticFlowControlCount; // Number of static flow control instructions used + UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used + UINT MacroInstructionCount; // Number of macro instructions used + UINT ArrayInstructionCount; // Number of array instructions used + UINT MovInstructionCount; // Number of mov instructions used + UINT MovcInstructionCount; // Number of movc instructions used + UINT ConversionInstructionCount; // Number of type conversion instructions used + UINT BitwiseInstructionCount; // Number of bitwise arithmetic instructions used + D3D_FEATURE_LEVEL MinFeatureLevel; // Min target of the function byte code + UINT64 RequiredFeatureFlags; // Required feature flags + + LPCSTR Name; // Function name + INT FunctionParameterCount; // Number of logical parameters in the function signature (not including return) + BOOL HasReturn; // TRUE, if function returns a value, false - it is a subroutine + BOOL Has10Level9VertexShader; // TRUE, if there is a 10L9 VS blob + BOOL Has10Level9PixelShader; // TRUE, if there is a 10L9 PS blob +} D3D12_FUNCTION_DESC; + +typedef struct _D3D12_PARAMETER_DESC +{ + LPCSTR Name; // Parameter name. + LPCSTR SemanticName; // Parameter semantic name (+index). + D3D_SHADER_VARIABLE_TYPE Type; // Element type. + D3D_SHADER_VARIABLE_CLASS Class; // Scalar/Vector/Matrix. + UINT Rows; // Rows are for matrix parameters. + UINT Columns; // Components or Columns in matrix. + D3D_INTERPOLATION_MODE InterpolationMode; // Interpolation mode. + D3D_PARAMETER_FLAGS Flags; // Parameter modifiers. + + UINT FirstInRegister; // The first input register for this parameter. + UINT FirstInComponent; // The first input register component for this parameter. + UINT FirstOutRegister; // The first output register for this parameter. + UINT FirstOutComponent; // The first output register component for this parameter. +} D3D12_PARAMETER_DESC; + + +////////////////////////////////////////////////////////////////////////////// +// Interfaces //////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3D12ShaderReflectionType ID3D12ShaderReflectionType; +typedef interface ID3D12ShaderReflectionType *LPD3D12SHADERREFLECTIONTYPE; + +typedef interface ID3D12ShaderReflectionVariable ID3D12ShaderReflectionVariable; +typedef interface ID3D12ShaderReflectionVariable *LPD3D12SHADERREFLECTIONVARIABLE; + +typedef interface ID3D12ShaderReflectionConstantBuffer ID3D12ShaderReflectionConstantBuffer; +typedef interface ID3D12ShaderReflectionConstantBuffer *LPD3D12SHADERREFLECTIONCONSTANTBUFFER; + +typedef interface ID3D12ShaderReflection ID3D12ShaderReflection; +typedef interface ID3D12ShaderReflection *LPD3D12SHADERREFLECTION; + +typedef interface ID3D12LibraryReflection ID3D12LibraryReflection; +typedef interface ID3D12LibraryReflection *LPD3D12LIBRARYREFLECTION; + +typedef interface ID3D12FunctionReflection ID3D12FunctionReflection; +typedef interface ID3D12FunctionReflection *LPD3D12FUNCTIONREFLECTION; + +typedef interface ID3D12FunctionParameterReflection ID3D12FunctionParameterReflection; +typedef interface ID3D12FunctionParameterReflection *LPD3D12FUNCTIONPARAMETERREFLECTION; + + +// {E913C351-783D-48CA-A1D1-4F306284AD56} +interface DECLSPEC_UUID("E913C351-783D-48CA-A1D1-4F306284AD56") ID3D12ShaderReflectionType; +DEFINE_GUID(IID_ID3D12ShaderReflectionType, +0xe913c351, 0x783d, 0x48ca, 0xa1, 0xd1, 0x4f, 0x30, 0x62, 0x84, 0xad, 0x56); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionType + +DECLARE_INTERFACE(ID3D12ShaderReflectionType) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_TYPE_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByName)(THIS_ _In_ LPCSTR Name) PURE; + STDMETHOD_(LPCSTR, GetMemberTypeName)(THIS_ _In_ UINT Index) PURE; + + STDMETHOD(IsEqual)(THIS_ _In_ ID3D12ShaderReflectionType* pType) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetSubType)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetBaseClass)(THIS) PURE; + STDMETHOD_(UINT, GetNumInterfaces)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetInterfaceByIndex)(THIS_ _In_ UINT uIndex) PURE; + STDMETHOD(IsOfType)(THIS_ _In_ ID3D12ShaderReflectionType* pType) PURE; + STDMETHOD(ImplementsInterface)(THIS_ _In_ ID3D12ShaderReflectionType* pBase) PURE; +}; + +// {8337A8A6-A216-444A-B2F4-314733A73AEA} +interface DECLSPEC_UUID("8337A8A6-A216-444A-B2F4-314733A73AEA") ID3D12ShaderReflectionVariable; +DEFINE_GUID(IID_ID3D12ShaderReflectionVariable, +0x8337a8a6, 0xa216, 0x444a, 0xb2, 0xf4, 0x31, 0x47, 0x33, 0xa7, 0x3a, 0xea); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionVariable + +DECLARE_INTERFACE(ID3D12ShaderReflectionVariable) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionType*, GetType)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetBuffer)(THIS) PURE; + + STDMETHOD_(UINT, GetInterfaceSlot)(THIS_ _In_ UINT uArrayIndex) PURE; +}; + +// {C59598B4-48B3-4869-B9B1-B1618B14A8B7} +interface DECLSPEC_UUID("C59598B4-48B3-4869-B9B1-B1618B14A8B7") ID3D12ShaderReflectionConstantBuffer; +DEFINE_GUID(IID_ID3D12ShaderReflectionConstantBuffer, +0xc59598b4, 0x48b3, 0x4869, 0xb9, 0xb1, 0xb1, 0x61, 0x8b, 0x14, 0xa8, 0xb7); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionConstantBuffer + +DECLARE_INTERFACE(ID3D12ShaderReflectionConstantBuffer) +{ + STDMETHOD(GetDesc)(THIS_ D3D12_SHADER_BUFFER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; +}; + +// The ID3D12ShaderReflection IID may change from SDK version to SDK version +// if the reflection API changes. This prevents new code with the new API +// from working with an old binary. Recompiling with the new header +// will pick up the new IID. + +// {5A58797D-A72C-478D-8BA2-EFC6B0EFE88E} +interface DECLSPEC_UUID("5A58797D-A72C-478D-8BA2-EFC6B0EFE88E") ID3D12ShaderReflection; +DEFINE_GUID(IID_ID3D12ShaderReflection, +0x5a58797d, 0xa72c, 0x478d, 0x8b, 0xa2, 0xef, 0xc6, 0xb0, 0xef, 0xe8, 0x8e); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflection + +DECLARE_INTERFACE_(ID3D12ShaderReflection, IUnknown) +{ + STDMETHOD(QueryInterface)(THIS_ _In_ REFIID iid, + _Out_ LPVOID *ppv) PURE; + STDMETHOD_(ULONG, AddRef)(THIS) PURE; + STDMETHOD_(ULONG, Release)(THIS) PURE; + + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetConstantBufferByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex, + _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) PURE; + + STDMETHOD(GetInputParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetOutputParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetPatchConstantParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name, + _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) PURE; + + STDMETHOD_(UINT, GetMovInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetMovcInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetConversionInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetBitwiseInstructionCount)(THIS) PURE; + + STDMETHOD_(D3D_PRIMITIVE, GetGSInputPrimitive)(THIS) PURE; + STDMETHOD_(BOOL, IsSampleFrequencyShader)(THIS) PURE; + + STDMETHOD_(UINT, GetNumInterfaceSlots)(THIS) PURE; + STDMETHOD(GetMinFeatureLevel)(THIS_ _Out_ enum D3D_FEATURE_LEVEL* pLevel) PURE; + + STDMETHOD_(UINT, GetThreadGroupSize)(THIS_ + _Out_opt_ UINT* pSizeX, + _Out_opt_ UINT* pSizeY, + _Out_opt_ UINT* pSizeZ) PURE; + + STDMETHOD_(UINT64, GetRequiresFlags)(THIS) PURE; +}; + +// {8E349D19-54DB-4A56-9DC9-119D87BDB804} +interface DECLSPEC_UUID("8E349D19-54DB-4A56-9DC9-119D87BDB804") ID3D12LibraryReflection; +DEFINE_GUID(IID_ID3D12LibraryReflection, +0x8e349d19, 0x54db, 0x4a56, 0x9d, 0xc9, 0x11, 0x9d, 0x87, 0xbd, 0xb8, 0x4); + +#undef INTERFACE +#define INTERFACE ID3D12LibraryReflection + +DECLARE_INTERFACE_(ID3D12LibraryReflection, IUnknown) +{ + STDMETHOD(QueryInterface)(THIS_ _In_ REFIID iid, _Out_ LPVOID * ppv) PURE; + STDMETHOD_(ULONG, AddRef)(THIS) PURE; + STDMETHOD_(ULONG, Release)(THIS) PURE; + + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_LIBRARY_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12FunctionReflection *, GetFunctionByIndex)(THIS_ _In_ INT FunctionIndex) PURE; +}; + +// {1108795C-2772-4BA9-B2A8-D464DC7E2799} +interface DECLSPEC_UUID("1108795C-2772-4BA9-B2A8-D464DC7E2799") ID3D12FunctionReflection; +DEFINE_GUID(IID_ID3D12FunctionReflection, +0x1108795c, 0x2772, 0x4ba9, 0xb2, 0xa8, 0xd4, 0x64, 0xdc, 0x7e, 0x27, 0x99); + +#undef INTERFACE +#define INTERFACE ID3D12FunctionReflection + +DECLARE_INTERFACE(ID3D12FunctionReflection) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_FUNCTION_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByIndex)(THIS_ _In_ UINT BufferIndex) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex, + _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable *, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name, + _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) PURE; + + // Use D3D_RETURN_PARAMETER_INDEX to get description of the return value. + STDMETHOD_(ID3D12FunctionParameterReflection *, GetFunctionParameter)(THIS_ _In_ INT ParameterIndex) PURE; +}; + +// {EC25F42D-7006-4F2B-B33E-02CC3375733F} +interface DECLSPEC_UUID("EC25F42D-7006-4F2B-B33E-02CC3375733F") ID3D12FunctionParameterReflection; +DEFINE_GUID(IID_ID3D12FunctionParameterReflection, +0xec25f42d, 0x7006, 0x4f2b, 0xb3, 0x3e, 0x2, 0xcc, 0x33, 0x75, 0x73, 0x3f); + +#undef INTERFACE +#define INTERFACE ID3D12FunctionParameterReflection + +DECLARE_INTERFACE(ID3D12FunctionParameterReflection) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_PARAMETER_DESC * pDesc) PURE; +}; + + +////////////////////////////////////////////////////////////////////////////// +// APIs ////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif //__D3D12SHADER_H__ + diff --git a/Nuake/dependencies/dxc/inc/dxcapi.h b/Nuake/dependencies/dxc/inc/dxcapi.h new file mode 100644 index 00000000..752041b7 --- /dev/null +++ b/Nuake/dependencies/dxc/inc/dxcapi.h @@ -0,0 +1,1309 @@ + +/////////////////////////////////////////////////////////////////////////////// +// // +// dxcapi.h // +// Copyright (C) Microsoft Corporation. All rights reserved. // +// This file is distributed under the University of Illinois Open Source // +// License. See LICENSE.TXT for details. // +// // +// Provides declarations for the DirectX Compiler API entry point. // +// // +/////////////////////////////////////////////////////////////////////////////// + +#ifndef __DXC_API__ +#define __DXC_API__ + +#ifdef _WIN32 +#ifndef DXC_API_IMPORT +#define DXC_API_IMPORT __declspec(dllimport) +#endif +#else +#ifndef DXC_API_IMPORT +#define DXC_API_IMPORT __attribute__((visibility("default"))) +#endif +#endif + +#ifdef _WIN32 + +#ifndef CROSS_PLATFORM_UUIDOF +// Warning: This macro exists in WinAdapter.h as well +#define CROSS_PLATFORM_UUIDOF(interface, spec) \ + struct __declspec(uuid(spec)) interface; +#endif + +#else + +#include "WinAdapter.h" +#include +#endif + +struct IMalloc; + +struct IDxcIncludeHandler; + +/// \brief Typedef for DxcCreateInstance function pointer. +/// +/// This can be used with GetProcAddress to get the DxcCreateInstance function. +typedef HRESULT(__stdcall *DxcCreateInstanceProc)(_In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID *ppv); + +/// \brief Typedef for DxcCreateInstance2 function pointer. +/// +/// This can be used with GetProcAddress to get the DxcCreateInstance2 function. +typedef HRESULT(__stdcall *DxcCreateInstance2Proc)(_In_ IMalloc *pMalloc, + _In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID *ppv); + +/// \brief Creates a single uninitialized object of the class associated with a +/// specified CLSID. +/// +/// \param rclsid The CLSID associated with the data and code that will be used +/// to create the object. +/// +/// \param riid A reference to the identifier of the interface to be used to +/// communicate with the object. +/// +/// \param ppv Address of pointer variable that receives the interface pointer +/// requested in riid. Upon successful return, *ppv contains the requested +/// interface pointer. Upon failure, *ppv contains NULL. +/// +/// While this function is similar to CoCreateInstance, there is no COM +/// involvement. +extern "C" DXC_API_IMPORT + HRESULT __stdcall DxcCreateInstance(_In_ REFCLSID rclsid, _In_ REFIID riid, + _Out_ LPVOID *ppv); + +/// \brief Version of DxcCreateInstance that takes an IMalloc interface. +/// +/// This can be used to create an instance of the compiler with a custom memory +/// allocator. +extern "C" DXC_API_IMPORT + HRESULT __stdcall DxcCreateInstance2(_In_ IMalloc *pMalloc, + _In_ REFCLSID rclsid, _In_ REFIID riid, + _Out_ LPVOID *ppv); + +// For convenience, equivalent definitions to CP_UTF8 and CP_UTF16. +#define DXC_CP_UTF8 65001 +#define DXC_CP_UTF16 1200 +#define DXC_CP_UTF32 12000 +// Use DXC_CP_ACP for: Binary; ANSI Text; Autodetect UTF with BOM +#define DXC_CP_ACP 0 + +/// Codepage for "wide" characters - UTF16 on Windows, UTF32 on other platforms. +#ifdef _WIN32 +#define DXC_CP_WIDE DXC_CP_UTF16 +#else +#define DXC_CP_WIDE DXC_CP_UTF32 +#endif + +/// Indicates that the shader hash was computed taking into account source +/// information (-Zss). +#define DXC_HASHFLAG_INCLUDES_SOURCE 1 + +/// Hash digest type for ShaderHash. +typedef struct DxcShaderHash { + UINT32 Flags; ///< DXC_HASHFLAG_* + BYTE HashDigest[16]; ///< The hash digest +} DxcShaderHash; + +#define DXC_FOURCC(ch0, ch1, ch2, ch3) \ + ((UINT32)(UINT8)(ch0) | (UINT32)(UINT8)(ch1) << 8 | \ + (UINT32)(UINT8)(ch2) << 16 | (UINT32)(UINT8)(ch3) << 24) +#define DXC_PART_PDB DXC_FOURCC('I', 'L', 'D', 'B') +#define DXC_PART_PDB_NAME DXC_FOURCC('I', 'L', 'D', 'N') +#define DXC_PART_PRIVATE_DATA DXC_FOURCC('P', 'R', 'I', 'V') +#define DXC_PART_ROOT_SIGNATURE DXC_FOURCC('R', 'T', 'S', '0') +#define DXC_PART_DXIL DXC_FOURCC('D', 'X', 'I', 'L') +#define DXC_PART_REFLECTION_DATA DXC_FOURCC('S', 'T', 'A', 'T') +#define DXC_PART_SHADER_HASH DXC_FOURCC('H', 'A', 'S', 'H') +#define DXC_PART_INPUT_SIGNATURE DXC_FOURCC('I', 'S', 'G', '1') +#define DXC_PART_OUTPUT_SIGNATURE DXC_FOURCC('O', 'S', 'G', '1') +#define DXC_PART_PATCH_CONSTANT_SIGNATURE DXC_FOURCC('P', 'S', 'G', '1') + +// Some option arguments are defined here for continuity with D3DCompile +// interface. +#define DXC_ARG_DEBUG L"-Zi" +#define DXC_ARG_SKIP_VALIDATION L"-Vd" +#define DXC_ARG_SKIP_OPTIMIZATIONS L"-Od" +#define DXC_ARG_PACK_MATRIX_ROW_MAJOR L"-Zpr" +#define DXC_ARG_PACK_MATRIX_COLUMN_MAJOR L"-Zpc" +#define DXC_ARG_AVOID_FLOW_CONTROL L"-Gfa" +#define DXC_ARG_PREFER_FLOW_CONTROL L"-Gfp" +#define DXC_ARG_ENABLE_STRICTNESS L"-Ges" +#define DXC_ARG_ENABLE_BACKWARDS_COMPATIBILITY L"-Gec" +#define DXC_ARG_IEEE_STRICTNESS L"-Gis" +#define DXC_ARG_OPTIMIZATION_LEVEL0 L"-O0" +#define DXC_ARG_OPTIMIZATION_LEVEL1 L"-O1" +#define DXC_ARG_OPTIMIZATION_LEVEL2 L"-O2" +#define DXC_ARG_OPTIMIZATION_LEVEL3 L"-O3" +#define DXC_ARG_WARNINGS_ARE_ERRORS L"-WX" +#define DXC_ARG_RESOURCES_MAY_ALIAS L"-res_may_alias" +#define DXC_ARG_ALL_RESOURCES_BOUND L"-all_resources_bound" +#define DXC_ARG_DEBUG_NAME_FOR_SOURCE L"-Zss" +#define DXC_ARG_DEBUG_NAME_FOR_BINARY L"-Zsb" + +CROSS_PLATFORM_UUIDOF(IDxcBlob, "8BA5FB08-5195-40e2-AC58-0D989C3A0102") +/// \brief A sized buffer that can be passed in and out of DXC APIs. +/// +/// This is an alias of ID3D10Blob and ID3DBlob. +struct IDxcBlob : public IUnknown { +public: + /// \brief Retrieves a pointer to the blob's data. + virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0; + + /// \brief Retrieves the size, in bytes, of the blob's data. + virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcBlobEncoding, "7241d424-2646-4191-97c0-98e96e42fc68") +/// \brief A blob that might have a known encoding. +struct IDxcBlobEncoding : public IDxcBlob { +public: + /// \brief Retrieve the encoding for this blob. + /// + /// \param pKnown Pointer to a variable that will be set to TRUE if the + /// encoding is known. + /// + /// \param pCodePage Pointer to variable that will be set to the encoding used + /// for this blog. + /// + /// If the encoding is not known then pCodePage will be set to CP_ACP. + virtual HRESULT STDMETHODCALLTYPE GetEncoding(_Out_ BOOL *pKnown, + _Out_ UINT32 *pCodePage) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcBlobWide, "A3F84EAB-0FAA-497E-A39C-EE6ED60B2D84") +/// \brief A blob containing a null-terminated wide string. +/// +/// This uses the native wide character encoding (utf16 on Windows, utf32 on +/// Linux). +/// +/// The value returned by GetBufferSize() is the size of the buffer, in bytes, +/// including the null-terminator. +/// +/// This interface is used to return output name strings DXC. Other string +/// output blobs, such as errors/warnings, preprocessed HLSL, or other text are +/// returned using encodings based on the -encoding option passed to the +/// compiler. +struct IDxcBlobWide : public IDxcBlobEncoding { +public: + /// \brief Retrieves a pointer to the string stored in this blob. + virtual LPCWSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; + + /// \brief Retrieves the length of the string stored in this blob, in + /// characters, excluding the null-terminator. + virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcBlobUtf8, "3DA636C9-BA71-4024-A301-30CBF125305B") +/// \brief A blob containing a UTF-8 encoded string. +/// +/// The value returned by GetBufferSize() is the size of the buffer, in bytes, +/// including the null-terminator. +/// +/// Depending on the -encoding option passed to the compiler, this interface is +/// used to return string output blobs, such as errors/warnings, preprocessed +/// HLSL, or other text. Output name strings always use IDxcBlobWide. +struct IDxcBlobUtf8 : public IDxcBlobEncoding { +public: + /// \brief Retrieves a pointer to the string stored in this blob. + virtual LPCSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; + + /// \brief Retrieves the length of the string stored in this blob, in + /// characters, excluding the null-terminator. + virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; +}; + +#ifdef _WIN32 +/// IDxcBlobUtf16 is a legacy alias for IDxcBlobWide on Win32. +typedef IDxcBlobWide IDxcBlobUtf16; +#endif + +CROSS_PLATFORM_UUIDOF(IDxcIncludeHandler, + "7f61fc7d-950d-467f-b3e3-3c02fb49187c") +/// \brief Interface for handling include directives. +/// +/// This interface can be implemented to customize handling of include +/// directives. +/// +/// Use IDxcUtils::CreateDefaultIncludeHandler to create a default +/// implementation that reads include files from the filesystem. +/// +struct IDxcIncludeHandler : public IUnknown { + /// \brief Load a source file to be included by the compiler. + /// + /// \param pFilename Candidate filename. + /// + /// \param ppIncludeSource Resultant source object for included file, nullptr + /// if not found. + virtual HRESULT STDMETHODCALLTYPE + LoadSource(_In_z_ LPCWSTR pFilename, + _COM_Outptr_result_maybenull_ IDxcBlob **ppIncludeSource) = 0; +}; + +/// \brief Structure for supplying bytes or text input to Dxc APIs. +typedef struct DxcBuffer { + /// \brief Pointer to the start of the buffer. + LPCVOID Ptr; + + /// \brief Size of the buffer in bytes. + SIZE_T Size; + + /// \brief Encoding of the buffer. + /// + /// Use Encoding = 0 for non-text bytes, ANSI text, or unknown with BOM. + UINT Encoding; +} DxcText; + +/// \brief Structure for supplying defines to Dxc APIs. +struct DxcDefine { + LPCWSTR Name; ///< The define name. + _Maybenull_ LPCWSTR Value; ///< Optional value for the define. +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompilerArgs, "73EFFE2A-70DC-45F8-9690-EFF64C02429D") +/// \brief Interface for managing arguments passed to DXC. +/// +/// Use IDxcUtils::BuildArguments to create an instance of this interface. +struct IDxcCompilerArgs : public IUnknown { + /// \brief Retrieve the array of arguments. + /// + /// This can be passed directly to the pArguments parameter of the Compile() + /// method. + virtual LPCWSTR *STDMETHODCALLTYPE GetArguments() = 0; + + /// \brief Retrieve the number of arguments. + /// + /// This can be passed directly to the argCount parameter of the Compile() + /// method. + virtual UINT32 STDMETHODCALLTYPE GetCount() = 0; + + /// \brief Add additional arguments to this list of compiler arguments. + virtual HRESULT STDMETHODCALLTYPE AddArguments( + _In_opt_count_(argCount) + LPCWSTR *pArguments, ///< Array of pointers to arguments to add. + _In_ UINT32 argCount ///< Number of arguments to add. + ) = 0; + + /// \brief Add additional UTF-8 encoded arguments to this list of compiler + /// arguments. + virtual HRESULT STDMETHODCALLTYPE AddArgumentsUTF8( + _In_opt_count_(argCount) + LPCSTR *pArguments, ///< Array of pointers to UTF-8 arguments to add. + _In_ UINT32 argCount ///< Number of arguments to add. + ) = 0; + + /// \brief Add additional defines to this list of compiler arguments. + virtual HRESULT STDMETHODCALLTYPE AddDefines( + _In_count_(defineCount) const DxcDefine *pDefines, ///< Array of defines. + _In_ UINT32 defineCount ///< Number of defines. + ) = 0; +}; + +////////////////////////// +// Legacy Interfaces +///////////////////////// + +CROSS_PLATFORM_UUIDOF(IDxcLibrary, "e5204dc7-d18c-4c3c-bdfb-851673980fe7") +/// \deprecated IDxcUtils replaces IDxcLibrary; please use IDxcUtils insted. +struct IDxcLibrary : public IUnknown { + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE SetMalloc(_In_opt_ IMalloc *pMalloc) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE + CreateBlobFromBlob(_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, + _COM_Outptr_ IDxcBlob **ppResult) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE + CreateBlobFromFile(_In_z_ LPCWSTR pFileName, _In_opt_ UINT32 *codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingFromPinned( + _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnHeapCopy( + _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnMalloc( + _In_bytecount_(size) LPCVOID pText, IMalloc *pIMalloc, UINT32 size, + UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE + CreateIncludeHandler(_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateStreamFromBlobReadOnly( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + // Renamed from GetBlobAsUtf16 to GetBlobAsWide + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + +#ifdef _WIN32 + // Alias to GetBlobAsWide on Win32 + /// \deprecated + inline HRESULT GetBlobAsUtf16(_In_ IDxcBlob *pBlob, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) { + return this->GetBlobAsWide(pBlob, pBlobEncoding); + } +#endif +}; + +CROSS_PLATFORM_UUIDOF(IDxcOperationResult, + "CEDB484A-D4E9-445A-B991-CA21CA157DC2") +/// \brief The results of a DXC operation. +/// +/// Note: IDxcResult replaces IDxcOperationResult and should be used wherever +/// possible. +struct IDxcOperationResult : public IUnknown { + /// \brief Retrieve the overall status of the operation. + virtual HRESULT STDMETHODCALLTYPE GetStatus(_Out_ HRESULT *pStatus) = 0; + + /// \brief Retrieve the primary output of the operation. + /// + /// This corresponds to: + /// * DXC_OUT_OBJECT - Compile() with shader or library target + /// * DXC_OUT_DISASSEMBLY - Disassemble() + /// * DXC_OUT_HLSL - Compile() with -P + /// * DXC_OUT_ROOT_SIGNATURE - Compile() with rootsig_* target + virtual HRESULT STDMETHODCALLTYPE + GetResult(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; + + /// \brief Retrieves the error buffer from the operation, if there is one. + /// + // This corresponds to calling IDxcResult::GetOutput() with DXC_OUT_ERRORS. + virtual HRESULT STDMETHODCALLTYPE + GetErrorBuffer(_COM_Outptr_result_maybenull_ IDxcBlobEncoding **ppErrors) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompiler, "8c210bf3-011f-4422-8d70-6f9acb8db617") +/// \deprecated Please use IDxcCompiler3 instead. +struct IDxcCompiler : public IUnknown { + /// \brief Compile a single entry point to the target shader model. + /// + /// \deprecated Please use IDxcCompiler3::Compile() instead. + virtual HRESULT STDMETHODCALLTYPE Compile( + _In_ IDxcBlob *pSource, // Source text to compile. + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in + // errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. + _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. + _In_opt_count_(argCount) + LPCWSTR *pArguments, // Array of pointers to arguments. + _In_ UINT32 argCount, // Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. + _In_ UINT32 defineCount, // Number of defines. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, // User-provided interface to handle #include + // directives (optional). + _COM_Outptr_ IDxcOperationResult * + *ppResult // Compiler output status, buffer, and errors. + ) = 0; + + /// \brief Preprocess source text. + /// + /// \deprecated Please use IDxcCompiler3::Compile() with the "-P" argument + /// instead. + virtual HRESULT STDMETHODCALLTYPE Preprocess( + _In_ IDxcBlob *pSource, // Source text to preprocess. + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in + // errors and include handlers. + _In_opt_count_(argCount) + LPCWSTR *pArguments, // Array of pointers to arguments. + _In_ UINT32 argCount, // Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. + _In_ UINT32 defineCount, // Number of defines. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, // user-provided interface to handle #include + // directives (optional). + _COM_Outptr_ IDxcOperationResult * + *ppResult // Preprocessor output status, buffer, and errors. + ) = 0; + + /// \brief Disassemble a program. + /// + /// \deprecated Please use IDxcCompiler3::Disassemble() instead. + virtual HRESULT STDMETHODCALLTYPE Disassemble( + _In_ IDxcBlob *pSource, // Program to disassemble. + _COM_Outptr_ IDxcBlobEncoding **ppDisassembly // Disassembly text. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompiler2, "A005A9D9-B8BB-4594-B5C9-0E633BEC4D37") +/// \deprecated Please use IDxcCompiler3 instead. +struct IDxcCompiler2 : public IDxcCompiler { + /// \brief Compile a single entry point to the target shader model with debug + /// information. + /// + /// \deprecated Please use IDxcCompiler3::Compile() instead. + virtual HRESULT STDMETHODCALLTYPE CompileWithDebug( + _In_ IDxcBlob *pSource, // Source text to compile. + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in + // errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. + _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. + _In_opt_count_(argCount) + LPCWSTR *pArguments, // Array of pointers to arguments. + _In_ UINT32 argCount, // Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. + _In_ UINT32 defineCount, // Number of defines. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, // user-provided interface to handle #include + // directives (optional). + _COM_Outptr_ IDxcOperationResult * + *ppResult, // Compiler output status, buffer, and errors. + _Outptr_opt_result_z_ LPWSTR + *ppDebugBlobName, // Suggested file name for debug blob. Must be + // CoTaskMemFree()'d. + _COM_Outptr_opt_ IDxcBlob **ppDebugBlob // Debug blob. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcLinker, "F1B5BE2A-62DD-4327-A1C2-42AC1E1E78E6") +/// \brief DXC linker interface. +/// +/// Use DxcCreateInstance with CLSID_DxcLinker to obtain an instance of this +/// interface. +struct IDxcLinker : public IUnknown { +public: + /// \brief Register a library with name to reference it later. + virtual HRESULT + RegisterLibrary(_In_opt_ LPCWSTR pLibName, ///< Name of the library. + _In_ IDxcBlob *pLib ///< Library blob. + ) = 0; + + /// \brief Links the shader and produces a shader blob that the Direct3D + /// runtime can use. + virtual HRESULT STDMETHODCALLTYPE Link( + _In_opt_ LPCWSTR pEntryName, ///< Entry point name. + _In_ LPCWSTR pTargetProfile, ///< shader profile to link. + _In_count_(libCount) + const LPCWSTR *pLibNames, ///< Array of library names to link. + _In_ UINT32 libCount, ///< Number of libraries to link. + _In_opt_count_(argCount) + const LPCWSTR *pArguments, ///< Array of pointers to arguments. + _In_ UINT32 argCount, ///< Number of arguments. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Linker output status, buffer, and errors. + ) = 0; +}; + +///////////////////////// +// Latest interfaces. Please use these. +//////////////////////// + +CROSS_PLATFORM_UUIDOF(IDxcUtils, "4605C4CB-2019-492A-ADA4-65F20BB7D67F") +/// \brief Various utility functions for DXC. +/// +/// Use DxcCreateInstance with CLSID_DxcUtils to obtain an instance of this +/// interface. +/// +/// IDxcUtils replaces IDxcLibrary. +struct IDxcUtils : public IUnknown { + /// \brief Create a sub-blob that holds a reference to the outer blob and + /// points to its memory. + /// + /// \param pBlob The outer blob. + /// + /// \param offset The offset inside the outer blob. + /// + /// \param length The size, in bytes, of the buffer to reference from the + /// output blob. + /// + /// \param ppResult Address of the pointer that receives a pointer to the + /// newly created blob. + virtual HRESULT STDMETHODCALLTYPE + CreateBlobFromBlob(_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, + _COM_Outptr_ IDxcBlob **ppResult) = 0; + + // For codePage, use 0 (or DXC_CP_ACP) for raw binary or ANSI code page. + + /// \brief Create a blob referencing existing memory, with no copy. + /// + /// \param pData Pointer to buffer containing the contents of the new blob. + /// + /// \param size The size of the pData buffer, in bytes. + /// + /// \param codePage The code page to use if the blob contains text. Use + /// DXC_CP_ACP for binary or ANSI code page. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// The user must manage the memory lifetime separately. + /// + /// This replaces IDxcLibrary::CreateBlobWithEncodingFromPinned. + virtual HRESULT STDMETHODCALLTYPE CreateBlobFromPinned( + _In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a blob, taking ownership of memory allocated with the + /// supplied allocator. + /// + /// \param pData Pointer to buffer containing the contents of the new blob. + /// + /// \param pIMalloc The memory allocator to use. + /// + /// \param size The size of thee pData buffer, in bytes. + /// + /// \param codePage The code page to use if the blob contains text. Use + /// DXC_CP_ACP for binary or ANSI code page. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// This replaces IDxcLibrary::CreateBlobWithEncodingOnMalloc. + virtual HRESULT STDMETHODCALLTYPE MoveToBlob( + _In_bytecount_(size) LPCVOID pData, IMalloc *pIMalloc, UINT32 size, + UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a blob containing a copy of the existing data. + /// + /// \param pData Pointer to buffer containing the contents of the new blob. + /// + /// \param size The size of thee pData buffer, in bytes. + /// + /// \param codePage The code page to use if the blob contains text. Use + /// DXC_CP_ACP for binary or ANSI code page. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// The new blob and its contents are allocated with the current allocator. + /// This replaces IDxcLibrary::CreateBlobWithEncodingOnHeapCopy. + virtual HRESULT STDMETHODCALLTYPE + CreateBlob(_In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a blob with data loaded from a file. + /// + /// \param pFileName The name of the file to load from. + /// + /// \param pCodePage Optional code page to use if the blob contains text. Pass + /// NULL for binary data. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// The new blob and its contents are allocated with the current allocator. + /// This replaces IDxcLibrary::CreateBlobFromFile. + virtual HRESULT STDMETHODCALLTYPE + LoadFile(_In_z_ LPCWSTR pFileName, _In_opt_ UINT32 *pCodePage, + _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a stream that reads data from a blob. + /// + /// \param pBlob The blob to read from. + /// + /// \param ppStream Address of the pointer that receives a pointer to the + /// newly created stream. + virtual HRESULT STDMETHODCALLTYPE CreateReadOnlyStreamFromBlob( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; + + /// \brief Create default file-based include handler. + /// + /// \param ppResult Address of the pointer that receives a pointer to the + /// newly created include handler. + virtual HRESULT STDMETHODCALLTYPE + CreateDefaultIncludeHandler(_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; + + /// \brief Convert or return matching encoded text blob as UTF-8. + /// + /// \param pBlob The blob to convert. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobUtf8 **ppBlobEncoding) = 0; + + /// \brief Convert or return matching encoded text blob as UTF-16. + /// + /// \param pBlob The blob to convert. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobWide **ppBlobEncoding) = 0; + +#ifdef _WIN32 + /// \brief Convert or return matching encoded text blob as UTF-16. + /// + /// \param pBlob The blob to convert. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// Alias to GetBlobAsWide on Win32. + inline HRESULT GetBlobAsUtf16(_In_ IDxcBlob *pBlob, + _COM_Outptr_ IDxcBlobWide **ppBlobEncoding) { + return this->GetBlobAsWide(pBlob, ppBlobEncoding); + } +#endif + + /// \brief Retrieve a single part from a DXIL container. + /// + /// \param pShader The shader to retrieve the part from. + /// + /// \param DxcPart The part to retrieve (eg DXC_PART_ROOT_SIGNATURE). + /// + /// \param ppPartData Address of the pointer that receives a pointer to the + /// part. + /// + /// \param pPartSizeInBytes Address of the pointer that receives the size of + /// the part. + /// + /// The returned pointer points inside the buffer passed in pShader. + virtual HRESULT STDMETHODCALLTYPE + GetDxilContainerPart(_In_ const DxcBuffer *pShader, _In_ UINT32 DxcPart, + _Outptr_result_nullonfailure_ void **ppPartData, + _Out_ UINT32 *pPartSizeInBytes) = 0; + + /// \brief Create reflection interface from serialized DXIL container or the + /// DXC_OUT_REFLECTION blob contents. + /// + /// \param pData The source data. + /// + /// \param iid The interface ID of the reflection interface to create. + /// + /// \param ppvReflection Address of the pointer that receives a pointer to the + /// newly created reflection interface. + /// + /// Use this with interfaces such as ID3D12ShaderReflection. + virtual HRESULT STDMETHODCALLTYPE CreateReflection( + _In_ const DxcBuffer *pData, REFIID iid, void **ppvReflection) = 0; + + /// \brief Build arguments that can be passed to the Compile method. + virtual HRESULT STDMETHODCALLTYPE BuildArguments( + _In_opt_z_ LPCWSTR pSourceName, ///< Optional file name for pSource. Used + ///< in errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, ///< Entry point name (-E). + _In_z_ LPCWSTR pTargetProfile, ///< Shader profile to compile (-T). + _In_opt_count_(argCount) + LPCWSTR *pArguments, ///< Array of pointers to arguments. + _In_ UINT32 argCount, ///< Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, ///< Array of defines. + _In_ UINT32 defineCount, ///< Number of defines. + _COM_Outptr_ IDxcCompilerArgs * + *ppArgs ///< Arguments you can use with Compile() method. + ) = 0; + + /// \brief Retrieve the hash and contents of a shader PDB. + /// + /// \param pPDBBlob The blob containing the PDB. + /// + /// \param ppHash Address of the pointer that receives a pointer to the hash + /// blob. + /// + /// \param ppContainer Address of the pointer that receives a pointer to the + /// bloc containing the contents of the PDB. + /// + virtual HRESULT STDMETHODCALLTYPE + GetPDBContents(_In_ IDxcBlob *pPDBBlob, _COM_Outptr_ IDxcBlob **ppHash, + _COM_Outptr_ IDxcBlob **ppContainer) = 0; +}; + +/// \brief Specifies the kind of output to retrieve from a IDxcResult. +/// +/// Note: text outputs returned from version 2 APIs are UTF-8 or UTF-16 based on +/// the -encoding option passed to the compiler. +typedef enum DXC_OUT_KIND { + DXC_OUT_NONE = 0, ///< No output. + DXC_OUT_OBJECT = 1, ///< IDxcBlob - Shader or library object. + DXC_OUT_ERRORS = 2, ///< IDxcBlobUtf8 or IDxcBlobWide. + DXC_OUT_PDB = 3, ///< IDxcBlob. + DXC_OUT_SHADER_HASH = 4, ///< IDxcBlob - DxcShaderHash of shader or shader + ///< with source info (-Zsb/-Zss). + DXC_OUT_DISASSEMBLY = 5, ///< IDxcBlobUtf8 or IDxcBlobWide - from Disassemble. + DXC_OUT_HLSL = + 6, ///< IDxcBlobUtf8 or IDxcBlobWide - from Preprocessor or Rewriter. + DXC_OUT_TEXT = 7, ///< IDxcBlobUtf8 or IDxcBlobWide - other text, such as + ///< -ast-dump or -Odump. + DXC_OUT_REFLECTION = 8, ///< IDxcBlob - RDAT part with reflection data. + DXC_OUT_ROOT_SIGNATURE = 9, ///< IDxcBlob - Serialized root signature output. + DXC_OUT_EXTRA_OUTPUTS = 10, ///< IDxcExtraOutputs - Extra outputs. + DXC_OUT_REMARKS = + 11, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. + DXC_OUT_TIME_REPORT = + 12, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. + DXC_OUT_TIME_TRACE = + 13, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. + + DXC_OUT_LAST = DXC_OUT_TIME_TRACE, ///< Last value for a counter. + + DXC_OUT_NUM_ENUMS, + DXC_OUT_FORCE_DWORD = 0xFFFFFFFF +} DXC_OUT_KIND; + +static_assert(DXC_OUT_NUM_ENUMS == DXC_OUT_LAST + 1, + "DXC_OUT_* Enum added and last value not updated."); + +CROSS_PLATFORM_UUIDOF(IDxcResult, "58346CDA-DDE7-4497-9461-6F87AF5E0659") +/// \brief Result of a DXC operation. +/// +/// DXC operations may have multiple outputs, such as a shader object and +/// errors. This interface provides access to the outputs. +struct IDxcResult : public IDxcOperationResult { + /// \brief Determines whether or not this result has the specified output. + /// + /// \param dxcOutKind The kind of output to check for. + virtual BOOL STDMETHODCALLTYPE HasOutput(_In_ DXC_OUT_KIND dxcOutKind) = 0; + + /// \brief Retrieves the specified output. + /// + /// \param dxcOutKind The kind of output to retrieve. + /// + /// \param iid The interface ID of the output interface. + /// + /// \param ppvObject Address of the pointer that receives a pointer to the + /// output. + /// + /// \param ppOutputName Optional address of a pointer to receive the name + /// blob, if there is one. + virtual HRESULT STDMETHODCALLTYPE + GetOutput(_In_ DXC_OUT_KIND dxcOutKind, _In_ REFIID iid, + _COM_Outptr_opt_result_maybenull_ void **ppvObject, + _COM_Outptr_ IDxcBlobWide **ppOutputName) = 0; + + /// \brief Retrieves the number of outputs available in this result. + virtual UINT32 GetNumOutputs() = 0; + + /// \brief Retrieves the output kind at the specified index. + virtual DXC_OUT_KIND GetOutputByIndex(UINT32 Index) = 0; + + /// \brief Retrieves the primary output kind for this result. + /// + /// See IDxcOperationResult::GetResult() for more information on the primary + /// output kinds. + virtual DXC_OUT_KIND PrimaryOutput() = 0; +}; + +// Special names for extra output that should get written to specific streams. +#define DXC_EXTRA_OUTPUT_NAME_STDOUT L"*stdout*" +#define DXC_EXTRA_OUTPUT_NAME_STDERR L"*stderr*" + +CROSS_PLATFORM_UUIDOF(IDxcExtraOutputs, "319b37a2-a5c2-494a-a5de-4801b2faf989") +/// \brief Additional outputs from a DXC operation. +/// +/// This can be used to obtain outputs that don't have an explicit DXC_OUT_KIND. +/// Use DXC_OUT_EXTRA_OUTPUTS to obtain instances of this. +struct IDxcExtraOutputs : public IUnknown { + /// \brief Retrieves the number of outputs available + virtual UINT32 STDMETHODCALLTYPE GetOutputCount() = 0; + + /// \brief Retrieves the specified output. + /// + /// \param uIndex The index of the output to retrieve. + /// + /// \param iid The interface ID of the output interface. + /// + /// \param ppvObject Optional address of the pointer that receives a pointer + /// to the output if there is one. + /// + /// \param ppOutputType Optional address of the pointer that receives the + /// output type name blob if there is one. + /// + /// \param ppOutputName Optional address of the pointer that receives the + /// output name blob if there is one. + virtual HRESULT STDMETHODCALLTYPE + GetOutput(_In_ UINT32 uIndex, _In_ REFIID iid, + _COM_Outptr_opt_result_maybenull_ void **ppvObject, + _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputType, + _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputName) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompiler3, "228B4687-5A6A-4730-900C-9702B2203F54") +/// \brief Interface to the DirectX Shader Compiler. +/// +/// Use DxcCreateInstance with CLSID_DxcCompiler to obtain an instance of this +/// interface. +struct IDxcCompiler3 : public IUnknown { + /// \brief Compile a shader. + /// + /// IDxcUtils::BuildArguments can be used to assist building the pArguments + /// and argCount parameters. + /// + /// Depending on the arguments, this method can be used to: + /// + /// * Compile a single entry point to the target shader model, + /// * Compile a library to a library target (-T lib_*) + /// * Compile a root signature (-T rootsig_*), + /// * Preprocess HLSL source (-P). + virtual HRESULT STDMETHODCALLTYPE Compile( + _In_ const DxcBuffer *pSource, ///< Source text to compile. + _In_opt_count_(argCount) + LPCWSTR *pArguments, ///< Array of pointers to arguments. + _In_ UINT32 argCount, ///< Number of arguments. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, ///< user-provided interface to handle include + ///< directives (optional). + _In_ REFIID riid, ///< Interface ID for the result. + _Out_ LPVOID *ppResult ///< IDxcResult: status, buffer, and errors. + ) = 0; + + /// \brief Disassemble a program. + virtual HRESULT STDMETHODCALLTYPE Disassemble( + _In_ const DxcBuffer + *pObject, ///< Program to disassemble: dxil container or bitcode. + _In_ REFIID riid, ///< Interface ID for the result. + _Out_ LPVOID + *ppResult ///< IDxcResult: status, disassembly text, and errors. + ) = 0; +}; + +static const UINT32 DxcValidatorFlags_Default = 0; +static const UINT32 DxcValidatorFlags_InPlaceEdit = + 1; // Validator is allowed to update shader blob in-place. +static const UINT32 DxcValidatorFlags_RootSignatureOnly = 2; +static const UINT32 DxcValidatorFlags_ModuleOnly = 4; +static const UINT32 DxcValidatorFlags_ValidMask = 0x7; + +CROSS_PLATFORM_UUIDOF(IDxcValidator, "A6E82BD2-1FD7-4826-9811-2857E797F49A") +/// \brief Interface to DXC shader validator. +/// +/// Use DxcCreateInstance with CLSID_DxcValidator to obtain an instance of this. +struct IDxcValidator : public IUnknown { + /// \brief Validate a shader. + virtual HRESULT STDMETHODCALLTYPE Validate( + _In_ IDxcBlob *pShader, ///< Shader to validate. + _In_ UINT32 Flags, ///< Validation flags. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Validation output status, buffer, and errors. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcValidator2, "458e1fd1-b1b2-4750-a6e1-9c10f03bed92") +/// \brief Interface to DXC shader validator. +/// +/// Use DxcCreateInstance with CLSID_DxcValidator to obtain an instance of this. +struct IDxcValidator2 : public IDxcValidator { + /// \brief Validate a shader with optional debug bitcode. + virtual HRESULT STDMETHODCALLTYPE ValidateWithDebug( + _In_ IDxcBlob *pShader, ///< Shader to validate. + _In_ UINT32 Flags, ///< Validation flags. + _In_opt_ DxcBuffer *pOptDebugBitcode, ///< Optional debug module bitcode + ///< to provide line numbers. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Validation output status, buffer, and errors. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcContainerBuilder, + "334b1f50-2292-4b35-99a1-25588d8c17fe") +/// \brief Interface to DXC container builder. +/// +/// Use DxcCreateInstance with CLSID_DxcContainerBuilder to obtain an instance +/// of this. +struct IDxcContainerBuilder : public IUnknown { + /// \brief Load a DxilContainer to the builder. + virtual HRESULT STDMETHODCALLTYPE + Load(_In_ IDxcBlob *pDxilContainerHeader) = 0; + + /// \brief Add a part to the container. + /// + /// \param fourCC The part identifier (eg DXC_PART_PDB). + /// + /// \param pSource The source blob. + virtual HRESULT STDMETHODCALLTYPE AddPart(_In_ UINT32 fourCC, + _In_ IDxcBlob *pSource) = 0; + + /// \brief Remove a part from the container. + /// + /// \param fourCC The part identifier (eg DXC_PART_PDB). + /// + /// \return S_OK on success, DXC_E_MISSING_PART if the part was not found, or + /// other standard HRESULT error code. + virtual HRESULT STDMETHODCALLTYPE RemovePart(_In_ UINT32 fourCC) = 0; + + /// \brief Build the container. + /// + /// \param ppResult Pointer to variable to receive the result. + virtual HRESULT STDMETHODCALLTYPE + SerializeContainer(_Out_ IDxcOperationResult **ppResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcAssembler, "091f7a26-1c1f-4948-904b-e6e3a8a771d5") +/// \brief Interface to DxcAssembler. +/// +/// Use DxcCreateInstance with CLSID_DxcAssembler to obtain an instance of this. +struct IDxcAssembler : public IUnknown { + /// \brief Assemble DXIL in LL or LLVM bitcode to DXIL container. + virtual HRESULT STDMETHODCALLTYPE AssembleToContainer( + _In_ IDxcBlob *pShader, ///< Shader to assemble. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Assembly output status, buffer, and errors. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcContainerReflection, + "d2c21b26-8350-4bdc-976a-331ce6f4c54c") +/// \brief Interface to DxcContainerReflection. +/// +/// Use DxcCreateInstance with CLSID_DxcContainerReflection to obtain an +/// instance of this. +struct IDxcContainerReflection : public IUnknown { + /// \brief Choose the container to perform reflection on + /// + /// \param pContainer The container to load. If null is passed then this + /// instance will release any held resources. + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainer) = 0; + + /// \brief Retrieves the number of parts in the container. + /// + /// \param pResult Pointer to variable to receive the result. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), or other standard HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE GetPartCount(_Out_ UINT32 *pResult) = 0; + + /// \brief Retrieve the kind of a specified part. + /// + /// \param idx The index of the part to retrieve the kind of. + /// + /// \param pResult Pointer to variable to receive the result. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard + /// HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE GetPartKind(UINT32 idx, + _Out_ UINT32 *pResult) = 0; + + /// \brief Retrieve the content of a specified part. + /// + /// \param idx The index of the part to retrieve. + /// + /// \param ppResult Pointer to variable to receive the result. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard + /// HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE + GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) = 0; + + /// \brief Retrieve the index of the first part with the specified kind. + /// + /// \param kind The kind to search for. + /// + /// \param pResult Pointer to variable to receive the index of the matching + /// part. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), HRESULT_FROM_WIN32(ERROR_NOT_FOUND) if there is no + /// part with the specified kind, or other standard HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE + FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) = 0; + + /// \brief Retrieve the reflection interface for a specified part. + /// + /// \param idx The index of the part to retrieve the reflection interface of. + /// + /// \param iid The IID of the interface to retrieve. + /// + /// \param ppvObject Pointer to variable to receive the result. + /// + /// Use this with interfaces such as ID3D12ShaderReflection. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard + /// HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE GetPartReflection(UINT32 idx, REFIID iid, + void **ppvObject) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcOptimizerPass, "AE2CD79F-CC22-453F-9B6B-B124E7A5204C") +/// \brief An optimizer pass. +/// +/// Instances of this can be obtained via IDxcOptimizer::GetAvailablePass. +struct IDxcOptimizerPass : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetOptionName(_COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDescription(_COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetOptionArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetOptionArgName(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetOptionArgDescription(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcOptimizer, "25740E2E-9CBA-401B-9119-4FB42F39F270") +/// \brief Interface to DxcOptimizer. +/// +/// Use DxcCreateInstance with CLSID_DxcOptimizer to obtain an instance of this. +struct IDxcOptimizer : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetAvailablePassCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetAvailablePass(UINT32 index, _COM_Outptr_ IDxcOptimizerPass **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + RunOptimizer(IDxcBlob *pBlob, _In_count_(optionCount) LPCWSTR *ppOptions, + UINT32 optionCount, _COM_Outptr_ IDxcBlob **pOutputModule, + _COM_Outptr_opt_ IDxcBlobEncoding **ppOutputText) = 0; +}; + +static const UINT32 DxcVersionInfoFlags_None = 0; +static const UINT32 DxcVersionInfoFlags_Debug = 1; // Matches VS_FF_DEBUG +static const UINT32 DxcVersionInfoFlags_Internal = + 2; // Internal Validator (non-signing) + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo, "b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e") +/// \brief PDB Version information. +/// +/// Use IDxcPdbUtils2::GetVersionInfo to obtain an instance of this. +struct IDxcVersionInfo : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetVersion(_Out_ UINT32 *pMajor, + _Out_ UINT32 *pMinor) = 0; + virtual HRESULT STDMETHODCALLTYPE GetFlags(_Out_ UINT32 *pFlags) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo2, "fb6904c4-42f0-4b62-9c46-983af7da7c83") +/// \brief PDB Version Information. +/// +/// Use IDxcPdbUtils2::GetVersionInfo to obtain a IDxcVersionInfo interface, and +/// then use QueryInterface to obtain an instance of this interface from it. +struct IDxcVersionInfo2 : public IDxcVersionInfo { + virtual HRESULT STDMETHODCALLTYPE GetCommitInfo( + _Out_ UINT32 *pCommitCount, ///< The total number commits. + _Outptr_result_z_ char **pCommitHash ///< The SHA of the latest commit. + ///< Must be CoTaskMemFree()'d. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo3, "5e13e843-9d25-473c-9ad2-03b2d0b44b1e") +/// \brief PDB Version Information. +/// +/// Use IDxcPdbUtils2::GetVersionInfo to obtain a IDxcVersionInfo interface, and +/// then use QueryInterface to obtain an instance of this interface from it. +struct IDxcVersionInfo3 : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetCustomVersionString( + _Outptr_result_z_ char * + *pVersionString ///< Custom version string for compiler. Must be + ///< CoTaskMemFree()'d. + ) = 0; +}; + +struct DxcArgPair { + const WCHAR *pName; + const WCHAR *pValue; +}; + +CROSS_PLATFORM_UUIDOF(IDxcPdbUtils, "E6C9647E-9D6A-4C3B-B94C-524B5A6C343D") +/// \deprecated Please use IDxcPdbUtils2 instead. +struct IDxcPdbUtils : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSourceName(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFlag(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetArg(_In_ UINT32 uIndex, + _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetArgPair(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pName, + _Outptr_result_z_ BSTR *pValue) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDefine(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetTargetProfile(_Outptr_result_z_ BSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetEntryPoint(_Outptr_result_z_ BSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetMainFileName(_Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetHash(_COM_Outptr_ IDxcBlob **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetName(_Outptr_result_z_ BSTR *pResult) = 0; + + virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFullPDB(_COM_Outptr_ IDxcBlob **ppFullPDB) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetVersionInfo(_COM_Outptr_ IDxcVersionInfo **ppVersionInfo) = 0; + + virtual HRESULT STDMETHODCALLTYPE + SetCompiler(_In_ IDxcCompiler3 *pCompiler) = 0; + virtual HRESULT STDMETHODCALLTYPE + CompileForFullPDB(_COM_Outptr_ IDxcResult **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE OverrideArgs(_In_ DxcArgPair *pArgPairs, + UINT32 uNumArgPairs) = 0; + virtual HRESULT STDMETHODCALLTYPE + OverrideRootSignature(_In_ const WCHAR *pRootSignature) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcPdbUtils2, "4315D938-F369-4F93-95A2-252017CC3807") +/// \brief DxcPdbUtils interface. +/// +/// Use DxcCreateInstance with CLSID_DxcPdbUtils to create an instance of this. +struct IDxcPdbUtils2 : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSourceName(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetLibraryPDBCount(UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetLibraryPDB( + _In_ UINT32 uIndex, _COM_Outptr_ IDxcPdbUtils2 **ppOutPdbUtils, + _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppLibraryName) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFlag(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetArg(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetArgPair( + _In_ UINT32 uIndex, _COM_Outptr_result_maybenull_ IDxcBlobWide **ppName, + _COM_Outptr_result_maybenull_ IDxcBlobWide **ppValue) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDefine(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetTargetProfile(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetEntryPoint(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetMainFileName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetHash(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetVersionInfo( + _COM_Outptr_result_maybenull_ IDxcVersionInfo **ppVersionInfo) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainID(_Out_ UINT32 *pID) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetCustomToolchainData(_COM_Outptr_result_maybenull_ IDxcBlob **ppBlob) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetWholeDxil(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; + + virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0; + virtual BOOL STDMETHODCALLTYPE IsPDBRef() = 0; +}; + +// Note: __declspec(selectany) requires 'extern' +// On Linux __declspec(selectany) is removed and using 'extern' results in link +// error. +#ifdef _MSC_VER +#define CLSID_SCOPE __declspec(selectany) extern +#else +#define CLSID_SCOPE +#endif + +CLSID_SCOPE const CLSID CLSID_DxcCompiler = { + 0x73e22d93, + 0xe6ce, + 0x47f3, + {0xb5, 0xbf, 0xf0, 0x66, 0x4f, 0x39, 0xc1, 0xb0}}; + +// {EF6A8087-B0EA-4D56-9E45-D07E1A8B7806} +CLSID_SCOPE const GUID CLSID_DxcLinker = { + 0xef6a8087, + 0xb0ea, + 0x4d56, + {0x9e, 0x45, 0xd0, 0x7e, 0x1a, 0x8b, 0x78, 0x6}}; + +// {CD1F6B73-2AB0-484D-8EDC-EBE7A43CA09F} +CLSID_SCOPE const CLSID CLSID_DxcDiaDataSource = { + 0xcd1f6b73, + 0x2ab0, + 0x484d, + {0x8e, 0xdc, 0xeb, 0xe7, 0xa4, 0x3c, 0xa0, 0x9f}}; + +// {3E56AE82-224D-470F-A1A1-FE3016EE9F9D} +CLSID_SCOPE const CLSID CLSID_DxcCompilerArgs = { + 0x3e56ae82, + 0x224d, + 0x470f, + {0xa1, 0xa1, 0xfe, 0x30, 0x16, 0xee, 0x9f, 0x9d}}; + +// {6245D6AF-66E0-48FD-80B4-4D271796748C} +CLSID_SCOPE const GUID CLSID_DxcLibrary = { + 0x6245d6af, + 0x66e0, + 0x48fd, + {0x80, 0xb4, 0x4d, 0x27, 0x17, 0x96, 0x74, 0x8c}}; + +CLSID_SCOPE const GUID CLSID_DxcUtils = CLSID_DxcLibrary; + +// {8CA3E215-F728-4CF3-8CDD-88AF917587A1} +CLSID_SCOPE const GUID CLSID_DxcValidator = { + 0x8ca3e215, + 0xf728, + 0x4cf3, + {0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1}}; + +// {D728DB68-F903-4F80-94CD-DCCF76EC7151} +CLSID_SCOPE const GUID CLSID_DxcAssembler = { + 0xd728db68, + 0xf903, + 0x4f80, + {0x94, 0xcd, 0xdc, 0xcf, 0x76, 0xec, 0x71, 0x51}}; + +// {b9f54489-55b8-400c-ba3a-1675e4728b91} +CLSID_SCOPE const GUID CLSID_DxcContainerReflection = { + 0xb9f54489, + 0x55b8, + 0x400c, + {0xba, 0x3a, 0x16, 0x75, 0xe4, 0x72, 0x8b, 0x91}}; + +// {AE2CD79F-CC22-453F-9B6B-B124E7A5204C} +CLSID_SCOPE const GUID CLSID_DxcOptimizer = { + 0xae2cd79f, + 0xcc22, + 0x453f, + {0x9b, 0x6b, 0xb1, 0x24, 0xe7, 0xa5, 0x20, 0x4c}}; + +// {94134294-411f-4574-b4d0-8741e25240d2} +CLSID_SCOPE const GUID CLSID_DxcContainerBuilder = { + 0x94134294, + 0x411f, + 0x4574, + {0xb4, 0xd0, 0x87, 0x41, 0xe2, 0x52, 0x40, 0xd2}}; + +// {54621dfb-f2ce-457e-ae8c-ec355faeec7c} +CLSID_SCOPE const GUID CLSID_DxcPdbUtils = { + 0x54621dfb, + 0xf2ce, + 0x457e, + {0xae, 0x8c, 0xec, 0x35, 0x5f, 0xae, 0xec, 0x7c}}; + +#endif diff --git a/Nuake/dependencies/dxc/inc/dxcerrors.h b/Nuake/dependencies/dxc/inc/dxcerrors.h new file mode 100644 index 00000000..ce50b83e --- /dev/null +++ b/Nuake/dependencies/dxc/inc/dxcerrors.h @@ -0,0 +1,30 @@ +/////////////////////////////////////////////////////////////////////////////// +// // +// dxcerror.h // +// Copyright (C) Microsoft Corporation. All rights reserved. // +// This file is distributed under the University of Illinois Open Source // +// License. See LICENSE.TXT for details. // +// // +// Provides definition of error codes. // +// // +/////////////////////////////////////////////////////////////////////////////// + +#ifndef __DXC_ERRORS__ +#define __DXC_ERRORS__ + +#ifndef FACILITY_GRAPHICS +#define FACILITY_GRAPHICS 36 +#endif + +#define DXC_EXCEPTION_CODE(name, status) \ + static constexpr DWORD EXCEPTION_##name = \ + (0xc0000000u | (FACILITY_GRAPHICS << 16) | \ + (0xff00u | (status & 0xffu))); + +DXC_EXCEPTION_CODE(LOAD_LIBRARY_FAILED, 0x00u) +DXC_EXCEPTION_CODE(NO_HMODULE, 0x01u) +DXC_EXCEPTION_CODE(GET_PROC_FAILED, 0x02u) + +#undef DXC_EXCEPTION_CODE + +#endif diff --git a/Nuake/dependencies/dxc/inc/dxcisense.h b/Nuake/dependencies/dxc/inc/dxcisense.h new file mode 100644 index 00000000..661de168 --- /dev/null +++ b/Nuake/dependencies/dxc/inc/dxcisense.h @@ -0,0 +1,959 @@ +/////////////////////////////////////////////////////////////////////////////// +// // +// dxcisense.h // +// Copyright (C) Microsoft Corporation. All rights reserved. // +// This file is distributed under the University of Illinois Open Source // +// License. See LICENSE.TXT for details. // +// // +// Provides declarations for the DirectX Compiler IntelliSense component. // +// // +/////////////////////////////////////////////////////////////////////////////// + +#ifndef __DXC_ISENSE__ +#define __DXC_ISENSE__ + +#include "dxcapi.h" +#ifndef _WIN32 +#include "WinAdapter.h" +#endif + +typedef enum DxcGlobalOptions { + DxcGlobalOpt_None = 0x0, + DxcGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1, + DxcGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2, + DxcGlobalOpt_ThreadBackgroundPriorityForAll = + DxcGlobalOpt_ThreadBackgroundPriorityForIndexing | + DxcGlobalOpt_ThreadBackgroundPriorityForEditing +} DxcGlobalOptions; + +typedef enum DxcTokenKind { + DxcTokenKind_Punctuation = + 0, // A token that contains some kind of punctuation. + DxcTokenKind_Keyword = 1, // A language keyword. + DxcTokenKind_Identifier = 2, // An identifier (that is not a keyword). + DxcTokenKind_Literal = 3, // A numeric, string, or character literal. + DxcTokenKind_Comment = 4, // A comment. + DxcTokenKind_Unknown = + 5, // An unknown token (possibly known to a future version). + DxcTokenKind_BuiltInType = 6, // A built-in type like int, void or float3. +} DxcTokenKind; + +typedef enum DxcTypeKind { + DxcTypeKind_Invalid = + 0, // Reprents an invalid type (e.g., where no type is available). + DxcTypeKind_Unexposed = + 1, // A type whose specific kind is not exposed via this interface. + // Builtin types + DxcTypeKind_Void = 2, + DxcTypeKind_Bool = 3, + DxcTypeKind_Char_U = 4, + DxcTypeKind_UChar = 5, + DxcTypeKind_Char16 = 6, + DxcTypeKind_Char32 = 7, + DxcTypeKind_UShort = 8, + DxcTypeKind_UInt = 9, + DxcTypeKind_ULong = 10, + DxcTypeKind_ULongLong = 11, + DxcTypeKind_UInt128 = 12, + DxcTypeKind_Char_S = 13, + DxcTypeKind_SChar = 14, + DxcTypeKind_WChar = 15, + DxcTypeKind_Short = 16, + DxcTypeKind_Int = 17, + DxcTypeKind_Long = 18, + DxcTypeKind_LongLong = 19, + DxcTypeKind_Int128 = 20, + DxcTypeKind_Float = 21, + DxcTypeKind_Double = 22, + DxcTypeKind_LongDouble = 23, + DxcTypeKind_NullPtr = 24, + DxcTypeKind_Overload = 25, + DxcTypeKind_Dependent = 26, + DxcTypeKind_ObjCId = 27, + DxcTypeKind_ObjCClass = 28, + DxcTypeKind_ObjCSel = 29, + DxcTypeKind_FirstBuiltin = DxcTypeKind_Void, + DxcTypeKind_LastBuiltin = DxcTypeKind_ObjCSel, + + DxcTypeKind_Complex = 100, + DxcTypeKind_Pointer = 101, + DxcTypeKind_BlockPointer = 102, + DxcTypeKind_LValueReference = 103, + DxcTypeKind_RValueReference = 104, + DxcTypeKind_Record = 105, + DxcTypeKind_Enum = 106, + DxcTypeKind_Typedef = 107, + DxcTypeKind_ObjCInterface = 108, + DxcTypeKind_ObjCObjectPointer = 109, + DxcTypeKind_FunctionNoProto = 110, + DxcTypeKind_FunctionProto = 111, + DxcTypeKind_ConstantArray = 112, + DxcTypeKind_Vector = 113, + DxcTypeKind_IncompleteArray = 114, + DxcTypeKind_VariableArray = 115, + DxcTypeKind_DependentSizedArray = 116, + DxcTypeKind_MemberPointer = 117 +} DxcTypeKind; + +// Describes the severity of a particular diagnostic. +typedef enum DxcDiagnosticSeverity { + // A diagnostic that has been suppressed, e.g., by a command-line option. + DxcDiagnostic_Ignored = 0, + + // This diagnostic is a note that should be attached to the previous + // (non-note) diagnostic. + DxcDiagnostic_Note = 1, + + // This diagnostic indicates suspicious code that may not be wrong. + DxcDiagnostic_Warning = 2, + + // This diagnostic indicates that the code is ill-formed. + DxcDiagnostic_Error = 3, + + // This diagnostic indicates that the code is ill-formed such that future + // parser rec unlikely to produce useful results. + DxcDiagnostic_Fatal = 4 + +} DxcDiagnosticSeverity; + +// Options to control the display of diagnostics. +typedef enum DxcDiagnosticDisplayOptions { + // Display the source-location information where the diagnostic was located. + DxcDiagnostic_DisplaySourceLocation = 0x01, + + // If displaying the source-location information of the diagnostic, + // also include the column number. + DxcDiagnostic_DisplayColumn = 0x02, + + // If displaying the source-location information of the diagnostic, + // also include information about source ranges in a machine-parsable format. + DxcDiagnostic_DisplaySourceRanges = 0x04, + + // Display the option name associated with this diagnostic, if any. + DxcDiagnostic_DisplayOption = 0x08, + + // Display the category number associated with this diagnostic, if any. + DxcDiagnostic_DisplayCategoryId = 0x10, + + // Display the category name associated with this diagnostic, if any. + DxcDiagnostic_DisplayCategoryName = 0x20, + + // Display the severity of the diagnostic message. + DxcDiagnostic_DisplaySeverity = 0x200 +} DxcDiagnosticDisplayOptions; + +typedef enum DxcTranslationUnitFlags { + // Used to indicate that no special translation-unit options are needed. + DxcTranslationUnitFlags_None = 0x0, + + // Used to indicate that the parser should construct a "detailed" + // preprocessing record, including all macro definitions and instantiations. + DxcTranslationUnitFlags_DetailedPreprocessingRecord = 0x01, + + // Used to indicate that the translation unit is incomplete. + DxcTranslationUnitFlags_Incomplete = 0x02, + + // Used to indicate that the translation unit should be built with an + // implicit precompiled header for the preamble. + DxcTranslationUnitFlags_PrecompiledPreamble = 0x04, + + // Used to indicate that the translation unit should cache some + // code-completion results with each reparse of the source file. + DxcTranslationUnitFlags_CacheCompletionResults = 0x08, + + // Used to indicate that the translation unit will be serialized with + // SaveTranslationUnit. + DxcTranslationUnitFlags_ForSerialization = 0x10, + + // DEPRECATED + DxcTranslationUnitFlags_CXXChainedPCH = 0x20, + + // Used to indicate that function/method bodies should be skipped while + // parsing. + DxcTranslationUnitFlags_SkipFunctionBodies = 0x40, + + // Used to indicate that brief documentation comments should be + // included into the set of code completions returned from this translation + // unit. + DxcTranslationUnitFlags_IncludeBriefCommentsInCodeCompletion = 0x80, + + // Used to indicate that compilation should occur on the caller's thread. + DxcTranslationUnitFlags_UseCallerThread = 0x800 +} DxcTranslationUnitFlags; + +typedef enum DxcCursorFormatting { + DxcCursorFormatting_Default = + 0x0, // Default rules, language-insensitive formatting. + DxcCursorFormatting_UseLanguageOptions = + 0x1, // Language-sensitive formatting. + DxcCursorFormatting_SuppressSpecifiers = 0x2, // Supresses type specifiers. + DxcCursorFormatting_SuppressTagKeyword = + 0x4, // Suppressed tag keyword (eg, 'class'). + DxcCursorFormatting_IncludeNamespaceKeyword = + 0x8, // Include namespace keyword. +} DxcCursorFormatting; + +enum DxcCursorKind { + /* Declarations */ + DxcCursor_UnexposedDecl = + 1, // A declaration whose specific kind is not exposed via this interface. + DxcCursor_StructDecl = 2, // A C or C++ struct. + DxcCursor_UnionDecl = 3, // A C or C++ union. + DxcCursor_ClassDecl = 4, // A C++ class. + DxcCursor_EnumDecl = 5, // An enumeration. + DxcCursor_FieldDecl = 6, // A field (in C) or non-static data member (in C++) + // in a struct, union, or C++ class. + DxcCursor_EnumConstantDecl = 7, // An enumerator constant. + DxcCursor_FunctionDecl = 8, // A function. + DxcCursor_VarDecl = 9, // A variable. + DxcCursor_ParmDecl = 10, // A function or method parameter. + DxcCursor_ObjCInterfaceDecl = 11, // An Objective-C interface. + DxcCursor_ObjCCategoryDecl = 12, // An Objective-C interface for a category. + DxcCursor_ObjCProtocolDecl = 13, // An Objective-C protocol declaration. + DxcCursor_ObjCPropertyDecl = 14, // An Objective-C property declaration. + DxcCursor_ObjCIvarDecl = 15, // An Objective-C instance variable. + DxcCursor_ObjCInstanceMethodDecl = 16, // An Objective-C instance method. + DxcCursor_ObjCClassMethodDecl = 17, // An Objective-C class method. + DxcCursor_ObjCImplementationDecl = 18, // An Objective-C \@implementation. + DxcCursor_ObjCCategoryImplDecl = + 19, // An Objective-C \@implementation for a category. + DxcCursor_TypedefDecl = 20, // A typedef + DxcCursor_CXXMethod = 21, // A C++ class method. + DxcCursor_Namespace = 22, // A C++ namespace. + DxcCursor_LinkageSpec = 23, // A linkage specification, e.g. 'extern "C"'. + DxcCursor_Constructor = 24, // A C++ constructor. + DxcCursor_Destructor = 25, // A C++ destructor. + DxcCursor_ConversionFunction = 26, // A C++ conversion function. + DxcCursor_TemplateTypeParameter = 27, // A C++ template type parameter. + DxcCursor_NonTypeTemplateParameter = 28, // A C++ non-type template parameter. + DxcCursor_TemplateTemplateParameter = + 29, // A C++ template template parameter. + DxcCursor_FunctionTemplate = 30, // A C++ function template. + DxcCursor_ClassTemplate = 31, // A C++ class template. + DxcCursor_ClassTemplatePartialSpecialization = + 32, // A C++ class template partial specialization. + DxcCursor_NamespaceAlias = 33, // A C++ namespace alias declaration. + DxcCursor_UsingDirective = 34, // A C++ using directive. + DxcCursor_UsingDeclaration = 35, // A C++ using declaration. + DxcCursor_TypeAliasDecl = 36, // A C++ alias declaration + DxcCursor_ObjCSynthesizeDecl = 37, // An Objective-C \@synthesize definition. + DxcCursor_ObjCDynamicDecl = 38, // An Objective-C \@dynamic definition. + DxcCursor_CXXAccessSpecifier = 39, // An access specifier. + + DxcCursor_FirstDecl = DxcCursor_UnexposedDecl, + DxcCursor_LastDecl = DxcCursor_CXXAccessSpecifier, + + /* References */ + DxcCursor_FirstRef = 40, /* Decl references */ + DxcCursor_ObjCSuperClassRef = 40, + DxcCursor_ObjCProtocolRef = 41, + DxcCursor_ObjCClassRef = 42, + /** + * \brief A reference to a type declaration. + * + * A type reference occurs anywhere where a type is named but not + * declared. For example, given: + * + * \code + * typedef unsigned size_type; + * size_type size; + * \endcode + * + * The typedef is a declaration of size_type (DxcCursor_TypedefDecl), + * while the type of the variable "size" is referenced. The cursor + * referenced by the type of size is the typedef for size_type. + */ + DxcCursor_TypeRef = 43, // A reference to a type declaration. + DxcCursor_CXXBaseSpecifier = 44, + DxcCursor_TemplateRef = + 45, // A reference to a class template, function template, template + // template parameter, or class template partial specialization. + DxcCursor_NamespaceRef = 46, // A reference to a namespace or namespace alias. + DxcCursor_MemberRef = + 47, // A reference to a member of a struct, union, or class that occurs in + // some non-expression context, e.g., a designated initializer. + /** + * \brief A reference to a labeled statement. + * + * This cursor kind is used to describe the jump to "start_over" in the + * goto statement in the following example: + * + * \code + * start_over: + * ++counter; + * + * goto start_over; + * \endcode + * + * A label reference cursor refers to a label statement. + */ + DxcCursor_LabelRef = 48, // A reference to a labeled statement. + + // A reference to a set of overloaded functions or function templates + // that has not yet been resolved to a specific function or function template. + // + // An overloaded declaration reference cursor occurs in C++ templates where + // a dependent name refers to a function. + DxcCursor_OverloadedDeclRef = 49, + DxcCursor_VariableRef = + 50, // A reference to a variable that occurs in some non-expression + // context, e.g., a C++ lambda capture list. + + DxcCursor_LastRef = DxcCursor_VariableRef, + + /* Error conditions */ + DxcCursor_FirstInvalid = 70, + DxcCursor_InvalidFile = 70, + DxcCursor_NoDeclFound = 71, + DxcCursor_NotImplemented = 72, + DxcCursor_InvalidCode = 73, + DxcCursor_LastInvalid = DxcCursor_InvalidCode, + + /* Expressions */ + DxcCursor_FirstExpr = 100, + + /** + * \brief An expression whose specific kind is not exposed via this + * interface. + * + * Unexposed expressions have the same operations as any other kind + * of expression; one can extract their location information, + * spelling, children, etc. However, the specific kind of the + * expression is not reported. + */ + DxcCursor_UnexposedExpr = 100, // An expression whose specific kind is not + // exposed via this interface. + DxcCursor_DeclRefExpr = + 101, // An expression that refers to some value declaration, such as a + // function, varible, or enumerator. + DxcCursor_MemberRefExpr = + 102, // An expression that refers to a member of a struct, union, class, + // Objective-C class, etc. + DxcCursor_CallExpr = 103, // An expression that calls a function. + DxcCursor_ObjCMessageExpr = 104, // An expression that sends a message to an + // Objective-C object or class. + DxcCursor_BlockExpr = 105, // An expression that represents a block literal. + DxcCursor_IntegerLiteral = 106, // An integer literal. + DxcCursor_FloatingLiteral = 107, // A floating point number literal. + DxcCursor_ImaginaryLiteral = 108, // An imaginary number literal. + DxcCursor_StringLiteral = 109, // A string literal. + DxcCursor_CharacterLiteral = 110, // A character literal. + DxcCursor_ParenExpr = + 111, // A parenthesized expression, e.g. "(1)". This AST node is only + // formed if full location information is requested. + DxcCursor_UnaryOperator = 112, // This represents the unary-expression's + // (except sizeof and alignof). + DxcCursor_ArraySubscriptExpr = 113, // [C99 6.5.2.1] Array Subscripting. + DxcCursor_BinaryOperator = + 114, // A builtin binary operation expression such as "x + y" or "x <= y". + DxcCursor_CompoundAssignOperator = 115, // Compound assignment such as "+=". + DxcCursor_ConditionalOperator = 116, // The ?: ternary operator. + DxcCursor_CStyleCastExpr = + 117, // An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ + // [expr.cast]), which uses the syntax (Type)expr, eg: (int)f. + DxcCursor_CompoundLiteralExpr = 118, // [C99 6.5.2.5] + DxcCursor_InitListExpr = 119, // Describes an C or C++ initializer list. + DxcCursor_AddrLabelExpr = + 120, // The GNU address of label extension, representing &&label. + DxcCursor_StmtExpr = + 121, // This is the GNU Statement Expression extension: ({int X=4; X;}) + DxcCursor_GenericSelectionExpr = 122, // Represents a C11 generic selection. + + /** \brief Implements the GNU __null extension, which is a name for a null + * pointer constant that has integral type (e.g., int or long) and is the same + * size and alignment as a pointer. + * + * The __null extension is typically only used by system headers, which define + * NULL as __null in C++ rather than using 0 (which is an integer that may not + * match the size of a pointer). + */ + DxcCursor_GNUNullExpr = 123, + DxcCursor_CXXStaticCastExpr = 124, // C++'s static_cast<> expression. + DxcCursor_CXXDynamicCastExpr = 125, // C++'s dynamic_cast<> expression. + DxcCursor_CXXReinterpretCastExpr = + 126, // C++'s reinterpret_cast<> expression. + DxcCursor_CXXConstCastExpr = 127, // C++'s const_cast<> expression. + + /** \brief Represents an explicit C++ type conversion that uses "functional" + * notion (C++ [expr.type.conv]). + * + * Example: + * \code + * x = int(0.5); + * \endcode + */ + DxcCursor_CXXFunctionalCastExpr = 128, + DxcCursor_CXXTypeidExpr = 129, // A C++ typeid expression (C++ [expr.typeid]). + DxcCursor_CXXBoolLiteralExpr = 130, // [C++ 2.13.5] C++ Boolean Literal. + DxcCursor_CXXNullPtrLiteralExpr = 131, // [C++0x 2.14.7] C++ Pointer Literal. + DxcCursor_CXXThisExpr = 132, // Represents the "this" expression in C++ + DxcCursor_CXXThrowExpr = 133, // [C++ 15] C++ Throw Expression, both 'throw' + // and 'throw' assignment-expression. + DxcCursor_CXXNewExpr = 134, // A new expression for memory allocation and + // constructor calls, e.g: "new CXXNewExpr(foo)". + DxcCursor_CXXDeleteExpr = + 135, // A delete expression for memory deallocation and destructor calls, + // e.g. "delete[] pArray". + DxcCursor_UnaryExpr = 136, // A unary expression. + DxcCursor_ObjCStringLiteral = + 137, // An Objective-C string literal i.e. @"foo". + DxcCursor_ObjCEncodeExpr = 138, // An Objective-C \@encode expression. + DxcCursor_ObjCSelectorExpr = 139, // An Objective-C \@selector expression. + DxcCursor_ObjCProtocolExpr = 140, // An Objective-C \@protocol expression. + + /** \brief An Objective-C "bridged" cast expression, which casts between + * Objective-C pointers and C pointers, transferring ownership in the process. + * + * \code + * NSString *str = (__bridge_transfer NSString *)CFCreateString(); + * \endcode + */ + DxcCursor_ObjCBridgedCastExpr = 141, + + /** \brief Represents a C++0x pack expansion that produces a sequence of + * expressions. + * + * A pack expansion expression contains a pattern (which itself is an + * expression) followed by an ellipsis. For example: + * + * \code + * template + * void forward(F f, Types &&...args) { + * f(static_cast(args)...); + * } + * \endcode + */ + DxcCursor_PackExpansionExpr = 142, + + /** \brief Represents an expression that computes the length of a parameter + * pack. + * + * \code + * template + * struct count { + * static const unsigned value = sizeof...(Types); + * }; + * \endcode + */ + DxcCursor_SizeOfPackExpr = 143, + + /* \brief Represents a C++ lambda expression that produces a local function + * object. + * + * \code + * void abssort(float *x, unsigned N) { + * std::sort(x, x + N, + * [](float a, float b) { + * return std::abs(a) < std::abs(b); + * }); + * } + * \endcode + */ + DxcCursor_LambdaExpr = 144, + DxcCursor_ObjCBoolLiteralExpr = 145, // Objective-c Boolean Literal. + DxcCursor_ObjCSelfExpr = + 146, // Represents the "self" expression in a ObjC method. + DxcCursor_LastExpr = DxcCursor_ObjCSelfExpr, + + /* Statements */ + DxcCursor_FirstStmt = 200, + /** + * \brief A statement whose specific kind is not exposed via this + * interface. + * + * Unexposed statements have the same operations as any other kind of + * statement; one can extract their location information, spelling, + * children, etc. However, the specific kind of the statement is not + * reported. + */ + DxcCursor_UnexposedStmt = 200, + + /** \brief A labelled statement in a function. + * + * This cursor kind is used to describe the "start_over:" label statement in + * the following example: + * + * \code + * start_over: + * ++counter; + * \endcode + * + */ + DxcCursor_LabelStmt = 201, + DxcCursor_CompoundStmt = + 202, // A group of statements like { stmt stmt }. This cursor kind is used + // to describe compound statements, e.g. function bodies. + DxcCursor_CaseStmt = 203, // A case statement. + DxcCursor_DefaultStmt = 204, // A default statement. + DxcCursor_IfStmt = 205, // An if statement + DxcCursor_SwitchStmt = 206, // A switch statement. + DxcCursor_WhileStmt = 207, // A while statement. + DxcCursor_DoStmt = 208, // A do statement. + DxcCursor_ForStmt = 209, // A for statement. + DxcCursor_GotoStmt = 210, // A goto statement. + DxcCursor_IndirectGotoStmt = 211, // An indirect goto statement. + DxcCursor_ContinueStmt = 212, // A continue statement. + DxcCursor_BreakStmt = 213, // A break statement. + DxcCursor_ReturnStmt = 214, // A return statement. + DxcCursor_GCCAsmStmt = 215, // A GCC inline assembly statement extension. + DxcCursor_AsmStmt = DxcCursor_GCCAsmStmt, + + DxcCursor_ObjCAtTryStmt = + 216, // Objective-C's overall \@try-\@catch-\@finally statement. + DxcCursor_ObjCAtCatchStmt = 217, // Objective-C's \@catch statement. + DxcCursor_ObjCAtFinallyStmt = 218, // Objective-C's \@finally statement. + DxcCursor_ObjCAtThrowStmt = 219, // Objective-C's \@throw statement. + DxcCursor_ObjCAtSynchronizedStmt = + 220, // Objective-C's \@synchronized statement. + DxcCursor_ObjCAutoreleasePoolStmt = + 221, // Objective-C's autorelease pool statement. + DxcCursor_ObjCForCollectionStmt = 222, // Objective-C's collection statement. + + DxcCursor_CXXCatchStmt = 223, // C++'s catch statement. + DxcCursor_CXXTryStmt = 224, // C++'s try statement. + DxcCursor_CXXForRangeStmt = 225, // C++'s for (* : *) statement. + + DxcCursor_SEHTryStmt = + 226, // Windows Structured Exception Handling's try statement. + DxcCursor_SEHExceptStmt = + 227, // Windows Structured Exception Handling's except statement. + DxcCursor_SEHFinallyStmt = + 228, // Windows Structured Exception Handling's finally statement. + + DxcCursor_MSAsmStmt = 229, // A MS inline assembly statement extension. + DxcCursor_NullStmt = 230, // The null satement ";": C99 6.8.3p3. + DxcCursor_DeclStmt = 231, // Adaptor class for mixing declarations with + // statements and expressions. + DxcCursor_OMPParallelDirective = 232, // OpenMP parallel directive. + DxcCursor_OMPSimdDirective = 233, // OpenMP SIMD directive. + DxcCursor_OMPForDirective = 234, // OpenMP for directive. + DxcCursor_OMPSectionsDirective = 235, // OpenMP sections directive. + DxcCursor_OMPSectionDirective = 236, // OpenMP section directive. + DxcCursor_OMPSingleDirective = 237, // OpenMP single directive. + DxcCursor_OMPParallelForDirective = 238, // OpenMP parallel for directive. + DxcCursor_OMPParallelSectionsDirective = + 239, // OpenMP parallel sections directive. + DxcCursor_OMPTaskDirective = 240, // OpenMP task directive. + DxcCursor_OMPMasterDirective = 241, // OpenMP master directive. + DxcCursor_OMPCriticalDirective = 242, // OpenMP critical directive. + DxcCursor_OMPTaskyieldDirective = 243, // OpenMP taskyield directive. + DxcCursor_OMPBarrierDirective = 244, // OpenMP barrier directive. + DxcCursor_OMPTaskwaitDirective = 245, // OpenMP taskwait directive. + DxcCursor_OMPFlushDirective = 246, // OpenMP flush directive. + DxcCursor_SEHLeaveStmt = + 247, // Windows Structured Exception Handling's leave statement. + DxcCursor_OMPOrderedDirective = 248, // OpenMP ordered directive. + DxcCursor_OMPAtomicDirective = 249, // OpenMP atomic directive. + DxcCursor_OMPForSimdDirective = 250, // OpenMP for SIMD directive. + DxcCursor_OMPParallelForSimdDirective = + 251, // OpenMP parallel for SIMD directive. + DxcCursor_OMPTargetDirective = 252, // OpenMP target directive. + DxcCursor_OMPTeamsDirective = 253, // OpenMP teams directive. + DxcCursor_OMPTaskgroupDirective = 254, // OpenMP taskgroup directive. + DxcCursor_OMPCancellationPointDirective = + 255, // OpenMP cancellation point directive. + DxcCursor_OMPCancelDirective = 256, // OpenMP cancel directive. + DxcCursor_LastStmt = DxcCursor_OMPCancelDirective, + + DxcCursor_TranslationUnit = + 300, // Cursor that represents the translation unit itself. + + /* Attributes */ + DxcCursor_FirstAttr = 400, + /** + * \brief An attribute whose specific kind is not exposed via this + * interface. + */ + DxcCursor_UnexposedAttr = 400, + + DxcCursor_IBActionAttr = 401, + DxcCursor_IBOutletAttr = 402, + DxcCursor_IBOutletCollectionAttr = 403, + DxcCursor_CXXFinalAttr = 404, + DxcCursor_CXXOverrideAttr = 405, + DxcCursor_AnnotateAttr = 406, + DxcCursor_AsmLabelAttr = 407, + DxcCursor_PackedAttr = 408, + DxcCursor_PureAttr = 409, + DxcCursor_ConstAttr = 410, + DxcCursor_NoDuplicateAttr = 411, + DxcCursor_CUDAConstantAttr = 412, + DxcCursor_CUDADeviceAttr = 413, + DxcCursor_CUDAGlobalAttr = 414, + DxcCursor_CUDAHostAttr = 415, + DxcCursor_CUDASharedAttr = 416, + DxcCursor_LastAttr = DxcCursor_CUDASharedAttr, + + /* Preprocessing */ + DxcCursor_PreprocessingDirective = 500, + DxcCursor_MacroDefinition = 501, + DxcCursor_MacroExpansion = 502, + DxcCursor_MacroInstantiation = DxcCursor_MacroExpansion, + DxcCursor_InclusionDirective = 503, + DxcCursor_FirstPreprocessing = DxcCursor_PreprocessingDirective, + DxcCursor_LastPreprocessing = DxcCursor_InclusionDirective, + + /* Extra Declarations */ + /** + * \brief A module import declaration. + */ + DxcCursor_ModuleImportDecl = 600, + DxcCursor_FirstExtraDecl = DxcCursor_ModuleImportDecl, + DxcCursor_LastExtraDecl = DxcCursor_ModuleImportDecl +}; + +enum DxcCursorKindFlags { + DxcCursorKind_None = 0, + DxcCursorKind_Declaration = 0x1, + DxcCursorKind_Reference = 0x2, + DxcCursorKind_Expression = 0x4, + DxcCursorKind_Statement = 0x8, + DxcCursorKind_Attribute = 0x10, + DxcCursorKind_Invalid = 0x20, + DxcCursorKind_TranslationUnit = 0x40, + DxcCursorKind_Preprocessing = 0x80, + DxcCursorKind_Unexposed = 0x100, +}; + +enum DxcCodeCompleteFlags { + DxcCodeCompleteFlags_None = 0, + DxcCodeCompleteFlags_IncludeMacros = 0x1, + DxcCodeCompleteFlags_IncludeCodePatterns = 0x2, + DxcCodeCompleteFlags_IncludeBriefComments = 0x4, +}; + +enum DxcCompletionChunkKind { + DxcCompletionChunk_Optional = 0, + DxcCompletionChunk_TypedText = 1, + DxcCompletionChunk_Text = 2, + DxcCompletionChunk_Placeholder = 3, + DxcCompletionChunk_Informative = 4, + DxcCompletionChunk_CurrentParameter = 5, + DxcCompletionChunk_LeftParen = 6, + DxcCompletionChunk_RightParen = 7, + DxcCompletionChunk_LeftBracket = 8, + DxcCompletionChunk_RightBracket = 9, + DxcCompletionChunk_LeftBrace = 10, + DxcCompletionChunk_RightBrace = 11, + DxcCompletionChunk_LeftAngle = 12, + DxcCompletionChunk_RightAngle = 13, + DxcCompletionChunk_Comma = 14, + DxcCompletionChunk_ResultType = 15, + DxcCompletionChunk_Colon = 16, + DxcCompletionChunk_SemiColon = 17, + DxcCompletionChunk_Equal = 18, + DxcCompletionChunk_HorizontalSpace = 19, + DxcCompletionChunk_VerticalSpace = 20, +}; + +struct IDxcCursor; +struct IDxcDiagnostic; +struct IDxcFile; +struct IDxcInclusion; +struct IDxcIntelliSense; +struct IDxcIndex; +struct IDxcSourceLocation; +struct IDxcSourceRange; +struct IDxcToken; +struct IDxcTranslationUnit; +struct IDxcType; +struct IDxcUnsavedFile; +struct IDxcCodeCompleteResults; +struct IDxcCompletionResult; +struct IDxcCompletionString; + +CROSS_PLATFORM_UUIDOF(IDxcCursor, "1467b985-288d-4d2a-80c1-ef89c42c40bc") +struct IDxcCursor : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetExtent(_Outptr_result_nullonfailure_ IDxcSourceRange **pRange) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetLocation(_Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetKind(_Out_ DxcCursorKind *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetKindFlags(_Out_ DxcCursorKindFlags *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSemanticParent(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetLexicalParent(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetCursorType(_Outptr_result_nullonfailure_ IDxcType **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetNumArguments(_Out_ int *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetArgumentAt( + int index, _Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetReferencedCursor(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; + /// For a cursor that is either a reference to or a declaration of + /// some entity, retrieve a cursor that describes the definition of that + /// entity. Some entities can be declared multiple times + /// within a translation unit, but only one of those declarations can also be + /// a definition. A cursor to the definition of this + /// entity; nullptr if there is no definition in this translation + /// unit. + virtual HRESULT STDMETHODCALLTYPE + GetDefinitionCursor(_Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + FindReferencesInFile(_In_ IDxcFile *file, unsigned skip, unsigned top, + _Out_ unsigned *pResultLength, + _Outptr_result_buffer_maybenull_(*pResultLength) + IDxcCursor ***pResult) = 0; + /// Gets the name for the entity references by the cursor, e.g. foo + /// for an 'int foo' variable. + virtual HRESULT STDMETHODCALLTYPE + GetSpelling(_Outptr_result_maybenull_ LPSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcCursor *other, + _Out_ BOOL *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE IsNull(_Out_ BOOL *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE IsDefinition(_Out_ BOOL *pResult) = 0; + /// Gets the display name for the cursor, including e.g. parameter + /// types for a function. + virtual HRESULT STDMETHODCALLTYPE GetDisplayName(_Out_ BSTR *pResult) = 0; + /// Gets the qualified name for the symbol the cursor refers + /// to. + virtual HRESULT STDMETHODCALLTYPE GetQualifiedName( + BOOL includeTemplateArgs, _Outptr_result_maybenull_ BSTR *pResult) = 0; + /// Gets a name for the cursor, applying the specified formatting + /// flags. + virtual HRESULT STDMETHODCALLTYPE + GetFormattedName(DxcCursorFormatting formatting, + _Outptr_result_maybenull_ BSTR *pResult) = 0; + /// Gets children in pResult up to top elements. + virtual HRESULT STDMETHODCALLTYPE + GetChildren(unsigned skip, unsigned top, _Out_ unsigned *pResultLength, + _Outptr_result_buffer_maybenull_(*pResultLength) + IDxcCursor ***pResult) = 0; + /// Gets the cursor following a location within a compound + /// cursor. + virtual HRESULT STDMETHODCALLTYPE + GetSnappedChild(_In_ IDxcSourceLocation *location, + _Outptr_result_maybenull_ IDxcCursor **pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcDiagnostic, "4f76b234-3659-4d33-99b0-3b0db994b564") +struct IDxcDiagnostic : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + FormatDiagnostic(DxcDiagnosticDisplayOptions options, + _Outptr_result_maybenull_ LPSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSeverity(_Out_ DxcDiagnosticSeverity *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetLocation(_Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSpelling(_Outptr_result_maybenull_ LPSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetCategoryText(_Outptr_result_maybenull_ LPSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetNumRanges(_Out_ unsigned *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetRangeAt(unsigned index, + _Outptr_result_nullonfailure_ IDxcSourceRange **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetNumFixIts(_Out_ unsigned *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFixItAt(unsigned index, + _Outptr_result_nullonfailure_ IDxcSourceRange **pReplacementRange, + _Outptr_result_maybenull_ LPSTR *pText) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcFile, "bb2fca9e-1478-47ba-b08c-2c502ada4895") +struct IDxcFile : public IUnknown { + /// Gets the file name for this file. + virtual HRESULT STDMETHODCALLTYPE + GetName(_Outptr_result_maybenull_ LPSTR *pResult) = 0; + /// Checks whether this file is equal to the other specified + /// file. + virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcFile *other, + _Out_ BOOL *pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcInclusion, "0c364d65-df44-4412-888e-4e552fc5e3d6") +struct IDxcInclusion : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetIncludedFile(_Outptr_result_nullonfailure_ IDxcFile **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetStackLength(_Out_ unsigned *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetStackItem(unsigned index, + _Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcIntelliSense, "b1f99513-46d6-4112-8169-dd0d6053f17d") +struct IDxcIntelliSense : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + CreateIndex(_Outptr_result_nullonfailure_ IDxcIndex **index) = 0; + virtual HRESULT STDMETHODCALLTYPE GetNullLocation( + _Outptr_result_nullonfailure_ IDxcSourceLocation **location) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetNullRange(_Outptr_result_nullonfailure_ IDxcSourceRange **location) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetRange(_In_ IDxcSourceLocation *start, _In_ IDxcSourceLocation *end, + _Outptr_result_nullonfailure_ IDxcSourceRange **location) = 0; + virtual HRESULT STDMETHODCALLTYPE GetDefaultDiagnosticDisplayOptions( + _Out_ DxcDiagnosticDisplayOptions *pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDefaultEditingTUOptions(_Out_ DxcTranslationUnitFlags *pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateUnsavedFile( + _In_ LPCSTR fileName, _In_ LPCSTR contents, unsigned contentLength, + _Outptr_result_nullonfailure_ IDxcUnsavedFile **pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcIndex, "937824a0-7f5a-4815-9ba7-7fc0424f4173") +struct IDxcIndex : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + SetGlobalOptions(DxcGlobalOptions options) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetGlobalOptions(_Out_ DxcGlobalOptions *options) = 0; + virtual HRESULT STDMETHODCALLTYPE ParseTranslationUnit( + _In_z_ const char *source_filename, + _In_count_(num_command_line_args) const char *const *command_line_args, + int num_command_line_args, + _In_count_(num_unsaved_files) IDxcUnsavedFile **unsaved_files, + unsigned num_unsaved_files, DxcTranslationUnitFlags options, + _Out_ IDxcTranslationUnit **pTranslationUnit) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcSourceLocation, + "8e7ddf1c-d7d3-4d69-b286-85fccba1e0cf") +struct IDxcSourceLocation : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcSourceLocation *other, + _Out_ BOOL *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetSpellingLocation( + _Outptr_opt_ IDxcFile **pFile, _Out_opt_ unsigned *pLine, + _Out_opt_ unsigned *pCol, _Out_opt_ unsigned *pOffset) = 0; + virtual HRESULT STDMETHODCALLTYPE IsNull(_Out_ BOOL *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetPresumedLocation(_Outptr_opt_ LPSTR *pFilename, _Out_opt_ unsigned *pLine, + _Out_opt_ unsigned *pCol) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcSourceRange, "f1359b36-a53f-4e81-b514-b6b84122a13f") +struct IDxcSourceRange : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE IsNull(_Out_ BOOL *pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetStart(_Out_ IDxcSourceLocation **pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetEnd(_Out_ IDxcSourceLocation **pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE GetOffsets(_Out_ unsigned *startOffset, + _Out_ unsigned *endOffset) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcToken, "7f90b9ff-a275-4932-97d8-3cfd234482a2") +struct IDxcToken : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetKind(_Out_ DxcTokenKind *pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetLocation(_Out_ IDxcSourceLocation **pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetExtent(_Out_ IDxcSourceRange **pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE GetSpelling(_Out_ LPSTR *pValue) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcTranslationUnit, + "9677dee0-c0e5-46a1-8b40-3db3168be63d") +struct IDxcTranslationUnit : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetCursor(_Out_ IDxcCursor **pCursor) = 0; + virtual HRESULT STDMETHODCALLTYPE + Tokenize(_In_ IDxcSourceRange *range, + _Outptr_result_buffer_maybenull_(*pTokenCount) IDxcToken ***pTokens, + _Out_ unsigned *pTokenCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetLocation(_In_ IDxcFile *file, unsigned line, unsigned column, + _Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetNumDiagnostics(_Out_ unsigned *pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDiagnostic(unsigned index, + _Outptr_result_nullonfailure_ IDxcDiagnostic **pValue) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFile(_In_ const char *name, + _Outptr_result_nullonfailure_ IDxcFile **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFileName(_Outptr_result_maybenull_ LPSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE Reparse(_In_count_(num_unsaved_files) + IDxcUnsavedFile **unsaved_files, + unsigned num_unsaved_files) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetCursorForLocation(_In_ IDxcSourceLocation *location, + _Outptr_result_nullonfailure_ IDxcCursor **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetLocationForOffset( + _In_ IDxcFile *file, unsigned offset, + _Outptr_result_nullonfailure_ IDxcSourceLocation **pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetSkippedRanges( + _In_ IDxcFile *file, _Out_ unsigned *pResultCount, + _Outptr_result_buffer_(*pResultCount) IDxcSourceRange ***pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDiagnosticDetails(unsigned index, DxcDiagnosticDisplayOptions options, + _Out_ unsigned *errorCode, _Out_ unsigned *errorLine, + _Out_ unsigned *errorColumn, _Out_ BSTR *errorFile, + _Out_ unsigned *errorOffset, _Out_ unsigned *errorLength, + _Out_ BSTR *errorMessage) = 0; + virtual HRESULT STDMETHODCALLTYPE GetInclusionList( + _Out_ unsigned *pResultCount, + _Outptr_result_buffer_(*pResultCount) IDxcInclusion ***pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE CodeCompleteAt( + _In_ const char *fileName, unsigned line, unsigned column, + _In_ IDxcUnsavedFile **pUnsavedFiles, unsigned numUnsavedFiles, + _In_ DxcCodeCompleteFlags options, + _Outptr_result_nullonfailure_ IDxcCodeCompleteResults **pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcType, "2ec912fd-b144-4a15-ad0d-1c5439c81e46") +struct IDxcType : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetSpelling(_Outptr_result_z_ LPSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE IsEqualTo(_In_ IDxcType *other, + _Out_ BOOL *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetKind(_Out_ DxcTypeKind *pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcUnsavedFile, "8ec00f98-07d0-4e60-9d7c-5a50b5b0017f") +struct IDxcUnsavedFile : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetFileName(_Outptr_result_z_ LPSTR *pFileName) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetContents(_Outptr_result_z_ LPSTR *pContents) = 0; + virtual HRESULT STDMETHODCALLTYPE GetLength(_Out_ unsigned *pLength) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCodeCompleteResults, + "1E06466A-FD8B-45F3-A78F-8A3F76EBB552") +struct IDxcCodeCompleteResults : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetNumResults(_Out_ unsigned *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetResultAt(unsigned index, + _Outptr_result_nullonfailure_ IDxcCompletionResult **pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompletionResult, + "943C0588-22D0-4784-86FC-701F802AC2B6") +struct IDxcCompletionResult : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetCursorKind(_Out_ DxcCursorKind *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetCompletionString( + _Outptr_result_nullonfailure_ IDxcCompletionString **pResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompletionString, + "06B51E0F-A605-4C69-A110-CD6E14B58EEC") +struct IDxcCompletionString : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetNumCompletionChunks(_Out_ unsigned *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetCompletionChunkKind( + unsigned chunkNumber, _Out_ DxcCompletionChunkKind *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetCompletionChunkText(unsigned chunkNumber, _Out_ LPSTR *pResult) = 0; +}; + +// Fun fact: 'extern' is required because const is by default static in C++, so +// CLSID_DxcIntelliSense is not visible externally (this is OK in C, since const +// is not by default static in C) + +#ifdef _MSC_VER +#define CLSID_SCOPE __declspec(selectany) extern +#else +#define CLSID_SCOPE +#endif + +CLSID_SCOPE const CLSID + CLSID_DxcIntelliSense = {/* 3047833c-d1c0-4b8e-9d40-102878605985 */ + 0x3047833c, + 0xd1c0, + 0x4b8e, + {0x9d, 0x40, 0x10, 0x28, 0x78, 0x60, 0x59, 0x85}}; + +#endif diff --git a/Nuake/src/Rendering/Renderer.cpp b/Nuake/src/Rendering/Renderer.cpp index ae510b3b..a9fcd132 100644 --- a/Nuake/src/Rendering/Renderer.cpp +++ b/Nuake/src/Rendering/Renderer.cpp @@ -104,29 +104,29 @@ namespace Nuake { RenderCommand::SetRendererAPI(RendererPlatforms::Vulkan); - ShaderManager::LoadShaders(); + //ShaderManager::LoadShaders(); - m_LightsUniformBuffer = CreateRef(128); - - Ref defaultMaterial = CreateRef(Vector3{1, 1, 1}); - defaultMaterial->SetName("white"); - MaterialManager::Get()->RegisterMaterial(defaultMaterial); - - CubeIndices.reserve(36); - for (int i = 0; i < 36; i++) - { - CubeIndices.push_back(i); - } - - CubeMesh = CreateRef(); - CubeMesh->AddSurface(CubeVertices, CubeIndices); - CubeMesh->SetMaterial(defaultMaterial); - - QuadMesh = CreateRef(); - QuadMesh->AddSurface(QuadVertices, { 0, 1, 2, 3, 4, 5 }); - QuadMesh->SetMaterial(defaultMaterial); - - SphereMesh = CreateSphereMesh(); + //m_LightsUniformBuffer = CreateRef(128); + // + //Ref defaultMaterial = CreateRef(Vector3{1, 1, 1}); + //defaultMaterial->SetName("white"); + //MaterialManager::Get()->RegisterMaterial(defaultMaterial); + // + //CubeIndices.reserve(36); + //for (int i = 0; i < 36; i++) + //{ + // CubeIndices.push_back(i); + //} + // + //CubeMesh = CreateRef(); + //CubeMesh->AddSurface(CubeVertices, CubeIndices); + //CubeMesh->SetMaterial(defaultMaterial); + // + //QuadMesh = CreateRef(); + //QuadMesh->AddSurface(QuadVertices, { 0, 1, 2, 3, 4, 5 }); + //QuadMesh->SetMaterial(defaultMaterial); + // + //SphereMesh = CreateSphereMesh(); } void Renderer::LoadShaders() diff --git a/Nuake/src/Rendering/Vulkan/ShaderCompiler.cpp b/Nuake/src/Rendering/Vulkan/ShaderCompiler.cpp new file mode 100644 index 00000000..aa0124f9 --- /dev/null +++ b/Nuake/src/Rendering/Vulkan/ShaderCompiler.cpp @@ -0,0 +1,132 @@ +#include "ShaderCompiler.h" + +#include "VulkanShader.h" + +#include +#include "dxcapi.h" +#include +#include +#include +#include +#include + + +using namespace Nuake; + +Ref ShaderCompiler::CompileShader(const std::string& path) +{ + HRESULT hres; + + // Initialize DXC library + CComPtr library; + hres = DxcCreateInstance(CLSID_DxcLibrary, IID_PPV_ARGS(&library)); + if (FAILED(hres)) + { + throw std::runtime_error("Could not init DXC Library"); + } + + // Initialize DXC compiler + CComPtr compiler; + hres = DxcCreateInstance(CLSID_DxcCompiler, IID_PPV_ARGS(&compiler)); + if (FAILED(hres)) + { + throw std::runtime_error("Could not init DXC Compiler"); + } + + // Initialize DXC utility + CComPtr utils; + hres = DxcCreateInstance(CLSID_DxcUtils, IID_PPV_ARGS(&utils)); + if (FAILED(hres)) + { + throw std::runtime_error("Could not init DXC Utility"); + } + + // Convert std::string to std::wstring + std::wstring_convert> converter; + std::wstring wpath = converter.from_bytes(path); + + // Load the HLSL text shader from disk + uint32_t codePage = DXC_CP_ACP; + CComPtr sourceBlob; + hres = utils->LoadFile(wpath.c_str(), &codePage, &sourceBlob); + if (FAILED(hres)) + { + throw std::runtime_error("Could not load shader file"); + } + + // Select target profile based on shader file extension + ShaderType shaderType; + LPCWSTR targetProfile{}; + size_t idx = path.rfind('.'); + if (idx != std::string::npos) + { + std::wstring extension = wpath.substr(idx + 1); + if (extension == L"vert") + { + targetProfile = L"vs_6_1"; + shaderType = ShaderType::Vertex; + } + else if (extension == L"frag") + { + targetProfile = L"ps_6_1"; + shaderType = ShaderType::Fragment; + } + else if (extension == L"comp") + { + targetProfile = L"cs_6_1"; + shaderType = ShaderType::Compute; + } + } + + // Configure the compiler arguments for compiling the HLSL shader to SPIR-V + std::vector arguments = { + // (Optional) name of the shader file to be displayed e.g. in an error message + wpath.c_str(), + // Shader main entry point + L"-E", L"main", + // Shader target profile + L"-T", targetProfile, + // Compile to SPIRV + L"-spirv" + }; + + // Compile shader + DxcBuffer buffer{}; + buffer.Encoding = DXC_CP_ACP; + buffer.Ptr = sourceBlob->GetBufferPointer(); + buffer.Size = sourceBlob->GetBufferSize(); + + CComPtr result{ nullptr }; + hres = compiler->Compile( + &buffer, + arguments.data(), + (uint32_t)arguments.size(), + nullptr, + IID_PPV_ARGS(&result) + ); + + if (SUCCEEDED(hres)) + { + result->GetStatus(&hres); + } + + // Output error if compilation failed + if (FAILED(hres) && (result)) + { + CComPtr errorBlob; + hres = result->GetErrorBuffer(&errorBlob); + if (SUCCEEDED(hres) && errorBlob) + { + throw std::runtime_error("Compilation failed"); + } + } + + // Get compilation result + CComPtr code; + result->GetResult(&code); + + Ref shader = CreateRef( + static_cast(code->GetBufferPointer()), + static_cast(code->GetBufferSize()), shaderType); + return shader; +} diff --git a/Nuake/src/Rendering/Vulkan/ShaderCompiler.h b/Nuake/src/Rendering/Vulkan/ShaderCompiler.h new file mode 100644 index 00000000..af8e43c2 --- /dev/null +++ b/Nuake/src/Rendering/Vulkan/ShaderCompiler.h @@ -0,0 +1,23 @@ +#pragma once + +#include "src/Core/Core.h" + +#include + +namespace Nuake +{ + class VulkanShader; + + class ShaderCompiler + { + public: + + static ShaderCompiler& Get() + { + static ShaderCompiler instance; + return instance; + } + + Ref CompileShader(const std::string& path); + }; +} \ No newline at end of file diff --git a/Nuake/src/Rendering/Vulkan/VulkanCheck.h b/Nuake/src/Rendering/Vulkan/VulkanCheck.h new file mode 100644 index 00000000..765af5ff --- /dev/null +++ b/Nuake/src/Rendering/Vulkan/VulkanCheck.h @@ -0,0 +1,76 @@ +#include +#include +#include +#include + +static std::unordered_map ErrorDescriptions = { + {VK_SUCCESS, "Command successfully completed"}, + {VK_NOT_READY, "A fence or query has not yet completed"}, + {VK_TIMEOUT, "A wait operation has not completed in the specified time"}, + {VK_EVENT_SET, "An event is signaled"}, + {VK_EVENT_RESET, "An event is unsignaled"}, + {VK_INCOMPLETE, "A return array was too small for the result"}, + {VK_SUBOPTIMAL_KHR, "A swapchain no longer matches the surface properties exactly, but can still be used to present to the surface successfully."}, + {VK_THREAD_IDLE_KHR, "A deferred operation is not complete but there is currently no work for this thread to do at the time of this call."}, + {VK_THREAD_DONE_KHR, "A deferred operation is not complete but there is no work remaining to assign to additional threads."}, + {VK_OPERATION_DEFERRED_KHR, "A deferred operation was requested and at least some of the work was deferred."}, + {VK_OPERATION_NOT_DEFERRED_KHR, "A deferred operation was requested and no operations were deferred."}, + {VK_PIPELINE_COMPILE_REQUIRED_EXT, "A requested pipeline creation would have required compilation, but the application requested compilation to not be performed."}, + {VK_ERROR_OUT_OF_HOST_MEMORY, "A host memory allocation has failed."}, + {VK_ERROR_OUT_OF_DEVICE_MEMORY, "A device memory allocation has failed."}, + {VK_ERROR_INITIALIZATION_FAILED, "Initialization of an object could not be completed for implementation-specific reasons."}, + {VK_ERROR_DEVICE_LOST, "The logical or physical device has been lost. See Lost Device"}, + {VK_ERROR_MEMORY_MAP_FAILED, "Mapping of a memory object has failed."}, + {VK_ERROR_LAYER_NOT_PRESENT, "A requested layer is not present or could not be loaded."}, + {VK_ERROR_EXTENSION_NOT_PRESENT, "A requested extension is not supported."}, + {VK_ERROR_FEATURE_NOT_PRESENT, "A requested feature is not supported."}, + {VK_ERROR_INCOMPATIBLE_DRIVER, "The requested version of Vulkan is not supported by the driver or is otherwise incompatible for implementation-specific reasons."}, + {VK_ERROR_TOO_MANY_OBJECTS, "Too many objects of the type have already been created."}, + {VK_ERROR_FORMAT_NOT_SUPPORTED, "A requested format is not supported on this device."}, + {VK_ERROR_FRAGMENTED_POOL, "A pool allocation has failed due to fragmentation of the pool’s memory. This must only be returned if no attempt to allocate host or device memory was made to accommodate the new allocation. This should be returned in preference to VK_ERROR_OUT_OF_POOL_MEMORY, but only if the implementation is certain that the pool allocation failure was due to fragmentation."}, + {VK_ERROR_SURFACE_LOST_KHR, "A surface is no longer available."}, + {VK_ERROR_NATIVE_WINDOW_IN_USE_KHR, "The requested window is already in use by Vulkan or another API in a manner which prevents it from being used again."}, + {VK_ERROR_OUT_OF_DATE_KHR, "A surface has changed in such a way that it is no longer compatible with the swapchain, and further presentation requests using the swapchain will fail. Applications must query the new surface properties and recreate their swapchain if they wish to continue presenting to the surface."}, + {VK_ERROR_INCOMPATIBLE_DISPLAY_KHR, "The display used by a swapchain does not use the same presentable image layout, or is incompatible in a way that prevents sharing an image."}, + {VK_ERROR_INVALID_SHADER_NV, "One or more shaders failed to compile or link. More details are reported back to the application via VK_EXT_debug_report if enabled."}, + {VK_ERROR_OUT_OF_POOL_MEMORY, "A pool memory allocation has failed. This must only be returned if no attempt to allocate host or device memory was made to accommodate the new allocation. If the failure was definitely due to fragmentation of the pool, VK_ERROR_FRAGMENTED_POOL should be returned instead."}, + {VK_ERROR_INVALID_EXTERNAL_HANDLE, "An external handle is not a valid handle of the specified type."}, + {VK_ERROR_FRAGMENTATION, "A descriptor pool creation has failed due to fragmentation."}, + {VK_ERROR_INVALID_DEVICE_ADDRESS_EXT, "A buffer creation failed because the requested address is not available."}, + {VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS, "A buffer creation or memory allocation failed because the requested address is not available. A shader group handle assignment failed because the requested shader group handle information is no longer valid."}, + {VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT, "An operation on a swapchain created with VK_FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT failed as it did not have exlusive full-screen access. This may occur due to implementation-dependent reasons, outside of the application’s control."}, + {VK_ERROR_UNKNOWN, "An unknown error has occurred; either the application has provided invalid input, or an implementation failure has occurred."} +}; + + +#define VK_CALL(x) VK_CHECK_CALL(x) + +#define VK_CHECK_CALL(x) VulkanCheckErrorStatus(x, __FILE__, __LINE__) + +static bool VulkanCheckErrorStatus(VkResult x, const char* file, int line) +{ + if (x != VK_SUCCESS) + { + std::cout << "\033[1;31;49m **Vulkan Function Call Error** Description : \033[0m" << ErrorDescriptions[x] << " \033[2;90;49m [at Line : " << line << " in File : " << file << "\033[0m]" << std::endl; + return true; + } + else return false; +} + +#define VK_LOG_SUCCESS(msg) std::cout << "\033[1;32m[VULKAN]\033[1;32m - SUCCESS : " << (msg) << " \033[0m\n"; + +#define VK_LOG(...) std::cout , "\033[1;32m[VULKAN]\033[1;33m - LOG : " , __VA_ARGS__ , " \033[0m" , std::endl + +#define DEVICE VKLogicalDevice::GetDeviceManager()->GetLogicalDevice() + +template +static std::ostream& operator,(std::ostream& out, const T& t) { + out << t; + return out; +} + +//overloaded version to handle all those special std::endl and others... +static std::ostream& operator,(std::ostream& out, std::ostream&(*f)(std::ostream&)) { + out << f; + return out; +} \ No newline at end of file diff --git a/Nuake/src/Rendering/Vulkan/VulkanImage/VkImage.h b/Nuake/src/Rendering/Vulkan/VulkanImage/VkImage.h new file mode 100644 index 00000000..ae343d89 --- /dev/null +++ b/Nuake/src/Rendering/Vulkan/VulkanImage/VkImage.h @@ -0,0 +1,8 @@ +#pragma once + + + +namespace Nuake +{ + +} \ No newline at end of file diff --git a/Nuake/src/Rendering/Vulkan/VulkanRenderer.cpp b/Nuake/src/Rendering/Vulkan/VulkanRenderer.cpp index c131fb31..f38c99d6 100644 --- a/Nuake/src/Rendering/Vulkan/VulkanRenderer.cpp +++ b/Nuake/src/Rendering/Vulkan/VulkanRenderer.cpp @@ -1,13 +1,14 @@ #include "VulkanRenderer.h" #include "src/Core/Logger.h" -#include +#include "ShaderCompiler.h" +#include "src/Rendering/RenderCommand.h" +#include "VulkanShader.h" #include "src/Window.h" #include - using namespace Nuake; @@ -40,6 +41,46 @@ void VkRenderer::Initialize() SelectGPU(); + // Pass the vulkanFunctions struct to the VMA allocator + VmaAllocatorCreateInfo allocatorInfo = {}; + allocatorInfo.physicalDevice = GPU; + allocatorInfo.device = Device; + allocatorInfo.instance = Instance; + allocatorInfo.flags = VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT; + allocatorInfo.pVulkanFunctions = { + allocatorInfo.pVulkanFunctions = new VmaVulkanFunctions{ + .vkGetInstanceProcAddr = vkGetInstanceProcAddr, + .vkGetDeviceProcAddr = vkGetDeviceProcAddr, + .vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties, + .vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties, + .vkAllocateMemory = vkAllocateMemory, + .vkFreeMemory = vkFreeMemory, + .vkMapMemory = vkMapMemory, + .vkUnmapMemory = vkUnmapMemory, + .vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges, + .vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges, + .vkBindBufferMemory = vkBindBufferMemory, + .vkBindImageMemory = vkBindImageMemory, + .vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements, + .vkGetImageMemoryRequirements = vkGetImageMemoryRequirements, + .vkCreateBuffer = vkCreateBuffer, + .vkDestroyBuffer = vkDestroyBuffer, + .vkCreateImage = vkCreateImage, + .vkDestroyImage = vkDestroyImage, + .vkCmdCopyBuffer = vkCmdCopyBuffer, + .vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR, + .vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR, + .vkBindBufferMemory2KHR = vkBindBufferMemory2KHR, + .vkBindImageMemory2KHR = vkBindImageMemory2KHR, + } + }; + + vmaCreateAllocator(&allocatorInfo, &Allocator); + + MainDeletionQueue.push_function([&]() { + vmaDestroyAllocator(Allocator); + }); + CreateSwapchain(Window::Get()->GetSize()); // Now lets grab the Queues @@ -50,70 +91,11 @@ void VkRenderer::Initialize() InitSync(); - VmaVulkanFunctions vulkanFunctions = {}; - vulkanFunctions.vkGetInstanceProcAddr = vkGetInstanceProcAddr; - vulkanFunctions.vkGetDeviceProcAddr = vkGetDeviceProcAddr; - vulkanFunctions.vkAllocateMemory = vkAllocateMemory; - vulkanFunctions.vkFreeMemory = vkFreeMemory; - vulkanFunctions.vkMapMemory = vkMapMemory; - vulkanFunctions.vkUnmapMemory = vkUnmapMemory; - vulkanFunctions.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges; - vulkanFunctions.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges; - vulkanFunctions.vkBindBufferMemory = vkBindBufferMemory; - vulkanFunctions.vkBindImageMemory = vkBindImageMemory; - vulkanFunctions.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements; - vulkanFunctions.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements; - vulkanFunctions.vkCreateBuffer = vkCreateBuffer; - vulkanFunctions.vkDestroyBuffer = vkDestroyBuffer; - vulkanFunctions.vkCreateImage = vkCreateImage; - vulkanFunctions.vkDestroyImage = vkDestroyImage; - vulkanFunctions.vkCmdCopyBuffer = vkCmdCopyBuffer; + InitDescriptors(); - // Optional: Include extension functions if needed - vulkanFunctions.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR; - vulkanFunctions.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR; - vulkanFunctions.vkBindBufferMemory2KHR = vkBindBufferMemory2KHR; - vulkanFunctions.vkBindImageMemory2KHR = vkBindImageMemory2KHR; + BackgroundShader = ShaderCompiler::Get().CompileShader("../Resources/Shaders/Vulkan/background.comp"); - // Pass the vulkanFunctions struct to the VMA allocator - VmaAllocatorCreateInfo allocatorInfo = {}; - allocatorInfo.physicalDevice = GPU; - allocatorInfo.device = Device; - allocatorInfo.instance = Instance; - allocatorInfo.flags = VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT; - allocatorInfo.pVulkanFunctions = { - allocatorInfo.pVulkanFunctions = new VmaVulkanFunctions{ - .vkGetInstanceProcAddr = vkGetInstanceProcAddr, - .vkGetDeviceProcAddr = vkGetDeviceProcAddr, - .vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties, - .vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties, - .vkAllocateMemory = vkAllocateMemory, - .vkFreeMemory = vkFreeMemory, - .vkMapMemory = vkMapMemory, - .vkUnmapMemory = vkUnmapMemory, - .vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges, - .vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges, - .vkBindBufferMemory = vkBindBufferMemory, - .vkBindImageMemory = vkBindImageMemory, - .vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements, - .vkGetImageMemoryRequirements = vkGetImageMemoryRequirements, - .vkCreateBuffer = vkCreateBuffer, - .vkDestroyBuffer = vkDestroyBuffer, - .vkCreateImage = vkCreateImage, - .vkDestroyImage = vkDestroyImage, - .vkCmdCopyBuffer = vkCmdCopyBuffer, - .vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR, - .vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR, - .vkBindBufferMemory2KHR = vkBindBufferMemory2KHR, - .vkBindImageMemory2KHR = vkBindImageMemory2KHR, - } - }; - - vmaCreateAllocator(&allocatorInfo, &Allocator); - - MainDeletionQueue.push_function([&]() { - vmaDestroyAllocator(Allocator); - }); + InitPipeline(); IsInitialized = true; } @@ -141,7 +123,7 @@ void VkRenderer::CleanUp() Frames[i].LocalDeletionQueue.flush(); } - + MainDeletionQueue.flush(); DestroySwapchain(); @@ -175,11 +157,9 @@ void VkRenderer::SelectGPU() VkPhysicalDeviceVulkan13Features features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES }; features.dynamicRendering = true; features.synchronization2 = true; - VkPhysicalDeviceVulkan12Features features12{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES }; features12.bufferDeviceAddress = true; features12.descriptorIndexing = true; - vkb::PhysicalDeviceSelector selector{ VkbInstance }; vkb::PhysicalDevice physicalDevice = selector .set_minimum_version(1, 3) @@ -196,6 +176,15 @@ void VkRenderer::SelectGPU() GPU = physicalDevice.physical_device; } +void VkRenderer::RecreateSwapchain() +{ + vkQueueWaitIdle(GPUQueue); + + DestroySwapchain(); + CreateSwapchain(Window::Get()->GetSize()); + UpdateDescriptorSets(); +} + void VkRenderer::CreateSwapchain(const Vector2& size) { vkb::SwapchainBuilder swapchainBuilder{ GPU, Device, Surface}; @@ -214,10 +203,50 @@ void VkRenderer::CreateSwapchain(const Vector2& size) SwapchainExtent = vkbSwapchain.extent; //store swapchain and its related images - + DrawExtent = VkExtent2D{ static_cast(size.x), static_cast(size.y) }; Swapchain = vkbSwapchain.swapchain; SwapchainImages = vkbSwapchain.get_images().value(); SwapchainImageViews = vkbSwapchain.get_image_views().value(); + + SurfaceSize = size; + + //draw image size will match the window + VkExtent3D drawImageExtent = { + size.x, + size.y, + 1 + }; + + //hardcoding the draw format to 32 bit float + DrawImage.imageFormat = VK_FORMAT_R16G16B16A16_SFLOAT; + DrawImage.imageExtent = drawImageExtent; + + VkImageUsageFlags drawImageUsages{}; + drawImageUsages |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + drawImageUsages |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; + drawImageUsages |= VK_IMAGE_USAGE_STORAGE_BIT; + drawImageUsages |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + + VkImageCreateInfo rimg_info = VulkanInit::ImageCreateInfo(DrawImage.imageFormat, drawImageUsages, drawImageExtent); + + //for the draw image, we want to allocate it from gpu local memory + VmaAllocationCreateInfo rimg_allocinfo = {}; + rimg_allocinfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + rimg_allocinfo.requiredFlags = VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + //allocate and create the image + VK_CALL(vmaCreateImage(Allocator, &rimg_info, &rimg_allocinfo, &DrawImage.image, &DrawImage.allocation, nullptr)); + + //build a image-view for the draw image to use for rendering + VkImageViewCreateInfo rview_info = VulkanInit::ImageviewCreateInfo(DrawImage.imageFormat, DrawImage.image, VK_IMAGE_ASPECT_COLOR_BIT); + + VK_CALL(vkCreateImageView(Device, &rview_info, nullptr, &DrawImage.imageView)); + + //add to deletion queues + //ainDeletionQueue.push_function([=]() { + // vkDestroyImageView(Device, DrawImage.imageView, nullptr); + // vmaDestroyImage(Allocator, DrawImage.image, DrawImage.allocation); + //); } void VkRenderer::DestroySwapchain() @@ -242,7 +271,7 @@ void VkRenderer::InitCommands() // allocate the default command buffer that we will use for rendering VkCommandBufferAllocateInfo cmdAllocInfo = VulkanInit::CommandBufferAllocateInfo(Frames[i].CommandPool, 1); - vkAllocateCommandBuffers(Device, &cmdAllocInfo, &Frames[i].CommandBuffer); + VK_CALL(vkAllocateCommandBuffers(Device, &cmdAllocInfo, &Frames[i].CommandBuffer)); } } @@ -257,74 +286,160 @@ void VkRenderer::InitSync() for (int i = 0; i < FRAME_OVERLAP; i++) { - vkCreateFence(Device, &fenceCreateInfo, nullptr, &Frames[i].RenderFence); + VK_CALL(vkCreateFence(Device, &fenceCreateInfo, nullptr, &Frames[i].RenderFence)); - vkCreateSemaphore(Device, &semaphoreCreateInfo, nullptr, &Frames[i].SwapchainSemaphore); - vkCreateSemaphore(Device, &semaphoreCreateInfo, nullptr, &Frames[i].RenderSemaphore); + VK_CALL(vkCreateSemaphore(Device, &semaphoreCreateInfo, nullptr, &Frames[i].SwapchainSemaphore)); + VK_CALL(vkCreateSemaphore(Device, &semaphoreCreateInfo, nullptr, &Frames[i].RenderSemaphore)); } } +void VkRenderer::InitDescriptors() +{ + //create a descriptor pool that will hold 10 sets with 1 image each + std::vector sizes = + { + { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1 } + }; + + GlobalDescriptorAllocator.InitPool(Device, 1, sizes); + + //make the descriptor set layout for our compute draw + { + DescriptorLayoutBuilder builder; + builder.AddBinding(0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE); + DrawImageDescriptorLayout = builder.Build(Device, VK_SHADER_STAGE_COMPUTE_BIT); + } + + DrawImageDescriptors = GlobalDescriptorAllocator.Allocate(Device, DrawImageDescriptorLayout); + + UpdateDescriptorSets(); +} + +void VkRenderer::UpdateDescriptorSets() +{ + VkDescriptorImageInfo imgInfo{}; + imgInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; + imgInfo.imageView = DrawImage.imageView; + + VkWriteDescriptorSet drawImageWrite = {}; + drawImageWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + drawImageWrite.pNext = nullptr; + + drawImageWrite.dstBinding = 0; + drawImageWrite.dstSet = DrawImageDescriptors; + drawImageWrite.descriptorCount = 1; + drawImageWrite.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + drawImageWrite.pImageInfo = &imgInfo; + + vkUpdateDescriptorSets(Device, 1, &drawImageWrite, 0, nullptr); +} + +void VkRenderer::InitPipeline() +{ + InitBackgroundPipeline(); +} + +void VkRenderer::InitBackgroundPipeline() +{ + VkPipelineLayoutCreateInfo computeLayout{}; + computeLayout.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + computeLayout.pNext = nullptr; + computeLayout.pSetLayouts = &DrawImageDescriptorLayout; + computeLayout.setLayoutCount = 1; + + VK_CALL(vkCreatePipelineLayout(Device, &computeLayout, nullptr, &PipelineLayout)); + + VkPipelineShaderStageCreateInfo stageinfo{}; + stageinfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stageinfo.pNext = nullptr; + stageinfo.stage = VK_SHADER_STAGE_COMPUTE_BIT; + stageinfo.module = BackgroundShader->GetModule(); + stageinfo.pName = "main"; + + VkComputePipelineCreateInfo computePipelineCreateInfo{}; + computePipelineCreateInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; + computePipelineCreateInfo.pNext = nullptr; + computePipelineCreateInfo.layout = PipelineLayout; + computePipelineCreateInfo.stage = stageinfo; + + VK_CALL(vkCreateComputePipelines(Device, VK_NULL_HANDLE, 1, &computePipelineCreateInfo, nullptr, &Pipeline)); + + MainDeletionQueue.push_function([&]() { + vkDestroyPipelineLayout(Device, PipelineLayout, nullptr); + vkDestroyPipeline(Device, Pipeline, nullptr); + }); +} + void VkRenderer::Draw() { - vkWaitForFences(Device, 1, &GetCurrentFrame().RenderFence, true, 1000000000); - vkResetFences(Device, 1, &GetCurrentFrame().RenderFence); + VK_CALL(vkWaitForFences(Device, 1, &GetCurrentFrame().RenderFence, true, 1000000000)); + + //GetCurrentFrame().LocalDeletionQueue.flush(); //request image from the swapchain uint32_t swapchainImageIndex; VkResult result = vkAcquireNextImageKHR(Device, Swapchain, 1000000000, GetCurrentFrame().SwapchainSemaphore, nullptr, &swapchainImageIndex); - if (result == VK_ERROR_OUT_OF_DATE_KHR) + if (result == VK_ERROR_OUT_OF_DATE_KHR || SurfaceSize != Window::Get()->GetSize()) { - DestroySwapchain(); - CreateSwapchain(Window::Get()->GetSize()); + RecreateSwapchain(); + //DestroySwapchain(); + //CreateSwapchain(Window::Get()->GetSize()); return; } + VK_CALL(vkResetFences(Device, 1, &GetCurrentFrame().RenderFence)); + // Note: this will be the meat of the engine that should be here. VkCommandBuffer cmd = GetCurrentFrame().CommandBuffer; - vkResetCommandBuffer(cmd, 0); + VK_CALL(vkResetCommandBuffer(cmd, 0)); // Begin the command buffer recording. We will use this command buffer exactly once, so we want to let vulkan know that // Note: We might reuse them later!!! VkCommandBufferBeginInfo cmdBeginInfo = VulkanInit::CommandBufferBeginInfo(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + DrawExtent.width = DrawImage.imageExtent.width; + DrawExtent.height = DrawImage.imageExtent.height; - // Start the command buffer recording - vkBeginCommandBuffer(cmd, &cmdBeginInfo); + // Create commands + VK_CALL(vkBeginCommandBuffer(cmd, &cmdBeginInfo)); { - // We transfer current frame from any layout to general layout. - VulkanUtil::TransitionImage(cmd, SwapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); + // Transfer rendering image to general layout + VulkanUtil::TransitionImage(cmd, DrawImage.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); - float flash = std::abs(std::sin(FrameNumber / 120.f)); - VkClearColorValue clearValue; - clearValue = { { 0.0f, 0.0f, flash, 1.0f } }; + // Execute compute shader that writes to the image + vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, Pipeline); + vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, PipelineLayout, 0, 1, &DrawImageDescriptors, 0, nullptr); - VkImageSubresourceRange clearRange = VulkanInit::ImageSubResourceRange(VK_IMAGE_ASPECT_COLOR_BIT); + VulkanUtil::TransitionImage(cmd, DrawImage.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); + vkCmdDispatch(cmd, std::ceil(DrawExtent.width / 16.0), std::ceil(DrawExtent.height / 16.0), 1); - // TODO: Move to -> RenderCommand::Clear(); - vkCmdClearColorImage(cmd, SwapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_GENERAL, &clearValue, 1, &clearRange); + // Transition rendering iamge to transfert onto swapchain images + VulkanUtil::TransitionImage(cmd, DrawImage.image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + VulkanUtil::TransitionImage(cmd, SwapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - // From writable, to presentable layout - VulkanUtil::TransitionImage(cmd, SwapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); + // Execute a copy from the rendering image into the swapchain + VulkanUtil::CopyImageToImage(cmd, DrawImage.image, SwapchainImages[swapchainImageIndex], DrawExtent, SwapchainExtent); + + // Transition the swapchain image to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR for presentation + VulkanUtil::TransitionImage(cmd, SwapchainImages[swapchainImageIndex], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); } - vkEndCommandBuffer(cmd); + VK_CALL(vkEndCommandBuffer(cmd)); VkCommandBufferSubmitInfo cmdinfo = VulkanInit::CommandBufferSubmitInfo(cmd); // Wait for both semaphore of swapchain and the texture of the frame. VkSemaphoreSubmitInfo waitInfo = VulkanInit::SemaphoreSubmitInfo(VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR, GetCurrentFrame().SwapchainSemaphore); VkSemaphoreSubmitInfo signalInfo = VulkanInit::SemaphoreSubmitInfo(VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT, GetCurrentFrame().RenderSemaphore); - - // Submit command!! VkSubmitInfo2 submit = VulkanInit::SubmitInfo(&cmdinfo, &signalInfo, &waitInfo); - //submit command buffer to the queue and execute it. + // Submit command buffer to the queue and execute it. // _renderFence will now block until the graphic commands finish execution - vkQueueSubmit2(GPUQueue, 1, &submit, GetCurrentFrame().RenderFence); + VK_CALL(vkQueueSubmit2(GPUQueue, 1, &submit, GetCurrentFrame().RenderFence)); - //prepare present - // this will put the image we just rendered to into the visible window. - // we want to wait on the _renderSemaphore for that, - // as its necessary that drawing commands have finished before the image is displayed to the user + // Prepare present + // This will put the image we just rendered to into the visible window. + // We want to wait on the _renderSemaphore for that, + // as it's necessary that drawing commands have finished before the image is displayed to the user VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.pNext = nullptr; @@ -336,12 +451,27 @@ void VkRenderer::Draw() presentInfo.pImageIndices = &swapchainImageIndex; - vkQueuePresentKHR(GPUQueue, &presentInfo); + VK_CALL(vkQueuePresentKHR(GPUQueue, &presentInfo)); - //increase the number of frames drawn + // Increase the number of frames drawn FrameNumber++; } +void VkRenderer::DrawBackground(VkCommandBuffer cmd) +{ + // This works + //VkClearColorValue clearValue; + //float flash = std::abs(std::sin(FrameNumber / 120.f)); + //clearValue = { { 0.0f, 0.0f, flash, 1.0f } }; + //VkImageSubresourceRange clearRange = VulkanInit::ImageSubResourceRange(VK_IMAGE_ASPECT_COLOR_BIT); + //vkCmdClearColorImage(cmd, DrawImage.image, VK_IMAGE_LAYOUT_GENERAL, &clearValue, 1, &clearRange); + + // This doesnt!! + vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, Pipeline); + vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, PipelineLayout, 0, 1, &DrawImageDescriptors, 0, nullptr); + vkCmdDispatch(cmd, std::ceil(DrawExtent.width / 16.0), std::ceil(DrawExtent.height / 16.0), 1); +} + // Since well only be using those settings, this is just a shorthand. // Well only be using VK_COMMAND_BUFFER_LEVEL_PRIMARY @@ -450,6 +580,49 @@ VkSubmitInfo2 VulkanInit::SubmitInfo(VkCommandBufferSubmitInfo * cmd, VkSemaphor return info; } +VkImageCreateInfo VulkanInit::ImageCreateInfo(VkFormat format, VkImageUsageFlags usageFlags, VkExtent3D extent) +{ + VkImageCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + info.pNext = nullptr; + + info.imageType = VK_IMAGE_TYPE_2D; + + info.format = format; + info.extent = extent; + + info.mipLevels = 1; + info.arrayLayers = 1; + + //for MSAA. we will not be using it by default, so default it to 1 sample per pixel. + info.samples = VK_SAMPLE_COUNT_1_BIT; + + //optimal tiling, which means the image is stored on the best gpu format + info.tiling = VK_IMAGE_TILING_LINEAR; + info.usage = usageFlags; + + return info; +} + +VkImageViewCreateInfo VulkanInit::ImageviewCreateInfo(VkFormat format, VkImage image, VkImageAspectFlags aspectFlags) +{ + // build a image-view for the depth image to use for rendering + VkImageViewCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + info.pNext = nullptr; + + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.image = image; + info.format = format; + info.subresourceRange.baseMipLevel = 0; + info.subresourceRange.levelCount = 1; + info.subresourceRange.baseArrayLayer = 0; + info.subresourceRange.layerCount = 1; + info.subresourceRange.aspectMask = aspectFlags; + + return info; +} + // This is a helper to transtion images between readable, writable layouts. void VulkanUtil::TransitionImage(VkCommandBuffer cmd, VkImage image, VkImageLayout currentLayout, VkImageLayout newLayout) { @@ -460,7 +633,6 @@ void VulkanUtil::TransitionImage(VkCommandBuffer cmd, VkImage image, VkImageLayo imageBarrier.srcAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT; imageBarrier.dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; imageBarrier.dstAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT | VK_ACCESS_2_MEMORY_READ_BIT; - imageBarrier.oldLayout = currentLayout; imageBarrier.newLayout = newLayout; @@ -477,3 +649,114 @@ void VulkanUtil::TransitionImage(VkCommandBuffer cmd, VkImage image, VkImageLayo vkCmdPipelineBarrier2(cmd, &depInfo); } + +void VulkanUtil::CopyImageToImage(VkCommandBuffer cmd, VkImage source, VkImage destination, VkExtent2D srcSize, VkExtent2D dstSize) +{ + VkImageBlit2 blitRegion{ .sType = VK_STRUCTURE_TYPE_IMAGE_BLIT_2, .pNext = nullptr }; + + blitRegion.srcOffsets[1].x = srcSize.width; + blitRegion.srcOffsets[1].y = srcSize.height; + blitRegion.srcOffsets[1].z = 1; + + blitRegion.dstOffsets[1].x = dstSize.width; + blitRegion.dstOffsets[1].y = dstSize.height; + blitRegion.dstOffsets[1].z = 1; + + blitRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + blitRegion.srcSubresource.baseArrayLayer = 0; + blitRegion.srcSubresource.layerCount = 1; + blitRegion.srcSubresource.mipLevel = 0; + + blitRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + blitRegion.dstSubresource.baseArrayLayer = 0; + blitRegion.dstSubresource.layerCount = 1; + blitRegion.dstSubresource.mipLevel = 0; + + VkBlitImageInfo2 blitInfo{ .sType = VK_STRUCTURE_TYPE_BLIT_IMAGE_INFO_2, .pNext = nullptr }; + blitInfo.dstImage = destination; + blitInfo.dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + blitInfo.srcImage = source; + blitInfo.srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + blitInfo.filter = VK_FILTER_LINEAR; + blitInfo.regionCount = 1; + blitInfo.pRegions = &blitRegion; + + vkCmdBlitImage2(cmd, &blitInfo); +} + +void DescriptorLayoutBuilder::AddBinding(uint32_t binding, VkDescriptorType type) +{ + VkDescriptorSetLayoutBinding newbind{}; + newbind.binding = binding; + newbind.descriptorCount = 1; + newbind.descriptorType = type; + + Bindings.push_back(newbind); +} + +void DescriptorLayoutBuilder::Clear() +{ + Bindings.clear(); +} + +VkDescriptorSetLayout DescriptorLayoutBuilder::Build(VkDevice device, VkShaderStageFlags shaderStages, void * pNext, VkDescriptorSetLayoutCreateFlags flags) +{ + for (auto& b : Bindings) { + b.stageFlags |= shaderStages; + } + + VkDescriptorSetLayoutCreateInfo info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO }; + info.pNext = pNext; + + info.pBindings = Bindings.data(); + info.bindingCount = (uint32_t)Bindings.size(); + info.flags = flags; + + VkDescriptorSetLayout set; + VK_CALL(vkCreateDescriptorSetLayout(device, &info, nullptr, &set)); + + return set; +} + +void DescriptorAllocator::InitPool(VkDevice device, uint32_t maxSets, std::span poolRatios) +{ + std::vector poolSizes; + for (PoolSizeRatio ratio : poolRatios) { + poolSizes.push_back(VkDescriptorPoolSize{ + .type = ratio.type, + .descriptorCount = uint32_t(ratio.ratio * maxSets) + }); + } + + VkDescriptorPoolCreateInfo pool_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO }; + pool_info.flags = 0; + pool_info.maxSets = maxSets; + pool_info.poolSizeCount = (uint32_t)poolSizes.size(); + pool_info.pPoolSizes = poolSizes.data(); + + VK_CALL(vkCreateDescriptorPool(device, &pool_info, nullptr, &pool)); +} + +void DescriptorAllocator::ClearDescriptors(VkDevice device) +{ + vkResetDescriptorPool(device, pool, 0); +} + +void DescriptorAllocator::DestroyPool(VkDevice device) +{ + vkDestroyDescriptorPool(device, pool, nullptr); +} + +VkDescriptorSet DescriptorAllocator::Allocate(VkDevice device, VkDescriptorSetLayout layout) +{ + VkDescriptorSetAllocateInfo allocInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO }; + allocInfo.pNext = nullptr; + allocInfo.descriptorPool = pool; + allocInfo.descriptorSetCount = 1; + allocInfo.pSetLayouts = &layout; + + VkDescriptorSet ds; + VK_CALL(vkAllocateDescriptorSets(device, &allocInfo, &ds)); + + return ds; +} diff --git a/Nuake/src/Rendering/Vulkan/VulkanRenderer.h b/Nuake/src/Rendering/Vulkan/VulkanRenderer.h index c1b08806..cd6af671 100644 --- a/Nuake/src/Rendering/Vulkan/VulkanRenderer.h +++ b/Nuake/src/Rendering/Vulkan/VulkanRenderer.h @@ -5,12 +5,25 @@ #include #include "vkb/VkBootstrap.h" -#include "vk_mem_alloc.h" +#include "VulkanCheck.h" +#include "vk_mem_alloc.h" +# #include +#include namespace Nuake { + class VulkanShader; + + struct AllocatedImage { + VkImage image; + VkImageView imageView; + VmaAllocation allocation; + VkExtent3D imageExtent; + VkFormat imageFormat; + }; + // Since we need to delete things in order, and manually doing it in the cleanup is // too tedious to maintain. We will use a queue of destructor to execute in inverse order // of insertion @@ -71,13 +84,40 @@ namespace Nuake }; + struct DescriptorLayoutBuilder + { + + std::vector Bindings; + + void AddBinding(uint32_t binding, VkDescriptorType type); + void Clear(); + VkDescriptorSetLayout Build(VkDevice device, VkShaderStageFlags shaderStages, void* pNext = nullptr, VkDescriptorSetLayoutCreateFlags flags = 0); + }; + + struct DescriptorAllocator + { + struct PoolSizeRatio + { + VkDescriptorType type; + float ratio; + }; + + VkDescriptorPool pool; + + void InitPool(VkDevice device, uint32_t maxSets, std::span poolRatios); + void ClearDescriptors(VkDevice device); + void DestroyPool(VkDevice device); + + VkDescriptorSet Allocate(VkDevice device, VkDescriptorSetLayout layout); + }; + constexpr unsigned int FRAME_OVERLAP = 2; class VkRenderer { private: bool IsInitialized = false; - + Vector2 SurfaceSize; VkInstance Instance; vkb::Instance VkbInstance; VkDebugUtilsMessengerEXT VkDebugMessenger; @@ -99,12 +139,27 @@ namespace Nuake FrameData Frames[FRAME_OVERLAP]; FrameData& GetCurrentFrame() { return Frames[FrameNumber % FRAME_OVERLAP]; }; + AllocatedImage DrawImage; + VkExtent2D DrawExtent; + VkQueue GPUQueue; uint32_t GPUQueueFamily; DeletionQueue MainDeletionQueue; VmaAllocator Allocator; + + // Descriptors + DescriptorAllocator GlobalDescriptorAllocator; + + VkDescriptorSet DrawImageDescriptors; + VkDescriptorSetLayout DrawImageDescriptorLayout; + + // Pipeline + VkPipeline Pipeline; + VkPipelineLayout PipelineLayout; + + Ref BackgroundShader; public: static VkRenderer& Get() @@ -116,19 +171,33 @@ namespace Nuake VkRenderer() = default; ~VkRenderer(); + VkDevice GetDevice() const + { + return Device; + } + public: void Initialize(); void CleanUp(); void GetInstance(); void SelectGPU(); + + void RecreateSwapchain(); void CreateSwapchain(const Vector2& size); void DestroySwapchain(); + + void InitCommands(); void InitSync(); + void InitDescriptors(); + void UpdateDescriptorSets(); + void InitPipeline(); + void InitBackgroundPipeline(); void Draw(); + void DrawBackground(VkCommandBuffer cmd); }; @@ -149,6 +218,8 @@ namespace Nuake static VkCommandBufferSubmitInfo CommandBufferSubmitInfo(VkCommandBuffer cmd); static VkSubmitInfo2 SubmitInfo(VkCommandBufferSubmitInfo* cmd, VkSemaphoreSubmitInfo* signalSemaphoreInfo, VkSemaphoreSubmitInfo* waitSemaphoreInfo); + static VkImageCreateInfo ImageCreateInfo(VkFormat format, VkImageUsageFlags usageFlags, VkExtent3D extent); + static VkImageViewCreateInfo ImageviewCreateInfo(VkFormat format, VkImage image, VkImageAspectFlags aspectFlags); }; class VulkanUtil @@ -158,5 +229,6 @@ namespace Nuake ~VulkanUtil() = delete; static void TransitionImage(VkCommandBuffer cmd, VkImage image, VkImageLayout currentLayout, VkImageLayout newLayout); + static void CopyImageToImage(VkCommandBuffer cmd, VkImage source, VkImage destination, VkExtent2D srcSize, VkExtent2D dstSize); }; } \ No newline at end of file diff --git a/Nuake/src/Rendering/Vulkan/VulkanShader.cpp b/Nuake/src/Rendering/Vulkan/VulkanShader.cpp new file mode 100644 index 00000000..980743b7 --- /dev/null +++ b/Nuake/src/Rendering/Vulkan/VulkanShader.cpp @@ -0,0 +1,15 @@ +#include "VulkanShader.h" +#include "VulkanRenderer.h" + +using namespace Nuake; + +VulkanShader::VulkanShader(uint32_t* bytecode, uint32_t bytecodeLength, ShaderType type) +{ + Type = type; + + VkShaderModuleCreateInfo shaderModuleCI{}; + shaderModuleCI.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + shaderModuleCI.codeSize = bytecodeLength; + shaderModuleCI.pCode = bytecode; + vkCreateShaderModule(VkRenderer::Get().GetDevice(), &shaderModuleCI, nullptr, &Module); +} \ No newline at end of file diff --git a/Nuake/src/Rendering/Vulkan/VulkanShader.h b/Nuake/src/Rendering/Vulkan/VulkanShader.h new file mode 100644 index 00000000..3e91bfdc --- /dev/null +++ b/Nuake/src/Rendering/Vulkan/VulkanShader.h @@ -0,0 +1,29 @@ +#pragma once + +#include "src/Core/Core.h" + +#include + +namespace Nuake +{ + enum class ShaderType + { + Vertex, + Fragment, + Compute + }; + + class VulkanShader + { + private: + VkShaderModule Module; + ShaderType Type; + + public: + VulkanShader(uint32_t* bytecode, uint32_t bytecodeLength, ShaderType type); + ~VulkanShader() = default; + + ShaderType GetType() const { return Type; } + VkShaderModule GetModule() const { return Module; } + }; +} \ No newline at end of file diff --git a/Nuake/src/Window.cpp b/Nuake/src/Window.cpp index f9f44d4c..65ec2836 100644 --- a/Nuake/src/Window.cpp +++ b/Nuake/src/Window.cpp @@ -72,9 +72,9 @@ int Window::Init() return -1; } - SetWindowIcon("resources/Images/nuake-logo.png"); + //SetWindowIcon("resources/Images/nuake-logo.png"); glfwMakeContextCurrent(this->window); - SetVSync(false); + //SetVSync(false); #ifndef NK_VK @@ -88,55 +88,55 @@ int Window::Init() #endif - if (glfwRawMouseMotionSupported()) - glfwSetInputMode(this->window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE); - - // TODO: Move this to renderer init. The window shouldnt have to do gl calls. - glfwWindowHint(GLFW_SAMPLES, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + //if (glfwRawMouseMotionSupported()) + // glfwSetInputMode(this->window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE); + // + //// TODO: Move this to renderer init. The window shouldnt have to do gl calls. + //glfwWindowHint(GLFW_SAMPLES, 4); + //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - glfwSetWindowUserPointer(window, this); - - glfwSetWindowCloseCallback(window, [](GLFWwindow* nativeWindow) - { - Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); - window->OnWindowClosed(*window); - }); - - glfwSetWindowFocusCallback(window, [](GLFWwindow* nativeWindow, int focused) - { - Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); - window->OnWindowFocused(*window, static_cast(focused)); - }); - - glfwSetDropCallback(window, [](GLFWwindow* nativeWindow, int count, const char** paths) - { - std::vector filePaths; - filePaths.reserve(count); - - int i; - for (i = 0; i < count; i++) - { - std::string filePath = std::string(paths[i]); - filePaths.push_back(filePath); - } - - Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); - window->OnDragNDropCallback(*window, filePaths); - }); - - glfwSetTitlebarHitTestCallback(window, [](GLFWwindow* nativeWindow, int x, int y, int* hit) - { - bool isHit = false; - Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); - - window->TitlebarHitTest(*window, x, y, isHit); - - *hit = isHit; - }); + //glfwSetWindowUserPointer(window, this); + // + //glfwSetWindowCloseCallback(window, [](GLFWwindow* nativeWindow) + // { + // Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); + // window->OnWindowClosed(*window); + // }); + // + //glfwSetWindowFocusCallback(window, [](GLFWwindow* nativeWindow, int focused) + // { + // Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); + // window->OnWindowFocused(*window, static_cast(focused)); + // }); + // + //glfwSetDropCallback(window, [](GLFWwindow* nativeWindow, int count, const char** paths) + // { + // std::vector filePaths; + // filePaths.reserve(count); + // + // int i; + // for (i = 0; i < count; i++) + // { + // std::string filePath = std::string(paths[i]); + // filePaths.push_back(filePath); + // } + // + // Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); + // window->OnDragNDropCallback(*window, filePaths); + // }); + // + //glfwSetTitlebarHitTestCallback(window, [](GLFWwindow* nativeWindow, int x, int y, int* hit) + //{ + // bool isHit = false; + // Window* window = reinterpret_cast(glfwGetWindowUserPointer(nativeWindow)); + // + // window->TitlebarHitTest(*window, x, y, isHit); + // + // *hit = isHit; + //}); #ifndef NK_VK // TODO: have clear color in environnement. @@ -163,9 +163,9 @@ int Window::Init() //glEnable(GL_CULL_FACE); // Create viewports - InitImgui(); + //InitImgui(); - Logger::Log("ImGui initialized ", "renderer"); + //Logger::Log("ImGui initialized ", "renderer"); return 0; } diff --git a/Resources/Shaders/Vulkan/background.comp b/Resources/Shaders/Vulkan/background.comp new file mode 100644 index 00000000..a5c01f28 --- /dev/null +++ b/Resources/Shaders/Vulkan/background.comp @@ -0,0 +1,28 @@ +// HLSL version for Shader Model 6.1 +RWTexture2D image : register(u0); + +// Define the size of a thread group +[numthreads(16, 16, 1)] +void main( + uint3 dispatchThreadID : SV_DispatchThreadID, + uint3 groupThreadID : SV_GroupThreadID, + uint3 groupID : SV_GroupID +) { + // Get the size of the image + uint2 size; + image.GetDimensions(size.x, size.y); + + // Current texel coordinates + uint2 texelCoord = dispatchThreadID.xy; + + if (texelCoord.x < size.x && texelCoord.y < size.y) { + float4 color = float4(0.0, 0.0, 0.0, 1.0); + + if (groupThreadID.x != 0 && groupThreadID.y != 0) { + color.x = float(texelCoord.x) / float(size.x); + color.y = float(texelCoord.y) / float(size.y); + } + + image[texelCoord] = color; + } +} \ No newline at end of file diff --git a/premake5.lua b/premake5.lua index ecfe6633..0e3d9c3a 100644 --- a/premake5.lua +++ b/premake5.lua @@ -183,15 +183,20 @@ project "Nuake" "%{prj.name}/dependencies/freetype/include", "%{prj.name}/dependencies/tracy/public/tracy", "%{prj.name}/dependencies/entt/src", - "%{prj.name}/dependencies/vma/include" + "%{prj.name}/dependencies/vma/include", + "%{prj.name}/dependencies/dxc/inc" } + libdirs { "%{prj.name}/dependencies/dxc/lib/x64" } + links { "soloud", "tracy", "yoga", - "vma" + "vma", + "dxcompiler" + } filter "system:linux"