diff options
| author | Jason Maskell <[email protected]> | 2016-05-09 10:39:54 +0200 |
|---|---|---|
| committer | Jason Maskell <[email protected]> | 2016-05-09 10:39:54 +0200 |
| commit | 79b3462799c28af8ba586349bd671b1b56e72353 (patch) | |
| tree | 3b06e36c390254c0dc7f3733a0d32af213d87293 /sample/d3d11/Effects11 | |
| download | waveworks_archive-79b3462799c28af8ba586349bd671b1b56e72353.tar.xz waveworks_archive-79b3462799c28af8ba586349bd671b1b56e72353.zip | |
Initial commit with PS4 and XBone stuff trimmed.
Diffstat (limited to 'sample/d3d11/Effects11')
| -rw-r--r-- | sample/d3d11/Effects11/Binary/EffectBinaryFormat.h | 666 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/Binary/EffectStateBase11.h | 49 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/Binary/EffectStates11.h | 236 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/Binary/SOParser.h | 311 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/Effect.h | 1226 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/EffectAPI.cpp | 29 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/EffectLoad.cpp | 3982 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/EffectLoad.h | 149 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/EffectNonRuntime.cpp | 2963 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/EffectReflection.cpp | 2151 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/EffectRuntime.cpp | 694 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/EffectVariable.inl | 4573 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/Inc/d3dx11dbg.h | 66 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/Inc/d3dx11effect.h | 1566 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/Inc/d3dxGlobal.h | 1337 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/d3dx11dbg.cpp | 62 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/d3dxGlobal.cpp | 351 | ||||
| -rw-r--r-- | sample/d3d11/Effects11/pchfx.h | 44 |
18 files changed, 20455 insertions, 0 deletions
diff --git a/sample/d3d11/Effects11/Binary/EffectBinaryFormat.h b/sample/d3d11/Effects11/Binary/EffectBinaryFormat.h new file mode 100644 index 0000000..50c5ce3 --- /dev/null +++ b/sample/d3d11/Effects11/Binary/EffectBinaryFormat.h @@ -0,0 +1,666 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: Effect.h +// Content: D3DX11 Effects Binary Format +// This is the binary file interface shared between the Effects +// compiler and runtime. +// +////////////////////////////////////////////////////////////////////////////// + +#pragma once + +namespace D3DX11Effects +{ + + +////////////////////////////////////////////////////////////////////////// +// Version Control +////////////////////////////////////////////////////////////////////////// + +#define D3D10_FXL_VERSION(_Major,_Minor) (('F' << 24) | ('X' << 16) | ((_Major) << 8) | (_Minor)) + +struct EVersionTag +{ + const char* m_pName; + DWORD m_Version; + UINT m_Tag; +}; + +// versions must be listed in ascending order +static CONST EVersionTag g_EffectVersions[] = +{ + { "fx_4_0", D3D10_FXL_VERSION(4,0), 0xFEFF1001 }, + { "fx_4_1", D3D10_FXL_VERSION(4,1), 0xFEFF1011 }, + { "fx_5_0", D3D10_FXL_VERSION(5,0), 0xFEFF2001 }, +}; +#define NUM_EFFECT10_VERSIONS ( sizeof(g_EffectVersions) / sizeof(EVersionTag) ) + + +////////////////////////////////////////////////////////////////////////// +// Reflection & Type structures +////////////////////////////////////////////////////////////////////////// + +// Enumeration of the possible left-hand side values of an assignment, +// divided up categorically by the type of block they may appear in +enum ELhsType +{ + ELHS_Invalid, + + // Pass block assignment types + + ELHS_PixelShaderBlock, // SBlock *pValue points to the block to apply + ELHS_VertexShaderBlock, + ELHS_GeometryShaderBlock, + ELHS_RenderTargetView, + ELHS_DepthStencilView, + + ELHS_RasterizerBlock, + ELHS_DepthStencilBlock, + ELHS_BlendBlock, + + ELHS_GenerateMips, // This is really a call to D3D::GenerateMips + + // Various SAssignment.Value.* + + ELHS_DS_StencilRef, // SAssignment.Value.pdValue + ELHS_B_BlendFactor, // D3D10_BLEND_CONFIG.BlendFactor, points to a float4 + ELHS_B_SampleMask, // D3D10_BLEND_CONFIG.SampleMask + + ELHS_GeometryShaderSO, // When setting SO assignments, GeometryShaderSO precedes the actual GeometryShader assn + + ELHS_ComputeShaderBlock, + ELHS_HullShaderBlock, + ELHS_DomainShaderBlock, + + // Rasterizer + + ELHS_FillMode = 0x20000, + ELHS_CullMode, + ELHS_FrontCC, + ELHS_DepthBias, + ELHS_DepthBiasClamp, + ELHS_SlopeScaledDepthBias, + ELHS_DepthClipEnable, + ELHS_ScissorEnable, + ELHS_MultisampleEnable, + ELHS_AntialiasedLineEnable, + + // Sampler + + ELHS_Filter = 0x30000, + ELHS_AddressU, + ELHS_AddressV, + ELHS_AddressW, + ELHS_MipLODBias, + ELHS_MaxAnisotropy, + ELHS_ComparisonFunc, + ELHS_BorderColor, + ELHS_MinLOD, + ELHS_MaxLOD, + ELHS_Texture, + + // DepthStencil + + ELHS_DepthEnable = 0x40000, + ELHS_DepthWriteMask, + ELHS_DepthFunc, + ELHS_StencilEnable, + ELHS_StencilReadMask, + ELHS_StencilWriteMask, + ELHS_FrontFaceStencilFailOp, + ELHS_FrontFaceStencilDepthFailOp, + ELHS_FrontFaceStencilPassOp, + ELHS_FrontFaceStencilFunc, + ELHS_BackFaceStencilFailOp, + ELHS_BackFaceStencilDepthFailOp, + ELHS_BackFaceStencilPassOp, + ELHS_BackFaceStencilFunc, + + // BlendState + + ELHS_AlphaToCoverage = 0x50000, + ELHS_BlendEnable, + ELHS_SrcBlend, + ELHS_DestBlend, + ELHS_BlendOp, + ELHS_SrcBlendAlpha, + ELHS_DestBlendAlpha, + ELHS_BlendOpAlpha, + ELHS_RenderTargetWriteMask, +}; + + + +enum EBlockType +{ + EBT_Invalid, + EBT_DepthStencil, + EBT_Blend, + EBT_Rasterizer, + EBT_Sampler, + EBT_Pass +}; + +enum EVarType +{ + EVT_Invalid, + EVT_Numeric, + EVT_Object, + EVT_Struct, + EVT_Interface, +}; + +enum EScalarType +{ + EST_Invalid, + EST_Float, + EST_Int, + EST_UInt, + EST_Bool, + EST_Count +}; + +enum ENumericLayout +{ + ENL_Invalid, + ENL_Scalar, + ENL_Vector, + ENL_Matrix, + ENL_Count +}; + +enum EObjectType +{ + EOT_Invalid, + EOT_String, + EOT_Blend, + EOT_DepthStencil, + EOT_Rasterizer, + EOT_PixelShader, + EOT_VertexShader, + EOT_GeometryShader, // Regular geometry shader + EOT_GeometryShaderSO, // Geometry shader with a attached StreamOut decl + EOT_Texture, + EOT_Texture1D, + EOT_Texture1DArray, + EOT_Texture2D, + EOT_Texture2DArray, + EOT_Texture2DMS, + EOT_Texture2DMSArray, + EOT_Texture3D, + EOT_TextureCube, + EOT_ConstantBuffer, + EOT_RenderTargetView, + EOT_DepthStencilView, + EOT_Sampler, + EOT_Buffer, + EOT_TextureCubeArray, + EOT_Count, + EOT_PixelShader5, + EOT_VertexShader5, + EOT_GeometryShader5, + EOT_ComputeShader5, + EOT_HullShader5, + EOT_DomainShader5, + EOT_RWTexture1D, + EOT_RWTexture1DArray, + EOT_RWTexture2D, + EOT_RWTexture2DArray, + EOT_RWTexture3D, + EOT_RWBuffer, + EOT_ByteAddressBuffer, + EOT_RWByteAddressBuffer, + EOT_StructuredBuffer, + EOT_RWStructuredBuffer, + EOT_RWStructuredBufferAlloc, + EOT_RWStructuredBufferConsume, + EOT_AppendStructuredBuffer, + EOT_ConsumeStructuredBuffer, +}; + +D3DX11INLINE BOOL IsObjectTypeHelper(EVarType InVarType, + EObjectType InObjType, + EObjectType TargetObjType) +{ + return (InVarType == EVT_Object) && (InObjType == TargetObjType); +} + +D3DX11INLINE BOOL IsSamplerHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && (InObjType == EOT_Sampler); +} + +D3DX11INLINE BOOL IsStateBlockObjectHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && ((InObjType == EOT_Blend) || (InObjType == EOT_DepthStencil) || (InObjType == EOT_Rasterizer) || IsSamplerHelper(InVarType, InObjType)); +} + +D3DX11INLINE BOOL IsShaderHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && ((InObjType == EOT_VertexShader) || + (InObjType == EOT_VertexShader5) || + (InObjType == EOT_HullShader5) || + (InObjType == EOT_DomainShader5) || + (InObjType == EOT_ComputeShader5) || + (InObjType == EOT_GeometryShader) || + (InObjType == EOT_GeometryShaderSO) || + (InObjType == EOT_GeometryShader5) || + (InObjType == EOT_PixelShader) || + (InObjType == EOT_PixelShader5)); +} + +D3DX11INLINE BOOL IsShader5Helper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && ((InObjType == EOT_VertexShader5) || + (InObjType == EOT_HullShader5) || + (InObjType == EOT_DomainShader5) || + (InObjType == EOT_ComputeShader5) || + (InObjType == EOT_GeometryShader5) || + (InObjType == EOT_PixelShader5)); +} + +D3DX11INLINE BOOL IsInterfaceHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Interface); +} + +D3DX11INLINE BOOL IsShaderResourceHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && ((InObjType == EOT_Texture) || + (InObjType == EOT_Texture1D) || + (InObjType == EOT_Texture1DArray) || + (InObjType == EOT_Texture2D) || + (InObjType == EOT_Texture2DArray) || + (InObjType == EOT_Texture2DMS) || + (InObjType == EOT_Texture2DMSArray) || + (InObjType == EOT_Texture3D) || + (InObjType == EOT_TextureCube) || + (InObjType == EOT_TextureCubeArray) || + (InObjType == EOT_Buffer) || + (InObjType == EOT_StructuredBuffer) || + (InObjType == EOT_ByteAddressBuffer)); +} + +D3DX11INLINE BOOL IsUnorderedAccessViewHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && + ((InObjType == EOT_RWTexture1D) || + (InObjType == EOT_RWTexture1DArray) || + (InObjType == EOT_RWTexture2D) || + (InObjType == EOT_RWTexture2DArray) || + (InObjType == EOT_RWTexture3D) || + (InObjType == EOT_RWBuffer) || + (InObjType == EOT_RWByteAddressBuffer) || + (InObjType == EOT_RWStructuredBuffer) || + (InObjType == EOT_RWStructuredBufferAlloc) || + (InObjType == EOT_RWStructuredBufferConsume) || + (InObjType == EOT_AppendStructuredBuffer) || + (InObjType == EOT_ConsumeStructuredBuffer)); +} + +D3DX11INLINE BOOL IsRenderTargetViewHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && (InObjType == EOT_RenderTargetView); +} + +D3DX11INLINE BOOL IsDepthStencilViewHelper(EVarType InVarType, + EObjectType InObjType) +{ + return (InVarType == EVT_Object) && (InObjType == EOT_DepthStencilView); +} + +D3DX11INLINE BOOL IsObjectAssignmentHelper(ELhsType LhsType) +{ + switch(LhsType) + { + case ELHS_VertexShaderBlock: + case ELHS_HullShaderBlock: + case ELHS_DepthStencilView: + case ELHS_GeometryShaderBlock: + case ELHS_PixelShaderBlock: + case ELHS_ComputeShaderBlock: + case ELHS_DepthStencilBlock: + case ELHS_RasterizerBlock: + case ELHS_BlendBlock: + case ELHS_Texture: + case ELHS_RenderTargetView: + case ELHS_DomainShaderBlock: + return TRUE; + } + return FALSE; +} + + + + +// Effect file format structures ///////////////////////////////////////////// +// File format: +// File header (SBinaryHeader Header) +// Unstructured data block (BYTE[Header.cbUnstructured)) +// Structured data block +// ConstantBuffer (SBinaryConstantBuffer CB) * Header.Effect.cCBs +// UINT NumAnnotations +// Annotation data (SBinaryAnnotation) * (NumAnnotations) *this structure is variable sized +// Variable data (SBinaryNumericVariable Var) * (CB.cVariables) +// UINT NumAnnotations +// Annotation data (SBinaryAnnotation) * (NumAnnotations) *this structure is variable sized +// Object variables (SBinaryObjectVariable Var) * (Header.cObjectVariables) *this structure is variable sized +// UINT NumAnnotations +// Annotation data (SBinaryAnnotation) * (NumAnnotations) *this structure is variable sized +// Interface variables (SBinaryInterfaceVariable Var) * (Header.cInterfaceVariables) *this structure is variable sized +// UINT NumAnnotations +// Annotation data (SBinaryAnnotation) * (NumAnnotations) *this structure is variable sized +// Groups (SBinaryGroup Group) * Header.cGroups +// UINT NumAnnotations +// Annotation data (SBinaryAnnotation) * (NumAnnotations) *this structure is variable sized +// Techniques (SBinaryTechnique Technique) * Group.cTechniques +// UINT NumAnnotations +// Annotation data (SBinaryAnnotation) * (NumAnnotations) *this structure is variable sized +// Pass (SBinaryPass Pass) * Technique.cPasses +// UINT NumAnnotations +// Annotation data (SBinaryAnnotation) * (NumAnnotations) *this structure is variable sized +// Pass assignments (SBinaryAssignment) * Pass.cAssignments + +struct SBinaryHeader +{ + struct SVarCounts + { + UINT cCBs; + UINT cNumericVariables; + UINT cObjectVariables; + }; + + UINT Tag; // should be equal to c_EffectFileTag + // this is used to identify ASCII vs Binary files + + SVarCounts Effect; + SVarCounts Pool; + + UINT cTechniques; + UINT cbUnstructured; + + UINT cStrings; + UINT cShaderResources; + + UINT cDepthStencilBlocks; + UINT cBlendStateBlocks; + UINT cRasterizerStateBlocks; + UINT cSamplers; + UINT cRenderTargetViews; + UINT cDepthStencilViews; + + UINT cTotalShaders; + UINT cInlineShaders; // of the aforementioned shaders, the number that are defined inline within pass blocks + + D3DX11INLINE bool RequiresPool() const + { + return (Pool.cCBs != 0) || + (Pool.cNumericVariables != 0) || + (Pool.cObjectVariables != 0); + } +}; + +struct SBinaryHeader5 : public SBinaryHeader +{ + UINT cGroups; + UINT cUnorderedAccessViews; + UINT cInterfaceVariables; + UINT cInterfaceVariableElements; + UINT cClassInstanceElements; +}; + +// Constant buffer definition +struct SBinaryConstantBuffer +{ + // private flags + static const UINT c_IsTBuffer = (1 << 0); + static const UINT c_IsSingle = (1 << 1); + + UINT oName; // Offset to constant buffer name + UINT Size; // Size, in bytes + UINT Flags; + UINT cVariables; // # of variables inside this buffer + UINT ExplicitBindPoint; // Defined if the effect file specifies a bind point using the register keyword + // otherwise, -1 +}; + +struct SBinaryAnnotation +{ + UINT oName; // Offset to variable name + UINT oType; // Offset to type information (SBinaryType) + + // For numeric annotations: + // UINT oDefaultValue; // Offset to default initializer value + // + // For string annotations: + // UINT oStringOffsets[Elements]; // Elements comes from the type data at oType +}; + +struct SBinaryNumericVariable +{ + UINT oName; // Offset to variable name + UINT oType; // Offset to type information (SBinaryType) + UINT oSemantic; // Offset to semantic information + UINT Offset; // Offset in parent constant buffer + UINT oDefaultValue; // Offset to default initializer value + UINT Flags; // Explicit bind point +}; + +struct SBinaryInterfaceVariable +{ + UINT oName; // Offset to variable name + UINT oType; // Offset to type information (SBinaryType) + UINT oDefaultValue; // Offset to default initializer array (SBinaryInterfaceInitializer[Elements]) + UINT Flags; +}; + +struct SBinaryInterfaceInitializer +{ + UINT oInstanceName; + UINT ArrayIndex; +}; + +struct SBinaryObjectVariable +{ + UINT oName; // Offset to variable name + UINT oType; // Offset to type information (SBinaryType) + UINT oSemantic; // Offset to semantic information + UINT ExplicitBindPoint; // Used when a variable has been explicitly bound (register(XX)). -1 if not + + // Initializer data: + // + // The type structure pointed to by oType gives you Elements, + // VarType (must be EVT_Object), and ObjectType + // + // For ObjectType == EOT_Blend, EOT_DepthStencil, EOT_Rasterizer, EOT_Sampler + // struct + // { + // UINT cAssignments; + // SBinaryAssignment Assignments[cAssignments]; + // } Blocks[Elements] + // + // For EObjectType == EOT_Texture*, EOT_Buffer + // <nothing> + // + // For EObjectType == EOT_*Shader, EOT_String + // UINT oData[Elements]; // offsets to a shader data block or a NULL-terminated string + // + // For EObjectType == EOT_GeometryShaderSO + // SBinaryGSSOInitializer[Elements] + // + // For EObjectType == EOT_*Shader5 + // SBinaryShaderData5[Elements] +}; + +struct SBinaryGSSOInitializer +{ + UINT oShader; // Offset to shader bytecode data block + UINT oSODecl; // Offset to StreamOutput decl string +}; + +struct SBinaryShaderData5 +{ + UINT oShader; // Offset to shader bytecode data block + UINT oSODecls[4]; // Offset to StreamOutput decl strings + UINT cSODecls; // Count of valid oSODecls entries. + UINT RasterizedStream; // Which stream is used for rasterization + UINT cInterfaceBindings; // Count of interface bindings. + UINT oInterfaceBindings; // Offset to SBinaryInterfaceInitializer[cInterfaceBindings]. +}; + +struct SBinaryType +{ + UINT oTypeName; // Offset to friendly type name ("float4", "VS_OUTPUT") + EVarType VarType; // Numeric, Object, or Struct + UINT Elements; // # of array elements (0 for non-arrays) + UINT TotalSize; // Size in bytes; not necessarily Stride * Elements for arrays + // because of possible gap left in final register + UINT Stride; // If an array, this is the spacing between elements. + // For unpacked arrays, always divisible by 16-bytes (1 register). + // No support for packed arrays + UINT PackedSize; // Size, in bytes, of this data typed when fully packed + + struct SBinaryMember + { + UINT oName; // Offset to structure member name ("m_pFoo") + UINT oSemantic; // Offset to semantic ("POSITION0") + UINT Offset; // Offset, in bytes, relative to start of parent structure + UINT oType; // Offset to member's type descriptor + }; + + // the data that follows depends on the VarType: + // Numeric: SType::SNumericType + // Object: EObjectType + // Struct: + // struct + // { + // UINT cMembers; + // SBinaryMembers Members[cMembers]; + // } MemberInfo + // struct + // { + // UINT oBaseClassType; // Offset to type information (SBinaryType) + // UINT cInterfaces; + // UINT oInterfaceTypes[cInterfaces]; + // } SBinaryTypeInheritance + // Interface: (nothing) +}; + +struct SBinaryNumericType +{ + ENumericLayout NumericLayout : 3; // scalar (1x1), vector (1xN), matrix (NxN) + EScalarType ScalarType : 5; // float32, int32, int8, etc. + UINT Rows : 3; // 1 <= Rows <= 4 + UINT Columns : 3; // 1 <= Columns <= 4 + UINT IsColumnMajor : 1; // applies only to matrices + UINT IsPackedArray : 1; // if this is an array, indicates whether elements should be greedily packed +}; + +struct SBinaryTypeInheritance +{ + UINT oBaseClass; // Offset to base class type info or 0 if no base class. + UINT cInterfaces; + + // Followed by UINT[cInterfaces] with offsets to the type + // info of each interface. +}; + +struct SBinaryGroup +{ + UINT oName; + UINT cTechniques; +}; + +struct SBinaryTechnique +{ + UINT oName; + UINT cPasses; +}; + +struct SBinaryPass +{ + UINT oName; + UINT cAssignments; +}; + +enum ECompilerAssignmentType +{ + ECAT_Invalid, // Assignment-specific data (always in the unstructured blob) + ECAT_Constant, // -N SConstant structures + ECAT_Variable, // -NULL terminated string with variable name ("foo") + ECAT_ConstIndex, // -SConstantIndex structure + ECAT_VariableIndex, // -SVariableIndex structure + ECAT_ExpressionIndex, // -SIndexedObjectExpression structure + ECAT_Expression, // -Data block containing FXLVM code + ECAT_InlineShader, // -Data block containing shader + ECAT_InlineShader5, // -Data block containing shader with extended 5.0 data (SBinaryShaderData5) +}; + +struct SBinaryAssignment +{ + UINT iState; // index into g_lvGeneral + UINT Index; // the particular index to assign to (see g_lvGeneral to find the # of valid indices) + ECompilerAssignmentType AssignmentType; + UINT oInitializer; // Offset of assignment-specific data + + //struct SConstantAssignment + //{ + // UINT NumConstants; // number of constants to follow + // SCompilerConstant Constants[NumConstants]; + //}; + + struct SConstantIndex + { + UINT oArrayName; + UINT Index; + }; + + struct SVariableIndex + { + UINT oArrayName; + UINT oIndexVarName; + }; + + struct SIndexedObjectExpression + { + UINT oArrayName; + UINT oCode; + }; + + struct SInlineShader + { + UINT oShader; + UINT oSODecl; + }; + + //struct SExpression or SInlineShader + //{ + // UINT DataSize; + // BYTE Data[DataSize]; + //} + +}; + +struct SBinaryConstant +{ + EScalarType Type; + union + { + BOOL bValue; + INT iValue; + float fValue; + }; +}; + + +} // end namespace D3DX11Effects diff --git a/sample/d3d11/Effects11/Binary/EffectStateBase11.h b/sample/d3d11/Effects11/Binary/EffectStateBase11.h new file mode 100644 index 0000000..3727da2 --- /dev/null +++ b/sample/d3d11/Effects11/Binary/EffectStateBase11.h @@ -0,0 +1,49 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectStateBase11.h +// Content: D3DX11 Effects States Header +// +////////////////////////////////////////////////////////////////////////////// + +#pragma once + +namespace D3DX11Effects +{ + +////////////////////////////////////////////////////////////////////////// +// Effect HLSL states and late resolve lists +////////////////////////////////////////////////////////////////////////// + +struct RValue +{ + const char *m_pName; + UINT m_Value; +}; + +#define RVALUE_END() { NULL, 0U } +#define RVALUE_ENTRY(prefix, x) { #x, (UINT)prefix##x } + +enum ELhsType; + +struct LValue +{ + const char *m_pName; // name of the LHS side of expression + EBlockType m_BlockType; // type of block it can appear in + D3D10_SHADER_VARIABLE_TYPE m_Type; // data type allows + UINT m_Cols; // number of [m_Type]'s required (1 for a scalar, 4 for a vector) + UINT m_Indices; // max index allowable (if LHS is an array; otherwise this is 1) + BOOL m_VectorScalar; // can be both vector and scalar (setting as a scalar sets all m_Indices values simultaneously) + CONST RValue *m_pRValue; // pointer to table of allowable RHS "late resolve" values + ELhsType m_LhsType; // ELHS_* enum value that corresponds to this entry + UINT m_Offset; // offset into the given block type where this value should be written + UINT m_Stride; // for vectors, byte stride between two consecutive values. if 0, m_Type's size is used +}; + +#define LVALUE_END() { NULL, D3D10_SVT_UINT, 0, 0, 0, NULL } + +extern CONST LValue g_lvGeneral[]; +extern CONST UINT g_lvGeneralCount; + +} // end namespace D3DX11Effects diff --git a/sample/d3d11/Effects11/Binary/EffectStates11.h b/sample/d3d11/Effects11/Binary/EffectStates11.h new file mode 100644 index 0000000..3bb3087 --- /dev/null +++ b/sample/d3d11/Effects11/Binary/EffectStates11.h @@ -0,0 +1,236 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectStates11.h +// Content: D3DX11 Effects States Header +// This file defines properties of states which can appear in +// state blocks and pass blocks. +// +////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include <EffectStateBase11.h> + +namespace D3DX11Effects +{ + +////////////////////////////////////////////////////////////////////////// +// Effect HLSL late resolve lists (state values) +////////////////////////////////////////////////////////////////////////// + +static CONST RValue g_rvNULL[] = +{ + { "NULL", 0 }, + RVALUE_END() +}; + + +static CONST RValue g_rvBOOL[] = +{ + { "FALSE", 0 }, + { "TRUE", 1 }, + RVALUE_END() +}; + +static CONST RValue g_rvDEPTH_WRITE_MASK[] = +{ + { "ZERO", D3D10_DEPTH_WRITE_MASK_ZERO }, + { "ALL", D3D10_DEPTH_WRITE_MASK_ALL }, + RVALUE_END() +}; + +static CONST RValue g_rvFILL[] = +{ + { "WIREFRAME", D3D10_FILL_WIREFRAME }, + { "SOLID", D3D10_FILL_SOLID }, + RVALUE_END() +}; + +static CONST RValue g_rvFILTER[] = +{ + RVALUE_ENTRY(D3D10_FILTER_, MIN_MAG_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, MIN_MAG_POINT_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, MIN_POINT_MAG_LINEAR_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, MIN_POINT_MAG_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, MIN_LINEAR_MAG_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, MIN_LINEAR_MAG_POINT_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, MIN_MAG_LINEAR_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, MIN_MAG_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, ANISOTROPIC ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_MAG_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_MAG_POINT_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_POINT_MAG_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_LINEAR_MAG_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_MAG_LINEAR_MIP_POINT ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_MIN_MAG_MIP_LINEAR ), + RVALUE_ENTRY(D3D10_FILTER_, COMPARISON_ANISOTROPIC ), + RVALUE_ENTRY(D3D10_FILTER_, TEXT_1BIT ), + RVALUE_END() +}; + +static CONST RValue g_rvBLEND[] = +{ + { "ZERO", D3D10_BLEND_ZERO }, + { "ONE", D3D10_BLEND_ONE }, + { "SRC_COLOR", D3D10_BLEND_SRC_COLOR }, + { "INV_SRC_COLOR", D3D10_BLEND_INV_SRC_COLOR }, + { "SRC_ALPHA", D3D10_BLEND_SRC_ALPHA }, + { "INV_SRC_ALPHA", D3D10_BLEND_INV_SRC_ALPHA }, + { "DEST_ALPHA", D3D10_BLEND_DEST_ALPHA }, + { "INV_DEST_ALPHA", D3D10_BLEND_INV_DEST_ALPHA }, + { "DEST_COLOR", D3D10_BLEND_DEST_COLOR }, + { "INV_DEST_COLOR", D3D10_BLEND_INV_DEST_COLOR }, + { "SRC_ALPHA_SAT", D3D10_BLEND_SRC_ALPHA_SAT }, + { "BLEND_FACTOR", D3D10_BLEND_BLEND_FACTOR }, + { "INV_BLEND_FACTOR", D3D10_BLEND_INV_BLEND_FACTOR }, + { "SRC1_COLOR", D3D10_BLEND_SRC1_COLOR }, + { "INV_SRC1_COLOR", D3D10_BLEND_INV_SRC1_COLOR }, + { "SRC1_ALPHA", D3D10_BLEND_SRC1_ALPHA }, + { "INV_SRC1_ALPHA", D3D10_BLEND_INV_SRC1_ALPHA }, + + RVALUE_END() +}; + +static CONST RValue g_rvTADDRESS[] = +{ + { "CLAMP", D3D10_TEXTURE_ADDRESS_CLAMP }, + { "WRAP", D3D10_TEXTURE_ADDRESS_WRAP }, + { "MIRROR", D3D10_TEXTURE_ADDRESS_MIRROR }, + { "BORDER", D3D10_TEXTURE_ADDRESS_BORDER }, + { "MIRROR_ONCE", D3D10_TEXTURE_ADDRESS_MIRROR_ONCE }, + RVALUE_END() +}; + +static CONST RValue g_rvCULL[] = +{ + { "NONE", D3D10_CULL_NONE }, + { "FRONT", D3D10_CULL_FRONT }, + { "BACK", D3D10_CULL_BACK }, + RVALUE_END() +}; + +static CONST RValue g_rvCMP[] = +{ + { "NEVER", D3D10_COMPARISON_NEVER }, + { "LESS", D3D10_COMPARISON_LESS }, + { "EQUAL", D3D10_COMPARISON_EQUAL }, + { "LESS_EQUAL", D3D10_COMPARISON_LESS_EQUAL }, + { "GREATER", D3D10_COMPARISON_GREATER }, + { "NOT_EQUAL", D3D10_COMPARISON_NOT_EQUAL }, + { "GREATER_EQUAL", D3D10_COMPARISON_GREATER_EQUAL }, + { "ALWAYS", D3D10_COMPARISON_ALWAYS }, + RVALUE_END() +}; + +static CONST RValue g_rvSTENCILOP[] = +{ + { "KEEP", D3D10_STENCIL_OP_KEEP }, + { "ZERO", D3D10_STENCIL_OP_ZERO }, + { "REPLACE", D3D10_STENCIL_OP_REPLACE }, + { "INCR_SAT", D3D10_STENCIL_OP_INCR_SAT }, + { "DECR_SAT", D3D10_STENCIL_OP_DECR_SAT }, + { "INVERT", D3D10_STENCIL_OP_INVERT }, + { "INCR", D3D10_STENCIL_OP_INCR }, + { "DECR", D3D10_STENCIL_OP_DECR }, + RVALUE_END() +}; + +static CONST RValue g_rvBLENDOP[] = +{ + { "ADD", D3D10_BLEND_OP_ADD }, + { "SUBTRACT", D3D10_BLEND_OP_SUBTRACT }, + { "REV_SUBTRACT", D3D10_BLEND_OP_REV_SUBTRACT }, + { "MIN", D3D10_BLEND_OP_MIN }, + { "MAX", D3D10_BLEND_OP_MAX }, + RVALUE_END() +}; + + +////////////////////////////////////////////////////////////////////////// +// Effect HLSL states +////////////////////////////////////////////////////////////////////////// + +#define strideof( s, m ) offsetof_fx(s,m[1]) - offsetof_fx(s,m[0]) + +CONST LValue g_lvGeneral[] = +{ + // RObjects + { "RasterizerState", EBT_Pass, D3D10_SVT_RASTERIZER, 1, 1, FALSE, NULL, ELHS_RasterizerBlock, offsetof_fx(SPassBlock, BackingStore.pRasterizerBlock), 0 }, + { "DepthStencilState", EBT_Pass, D3D10_SVT_DEPTHSTENCIL, 1, 1, FALSE, NULL, ELHS_DepthStencilBlock, offsetof_fx(SPassBlock, BackingStore.pDepthStencilBlock), 0 }, + { "BlendState", EBT_Pass, D3D10_SVT_BLEND, 1, 1, FALSE, NULL, ELHS_BlendBlock, offsetof_fx(SPassBlock, BackingStore.pBlendBlock), 0 }, + { "RenderTargetView", EBT_Pass, D3D10_SVT_RENDERTARGETVIEW, 1, 8, FALSE, NULL, ELHS_RenderTargetView, offsetof_fx(SPassBlock, BackingStore.pRenderTargetViews), 0 }, + { "DepthStencilView", EBT_Pass, D3D10_SVT_DEPTHSTENCILVIEW, 1, 8, FALSE, NULL, ELHS_DepthStencilView, offsetof_fx(SPassBlock, BackingStore.pDepthStencilView), 0 }, + { "GenerateMips", EBT_Pass, D3D10_SVT_TEXTURE, 1, 1, FALSE, NULL, ELHS_GenerateMips, 0, 0 }, + // Shaders + { "VertexShader", EBT_Pass, D3D10_SVT_VERTEXSHADER, 1, 1, FALSE, g_rvNULL, ELHS_VertexShaderBlock, offsetof_fx(SPassBlock, BackingStore.pVertexShaderBlock), 0 }, + { "PixelShader", EBT_Pass, D3D10_SVT_PIXELSHADER, 1, 1, FALSE, g_rvNULL, ELHS_PixelShaderBlock, offsetof_fx(SPassBlock, BackingStore.pPixelShaderBlock), 0 }, + { "GeometryShader", EBT_Pass, D3D10_SVT_GEOMETRYSHADER, 1, 1, FALSE, g_rvNULL, ELHS_GeometryShaderBlock, offsetof_fx(SPassBlock, BackingStore.pGeometryShaderBlock), 0 }, + // RObject config assignments + { "DS_StencilRef", EBT_Pass, D3D10_SVT_UINT, 1, 1, FALSE, NULL, ELHS_DS_StencilRef, offsetof_fx(SPassBlock, BackingStore.StencilRef), 0 }, + { "AB_BlendFactor", EBT_Pass, D3D10_SVT_FLOAT, 4, 1, FALSE, NULL, ELHS_B_BlendFactor, offsetof_fx(SPassBlock, BackingStore.BlendFactor), 0 }, + { "AB_SampleMask", EBT_Pass, D3D10_SVT_UINT, 1, 1, FALSE, NULL, ELHS_B_SampleMask, offsetof_fx(SPassBlock, BackingStore.SampleMask), 0 }, + + { "FillMode", EBT_Rasterizer, D3D10_SVT_UINT, 1, 1, FALSE, g_rvFILL, ELHS_FillMode, offsetof_fx(SRasterizerBlock, BackingStore.FillMode), 0 }, + { "CullMode", EBT_Rasterizer, D3D10_SVT_UINT, 1, 1, FALSE, g_rvCULL, ELHS_CullMode, offsetof_fx(SRasterizerBlock, BackingStore.CullMode), 0 }, + { "FrontCounterClockwise", EBT_Rasterizer, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_FrontCC, offsetof_fx(SRasterizerBlock, BackingStore.FrontCounterClockwise), 0 }, + { "DepthBias", EBT_Rasterizer, D3D10_SVT_UINT, 1, 1, FALSE, NULL, ELHS_DepthBias, offsetof_fx(SRasterizerBlock, BackingStore.DepthBias), 0 }, + { "DepthBiasClamp", EBT_Rasterizer, D3D10_SVT_FLOAT, 1, 1, FALSE, NULL, ELHS_DepthBiasClamp, offsetof_fx(SRasterizerBlock, BackingStore.DepthBiasClamp), 0 }, + { "SlopeScaledDepthBias", EBT_Rasterizer, D3D10_SVT_FLOAT, 1, 1, FALSE, NULL, ELHS_SlopeScaledDepthBias, offsetof_fx(SRasterizerBlock, BackingStore.SlopeScaledDepthBias), 0 }, + { "DepthClipEnable", EBT_Rasterizer, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_DepthClipEnable, offsetof_fx(SRasterizerBlock, BackingStore.DepthClipEnable), 0 }, + { "ScissorEnable", EBT_Rasterizer, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_ScissorEnable, offsetof_fx(SRasterizerBlock, BackingStore.ScissorEnable), 0 }, + { "MultisampleEnable", EBT_Rasterizer, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_MultisampleEnable, offsetof_fx(SRasterizerBlock, BackingStore.MultisampleEnable), 0 }, + { "AntialiasedLineEnable", EBT_Rasterizer, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_AntialiasedLineEnable, offsetof_fx(SRasterizerBlock, BackingStore.AntialiasedLineEnable), 0 }, + + { "DepthEnable", EBT_DepthStencil, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_DepthEnable, offsetof_fx(SDepthStencilBlock, BackingStore.DepthEnable), 0 }, + { "DepthWriteMask", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvDEPTH_WRITE_MASK, ELHS_DepthWriteMask, offsetof_fx(SDepthStencilBlock, BackingStore.DepthWriteMask), 0 }, + { "DepthFunc", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvCMP, ELHS_DepthFunc, offsetof_fx(SDepthStencilBlock, BackingStore.DepthFunc), 0 }, + { "StencilEnable", EBT_DepthStencil, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_StencilEnable, offsetof_fx(SDepthStencilBlock, BackingStore.StencilEnable), 0 }, + { "StencilReadMask", EBT_DepthStencil, D3D10_SVT_UINT8, 1, 1, FALSE, NULL, ELHS_StencilReadMask, offsetof_fx(SDepthStencilBlock, BackingStore.StencilReadMask), 0 }, + { "StencilWriteMask", EBT_DepthStencil, D3D10_SVT_UINT8, 1, 1, FALSE, NULL, ELHS_StencilWriteMask, offsetof_fx(SDepthStencilBlock, BackingStore.StencilWriteMask), 0 }, + { "FrontFaceStencilFail", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvSTENCILOP, ELHS_FrontFaceStencilFailOp, offsetof_fx(SDepthStencilBlock, BackingStore.FrontFace.StencilFailOp), 0 }, + { "FrontFaceStencilDepthFail", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvSTENCILOP, ELHS_FrontFaceStencilDepthFailOp,offsetof_fx(SDepthStencilBlock, BackingStore.FrontFace.StencilDepthFailOp), 0 }, + { "FrontFaceStencilPass", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvSTENCILOP, ELHS_FrontFaceStencilPassOp, offsetof_fx(SDepthStencilBlock, BackingStore.FrontFace.StencilPassOp), 0 }, + { "FrontFaceStencilFunc", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvCMP, ELHS_FrontFaceStencilFunc, offsetof_fx(SDepthStencilBlock, BackingStore.FrontFace.StencilFunc), 0 }, + { "BackFaceStencilFail", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvSTENCILOP, ELHS_BackFaceStencilFailOp, offsetof_fx(SDepthStencilBlock, BackingStore.BackFace.StencilFailOp), 0 }, + { "BackFaceStencilDepthFail", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvSTENCILOP, ELHS_BackFaceStencilDepthFailOp,offsetof_fx(SDepthStencilBlock, BackingStore.BackFace.StencilDepthFailOp), 0 }, + { "BackFaceStencilPass", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvSTENCILOP, ELHS_BackFaceStencilPassOp, offsetof_fx(SDepthStencilBlock, BackingStore.BackFace.StencilPassOp), 0 }, + { "BackFaceStencilFunc", EBT_DepthStencil, D3D10_SVT_UINT, 1, 1, FALSE, g_rvCMP, ELHS_BackFaceStencilFunc, offsetof_fx(SDepthStencilBlock, BackingStore.BackFace.StencilFunc), 0 }, + + { "AlphaToCoverageEnable", EBT_Blend, D3D10_SVT_BOOL, 1, 1, FALSE, g_rvBOOL, ELHS_AlphaToCoverage, offsetof_fx(SBlendBlock, BackingStore.AlphaToCoverageEnable), 0 }, + { "BlendEnable", EBT_Blend, D3D10_SVT_BOOL, 1, 8, FALSE, g_rvBOOL, ELHS_BlendEnable, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].BlendEnable), strideof(SBlendBlock, BackingStore.RenderTarget) }, + { "SrcBlend", EBT_Blend, D3D10_SVT_UINT, 1, 8, TRUE, g_rvBLEND, ELHS_SrcBlend, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].SrcBlend), strideof(SBlendBlock, BackingStore.RenderTarget) }, + { "DestBlend", EBT_Blend, D3D10_SVT_UINT, 1, 8, TRUE, g_rvBLEND, ELHS_DestBlend, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].DestBlend), strideof(SBlendBlock, BackingStore.RenderTarget) }, + { "BlendOp", EBT_Blend, D3D10_SVT_UINT, 1, 8, TRUE, g_rvBLENDOP, ELHS_BlendOp, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].BlendOp), strideof(SBlendBlock, BackingStore.RenderTarget) }, + { "SrcBlendAlpha", EBT_Blend, D3D10_SVT_UINT, 1, 8, TRUE, g_rvBLEND, ELHS_SrcBlendAlpha, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].SrcBlendAlpha), strideof(SBlendBlock, BackingStore.RenderTarget) }, + { "DestBlendAlpha", EBT_Blend, D3D10_SVT_UINT, 1, 8, TRUE, g_rvBLEND, ELHS_DestBlendAlpha, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].DestBlendAlpha), strideof(SBlendBlock, BackingStore.RenderTarget) }, + { "BlendOpAlpha", EBT_Blend, D3D10_SVT_UINT, 1, 8, TRUE, g_rvBLENDOP, ELHS_BlendOpAlpha, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].BlendOpAlpha), strideof(SBlendBlock, BackingStore.RenderTarget) }, + { "RenderTargetWriteMask", EBT_Blend, D3D10_SVT_UINT8, 1, 8, FALSE, NULL, ELHS_RenderTargetWriteMask, offsetof_fx(SBlendBlock, BackingStore.RenderTarget[0].RenderTargetWriteMask), strideof(SBlendBlock, BackingStore.RenderTarget) }, + + { "Filter", EBT_Sampler, D3D10_SVT_UINT, 1, 1, FALSE, g_rvFILTER, ELHS_Filter, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.Filter), 0 }, + { "AddressU", EBT_Sampler, D3D10_SVT_UINT, 1, 1, FALSE, g_rvTADDRESS, ELHS_AddressU, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.AddressU), 0 }, + { "AddressV", EBT_Sampler, D3D10_SVT_UINT, 1, 1, FALSE, g_rvTADDRESS, ELHS_AddressV, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.AddressV), 0 }, + { "AddressW", EBT_Sampler, D3D10_SVT_UINT, 1, 1, FALSE, g_rvTADDRESS, ELHS_AddressW, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.AddressW), 0 }, + { "MipLODBias", EBT_Sampler, D3D10_SVT_FLOAT, 1, 1, FALSE, NULL, ELHS_MipLODBias, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.MipLODBias), 0 }, + { "MaxAnisotropy", EBT_Sampler, D3D10_SVT_UINT, 1, 1, FALSE, NULL, ELHS_MaxAnisotropy, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.MaxAnisotropy), 0 }, + { "ComparisonFunc", EBT_Sampler, D3D10_SVT_UINT, 1, 1, FALSE, g_rvCMP, ELHS_ComparisonFunc, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.ComparisonFunc), 0 }, + { "BorderColor", EBT_Sampler, D3D10_SVT_FLOAT, 4, 1, FALSE, NULL, ELHS_BorderColor, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.BorderColor), 0 }, + { "MinLOD", EBT_Sampler, D3D10_SVT_FLOAT, 1, 1, FALSE, NULL, ELHS_MinLOD, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.MinLOD), 0 }, + { "MaxLOD", EBT_Sampler, D3D10_SVT_FLOAT, 1, 1, FALSE, NULL, ELHS_MaxLOD, offsetof_fx(SSamplerBlock, BackingStore.SamplerDesc.MaxLOD), 0 }, + { "Texture", EBT_Sampler, D3D10_SVT_TEXTURE, 1, 1, FALSE, g_rvNULL, ELHS_Texture, offsetof_fx(SSamplerBlock, BackingStore.pTexture), 0 }, + + // D3D11 + { "HullShader", EBT_Pass, D3D11_SVT_HULLSHADER, 1, 1, FALSE, g_rvNULL, ELHS_HullShaderBlock, offsetof_fx(SPassBlock, BackingStore.pHullShaderBlock), 0 }, + { "DomainShader", EBT_Pass, D3D11_SVT_DOMAINSHADER, 1, 1, FALSE, g_rvNULL, ELHS_DomainShaderBlock, offsetof_fx(SPassBlock, BackingStore.pDomainShaderBlock), 0 }, + { "ComputeShader", EBT_Pass, D3D11_SVT_COMPUTESHADER, 1, 1, FALSE, g_rvNULL, ELHS_ComputeShaderBlock, offsetof_fx(SPassBlock, BackingStore.pComputeShaderBlock), 0 }, +}; + +#define NUM_STATES (sizeof(g_lvGeneral) / sizeof(LValue)) +#define MAX_VECTOR_SCALAR_INDEX 8 + +CONST UINT g_lvGeneralCount = NUM_STATES; + +} // end namespace D3DX11Effects diff --git a/sample/d3d11/Effects11/Binary/SOParser.h b/sample/d3d11/Effects11/Binary/SOParser.h new file mode 100644 index 0000000..1fb95a9 --- /dev/null +++ b/sample/d3d11/Effects11/Binary/SOParser.h @@ -0,0 +1,311 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: SOParser.h +// Content: D3DX11 Effects Stream Out Decl Parser +// +////////////////////////////////////////////////////////////////////////////// + +#pragma once + +namespace D3DX11Effects +{ + + +////////////////////////////////////////////////////////////////////////// +// CSOParser +////////////////////////////////////////////////////////////////////////// + +class CSOParser +{ + + CEffectVector<D3D11_SO_DECLARATION_ENTRY> m_vDecls; // Set of parsed decl entries + D3D11_SO_DECLARATION_ENTRY m_newEntry; // Currently parsing entry + LPSTR m_SemanticString[D3D11_SO_BUFFER_SLOT_COUNT]; // Copy of strings + + static const UINT MAX_ERROR_SIZE = 254; + char m_pError[ MAX_ERROR_SIZE + 1 ]; // Error buffer + +public: + CSOParser() + { + ZeroMemory(&m_newEntry, sizeof(m_newEntry)); + ZeroMemory(m_SemanticString, sizeof(m_SemanticString)); + m_pError[0] = 0; + } + + ~CSOParser() + { + for( UINT Stream = 0; Stream < D3D11_SO_STREAM_COUNT; Stream++ ) + { + SAFE_DELETE_ARRAY( m_SemanticString[Stream] ); + } + } + + // Parse a single string, assuming stream 0 + HRESULT Parse( __in_z LPCSTR pString ) + { + m_vDecls.Clear(); + return Parse( 0, pString ); + } + + // Parse all 4 streams + HRESULT Parse( __in_z LPSTR pStreams[D3D11_SO_STREAM_COUNT] ) + { + HRESULT hr = S_OK; + m_vDecls.Clear(); + for( UINT iDecl=0; iDecl < D3D11_SO_STREAM_COUNT; ++iDecl ) + { + hr = Parse( iDecl, pStreams[iDecl] ); + if( FAILED(hr) ) + { + char pStream[16]; + StringCchPrintfA( pStream, 16, " in stream %d.", iDecl ); + pStream[15] = 0; + StringCchCatA( m_pError, MAX_ERROR_SIZE, pStream ); + return hr; + } + } + return hr; + } + + // Return resulting declarations + D3D11_SO_DECLARATION_ENTRY *GetDeclArray() + { + return &m_vDecls[0]; + } + + char* GetErrorString() + { + return m_pError; + } + + UINT GetDeclCount() const + { + return m_vDecls.GetSize(); + } + + // Return resulting buffer strides + void GetStrides( UINT strides[4] ) + { + UINT len = GetDeclCount(); + strides[0] = strides[1] = strides[2] = strides[3] = 0; + + for( UINT i=0; i < len; i++ ) + { + strides[m_vDecls[i].OutputSlot] += m_vDecls[i].ComponentCount * sizeof(float); + } + } + +protected: + + // Parse a single string "[<slot> :] <semantic>[<index>][.<mask>]; [[<slot> :] <semantic>[<index>][.<mask>][;]]" + HRESULT Parse( UINT Stream, __in_z LPCSTR pString ) + { + HRESULT hr = S_OK; + + m_pError[0] = 0; + + if( pString == NULL ) + return S_OK; + + UINT len = (UINT)strlen( pString ); + if( len == 0 ) + return S_OK; + + SAFE_DELETE_ARRAY( m_SemanticString[Stream] ); + VN( m_SemanticString[Stream] = NEW char[len + 1] ); + StringCchCopyA( m_SemanticString[Stream], len + 1, pString ); + + LPSTR pSemantic = m_SemanticString[Stream]; + + while( TRUE ) + { + // Each decl entry is delimited by a semi-colon + LPSTR pSemi = strchr( pSemantic, ';' ); + + // strip leading and trailing spaces + LPSTR pEnd; + if( pSemi != NULL ) + { + *pSemi = '\0'; + pEnd = pSemi - 1; + } + else + { + pEnd = pSemantic + strlen( pSemantic ); + } + while( isspace( (unsigned char)*pSemantic ) ) + pSemantic++; + while( pEnd > pSemantic && isspace( (unsigned char)*pEnd ) ) + { + *pEnd = '\0'; + pEnd--; + } + + if( *pSemantic != '\0' ) + { + VH( AddSemantic( pSemantic ) ); + m_newEntry.Stream = Stream; + + VH( m_vDecls.Add( m_newEntry ) ); + } + if( pSemi == NULL ) + break; + pSemantic = pSemi + 1; + } + +lExit: + return hr; + } + + // Parse a single decl "[<slot> :] <semantic>[<index>][.<mask>]" + HRESULT AddSemantic( __inout_z LPSTR pSemantic ) + { + HRESULT hr = S_OK; + + D3DXASSERT( pSemantic ); + + ZeroMemory( &m_newEntry, sizeof(m_newEntry) ); + VH( ConsumeOutputSlot( &pSemantic ) ); + VH( ConsumeRegisterMask( pSemantic ) ); + VH( ConsumeSemanticIndex( pSemantic ) ); + + // pSenantic now contains only the SemanticName (all other fields were consumed) + if( strcmp( "$SKIP", pSemantic ) != 0 ) + { + m_newEntry.SemanticName = pSemantic; + } + +lExit: + return hr; + } + + // Parse optional mask "[.<mask>]" + HRESULT ConsumeRegisterMask( __inout_z LPSTR pSemantic ) + { + HRESULT hr = S_OK; + const char *pFullMask1 = "xyzw"; + const char *pFullMask2 = "rgba"; + SIZE_T stringLength; + SIZE_T startComponent = 0; + LPCSTR p; + + D3DXASSERT( pSemantic ); + + pSemantic = strchr( pSemantic, '.' ); + + if( pSemantic == NULL ) + { + m_newEntry.ComponentCount = 4; + return S_OK; + } + + *pSemantic = '\0'; + pSemantic++; + + stringLength = strlen( pSemantic ); + p = strstr(pFullMask1, pSemantic ); + if( p ) + { + startComponent = (UINT)( p - pFullMask1 ); + } + else + { + p = strstr( pFullMask2, pSemantic ); + if( p ) + startComponent = (UINT)( p - pFullMask2 ); + else + { + StringCchPrintfA( m_pError, MAX_ERROR_SIZE, "ID3D11Effect::ParseSODecl - invalid mask declaration '%s'", pSemantic ); + VH( E_FAIL ); + } + + } + + if( stringLength == 0 ) + stringLength = 4; + + m_newEntry.StartComponent = (BYTE)startComponent; + m_newEntry.ComponentCount = (BYTE)stringLength; + +lExit: + return hr; + } + + // Parse optional output slot "[<slot> :]" + HRESULT ConsumeOutputSlot( __deref_inout_z LPSTR* ppSemantic ) + { + D3DXASSERT( ppSemantic && *ppSemantic ); + + HRESULT hr = S_OK; + LPSTR pColon = strchr( *ppSemantic, ':' ); + + if( pColon == NULL ) + return S_OK; + + if( pColon == *ppSemantic ) + { + StringCchCopyA( m_pError, MAX_ERROR_SIZE, + "ID3D11Effect::ParseSODecl - Invalid output slot" ); + VH( E_FAIL ); + } + + *pColon = '\0'; + int outputSlot = atoi( *ppSemantic ); + if( outputSlot < 0 || outputSlot > 255 ) + { + StringCchCopyA( m_pError, MAX_ERROR_SIZE, + "ID3D11Effect::ParseSODecl - Invalid output slot" ); + VH( E_FAIL ); + } + m_newEntry.OutputSlot = (BYTE)outputSlot; + + while( *ppSemantic < pColon ) + { + if( !isdigit( (unsigned char)**ppSemantic ) ) + { + StringCchPrintfA( m_pError, MAX_ERROR_SIZE, "ID3D11Effect::ParseSODecl - Non-digit '%c' in output slot", **ppSemantic ); + VH( E_FAIL ); + } + (*ppSemantic)++; + } + + // skip the colon (which is now '\0') + (*ppSemantic)++; + + while( isspace( (unsigned char)**ppSemantic ) ) + (*ppSemantic)++; + +lExit: + return hr; + } + + // Parse optional index "[<index>]" + HRESULT ConsumeSemanticIndex( __inout_z LPSTR pSemantic ) + { + D3DXASSERT( pSemantic ); + + UINT uLen = (UINT)strlen( pSemantic ); + + // Grab semantic index + while( uLen > 0 && isdigit( (unsigned char)pSemantic[uLen - 1] ) ) + uLen--; + + if( isdigit( (unsigned char)pSemantic[uLen] ) ) + { + m_newEntry.SemanticIndex = atoi( pSemantic + uLen ); + pSemantic[uLen] = '\0'; + } + else + { + m_newEntry.SemanticIndex = 0; + } + + return S_OK; + } +}; + + +} // end namespace D3DX11Effects diff --git a/sample/d3d11/Effects11/Effect.h b/sample/d3d11/Effects11/Effect.h new file mode 100644 index 0000000..ec0dafa --- /dev/null +++ b/sample/d3d11/Effects11/Effect.h @@ -0,0 +1,1226 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: Effect.h +// Content: D3DX11 Effects Header for ID3DX11Effect Implementation +// +////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "EffectBinaryFormat.h" + +using namespace D3DX11Core; + +namespace D3DX11Effects +{ + +////////////////////////////////////////////////////////////////////////// +// Forward defines +////////////////////////////////////////////////////////////////////////// + +struct SBaseBlock; +struct SShaderBlock; +struct SPassBlock; +struct SClassInstance; +struct SInterface; +struct SShaderResource; +struct SUnorderedAccessView; +struct SRenderTargetView; +struct SDepthStencilView; +struct SSamplerBlock; +struct SDepthStencilBlock; +struct SBlendBlock; +struct SRasterizerBlock; +struct SString; +struct SD3DShaderVTable; +struct SClassInstanceGlobalVariable; + +struct SAssignment; +struct SVariable; +struct SGlobalVariable; +struct SAnnotation; +struct SConstantBuffer; + +class CEffect; +class CEffectLoader; + +enum ELhsType; + +// Allows the use of 32-bit and 64-bit timers depending on platform type +typedef SIZE_T Timer; + +////////////////////////////////////////////////////////////////////////// +// Reflection & Type structures +////////////////////////////////////////////////////////////////////////// + +// CEffectMatrix is used internally instead of float arrays +struct CEffectMatrix +{ + union + { + struct + { + float _11, _12, _13, _14; + float _21, _22, _23, _24; + float _31, _32, _33, _34; + float _41, _42, _43, _44; + + }; + float m[4][4]; + }; +}; + +struct CEffectVector4 +{ + float x; + float y; + float z; + float w; +}; + +union UDataPointer +{ + void *pGeneric; + BYTE *pNumeric; + float *pNumericFloat; + UINT *pNumericDword; + int *pNumericInt; + BOOL *pNumericBool; + SString *pString; + SShaderBlock *pShader; + SBaseBlock *pBlock; + SBlendBlock *pBlend; + SDepthStencilBlock *pDepthStencil; + SRasterizerBlock *pRasterizer; + SInterface *pInterface; + SShaderResource *pShaderResource; + SUnorderedAccessView *pUnorderedAccessView; + SRenderTargetView *pRenderTargetView; + SDepthStencilView *pDepthStencilView; + SSamplerBlock *pSampler; + CEffectVector4 *pVector; + CEffectMatrix *pMatrix; + UINT_PTR Offset; +}; + +enum EMemberDataType +{ + MDT_ClassInstance, + MDT_BlendState, + MDT_DepthStencilState, + MDT_RasterizerState, + MDT_SamplerState, + MDT_Buffer, + MDT_ShaderResourceView, +}; + +struct SMemberDataPointer +{ + EMemberDataType Type; + union + { + IUnknown *pGeneric; + ID3D11ClassInstance *pD3DClassInstance; + ID3D11BlendState *pD3DEffectsManagedBlendState; + ID3D11DepthStencilState *pD3DEffectsManagedDepthStencilState; + ID3D11RasterizerState *pD3DEffectsManagedRasterizerState; + ID3D11SamplerState *pD3DEffectsManagedSamplerState; + ID3D11Buffer *pD3DEffectsManagedConstantBuffer; + ID3D11ShaderResourceView*pD3DEffectsManagedTextureBuffer; + } Data; +}; + +struct SType : public ID3DX11EffectType +{ + static const UINT_PTR c_InvalidIndex = (UINT) -1; + static const UINT c_ScalarSize = sizeof(UINT); + + // packing rule constants + static const UINT c_ScalarsPerRegister = 4; + static const UINT c_RegisterSize = c_ScalarsPerRegister * c_ScalarSize; // must be a power of 2!! + + EVarType VarType; // numeric, object, struct + UINT Elements; // # of array elements (0 for non-arrays) + char *pTypeName; // friendly name of the type: "VS_OUTPUT", "float4", etc. + + // *Size and stride values are always 0 for object types + // *Annotations adhere to packing rules (even though they do not reside in constant buffers) + // for consistency's sake + // + // Packing rules: + // *Structures and array elements are always register aligned + // *Single-row values (or, for column major matrices, single-column) are greedily + // packed unless doing so would span a register boundary, in which case they are + // register aligned + + UINT TotalSize; // Total size of this data type in a constant buffer from + // start to finish (padding in between elements is included, + // but padding at the end is not since that would require + // knowledge of the following data type). + + UINT Stride; // Number of bytes to advance between elements. + // Typically a multiple of 16 for arrays, vectors, matrices. + // For scalars and small vectors/matrices, this can be 4 or 8. + + UINT PackedSize; // Size, in bytes, of this data typed when fully packed + + union + { + SBinaryNumericType NumericType; + EObjectType ObjectType; // not all values of EObjectType are valid here (e.g. constant buffer) + struct + { + SVariable *pMembers; // array of type instances describing structure members + UINT Members; + bool ImplementsInterface; // true if this type implements an interface + bool HasSuperClass; // true if this type has a parent class + } StructType; + void* InterfaceType; // nothing for interfaces + }; + + + SType() : + VarType(EVT_Invalid), + Elements(0), + pTypeName(NULL), + TotalSize(0), + Stride(0), + PackedSize(0) + { + C_ASSERT( sizeof(NumericType) <= sizeof(StructType) ); + C_ASSERT( sizeof(ObjectType) <= sizeof(StructType) ); + C_ASSERT( sizeof(InterfaceType) <= sizeof(StructType) ); + ZeroMemory( &StructType, sizeof(StructType) ); + } + + BOOL IsEqual(SType *pOtherType) const; + + BOOL IsObjectType(EObjectType ObjType) const + { + return IsObjectTypeHelper(VarType, ObjectType, ObjType); + } + BOOL IsShader() const + { + return IsShaderHelper(VarType, ObjectType); + } + BOOL BelongsInConstantBuffer() const + { + return (VarType == EVT_Numeric) || (VarType == EVT_Struct); + } + BOOL IsStateBlockObject() const + { + return IsStateBlockObjectHelper(VarType, ObjectType); + } + BOOL IsClassInstance() const + { + return (VarType == EVT_Struct) && StructType.ImplementsInterface; + } + BOOL IsInterface() const + { + return IsInterfaceHelper(VarType, ObjectType); + } + BOOL IsShaderResource() const + { + return IsShaderResourceHelper(VarType, ObjectType); + } + BOOL IsUnorderedAccessView() const + { + return IsUnorderedAccessViewHelper(VarType, ObjectType); + } + BOOL IsSampler() const + { + return IsSamplerHelper(VarType, ObjectType); + } + BOOL IsRenderTargetView() const + { + return IsRenderTargetViewHelper(VarType, ObjectType); + } + BOOL IsDepthStencilView() const + { + return IsDepthStencilViewHelper(VarType, ObjectType); + } + + UINT GetTotalUnpackedSize(BOOL IsSingleElement) const; + UINT GetTotalPackedSize(BOOL IsSingleElement) const; + HRESULT GetDescHelper(D3DX11_EFFECT_TYPE_DESC *pDesc, BOOL IsSingleElement) const; + + STDMETHOD_(BOOL, IsValid)() { return TRUE; } + STDMETHOD(GetDesc)(D3DX11_EFFECT_TYPE_DESC *pDesc) { return GetDescHelper(pDesc, FALSE); } + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(LPCSTR Name); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(LPCSTR Semantic); + STDMETHOD_(LPCSTR, GetMemberName)(UINT Index); + STDMETHOD_(LPCSTR, GetMemberSemantic)(UINT Index); +}; + +// Represents a type structure for a single element. +// It seems pretty trivial, but it has a different virtual table which enables +// us to accurately represent a type that consists of a single element +struct SSingleElementType : public ID3DX11EffectType +{ + SType *pType; + + STDMETHOD_(BOOL, IsValid)() { return TRUE; } + STDMETHOD(GetDesc)(D3DX11_EFFECT_TYPE_DESC *pDesc) { return ((SType*)pType)->GetDescHelper(pDesc, TRUE); } + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(UINT Index) { return ((SType*)pType)->GetMemberTypeByIndex(Index); } + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(LPCSTR Name) { return ((SType*)pType)->GetMemberTypeByName(Name); } + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(LPCSTR Semantic) { return ((SType*)pType)->GetMemberTypeBySemantic(Semantic); } + STDMETHOD_(LPCSTR, GetMemberName)(UINT Index) { return ((SType*)pType)->GetMemberName(Index); } + STDMETHOD_(LPCSTR, GetMemberSemantic)(UINT Index) { return ((SType*)pType)->GetMemberSemantic(Index); } +}; + +////////////////////////////////////////////////////////////////////////// +// Block definitions +////////////////////////////////////////////////////////////////////////// + +void * GetBlockByIndex(EVarType VarType, EObjectType ObjectType, void *pBaseBlock, UINT Index); + +struct SBaseBlock +{ + EBlockType BlockType; + + BOOL IsUserManaged:1; + + UINT AssignmentCount; + SAssignment *pAssignments; + + SBaseBlock(); + + BOOL ApplyAssignments(CEffect *pEffect); + + D3DX11INLINE SSamplerBlock *AsSampler() const + { + D3DXASSERT( BlockType == EBT_Sampler ); + return (SSamplerBlock*) this; + } + + D3DX11INLINE SDepthStencilBlock *AsDepthStencil() const + { + D3DXASSERT( BlockType == EBT_DepthStencil ); + return (SDepthStencilBlock*) this; + } + + D3DX11INLINE SBlendBlock *AsBlend() const + { + D3DXASSERT( BlockType == EBT_Blend ); + return (SBlendBlock*) this; + } + + D3DX11INLINE SRasterizerBlock *AsRasterizer() const + { + D3DXASSERT( BlockType == EBT_Rasterizer ); + return (SRasterizerBlock*) this; + } + + D3DX11INLINE SPassBlock *AsPass() const + { + D3DXASSERT( BlockType == EBT_Pass ); + return (SPassBlock*) this; + } +}; + +struct STechnique : public ID3DX11EffectTechnique +{ + char *pName; + + UINT PassCount; + SPassBlock *pPasses; + + UINT AnnotationCount; + SAnnotation *pAnnotations; + + BOOL InitiallyValid; + BOOL HasDependencies; + + STechnique(); + + STDMETHOD_(BOOL, IsValid)(); + STDMETHOD(GetDesc)(D3DX11_TECHNIQUE_DESC *pDesc); + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name); + + STDMETHOD_(ID3DX11EffectPass*, GetPassByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectPass*, GetPassByName)(LPCSTR Name); + + STDMETHOD(ComputeStateBlockMask)(D3DX11_STATE_BLOCK_MASK *pStateBlockMask); +}; + +struct SGroup : public ID3DX11EffectGroup +{ + char *pName; + + UINT TechniqueCount; + STechnique *pTechniques; + + UINT AnnotationCount; + SAnnotation *pAnnotations; + + BOOL InitiallyValid; + BOOL HasDependencies; + + SGroup(); + + STDMETHOD_(BOOL, IsValid)(); + STDMETHOD(GetDesc)(D3DX11_GROUP_DESC *pDesc); + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name); + + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(LPCSTR Name); +}; + +struct SPassBlock : SBaseBlock, public ID3DX11EffectPass +{ + struct + { + ID3D11BlendState* pBlendState; + FLOAT BlendFactor[4]; + UINT SampleMask; + ID3D11DepthStencilState *pDepthStencilState; + UINT StencilRef; + union + { + D3D11_SO_DECLARATION_ENTRY *pEntry; + char *pEntryDesc; + } GSSODesc; + + // Pass assignments can write directly into these + SBlendBlock *pBlendBlock; + SDepthStencilBlock *pDepthStencilBlock; + SRasterizerBlock *pRasterizerBlock; + UINT RenderTargetViewCount; + SRenderTargetView *pRenderTargetViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT]; + SDepthStencilView *pDepthStencilView; + SShaderBlock *pVertexShaderBlock; + SShaderBlock *pPixelShaderBlock; + SShaderBlock *pGeometryShaderBlock; + SShaderBlock *pComputeShaderBlock; + SShaderBlock *pDomainShaderBlock; + SShaderBlock *pHullShaderBlock; + } BackingStore; + + char *pName; + + UINT AnnotationCount; + SAnnotation *pAnnotations; + + CEffect *pEffect; + + BOOL InitiallyValid; // validity of all state objects and shaders in pass upon BindToDevice + BOOL HasDependencies; // if pass expressions or pass state blocks have dependencies on variables (if true, IsValid != InitiallyValid possibly) + + SPassBlock(); + + void ApplyPassAssignments(); + BOOL CheckShaderDependencies( SShaderBlock* pBlock ); + BOOL CheckDependencies(); + + template<EObjectType EShaderType> + HRESULT GetShaderDescHelper(D3DX11_PASS_SHADER_DESC *pDesc); + + STDMETHOD_(BOOL, IsValid)(); + STDMETHOD(GetDesc)(D3DX11_PASS_DESC *pDesc); + + STDMETHOD(GetVertexShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc); + STDMETHOD(GetGeometryShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc); + STDMETHOD(GetPixelShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc); + STDMETHOD(GetHullShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc); + STDMETHOD(GetDomainShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc); + STDMETHOD(GetComputeShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc); + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name); + + STDMETHOD(Apply)(UINT Flags, ID3D11DeviceContext* pContext); + + STDMETHOD(ComputeStateBlockMask)(D3DX11_STATE_BLOCK_MASK *pStateBlockMask); +}; + +struct SDepthStencilBlock : SBaseBlock +{ + ID3D11DepthStencilState *pDSObject; + D3D11_DEPTH_STENCIL_DESC BackingStore; + BOOL IsValid; + + SDepthStencilBlock(); +}; + +struct SBlendBlock : SBaseBlock +{ + ID3D11BlendState *pBlendObject; + D3D11_BLEND_DESC BackingStore; + BOOL IsValid; + + SBlendBlock(); +}; + +struct SRasterizerBlock : SBaseBlock +{ + ID3D11RasterizerState *pRasterizerObject; + D3D11_RASTERIZER_DESC BackingStore; + BOOL IsValid; + + SRasterizerBlock(); +}; + +struct SSamplerBlock : SBaseBlock +{ + ID3D11SamplerState *pD3DObject; + struct + { + D3D11_SAMPLER_DESC SamplerDesc; + // Sampler "TEXTURE" assignments can write directly into this + SShaderResource *pTexture; + } BackingStore; + + SSamplerBlock(); +}; + +struct SInterface +{ + SClassInstanceGlobalVariable* pClassInstance; + + SInterface() + { + pClassInstance = NULL; + } +}; + +struct SShaderResource +{ + ID3D11ShaderResourceView *pShaderResource; + + SShaderResource() + { + pShaderResource = NULL; + } + +}; + +struct SUnorderedAccessView +{ + ID3D11UnorderedAccessView *pUnorderedAccessView; + + SUnorderedAccessView() + { + pUnorderedAccessView = NULL; + } + +}; + +struct SRenderTargetView +{ + ID3D11RenderTargetView *pRenderTargetView; + + SRenderTargetView(); +}; + +struct SDepthStencilView +{ + ID3D11DepthStencilView *pDepthStencilView; + + SDepthStencilView(); +}; + + +template<class T, class D3DTYPE> struct SShaderDependency +{ + UINT StartIndex; + UINT Count; + + T *ppFXPointers; // Array of ptrs to FX objects (CBs, SShaderResources, etc) + D3DTYPE *ppD3DObjects; // Array of ptrs to matching D3D objects + + SShaderDependency() + { + StartIndex = Count = 0; + + ppD3DObjects = NULL; + ppFXPointers = NULL; + } +}; + +typedef SShaderDependency<SConstantBuffer*, ID3D11Buffer*> SShaderCBDependency; +typedef SShaderDependency<SSamplerBlock*, ID3D11SamplerState*> SShaderSamplerDependency; +typedef SShaderDependency<SShaderResource*, ID3D11ShaderResourceView*> SShaderResourceDependency; +typedef SShaderDependency<SUnorderedAccessView*, ID3D11UnorderedAccessView*> SUnorderedAccessViewDependency; +typedef SShaderDependency<SInterface*, ID3D11ClassInstance*> SInterfaceDependency; + +// Shader VTables are used to eliminate branching in ApplyShaderBlock. +// The effect owns three D3DShaderVTables, one for PS, one for VS, and one for GS. +struct SD3DShaderVTable +{ + void ( __stdcall ID3D11DeviceContext::*pSetShader)(ID3D11DeviceChild* pShader, ID3D11ClassInstance*const* ppClassInstances, UINT NumClassInstances); + void ( __stdcall ID3D11DeviceContext::*pSetConstantBuffers)(UINT StartConstantSlot, UINT NumBuffers, ID3D11Buffer *const *pBuffers); + void ( __stdcall ID3D11DeviceContext::*pSetSamplers)(UINT Offset, UINT NumSamplers, ID3D11SamplerState*const* pSamplers); + void ( __stdcall ID3D11DeviceContext::*pSetShaderResources)(UINT Offset, UINT NumResources, ID3D11ShaderResourceView *const *pResources); + HRESULT ( __stdcall ID3D11Device::*pCreateShader)(const void *pShaderBlob, SIZE_T ShaderBlobSize, ID3D11ClassLinkage* pClassLinkage, ID3D11DeviceChild **ppShader); +}; + + +struct SShaderBlock +{ + enum ESigType + { + ST_Input, + ST_Output, + ST_PatchConstant, + }; + + struct SInterfaceParameter + { + char *pName; + UINT Index; + }; + + // this data is classified as reflection-only and will all be discarded at runtime + struct SReflectionData + { + BYTE *pBytecode; + UINT BytecodeLength; + char *pStreamOutDecls[4]; // set with ConstructGSWithSO + UINT RasterizedStream; // set with ConstructGSWithSO + BOOL IsNullGS; + ID3D11ShaderReflection *pReflection; + UINT InterfaceParameterCount; // set with BindInterfaces (used for function interface parameters) + SInterfaceParameter *pInterfaceParameters; // set with BindInterfaces (used for function interface parameters) + }; + + BOOL IsValid; + SD3DShaderVTable *pVT; + + // This value is NULL if the shader is NULL or was never initialized + SReflectionData *pReflectionData; + + ID3D11DeviceChild *pD3DObject; + + UINT CBDepCount; + SShaderCBDependency *pCBDeps; + + UINT SampDepCount; + SShaderSamplerDependency *pSampDeps; + + UINT InterfaceDepCount; + SInterfaceDependency *pInterfaceDeps; + + UINT ResourceDepCount; + SShaderResourceDependency *pResourceDeps; + + UINT UAVDepCount; + SUnorderedAccessViewDependency *pUAVDeps; + + UINT TBufferDepCount; + SConstantBuffer **ppTbufDeps; + + ID3DBlob *pInputSignatureBlob; // The input signature is separated from the bytecode because it + // is always available, even after Optimize() has been called. + + SShaderBlock(SD3DShaderVTable *pVirtualTable = NULL); + + EObjectType GetShaderType(); + + HRESULT OnDeviceBind(); + + // Public API helpers + HRESULT ComputeStateBlockMask(D3DX11_STATE_BLOCK_MASK *pStateBlockMask); + + HRESULT GetShaderDesc(D3DX11_EFFECT_SHADER_DESC *pDesc, BOOL IsInline); + + HRESULT GetVertexShader(ID3D11VertexShader **ppVS); + HRESULT GetGeometryShader(ID3D11GeometryShader **ppGS); + HRESULT GetPixelShader(ID3D11PixelShader **ppPS); + HRESULT GetHullShader(ID3D11HullShader **ppPS); + HRESULT GetDomainShader(ID3D11DomainShader **ppPS); + HRESULT GetComputeShader(ID3D11ComputeShader **ppPS); + + HRESULT GetSignatureElementDesc(ESigType SigType, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); +}; + + + +struct SString +{ + char *pString; + + SString(); +}; + + + +////////////////////////////////////////////////////////////////////////// +// Global Variable & Annotation structure/interface definitions +////////////////////////////////////////////////////////////////////////// + +// +// This is a general structure that can describe +// annotations, variables, and structure members +// +struct SVariable +{ + // For annotations/variables/variable members: + // 1) If numeric, pointer to data (for variables: points into backing store, + // for annotations, points into reflection heap) + // OR + // 2) If object, pointer to the block. If object array, subsequent array elements are found in + // contiguous blocks; the Nth block is found by ((<SpecificBlockType> *) pBlock) + N + // (this is because variables that are arrays of objects have their blocks allocated contiguously) + // + // For structure members: + // Offset of this member (in bytes) from parent structure (structure members must be numeric/struct) + UDataPointer Data; + union + { + UINT MemberDataOffsetPlus4; // 4 added so that 0 == NULL can represent "unused" + SMemberDataPointer *pMemberData; + }; + + SType *pType; + char *pName; + char *pSemantic; + UINT ExplicitBindPoint; + + SVariable() + { + ZeroMemory(this, sizeof(*this)); + ExplicitBindPoint = -1; + } +}; + +// Template definitions for all of the various ID3DX11EffectVariable specializations +#include "EffectVariable.inl" + + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderVariable (SAnonymousShader implementation) +//////////////////////////////////////////////////////////////////////////////// + +struct SAnonymousShader : public TUncastableVariable<ID3DX11EffectShaderVariable>, public ID3DX11EffectType +{ + SShaderBlock *pShaderBlock; + + SAnonymousShader(SShaderBlock *pBlock = NULL); + + // ID3DX11EffectShaderVariable interface + STDMETHOD_(BOOL, IsValid)(); + STDMETHOD_(ID3DX11EffectType*, GetType)(); + STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc); + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name); + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(LPCSTR Name); + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(LPCSTR Semantic); + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(UINT Index); + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(); + + // other casts are handled by TUncastableVariable + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(); + + STDMETHOD(SetRawValue)(CONST void *pData, UINT Offset, UINT Count); + STDMETHOD(GetRawValue)(__out_bcount(Count) void *pData, UINT Offset, UINT Count); + + STDMETHOD(GetShaderDesc)(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc); + + STDMETHOD(GetVertexShader)(UINT ShaderIndex, ID3D11VertexShader **ppVS); + STDMETHOD(GetGeometryShader)(UINT ShaderIndex, ID3D11GeometryShader **ppGS); + STDMETHOD(GetPixelShader)(UINT ShaderIndex, ID3D11PixelShader **ppPS); + STDMETHOD(GetHullShader)(UINT ShaderIndex, ID3D11HullShader **ppPS); + STDMETHOD(GetDomainShader)(UINT ShaderIndex, ID3D11DomainShader **ppPS); + STDMETHOD(GetComputeShader)(UINT ShaderIndex, ID3D11ComputeShader **ppPS); + + STDMETHOD(GetInputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); + STDMETHOD(GetOutputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); + STDMETHOD(GetPatchConstantSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); + + // ID3DX11EffectType interface + STDMETHOD(GetDesc)(D3DX11_EFFECT_TYPE_DESC *pDesc); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(LPCSTR Name); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(LPCSTR Semantic); + + STDMETHOD_(LPCSTR, GetMemberName)(UINT Index); + STDMETHOD_(LPCSTR, GetMemberSemantic)(UINT Index); +}; + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectConstantBuffer (SConstantBuffer implementation) +//////////////////////////////////////////////////////////////////////////////// + +struct SConstantBuffer : public TUncastableVariable<ID3DX11EffectConstantBuffer>, public ID3DX11EffectType +{ + ID3D11Buffer *pD3DObject; + SShaderResource TBuffer; // NULL iff IsTbuffer == FALSE + + BYTE *pBackingStore; + UINT Size; // in bytes + + char *pName; + + UINT AnnotationCount; + SAnnotation *pAnnotations; + + UINT VariableCount; // # of variables contained in this cbuffer + SGlobalVariable *pVariables; // array of size [VariableCount], points into effect's contiguous variable list + UINT ExplicitBindPoint; // Used when a CB has been explicitly bound (register(bXX)). -1 if not + + BOOL IsDirty:1; // Set when any member is updated; cleared on CB apply + BOOL IsTBuffer:1; // TRUE iff TBuffer.pShaderResource != NULL + BOOL IsUserManaged:1; // Set if you don't want effects to update this buffer + BOOL IsEffectOptimized:1;// Set if the effect has been optimized + BOOL IsUsedByExpression:1;// Set if used by any expressions + BOOL IsUserPacked:1; // Set if the elements have user-specified offsets + BOOL IsSingle:1; // Set to true if you want to share this CB with cloned Effects + BOOL IsNonUpdatable:1; // Set to true if you want to share this CB with cloned Effects + + union + { + // These are used to store the original ID3D11Buffer* for use in UndoSetConstantBuffer + UINT MemberDataOffsetPlus4; // 4 added so that 0 == NULL can represent "unused" + SMemberDataPointer *pMemberData; + }; + + CEffect *pEffect; + + SConstantBuffer() + { + pD3DObject = NULL; + ZeroMemory(&TBuffer, sizeof(TBuffer)); + ExplicitBindPoint = -1; + pBackingStore = NULL; + Size = 0; + pName = NULL; + VariableCount = 0; + pVariables = NULL; + AnnotationCount = 0; + pAnnotations = NULL; + IsDirty = FALSE; + IsTBuffer = FALSE; + IsUserManaged = FALSE; + IsEffectOptimized = FALSE; + IsUsedByExpression = FALSE; + IsUserPacked = FALSE; + IsSingle = FALSE; + IsNonUpdatable = FALSE; + pEffect = NULL; + } + + bool ClonedSingle() const; + + // ID3DX11EffectConstantBuffer interface + STDMETHOD_(BOOL, IsValid)(); + STDMETHOD_(ID3DX11EffectType*, GetType)(); + STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc); + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name); + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(LPCSTR Name); + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(LPCSTR Semantic); + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(UINT Index); + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(); + + // other casts are handled by TUncastableVariable + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(); + + STDMETHOD(SetRawValue)(CONST void *pData, UINT Offset, UINT Count); + STDMETHOD(GetRawValue)(__out_bcount(Count) void *pData, UINT Offset, UINT Count); + + STDMETHOD(SetConstantBuffer)(ID3D11Buffer *pConstantBuffer); + STDMETHOD(GetConstantBuffer)(ID3D11Buffer **ppConstantBuffer); + STDMETHOD(UndoSetConstantBuffer)(); + + STDMETHOD(SetTextureBuffer)(ID3D11ShaderResourceView *pTextureBuffer); + STDMETHOD(GetTextureBuffer)(ID3D11ShaderResourceView **ppTextureBuffer); + STDMETHOD(UndoSetTextureBuffer)(); + + // ID3DX11EffectType interface + STDMETHOD(GetDesc)(D3DX11_EFFECT_TYPE_DESC *pDesc); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(LPCSTR Name); + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(LPCSTR Semantic); + + STDMETHOD_(LPCSTR, GetMemberName)(UINT Index); + STDMETHOD_(LPCSTR, GetMemberSemantic)(UINT Index); +}; + + +////////////////////////////////////////////////////////////////////////// +// Assignments +////////////////////////////////////////////////////////////////////////// + +enum ERuntimeAssignmentType +{ + ERAT_Invalid, + // [Destination] refers to the destination location, which is always the backing store of the pass/state block. + // [Source] refers to the current source of data, always coming from either a constant buffer's + // backing store (for numeric assignments), an object variable's block array, or an anonymous (unowned) block + + // Numeric variables: + ERAT_Constant, // Source is unused. + // No dependencies; this assignment can be safely removed after load. + ERAT_NumericVariable, // Source points to the CB's backing store where the value lives. + // 1 dependency: the variable itself. + ERAT_NumericConstIndex, // Source points to the CB's backing store where the value lives, offset by N. + // 1 dependency: the variable array being indexed. + ERAT_NumericVariableIndex, // Source points to the last used element of the variable in the CB's backing store. + // 2 dependencies: the index variable followed by the array variable. + + // Object variables: + ERAT_ObjectInlineShader, // An anonymous, immutable shader block pointer is copied to the destination immediately. + // No dependencies; this assignment can be safely removed after load. + ERAT_ObjectVariable, // A pointer to the block owned by the object variable is copied to the destination immediately. + // No dependencies; this assignment can be safely removed after load. + ERAT_ObjectConstIndex, // A pointer to the Nth block owned by an object variable is copied to the destination immediately. + // No dependencies; this assignment can be safely removed after load. + ERAT_ObjectVariableIndex, // Source points to the first block owned by an object variable array + // (the offset from this, N, is taken from another variable). + // 1 dependency: the variable being used to index the array. +}; + +struct SAssignment +{ + struct SDependency + { + SGlobalVariable *pVariable; + + SDependency() + { + pVariable = NULL; + } + }; + + ELhsType LhsType; // PS, VS, DepthStencil etc. + + // The value of SAssignment.AssignmentType determines how the other fields behave + // (DependencyCount, pDependencies, Destination, and Source) + ERuntimeAssignmentType AssignmentType; + + Timer LastRecomputedTime; + + // see comments in ERuntimeAssignmentType for how dependencies and data pointers are handled + UINT DependencyCount; + SDependency *pDependencies; + + UDataPointer Destination; // This value never changes after load, and always refers to the backing store + UDataPointer Source; // This value, on the other hand, can change if variable- or expression- driven + + UINT DataSize : 16; // Size of the data element to be copied in bytes (if numeric) or + // stride of the block type (if object) + UINT MaxElements : 16; // Max allowable index (needed because we don't store object arrays as dependencies, + // and therefore have no way of getting their Element count) + + BOOL IsObjectAssignment() // True for Shader and RObject assignments (the type that appear in pass blocks) + { + return IsObjectAssignmentHelper(LhsType); + } + + SAssignment() + { + LhsType = ELHS_Invalid; + AssignmentType = ERAT_Invalid; + + Destination.pGeneric = NULL; + Source.pGeneric = NULL; + + LastRecomputedTime = 0; + DependencyCount = 0; + pDependencies = NULL; + + DataSize = 0; + } +}; + +////////////////////////////////////////////////////////////////////////// +// Private effect heaps +////////////////////////////////////////////////////////////////////////// + +// Used to efficiently reallocate data +// 1) For every piece of data that needs reallocation, move it to its new location +// and add an entry into the table +// 2) For everyone that references one of these data blocks, do a quick table lookup +// to find the old pointer and then replace it with the new one +struct SPointerMapping +{ + void *pOld; + void *pNew; + + static BOOL AreMappingsEqual(const SPointerMapping &pMap1, const SPointerMapping &pMap2) + { + return (pMap1.pOld == pMap2.pOld); + } + + UINT Hash() + { + // hash the pointer itself + // (using the pointer as a hash would be very bad) + return ComputeHash((BYTE*)&pOld, sizeof(pOld)); + } +}; + +typedef CEffectHashTableWithPrivateHeap<SPointerMapping, SPointerMapping::AreMappingsEqual> CPointerMappingTable; + +// Assist adding data to a block of memory +class CEffectHeap +{ +protected: + BYTE *m_pData; + UINT m_dwBufferSize; + UINT m_dwSize; + + template <bool bCopyData> + HRESULT AddDataInternal(const void *pData, UINT dwSize, void **ppPointer); + +public: + HRESULT ReserveMemory(UINT dwSize); + UINT GetSize(); + BYTE* GetDataStart() { return m_pData; } + + // AddData and AddString append existing data to the buffer - they change m_dwSize. Users are + // not expected to modify the data pointed to by the return pointer + HRESULT AddString(const char *pString, __deref_out_z char **ppPointer); + HRESULT AddData(const void *pData, UINT dwSize, void **ppPointer); + + // Allocate behaves like a standard new - it will allocate memory, move m_dwSize. The caller is + // expected to use the returned pointer + void* Allocate(UINT dwSize); + + // Move data from the general heap and optional free memory + HRESULT MoveData(void **ppData, UINT size); + HRESULT MoveString(__deref_inout_z char **ppStringData); + HRESULT MoveInterfaceParameters(UINT InterfaceCount, __in_ecount(1) SShaderBlock::SInterfaceParameter **ppInterfaces); + HRESULT MoveEmptyDataBlock(void **ppData, UINT size); + + BOOL IsInHeap(void *pData) const + { + return (pData >= m_pData && pData < (m_pData + m_dwBufferSize)); + } + + CEffectHeap(); + ~CEffectHeap(); +}; + +class CEffectReflection +{ +public: + // Single memory block support + CEffectHeap m_Heap; +}; + + +class CEffect : public ID3DX11Effect +{ + friend struct SBaseBlock; + friend struct SPassBlock; + friend class CEffectLoader; + friend struct SConstantBuffer; + friend struct TSamplerVariable<TGlobalVariable<ID3DX11EffectSamplerVariable>>; + friend struct TSamplerVariable<TVariable<TMember<ID3DX11EffectSamplerVariable>>>; + +protected: + + UINT m_RefCount; + UINT m_Flags; + + // Private heap - all pointers should point into here + CEffectHeap m_Heap; + + // Reflection object + CEffectReflection *m_pReflection; + + // global variables in the effect (aka parameters) + UINT m_VariableCount; + SGlobalVariable *m_pVariables; + + // anonymous shader variables (one for every inline shader assignment) + UINT m_AnonymousShaderCount; + SAnonymousShader *m_pAnonymousShaders; + + // techniques within this effect (the actual data is located in each group) + UINT m_TechniqueCount; + + // groups within this effect + UINT m_GroupCount; + SGroup *m_pGroups; + SGroup *m_pNullGroup; + + UINT m_ShaderBlockCount; + SShaderBlock *m_pShaderBlocks; + + UINT m_DepthStencilBlockCount; + SDepthStencilBlock *m_pDepthStencilBlocks; + + UINT m_BlendBlockCount; + SBlendBlock *m_pBlendBlocks; + + UINT m_RasterizerBlockCount; + SRasterizerBlock *m_pRasterizerBlocks; + + UINT m_SamplerBlockCount; + SSamplerBlock *m_pSamplerBlocks; + + UINT m_MemberDataCount; + SMemberDataPointer *m_pMemberDataBlocks; + + UINT m_InterfaceCount; + SInterface *m_pInterfaces; + + UINT m_CBCount; + SConstantBuffer *m_pCBs; + + UINT m_StringCount; + SString *m_pStrings; + + UINT m_ShaderResourceCount; + SShaderResource *m_pShaderResources; + + UINT m_UnorderedAccessViewCount; + SUnorderedAccessView *m_pUnorderedAccessViews; + + UINT m_RenderTargetViewCount; + SRenderTargetView *m_pRenderTargetViews; + + UINT m_DepthStencilViewCount; + SDepthStencilView *m_pDepthStencilViews; + + Timer m_LocalTimer; + + // temporary index variable for assignment evaluation + UINT m_FXLIndex; + + ID3D11Device *m_pDevice; + ID3D11DeviceContext *m_pContext; + ID3D11ClassLinkage *m_pClassLinkage; + + // Master lists of reflection interfaces + CEffectVectorOwner<SSingleElementType> m_pTypeInterfaces; + CEffectVectorOwner<SMember> m_pMemberInterfaces; + + ////////////////////////////////////////////////////////////////////////// + // String & Type pooling + + typedef SType *LPSRUNTIMETYPE; + static BOOL AreTypesEqual(const LPSRUNTIMETYPE &pType1, const LPSRUNTIMETYPE &pType2) { return (pType1->IsEqual(pType2)); } + static BOOL AreStringsEqual(__in const LPCSTR &pStr1, __in const LPCSTR &pStr2) { return strcmp(pStr1, pStr2) == 0; } + + typedef CEffectHashTableWithPrivateHeap<SType *, AreTypesEqual> CTypeHashTable; + typedef CEffectHashTableWithPrivateHeap<LPCSTR, AreStringsEqual> CStringHashTable; + + // These are used to pool types & type-related strings + // until Optimize() is called + CTypeHashTable *m_pTypePool; + CStringHashTable *m_pStringPool; + CDataBlockStore *m_pPooledHeap; + // After Optimize() is called, the type/string pools should be deleted and all + // remaining data should be migrated into the optimized type heap + CEffectHeap *m_pOptimizedTypeHeap; + + // Pools a string or type and modifies the pointer + void AddStringToPool(const char **ppString); + void AddTypeToPool(SType **ppType); + + HRESULT OptimizeTypes(CPointerMappingTable *pMappingTable, bool Cloning = false); + + + ////////////////////////////////////////////////////////////////////////// + // Runtime (performance critical) + + void ApplyShaderBlock(SShaderBlock *pBlock); + BOOL ApplyRenderStateBlock(SBaseBlock *pBlock); + BOOL ApplySamplerBlock(SSamplerBlock *pBlock); + void ApplyPassBlock(SPassBlock *pBlock); + BOOL EvaluateAssignment(SAssignment *pAssignment); + BOOL ValidateShaderBlock( SShaderBlock* pBlock ); + BOOL ValidatePassBlock( SPassBlock* pBlock ); + + ////////////////////////////////////////////////////////////////////////// + // Non-runtime functions (not performance critical) + + SGlobalVariable *FindLocalVariableByName(LPCSTR pVarName); // Looks in the current effect only + SGlobalVariable *FindVariableByName(LPCSTR pVarName); + SVariable *FindVariableByNameWithParsing(LPCSTR pVarName); + SConstantBuffer *FindCB(LPCSTR pName); + void ReplaceCBReference(SConstantBuffer *pOldBufferBlock, ID3D11Buffer *pNewBuffer); // Used by user-managed CBs + void ReplaceSamplerReference(SSamplerBlock *pOldSamplerBlock, ID3D11SamplerState *pNewSampler); + void AddRefAllForCloning( CEffect* pEffectSource ); + HRESULT CopyMemberInterfaces( CEffect* pEffectSource ); + HRESULT CopyStringPool( CEffect* pEffectSource, CPointerMappingTable& mappingTable ); + HRESULT CopyTypePool( CEffect* pEffectSource, CPointerMappingTable& mappingTableTypes, CPointerMappingTable& mappingTableStrings ); + HRESULT CopyOptimizedTypePool( CEffect* pEffectSource, CPointerMappingTable& mappingTableTypes ); + HRESULT RecreateCBs(); + HRESULT FixupMemberInterface( SMember* pMember, CEffect* pEffectSource, CPointerMappingTable& mappingTableStrings ); + + void ValidateIndex(UINT Elements); + + void IncrementTimer(); + void HandleLocalTimerRollover(); + + friend struct SConstantBuffer; + +public: + CEffect( UINT Flags = 0 ); + virtual ~CEffect(); + void ReleaseShaderRefection(); + + // Initialize must be called after the effect is created + HRESULT LoadEffect(CONST void *pEffectBuffer, UINT cbEffectBuffer); + + // Once the effect is fully loaded, call BindToDevice to attach it to a device + HRESULT BindToDevice(ID3D11Device *pDevice); + + Timer GetCurrentTime() const { return m_LocalTimer; } + + BOOL IsReflectionData(void *pData) const { return m_pReflection->m_Heap.IsInHeap(pData); } + BOOL IsRuntimeData(void *pData) const { return m_Heap.IsInHeap(pData); } + + ////////////////////////////////////////////////////////////////////////// + // Public interface + + // IUnknown + STDMETHOD(QueryInterface)(REFIID iid, LPVOID *ppv); + STDMETHOD_(ULONG, AddRef)(); + STDMETHOD_(ULONG, Release)(); + + STDMETHOD_(BOOL, IsValid)() { return TRUE; } + + STDMETHOD(GetDevice)(ID3D11Device** ppDevice); + + STDMETHOD(GetDesc)(D3DX11_EFFECT_DESC *pDesc); + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByName)(LPCSTR Name); + + STDMETHOD_(ID3DX11EffectVariable*, GetVariableByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectVariable*, GetVariableByName)(LPCSTR Name); + STDMETHOD_(ID3DX11EffectVariable*, GetVariableBySemantic)(LPCSTR Semantic); + + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(LPCSTR Name); + + STDMETHOD_(ID3DX11EffectGroup*, GetGroupByIndex)(UINT Index); + STDMETHOD_(ID3DX11EffectGroup*, GetGroupByName)(LPCSTR Name); + + STDMETHOD_(ID3D11ClassLinkage*, GetClassLinkage)(); + + STDMETHOD(CloneEffect)(UINT Flags, ID3DX11Effect** ppClonedEffect); + STDMETHOD(Optimize)(); + STDMETHOD_(BOOL, IsOptimized)(); + + ////////////////////////////////////////////////////////////////////////// + // New reflection helpers + + ID3DX11EffectType * CreatePooledSingleElementTypeInterface(SType *pType); + ID3DX11EffectVariable * CreatePooledVariableMemberInterface(TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity, SVariable *pMember, UDataPointer Data, BOOL IsSingleElement, UINT Index); + +}; + +} diff --git a/sample/d3d11/Effects11/EffectAPI.cpp b/sample/d3d11/Effects11/EffectAPI.cpp new file mode 100644 index 0000000..e373e51 --- /dev/null +++ b/sample/d3d11/Effects11/EffectAPI.cpp @@ -0,0 +1,29 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectAPI.cpp +// Content: D3DX11 Effect DLL entry points +// +////////////////////////////////////////////////////////////////////////////// + +#include "pchfx.h" + +using namespace D3DX11Effects; + +HRESULT WINAPI D3DX11CreateEffectFromMemory(CONST void *pData, SIZE_T DataLength, UINT FXFlags, ID3D11Device *pDevice, ID3DX11Effect **ppEffect) +{ + HRESULT hr = S_OK; + + // Note that pData must point to a compiled effect, not HLSL + VN( *ppEffect = NEW CEffect( FXFlags & D3DX11_EFFECT_RUNTIME_VALID_FLAGS) ); + VH( ((CEffect*)(*ppEffect))->LoadEffect(pData, static_cast<UINT>(DataLength)) ); + VH( ((CEffect*)(*ppEffect))->BindToDevice(pDevice) ); + +lExit: + if (FAILED(hr)) + { + SAFE_RELEASE(*ppEffect); + } + return hr; +} diff --git a/sample/d3d11/Effects11/EffectLoad.cpp b/sample/d3d11/Effects11/EffectLoad.cpp new file mode 100644 index 0000000..0e1cf32 --- /dev/null +++ b/sample/d3d11/Effects11/EffectLoad.cpp @@ -0,0 +1,3982 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectLoad.cpp +// Content: D3DX11 Effects file loading code +// +////////////////////////////////////////////////////////////////////////////// + +#include "pchfx.h" + +#include <EffectStates11.h> + +#define PRIVATENEW new(m_BulkHeap) + +namespace D3DX11Effects +{ + +LPCSTR g_szEffectLoadArea = "D3D11EffectLoader"; + +SRasterizerBlock g_NullRasterizer; +SDepthStencilBlock g_NullDepthStencil; +SBlendBlock g_NullBlend; +SShaderResource g_NullTexture; +SInterface g_NullInterface; +SUnorderedAccessView g_NullUnorderedAccessView; +SRenderTargetView g_NullRenderTargetView; +SDepthStencilView g_NullDepthStencilView; + +// these VTables must be setup in the proper order: +// 1) SetShader +// 2) SetConstantBuffers +// 3) SetSamplers +// 4) SetShaderResources +// 5) CreateShader +SD3DShaderVTable g_vtPS = { + (void (__stdcall ID3D11DeviceContext::*)(ID3D11DeviceChild*, ID3D11ClassInstance*const*, UINT)) &ID3D11DeviceContext::PSSetShader, + &ID3D11DeviceContext::PSSetConstantBuffers, + &ID3D11DeviceContext::PSSetSamplers, + &ID3D11DeviceContext::PSSetShaderResources, + (HRESULT (__stdcall ID3D11Device::*)(const void *, SIZE_T, ID3D11ClassLinkage*, ID3D11DeviceChild **)) &ID3D11Device::CreatePixelShader +}; + +SD3DShaderVTable g_vtVS = { + (void (__stdcall ID3D11DeviceContext::*)(ID3D11DeviceChild*, ID3D11ClassInstance*const*, UINT)) &ID3D11DeviceContext::VSSetShader, + &ID3D11DeviceContext::VSSetConstantBuffers, + &ID3D11DeviceContext::VSSetSamplers, + &ID3D11DeviceContext::VSSetShaderResources, + (HRESULT (__stdcall ID3D11Device::*)(const void *, SIZE_T, ID3D11ClassLinkage*, ID3D11DeviceChild **)) &ID3D11Device::CreateVertexShader +}; + +SD3DShaderVTable g_vtGS = { + (void (__stdcall ID3D11DeviceContext::*)(ID3D11DeviceChild*, ID3D11ClassInstance*const*, UINT)) &ID3D11DeviceContext::GSSetShader, + &ID3D11DeviceContext::GSSetConstantBuffers, + &ID3D11DeviceContext::GSSetSamplers, + &ID3D11DeviceContext::GSSetShaderResources, + (HRESULT (__stdcall ID3D11Device::*)(const void *, SIZE_T, ID3D11ClassLinkage*, ID3D11DeviceChild **)) &ID3D11Device::CreateGeometryShader +}; + +SD3DShaderVTable g_vtHS = { + (void (__stdcall ID3D11DeviceContext::*)(ID3D11DeviceChild*, ID3D11ClassInstance*const*, UINT)) &ID3D11DeviceContext::HSSetShader, + &ID3D11DeviceContext::HSSetConstantBuffers, + &ID3D11DeviceContext::HSSetSamplers, + &ID3D11DeviceContext::HSSetShaderResources, + (HRESULT (__stdcall ID3D11Device::*)(const void *, SIZE_T, ID3D11ClassLinkage*, ID3D11DeviceChild **)) &ID3D11Device::CreateHullShader +}; + +SD3DShaderVTable g_vtDS = { + (void (__stdcall ID3D11DeviceContext::*)(ID3D11DeviceChild*, ID3D11ClassInstance*const*, UINT)) &ID3D11DeviceContext::DSSetShader, + &ID3D11DeviceContext::DSSetConstantBuffers, + &ID3D11DeviceContext::DSSetSamplers, + &ID3D11DeviceContext::DSSetShaderResources, + (HRESULT (__stdcall ID3D11Device::*)(const void *, SIZE_T, ID3D11ClassLinkage*, ID3D11DeviceChild **)) &ID3D11Device::CreateDomainShader +}; + +SD3DShaderVTable g_vtCS = { + (void (__stdcall ID3D11DeviceContext::*)(ID3D11DeviceChild*, ID3D11ClassInstance*const*, UINT)) &ID3D11DeviceContext::CSSetShader, + &ID3D11DeviceContext::CSSetConstantBuffers, + &ID3D11DeviceContext::CSSetSamplers, + &ID3D11DeviceContext::CSSetShaderResources, + (HRESULT (__stdcall ID3D11Device::*)(const void *, SIZE_T, ID3D11ClassLinkage*, ID3D11DeviceChild **)) &ID3D11Device::CreateComputeShader +}; + +SShaderBlock g_NullVS(&g_vtVS); +SShaderBlock g_NullGS(&g_vtGS); +SShaderBlock g_NullPS(&g_vtPS); +SShaderBlock g_NullHS(&g_vtHS); +SShaderBlock g_NullDS(&g_vtDS); +SShaderBlock g_NullCS(&g_vtCS); + +D3D10_SHADER_VARIABLE_TYPE GetSimpleParameterTypeFromObjectType(EObjectType ObjectType) +{ + switch (ObjectType) + { + case EOT_String: + return D3D10_SVT_STRING; + case EOT_Blend: + return D3D10_SVT_BLEND; + case EOT_DepthStencil: + return D3D10_SVT_DEPTHSTENCIL; + case EOT_Rasterizer: + return D3D10_SVT_RASTERIZER; + case EOT_PixelShader: + case EOT_PixelShader5: + return D3D10_SVT_PIXELSHADER; + case EOT_VertexShader: + case EOT_VertexShader5: + return D3D10_SVT_VERTEXSHADER; + case EOT_GeometryShader: + case EOT_GeometryShaderSO: + case EOT_GeometryShader5: + return D3D10_SVT_GEOMETRYSHADER; + case EOT_HullShader5: + return D3D11_SVT_HULLSHADER; + case EOT_DomainShader5: + return D3D11_SVT_DOMAINSHADER; + case EOT_ComputeShader5: + return D3D11_SVT_COMPUTESHADER; + case EOT_RenderTargetView: + return D3D10_SVT_RENDERTARGETVIEW; + case EOT_DepthStencilView: + return D3D10_SVT_DEPTHSTENCILVIEW; + case EOT_Texture: + case EOT_Texture1D: + case EOT_Texture1DArray: + case EOT_Texture2D: + case EOT_Texture2DArray: + case EOT_Texture2DMS: + case EOT_Texture2DMSArray: + case EOT_Texture3D: + case EOT_TextureCube: + case EOT_TextureCubeArray: + return D3D10_SVT_TEXTURE; + case EOT_Buffer: + return D3D10_SVT_BUFFER; + case EOT_Sampler: + return D3D10_SVT_SAMPLER; + case EOT_ByteAddressBuffer: + return D3D11_SVT_BYTEADDRESS_BUFFER; + case EOT_StructuredBuffer: + return D3D11_SVT_STRUCTURED_BUFFER; + case EOT_RWTexture1D: + return D3D11_SVT_RWTEXTURE1D; + case EOT_RWTexture1DArray: + return D3D11_SVT_RWTEXTURE1DARRAY; + case EOT_RWTexture2D: + return D3D11_SVT_RWTEXTURE2D; + case EOT_RWTexture2DArray: + return D3D11_SVT_RWTEXTURE2DARRAY; + case EOT_RWTexture3D: + return D3D11_SVT_RWTEXTURE3D; + case EOT_RWBuffer: + return D3D11_SVT_RWBUFFER; + case EOT_RWByteAddressBuffer: + return D3D11_SVT_RWBYTEADDRESS_BUFFER; + case EOT_RWStructuredBuffer: + case EOT_RWStructuredBufferAlloc: + case EOT_RWStructuredBufferConsume: + return D3D11_SVT_RWSTRUCTURED_BUFFER; + case EOT_AppendStructuredBuffer: + return D3D11_SVT_APPEND_STRUCTURED_BUFFER; + case EOT_ConsumeStructuredBuffer: + return D3D11_SVT_CONSUME_STRUCTURED_BUFFER; + default: + D3DXASSERT(0); + } + return D3D10_SVT_VOID; +} + +inline HRESULT VerifyPointer(UINT oBase, UINT dwSize, UINT dwMaxSize) +{ + UINT dwAdd = oBase + dwSize; + if (dwAdd < oBase || dwAdd > dwMaxSize) + return E_FAIL; + return S_OK; +} + +////////////////////////////////////////////////////////////////////////// +// EffectHeap +// A simple class which assists in adding data to a block of memory +////////////////////////////////////////////////////////////////////////// + +CEffectHeap::CEffectHeap() +{ + m_pData = NULL; + m_dwSize = m_dwBufferSize = 0; +} + +CEffectHeap::~CEffectHeap() +{ + SAFE_DELETE_ARRAY(m_pData); +} + +UINT CEffectHeap::GetSize() +{ + return m_dwSize; +} + +HRESULT CEffectHeap::ReserveMemory(UINT dwSize) +{ + HRESULT hr = S_OK; + + D3DXASSERT(!m_pData); + D3DXASSERT(dwSize == AlignToPowerOf2(dwSize, c_DataAlignment)); + + m_dwBufferSize = dwSize; + + VN( m_pData = NEW BYTE[m_dwBufferSize] ); + + // make sure that we have machine word alignment + D3DXASSERT(m_pData == AlignToPowerOf2(m_pData, c_DataAlignment)); + +lExit: + return hr; +} + +HRESULT CEffectHeap::AddString(const char *pString, __deref_out_z char **ppPointer) +{ + size_t size = strlen(pString) + 1; + D3DXASSERT( size <= 0xffffffff ); + return AddData(pString, (UINT)size, (void**) ppPointer); +} + +// This data is forcibly aligned, so make sure you account for that in calculating heap size +template <bool bCopyData> +HRESULT CEffectHeap::AddDataInternal(const void *pData, UINT dwSize, void **ppPointer) +{ + CCheckedDword chkFinalSize( m_dwSize ); + UINT finalSize; + HRESULT hr = S_OK; + + chkFinalSize += dwSize; + chkFinalSize += c_DataAlignment; // account for alignment + + VHD( chkFinalSize.GetValue(&finalSize), "Overflow while adding data to Effect heap." ); + + // align original value + finalSize = AlignToPowerOf2(finalSize - c_DataAlignment, c_DataAlignment); + VBD( finalSize <= m_dwBufferSize, "Overflow adding data to Effect heap." ); + + *ppPointer = m_pData + m_dwSize; + D3DXASSERT(*ppPointer == AlignToPowerOf2(*ppPointer, c_DataAlignment)); + + if( bCopyData ) + { + memcpy(*ppPointer, pData, dwSize); + } + m_dwSize = finalSize; + +lExit: + if (FAILED(hr)) + *ppPointer = NULL; + + return hr; +} + +HRESULT CEffectHeap::AddData(const void *pData, UINT dwSize, void **ppPointer) +{ + return AddDataInternal<true>( pData, dwSize, ppPointer ); +} + +// Moves a string from the general heap to the private heap and modifies the pointer to +// point to the new memory block. +// The general heap is freed as a whole, so we don't worry about leaking the given string pointer. +// This data is forcibly aligned, so make sure you account for that in calculating heap size +HRESULT CEffectHeap::MoveString(__deref_inout_z char **ppString) +{ + HRESULT hr; + char *pNewPointer; + + if (*ppString == NULL) + return S_OK; + + hr = AddString(*ppString, &pNewPointer); + *ppString = pNewPointer; + + return hr; +} + +// Allocates space but does not move data +// The general heap is freed as a whole, so we don't worry about leaking the given string pointer. +// This data is forcibly aligned, so make sure you account for that in calculating heap size +HRESULT CEffectHeap::MoveEmptyDataBlock(void **ppData, UINT size) +{ + HRESULT hr; + void *pNewPointer; + + hr = AddDataInternal<false>(*ppData, size, &pNewPointer); + + *ppData = pNewPointer; + if (size == 0) + { + // To help catch bugs, set zero-byte blocks to null. There's no real reason to do this + *ppData = NULL; + } + + return hr; +} + +// Moves an array of SInterfaceParameters from the general heap to the private heap and modifies the pointer to +// point to the new memory block. +// The general heap is freed as a whole, so we don't worry about leaking the given string pointer. +// This data is forcibly aligned, so make sure you account for that in calculating heap size +HRESULT CEffectHeap::MoveInterfaceParameters(UINT InterfaceCount, __in_ecount(1) SShaderBlock::SInterfaceParameter **ppInterfaces) +{ + HRESULT hr; + SShaderBlock::SInterfaceParameter *pNewPointer; + + if (*ppInterfaces == NULL) + return S_OK; + + VBD( InterfaceCount <= D3D11_SHADER_MAX_INTERFACES, "Internal loading error: InterfaceCount > D3D11_SHADER_MAX_INTERFACES." ); + VH( AddData(*ppInterfaces, InterfaceCount * sizeof(SShaderBlock::SInterfaceParameter), (void**)&pNewPointer) ); + + for( UINT i=0; i < InterfaceCount; i++ ) + { + VH( MoveString( &pNewPointer[i].pName ) ); + } + + *ppInterfaces = pNewPointer; + +lExit: + return hr; +} + + +// Moves data from the general heap to the private heap and modifies the pointer to +// point to the new memory block +// The general heap is freed as a whole, so we don't worry about leaking the given pointer. +// This data is forcibly aligned, so make sure you account for that in calculating heap size +HRESULT CEffectHeap::MoveData(void **ppData, UINT size) +{ + HRESULT hr; + void *pNewPointer; + + hr = AddData(*ppData, size, &pNewPointer); + + *ppData = pNewPointer; + if (size == 0) + { + // To help catch bugs, set zero-byte blocks to null. There's no real reason to do this + *ppData = NULL; + } + + return hr; +} + + +////////////////////////////////////////////////////////////////////////// +// Load API +////////////////////////////////////////////////////////////////////////// + +HRESULT CEffect::LoadEffect(CONST void *pEffectBuffer, UINT cbEffectBuffer) +{ + HRESULT hr = S_OK; + CEffectLoader loader; + + if (!pEffectBuffer) + { + DPF(0, "%s: pEffectBuffer is NULL.", g_szEffectLoadArea); + VH( E_INVALIDARG ); + } + + VH( loader.LoadEffect(this, pEffectBuffer, cbEffectBuffer) ); + +lExit: + if( FAILED( hr ) ) + { + // Release here because m_pShaderBlocks may still be in loader.m_BulkHeap if loading failed before we reallocated the memory + ReleaseShaderRefection(); + } + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// CEffectLoader +// A helper class which loads an effect +////////////////////////////////////////////////////////////////////////// + +HRESULT CEffectLoader::GetUnstructuredDataBlock(UINT offset, UINT *pdwSize, void **ppData) +{ + HRESULT hr = S_OK; + UINT *pBlockSize; + + VH( m_msUnstructured.ReadAtOffset(offset, sizeof(*pBlockSize), (void**) &pBlockSize ) ); + *pdwSize = *pBlockSize; + + VH( m_msUnstructured.Read(ppData, *pdwSize) ); + +lExit: + return hr; +} + +// position in buffer is lost on error +// +// This function should be used in 1:1 conjunction with CEffectHeap::MoveString; +// that is, any string added to the reflection heap with this function +// must be relocated with MoveString at some point later on. +HRESULT CEffectLoader::GetStringAndAddToReflection(UINT offset, __out_ecount_full(1) char **ppString) +{ + HRESULT hr = S_OK; + LPCSTR pName; + SIZE_T oldPos; + + if (offset == 0) + { + *ppString = NULL; + goto lExit; + } + + oldPos = m_msUnstructured.GetPosition(); + + VH( m_msUnstructured.ReadAtOffset(offset, &pName) ); + m_ReflectionMemory += AlignToPowerOf2( (UINT)strlen(pName) + 1, c_DataAlignment); + *ppString = const_cast<char*>(pName); + + m_msUnstructured.Seek(oldPos); + +lExit: + return hr; +} + +// position in buffer is lost on error +// +// This function should be used in 1:1 conjunction with CEffectHeap::MoveInterfaceParameters; +// that is, any array of parameters added to the reflection heap with this function +// must be relocated with MoveInterfaceParameters at some point later on. +HRESULT CEffectLoader::GetInterfaceParametersAndAddToReflection( UINT InterfaceCount, UINT offset, __out_ecount_full(1) SShaderBlock::SInterfaceParameter **ppInterfaces ) +{ + HRESULT hr = S_OK; + SBinaryInterfaceInitializer* pInterfaceInitializer; + SIZE_T oldPos; + + if (offset == 0) + { + *ppInterfaces = NULL; + goto lExit; + } + + oldPos = m_msUnstructured.GetPosition(); + + VBD( InterfaceCount <= D3D11_SHADER_MAX_INTERFACES, "Internal loading error: InterfaceCount > D3D11_SHADER_MAX_INTERFACES." ); + m_ReflectionMemory += AlignToPowerOf2(InterfaceCount * sizeof(SShaderBlock::SInterfaceParameter), c_DataAlignment); + D3DXASSERT( ppInterfaces ); + (*ppInterfaces) = PRIVATENEW SShaderBlock::SInterfaceParameter[InterfaceCount]; + VN( *ppInterfaces ); + + VHD( m_msUnstructured.ReadAtOffset(offset, sizeof(SBinaryInterfaceInitializer) * InterfaceCount, (void**)&pInterfaceInitializer), + "Invalid pEffectBuffer: cannot read interface initializer." ); + + for( UINT i=0; i < InterfaceCount; i++ ) + { + (*ppInterfaces)[i].Index = pInterfaceInitializer[i].ArrayIndex; + VHD( m_msUnstructured.ReadAtOffset(pInterfaceInitializer[i].oInstanceName, const_cast<LPCSTR*>(&(*ppInterfaces)[i].pName)), + "Invalid pEffectBuffer: cannot read interface initializer." ); + m_ReflectionMemory += AlignToPowerOf2( (UINT)strlen((*ppInterfaces)[i].pName) + 1, c_DataAlignment); + } + + m_msUnstructured.Seek(oldPos); + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupCBPointer(SConstantBuffer **ppCB) +{ + HRESULT hr = S_OK; + + SIZE_T index = (SConstantBuffer*)*ppCB - m_pOldCBs; + D3DXASSERT( index * sizeof(SConstantBuffer) == ((size_t)(SConstantBuffer*)*ppCB - (size_t)m_pOldCBs) ); + VBD( index < m_pEffect->m_CBCount, "Internal loading error: invalid constant buffer index." ); + *ppCB = (SConstantBuffer*)(m_pEffect->m_pCBs + index); + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupShaderPointer(SShaderBlock **ppShaderBlock) +{ + HRESULT hr = S_OK; + if (*ppShaderBlock != &g_NullVS && *ppShaderBlock != &g_NullGS && *ppShaderBlock != &g_NullPS && + *ppShaderBlock != &g_NullHS && *ppShaderBlock != &g_NullDS && *ppShaderBlock != &g_NullCS && + *ppShaderBlock != NULL) + { + SIZE_T index = *ppShaderBlock - m_pOldShaders; + D3DXASSERT( index * sizeof(SShaderBlock) == ((size_t)*ppShaderBlock - (size_t)m_pOldShaders) ); + VBD( index < m_pEffect->m_ShaderBlockCount, "Internal loading error: invalid shader index." ); + *ppShaderBlock = m_pEffect->m_pShaderBlocks + index; + } +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupDSPointer(SDepthStencilBlock **ppDSBlock) +{ + HRESULT hr = S_OK; + if (*ppDSBlock != &g_NullDepthStencil && *ppDSBlock != NULL) + { + SIZE_T index = *ppDSBlock - m_pOldDS; + D3DXASSERT( index * sizeof(SDepthStencilBlock) == ((size_t)*ppDSBlock - (size_t)m_pOldDS) ); + VBD( index < m_pEffect->m_DepthStencilBlockCount, "Internal loading error: invalid depth-stencil state index." ); + *ppDSBlock = m_pEffect->m_pDepthStencilBlocks + index; + } +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupABPointer(SBlendBlock **ppABBlock) +{ + HRESULT hr = S_OK; + if (*ppABBlock != &g_NullBlend && *ppABBlock != NULL) + { + SIZE_T index = *ppABBlock - m_pOldAB; + D3DXASSERT( index * sizeof(SBlendBlock) == ((size_t)*ppABBlock - (size_t)m_pOldAB) ); + VBD( index < m_pEffect->m_BlendBlockCount, "Internal loading error: invalid blend state index." ); + *ppABBlock = m_pEffect->m_pBlendBlocks + index; + } +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupRSPointer(SRasterizerBlock **ppRSBlock) +{ + HRESULT hr = S_OK; + if (*ppRSBlock != &g_NullRasterizer && *ppRSBlock != NULL) + { + SIZE_T index = *ppRSBlock - m_pOldRS; + D3DXASSERT( index * sizeof(SRasterizerBlock) == ((size_t)*ppRSBlock - (size_t)m_pOldRS) ); + VBD( index < m_pEffect->m_RasterizerBlockCount, "Internal loading error: invalid rasterizer state index." ); + *ppRSBlock = m_pEffect->m_pRasterizerBlocks + index; + } +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupSamplerPointer(SSamplerBlock **ppSampler) +{ + HRESULT hr = S_OK; + SIZE_T index = *ppSampler - m_pOldSamplers; + D3DXASSERT( index * sizeof(SSamplerBlock) == ((size_t)*ppSampler - (size_t)m_pOldSamplers) ); + VBD( index < m_pEffect->m_SamplerBlockCount, "Internal loading error: invalid sampler index." ); + *ppSampler = m_pEffect->m_pSamplerBlocks + index; + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupInterfacePointer(SInterface **ppInterface, bool CheckBackgroundInterfaces) +{ + HRESULT hr = S_OK; + if (*ppInterface != &g_NullInterface && *ppInterface != NULL) + { + SIZE_T index = *ppInterface - m_pOldInterfaces; + if(index < m_OldInterfaceCount) + { + D3DXASSERT( index * sizeof(SInterface) == ((size_t)*ppInterface - (size_t)m_pOldInterfaces) ); + *ppInterface = m_pEffect->m_pInterfaces + index; + } + else + { + VBD( CheckBackgroundInterfaces, "Internal loading error: invalid interface pointer." ); + for( index=0; index < m_BackgroundInterfaces.GetSize(); index++ ) + { + if( *ppInterface == m_BackgroundInterfaces[ (UINT)index ] ) + { + // The interfaces m_BackgroundInterfaces were concatenated to the original ones in m_pEffect->m_pInterfaces + *ppInterface = m_pEffect->m_pInterfaces + (m_OldInterfaceCount + index); + break; + } + } + VBD( index < m_BackgroundInterfaces.GetSize(), "Internal loading error: invalid interface pointer." ); + } + } + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupShaderResourcePointer(SShaderResource **ppResource) +{ + HRESULT hr = S_OK; + if (*ppResource != &g_NullTexture && *ppResource != NULL) + { + SIZE_T index = *ppResource - m_pOldShaderResources; + D3DXASSERT( index * sizeof(SShaderResource) == ((size_t)*ppResource - (size_t)m_pOldShaderResources) ); + + // could be a TBuffer or a texture; better check first + if (index < m_pEffect->m_ShaderResourceCount) + { + *ppResource = m_pEffect->m_pShaderResources + index; + } + else + { + // if this is a TBuffer, then the shader resource pointer + // actually points into a SConstantBuffer's TBuffer field + index = (SConstantBuffer*)*ppResource - (SConstantBuffer*)&m_pOldCBs->TBuffer; + D3DXASSERT( index * sizeof(SConstantBuffer) == ((size_t)(SConstantBuffer*)*ppResource - (size_t)(SConstantBuffer*)&m_pOldCBs->TBuffer) ); + VBD( index < m_pEffect->m_CBCount, "Internal loading error: invalid SRV index." ); + *ppResource = &m_pEffect->m_pCBs[index].TBuffer; + } + } + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupUnorderedAccessViewPointer(SUnorderedAccessView **ppUnorderedAccessView) +{ + HRESULT hr = S_OK; + if (*ppUnorderedAccessView != &g_NullUnorderedAccessView && *ppUnorderedAccessView != NULL) + { + SIZE_T index = *ppUnorderedAccessView - m_pOldUnorderedAccessViews; + D3DXASSERT( index * sizeof(SUnorderedAccessView) == ((size_t)*ppUnorderedAccessView - (size_t)m_pOldUnorderedAccessViews) ); + + VBD( index < m_pEffect->m_UnorderedAccessViewCount, "Internal loading error: invalid UAV index." ); + *ppUnorderedAccessView = m_pEffect->m_pUnorderedAccessViews + index; + } + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupRenderTargetViewPointer(SRenderTargetView **ppRenderTargetView) +{ + HRESULT hr = S_OK; + if (*ppRenderTargetView != &g_NullRenderTargetView && *ppRenderTargetView != NULL) + { + SIZE_T index = *ppRenderTargetView - m_pOldRenderTargetViews; + D3DXASSERT( index * sizeof(SRenderTargetView) == ((size_t)*ppRenderTargetView - (size_t)m_pOldRenderTargetViews) ); + VBD( index < m_pEffect->m_RenderTargetViewCount, "Internal loading error: invalid RTV index." ); + *ppRenderTargetView = m_pEffect->m_pRenderTargetViews + index; + } + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupDepthStencilViewPointer(SDepthStencilView **ppDepthStencilView) +{ + HRESULT hr = S_OK; + if (*ppDepthStencilView != &g_NullDepthStencilView && *ppDepthStencilView != NULL) + { + SIZE_T index = *ppDepthStencilView - m_pOldDepthStencilViews; + D3DXASSERT( index * sizeof(SDepthStencilView) == ((size_t)*ppDepthStencilView - (size_t)m_pOldDepthStencilViews) ); + VBD( index < m_pEffect->m_DepthStencilViewCount, "Internal loading error: invalid DSV index." ); + *ppDepthStencilView = m_pEffect->m_pDepthStencilViews + index; + } + +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupStringPointer(SString **ppString) +{ + HRESULT hr = S_OK; + SIZE_T index = *ppString - m_pOldStrings; + D3DXASSERT( index * sizeof(SString) == ((size_t)*ppString - (size_t)m_pOldStrings) ); + VBD(index < m_pEffect->m_StringCount, "Internal loading error: invalid string index." ); + *ppString = m_pEffect->m_pStrings + index; +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupMemberDataPointer(SMemberDataPointer **ppMemberData) +{ + HRESULT hr = S_OK; + SIZE_T index = *ppMemberData - m_pOldMemberDataBlocks; + D3DXASSERT( index * sizeof(SMemberDataPointer) == ((size_t)*ppMemberData - (size_t)m_pOldMemberDataBlocks) ); + VBD( index < m_pEffect->m_MemberDataCount, "Internal loading error: invalid member block index." ); + *ppMemberData = m_pEffect->m_pMemberDataBlocks + index; +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupVariablePointer(SGlobalVariable **ppVar) +{ + HRESULT hr = S_OK; + SIZE_T index = *ppVar - m_pOldVars; + + if( index < m_pEffect->m_VariableCount ) + { + D3DXASSERT( index * sizeof(SGlobalVariable) == ((size_t)*ppVar - (size_t)m_pOldVars) ); + *ppVar = m_pEffect->m_pVariables + index; + } + else if( m_pvOldMemberInterfaces ) + { + // When cloning, m_pvOldMemberInterfaces may be non-NULL, and *ppVar may point to a variable in it. + const SIZE_T Members = m_pvOldMemberInterfaces->GetSize(); + for( index=0; index < Members; index++ ) + { + if( (ID3DX11EffectVariable*)(*m_pvOldMemberInterfaces)[ (UINT)index] == (ID3DX11EffectVariable*)*ppVar ) + { + break; + } + } + VBD( index < Members, "Internal loading error: invalid member pointer." ); + *ppVar = (SGlobalVariable*)m_pEffect->m_pMemberInterfaces[ (UINT)index]; + } +lExit: + return hr; +} + +HRESULT CEffectLoader::FixupGroupPointer(SGroup **ppGroup) +{ + HRESULT hr = S_OK; + if( *ppGroup != NULL ) + { + SIZE_T index = *ppGroup - m_pOldGroups; + D3DXASSERT( index * sizeof(SGroup) == ((size_t)*ppGroup - (size_t)m_pOldGroups) ); + VBD( index < m_pEffect->m_GroupCount, "Internal loading error: invalid group index." ); + *ppGroup = m_pEffect->m_pGroups + index; + } +lExit: + return hr; +} + +HRESULT GetEffectVersion( UINT effectFileTag, DWORD* pVersion ) +{ + D3DXASSERT( pVersion != NULL ); + if( !pVersion ) + return E_FAIL; + + for( UINT i = 0; i < NUM_EFFECT10_VERSIONS; i++ ) + { + if( g_EffectVersions[i].m_Tag == effectFileTag ) + { + *pVersion = g_EffectVersions[i].m_Version; + return S_OK; + } + } + + return E_FAIL; +} + +HRESULT CEffectLoader::LoadEffect(CEffect *pEffect, CONST void *pEffectBuffer, UINT cbEffectBuffer) +{ + HRESULT hr = S_OK; + UINT i, varSize, cMemberDataBlocks; + CCheckedDword chkVariables = 0; + + // Used for cloning + m_pvOldMemberInterfaces = NULL; + + m_BulkHeap.EnableAlignment(); + + D3DXASSERT(pEffect && pEffectBuffer); + m_pEffect = pEffect; + m_EffectMemory = m_ReflectionMemory = 0; + + VN( m_pEffect->m_pReflection = NEW CEffectReflection() ); + m_pReflection = m_pEffect->m_pReflection; + + // Begin effect load + VN( m_pEffect->m_pTypePool = NEW CEffect::CTypeHashTable ); + VN( m_pEffect->m_pStringPool = NEW CEffect::CStringHashTable ); + VN( m_pEffect->m_pPooledHeap = NEW CDataBlockStore ); + m_pEffect->m_pPooledHeap->EnableAlignment(); + m_pEffect->m_pTypePool->SetPrivateHeap(m_pEffect->m_pPooledHeap); + m_pEffect->m_pStringPool->SetPrivateHeap(m_pEffect->m_pPooledHeap); + + VH( m_pEffect->m_pTypePool->AutoGrow() ); + VH( m_pEffect->m_pStringPool->AutoGrow() ); + + // Load from blob + m_pData = (BYTE*)pEffectBuffer; + m_dwBufferSize = cbEffectBuffer; + + VH( m_msStructured.SetData(m_pData, m_dwBufferSize) ); + + // At this point, we assume that the blob is valid + VHD( m_msStructured.Read((void**) &m_pHeader, sizeof(*m_pHeader)), "pEffectBuffer is too small." ); + + // Verify the version + if( FAILED( hr = GetEffectVersion( m_pHeader->Tag, &m_Version ) ) ) + { + DPF(0, "Effect version is unrecognized. This runtime supports fx_5_0 to %s.", g_EffectVersions[NUM_EFFECT10_VERSIONS-1].m_pName ); + VH( hr ); + } + + if( m_pHeader->RequiresPool() || m_pHeader->Pool.cObjectVariables > 0 || m_pHeader->Pool.cNumericVariables > 0 ) + { + DPF(0, "Effect11 does not support EffectPools." ); + VH( E_FAIL ); + } + + // Get shader block count + VBD( m_pHeader->cInlineShaders <= m_pHeader->cTotalShaders, "Invalid Effect header: cInlineShaders > cTotalShaders." ); + + // Make sure the counts for the Effect don't overflow + chkVariables = m_pHeader->Effect.cObjectVariables; + chkVariables += m_pHeader->Effect.cNumericVariables; + chkVariables += m_pHeader->cInterfaceVariables; + chkVariables *= sizeof(SGlobalVariable); + VH( chkVariables.GetValue(&varSize) ); + + // Make sure the counts for the SMemberDataPointers don't overflow + chkVariables = m_pHeader->cClassInstanceElements; + chkVariables += m_pHeader->cBlendStateBlocks; + chkVariables += m_pHeader->cRasterizerStateBlocks; + chkVariables += m_pHeader->cDepthStencilBlocks; + chkVariables += m_pHeader->cSamplers; + chkVariables += m_pHeader->Effect.cCBs; // Buffer (for CBuffers and TBuffers) + chkVariables += m_pHeader->Effect.cCBs; // SRV (for TBuffers) + VHD( chkVariables.GetValue(&cMemberDataBlocks), "Overflow: too many Effect variables." ); + + // Allocate effect resources + VN( m_pEffect->m_pCBs = PRIVATENEW SConstantBuffer[m_pHeader->Effect.cCBs] ); + VN( m_pEffect->m_pDepthStencilBlocks = PRIVATENEW SDepthStencilBlock[m_pHeader->cDepthStencilBlocks] ); + VN( m_pEffect->m_pRasterizerBlocks = PRIVATENEW SRasterizerBlock[m_pHeader->cRasterizerStateBlocks] ); + VN( m_pEffect->m_pBlendBlocks = PRIVATENEW SBlendBlock[m_pHeader->cBlendStateBlocks] ); + VN( m_pEffect->m_pSamplerBlocks = PRIVATENEW SSamplerBlock[m_pHeader->cSamplers] ); + + // we allocate raw bytes for variables because they are polymorphic types that need to be placement new'ed + VN( m_pEffect->m_pVariables = (SGlobalVariable *)PRIVATENEW BYTE[varSize] ); + VN( m_pEffect->m_pAnonymousShaders = PRIVATENEW SAnonymousShader[m_pHeader->cInlineShaders] ); + + VN( m_pEffect->m_pGroups = PRIVATENEW SGroup[m_pHeader->cGroups] ); + VN( m_pEffect->m_pShaderBlocks = PRIVATENEW SShaderBlock[m_pHeader->cTotalShaders] ); + VN( m_pEffect->m_pStrings = PRIVATENEW SString[m_pHeader->cStrings] ); + VN( m_pEffect->m_pShaderResources = PRIVATENEW SShaderResource[m_pHeader->cShaderResources] ); + VN( m_pEffect->m_pUnorderedAccessViews = PRIVATENEW SUnorderedAccessView[m_pHeader->cUnorderedAccessViews] ); + VN( m_pEffect->m_pInterfaces = PRIVATENEW SInterface[m_pHeader->cInterfaceVariableElements] ); + VN( m_pEffect->m_pMemberDataBlocks = PRIVATENEW SMemberDataPointer[cMemberDataBlocks] ); + VN( m_pEffect->m_pRenderTargetViews = PRIVATENEW SRenderTargetView[m_pHeader->cRenderTargetViews] ); + VN( m_pEffect->m_pDepthStencilViews = PRIVATENEW SDepthStencilView[m_pHeader->cDepthStencilViews] ); + + UINT oStructured = m_pHeader->cbUnstructured + sizeof(SBinaryHeader5); + VHD( m_msStructured.Seek(oStructured), "Invalid pEffectBuffer: Missing structured data block." ); + VH( m_msUnstructured.SetData(m_pData + sizeof(SBinaryHeader5), oStructured - sizeof(SBinaryHeader5)) ); + + VH( LoadCBs() ); + VH( LoadObjectVariables() ); + VH( LoadInterfaceVariables() ); + VH( LoadGroups() ); + + // Build shader dependencies + for (i=0; i<m_pEffect->m_ShaderBlockCount; i++) + { + VH( BuildShaderBlock(&m_pEffect->m_pShaderBlocks[i]) ); + } + + for( UINT iGroup=0; iGroup<m_pHeader->cGroups; iGroup++ ) + { + SGroup *pGroup = &m_pEffect->m_pGroups[iGroup]; + pGroup->HasDependencies = FALSE; + + for( UINT iTechnique=0; iTechnique < pGroup->TechniqueCount; iTechnique++ ) + { + STechnique* pTech = &pGroup->pTechniques[iTechnique]; + pTech->HasDependencies = FALSE; + + for( UINT iPass=0; iPass < pTech->PassCount; iPass++ ) + { + SPassBlock *pPass = &pTech->pPasses[iPass]; + + pTech->HasDependencies |= pPass->CheckDependencies(); + } + pGroup->HasDependencies |= pTech->HasDependencies; + } + } + + VH( InitializeReflectionDataAndMoveStrings() ); + VH( ReallocateReflectionData() ); + VH( ReallocateEffectData() ); + + VB( m_pReflection->m_Heap.GetSize() == m_ReflectionMemory ); + + // Verify that all of the various block/variable types were loaded + VBD( m_pEffect->m_VariableCount == (m_pHeader->Effect.cObjectVariables + m_pHeader->Effect.cNumericVariables + m_pHeader->cInterfaceVariables), "Internal loading error: mismatched variable count." ); + VBD( m_pEffect->m_ShaderBlockCount == m_pHeader->cTotalShaders, "Internal loading error: mismatched shader block count." ); + VBD( m_pEffect->m_AnonymousShaderCount == m_pHeader->cInlineShaders, "Internal loading error: mismatched anonymous variable count." ); + VBD( m_pEffect->m_ShaderResourceCount == m_pHeader->cShaderResources, "Internal loading error: mismatched SRV count." ); + VBD( m_pEffect->m_InterfaceCount == m_pHeader->cInterfaceVariableElements + m_BackgroundInterfaces.GetSize(), "Internal loading error: mismatched interface count." ); + VBD( m_pEffect->m_UnorderedAccessViewCount == m_pHeader->cUnorderedAccessViews, "Internal loading error: mismatched UAV count." ); + VBD( m_pEffect->m_MemberDataCount == cMemberDataBlocks, "Internal loading error: mismatched member data block count." ); + VBD( m_pEffect->m_RenderTargetViewCount == m_pHeader->cRenderTargetViews, "Internal loading error: mismatched RTV count." ); + VBD( m_pEffect->m_DepthStencilViewCount == m_pHeader->cDepthStencilViews, "Internal loading error: mismatched DSV count." ); + VBD( m_pEffect->m_DepthStencilBlockCount == m_pHeader->cDepthStencilBlocks, "Internal loading error: mismatched depth-stencil state count." ); + VBD( m_pEffect->m_BlendBlockCount == m_pHeader->cBlendStateBlocks, "Internal loading error: mismatched blend state count." ); + VBD( m_pEffect->m_RasterizerBlockCount == m_pHeader->cRasterizerStateBlocks, "Internal loading error: mismatched rasterizer state count." ); + VBD( m_pEffect->m_SamplerBlockCount == m_pHeader->cSamplers, "Internal loading error: mismatched sampler count." ); + VBD( m_pEffect->m_StringCount == m_pHeader->cStrings, "Internal loading error: mismatched string count." ); + + // Uncomment if you really need this information + // DPF(0, "Effect heap size: %d, reflection heap size: %d, allocations avoided: %d", m_EffectMemory, m_ReflectionMemory, m_BulkHeap.m_cAllocations); + +lExit: + return hr; +} + +// position in buffer is lost on error +HRESULT CEffectLoader::LoadStringAndAddToPool(__out_ecount_full(1) char **ppString, UINT dwOffset) +{ + HRESULT hr = S_OK; + char *pName; + UINT hash; + SIZE_T oldPos; + CEffect::CStringHashTable::CIterator iter; + UINT len; + + if (dwOffset == 0) + { + *ppString = NULL; + goto lExit; + } + + oldPos = m_msUnstructured.GetPosition(); + + VHD( m_msUnstructured.ReadAtOffset(dwOffset, (LPCSTR *) &pName), "Invalid pEffectBuffer: cannot read string." ); + len = (UINT)strlen(pName); + hash = ComputeHash((BYTE *)pName, len); + if (FAILED(m_pEffect->m_pStringPool->FindValueWithHash(pName, hash, &iter))) + { + D3DXASSERT( m_pEffect->m_pPooledHeap != NULL ); + VN( (*ppString) = new(*m_pEffect->m_pPooledHeap) char[len + 1] ); + memcpy(*ppString, pName, len + 1); + VHD( m_pEffect->m_pStringPool->AddValueWithHash(*ppString, hash), "Internal loading error: failed to add string to pool." ); + } + else + { + *ppString = const_cast<LPSTR>(iter.GetData()); + } + + m_msUnstructured.Seek(oldPos); + +lExit: + return hr; +} + +HRESULT CEffectLoader::LoadTypeAndAddToPool(SType **ppType, UINT dwOffset) +{ + HRESULT hr = S_OK; + SBinaryType *psType; + SBinaryNumericType *pNumericType; + EObjectType *pObjectType; + UINT cMembers, iMember, cInterfaces; + UINT oBaseClassType; + SType temporaryType; + CEffect::CTypeHashTable::CIterator iter; + BYTE *pHashBuffer; + UINT hash; + SVariable *pTempMembers = NULL; + + m_HashBuffer.Empty(); + + VHD( m_msUnstructured.ReadAtOffset(dwOffset, sizeof(SBinaryType), (void**) &psType), "Invalid pEffectBuffer: cannot read type." ); + VHD( LoadStringAndAddToPool(&temporaryType.pTypeName, psType->oTypeName), "Invalid pEffectBuffer: cannot read type name." ); + temporaryType.VarType = psType->VarType; + temporaryType.Elements = psType->Elements; + temporaryType.TotalSize = psType->TotalSize; + temporaryType.Stride = psType->Stride; + temporaryType.PackedSize = psType->PackedSize; + + // sanity check elements, size, stride, etc. + UINT cElements = max(1, temporaryType.Elements); + VBD( cElements * temporaryType.Stride == AlignToPowerOf2(temporaryType.TotalSize, SType::c_RegisterSize), "Invalid pEffectBuffer: invalid type size." ); + VBD( temporaryType.Stride % SType::c_RegisterSize == 0, "Invalid pEffectBuffer: invalid type stride." ); + VBD( temporaryType.PackedSize <= temporaryType.TotalSize && temporaryType.PackedSize % cElements == 0, "Invalid pEffectBuffer: invalid type packed size." ); + + switch(temporaryType.VarType) + { + case EVT_Object: + VHD( m_msUnstructured.Read((void**) &pObjectType, sizeof(UINT)), "Invalid pEffectBuffer: cannot read object type." ); + temporaryType.ObjectType = *pObjectType; + VBD( temporaryType.VarType > EOT_Invalid && temporaryType.VarType < EOT_Count, "Invalid pEffectBuffer: invalid object type." ); + + VN( pHashBuffer = m_HashBuffer.AddRange(sizeof(temporaryType.VarType) + sizeof(temporaryType.Elements) + + sizeof(temporaryType.pTypeName) + sizeof(temporaryType.ObjectType)) ); + memcpy(pHashBuffer, &temporaryType.VarType, sizeof(temporaryType.VarType)); + pHashBuffer += sizeof(temporaryType.VarType); + memcpy(pHashBuffer, &temporaryType.Elements, sizeof(temporaryType.Elements)); + pHashBuffer += sizeof(temporaryType.Elements); + memcpy(pHashBuffer, &temporaryType.pTypeName, sizeof(temporaryType.pTypeName)); + pHashBuffer += sizeof(temporaryType.pTypeName); + memcpy(pHashBuffer, &temporaryType.ObjectType, sizeof(temporaryType.ObjectType)); + break; + + case EVT_Interface: + temporaryType.InterfaceType = NULL; + + VN( pHashBuffer = m_HashBuffer.AddRange(sizeof(temporaryType.VarType) + sizeof(temporaryType.Elements) + + sizeof(temporaryType.pTypeName) + sizeof(temporaryType.ObjectType)) ); + memcpy(pHashBuffer, &temporaryType.VarType, sizeof(temporaryType.VarType)); + pHashBuffer += sizeof(temporaryType.VarType); + memcpy(pHashBuffer, &temporaryType.Elements, sizeof(temporaryType.Elements)); + pHashBuffer += sizeof(temporaryType.Elements); + memcpy(pHashBuffer, &temporaryType.pTypeName, sizeof(temporaryType.pTypeName)); + pHashBuffer += sizeof(temporaryType.pTypeName); + memcpy(pHashBuffer, &temporaryType.ObjectType, sizeof(temporaryType.ObjectType)); + break; + + case EVT_Numeric: + VHD( m_msUnstructured.Read((void**) &pNumericType, sizeof(SBinaryNumericType)), "Invalid pEffectBuffer: cannot read numeric type." ); + temporaryType.NumericType = *pNumericType; + VBD( temporaryType.NumericType.Rows >= 1 && temporaryType.NumericType.Rows <= 4 && + temporaryType.NumericType.Columns >= 1 && temporaryType.NumericType.Columns <= 4 && + temporaryType.NumericType.NumericLayout != ENL_Invalid && temporaryType.NumericType.NumericLayout < ENL_Count && + temporaryType.NumericType.ScalarType > EST_Invalid && temporaryType.NumericType.ScalarType < EST_Count, + "Invalid pEffectBuffer: invalid numeric type."); + + if (temporaryType.NumericType.NumericLayout != ENL_Matrix) + { + VBD( temporaryType.NumericType.IsColumnMajor == FALSE, "Invalid pEffectBuffer: only matricies can be column major." ); + } + + VN( pHashBuffer = m_HashBuffer.AddRange(sizeof(temporaryType.VarType) + sizeof(temporaryType.Elements) + + sizeof(temporaryType.pTypeName) + sizeof(temporaryType.NumericType)) ); + memcpy(pHashBuffer, &temporaryType.VarType, sizeof(temporaryType.VarType)); + pHashBuffer += sizeof(temporaryType.VarType); + memcpy(pHashBuffer, &temporaryType.Elements, sizeof(temporaryType.Elements)); + pHashBuffer += sizeof(temporaryType.Elements); + memcpy(pHashBuffer, &temporaryType.pTypeName, sizeof(temporaryType.pTypeName)); + pHashBuffer += sizeof(temporaryType.pTypeName); + memcpy(pHashBuffer, &temporaryType.NumericType, sizeof(temporaryType.NumericType)); + break; + + case EVT_Struct: + VHD( m_msUnstructured.Read(&cMembers), "Invalid pEffectBuffer: cannot read struct." ); + + temporaryType.StructType.Members = cMembers; + + VN( pTempMembers = NEW SVariable[cMembers] ); + temporaryType.StructType.pMembers = pTempMembers; + + // read up all of the member descriptors at once + SBinaryType::SBinaryMember *psMember; + VHD( m_msUnstructured.Read((void**) &psMember, cMembers * sizeof(*psMember)), "Invalid pEffectBuffer: cannot read struct members." ); + + { + // Determine if this type implements an interface + VHD( m_msUnstructured.Read(&oBaseClassType), "Invalid pEffectBuffer: cannot read base class type." ); + VHD( m_msUnstructured.Read(&cInterfaces), "Invalid pEffectBuffer: cannot read interfaces." ); + if( cInterfaces > 0 ) + { + temporaryType.StructType.ImplementsInterface = 1; + temporaryType.StructType.HasSuperClass = ( oBaseClassType > 0 ) ? 1 : 0; + } + else if( oBaseClassType > 0 ) + { + // Get parent type and copy its ImplementsInterface + SType* pBaseClassType; + VH( LoadTypeAndAddToPool(&pBaseClassType, oBaseClassType) ); + temporaryType.StructType.ImplementsInterface = pBaseClassType->StructType.ImplementsInterface; + temporaryType.StructType.HasSuperClass = 1; + } + // Read (and ignore) the interface types + UINT *poInterface; + VHD( m_msUnstructured.Read((void**) &poInterface, cInterfaces * sizeof(poInterface)), "Invalid pEffectBuffer: cannot read interface types." ); + } + + UINT totalSize; + totalSize = 0; + for (iMember=0; iMember<cMembers; iMember++) + { + SVariable *pMember; + + pMember = temporaryType.StructType.pMembers + iMember; + + VBD( psMember[iMember].Offset == totalSize || + psMember[iMember].Offset == AlignToPowerOf2(totalSize, SType::c_RegisterSize), + "Internal loading error: invalid member offset." ); + + pMember->Data.Offset = psMember[iMember].Offset; + + VH( LoadTypeAndAddToPool(&pMember->pType, psMember[iMember].oType) ); + VH( LoadStringAndAddToPool(&pMember->pName, psMember[iMember].oName) ); + VH( LoadStringAndAddToPool(&pMember->pSemantic, psMember[iMember].oSemantic) ); + + totalSize = psMember[iMember].Offset + pMember->pType->TotalSize; + } + VBD( AlignToPowerOf2(totalSize, SType::c_RegisterSize) == temporaryType.Stride, "Internal loading error: invlid type size." ); + + VN( pHashBuffer = m_HashBuffer.AddRange(sizeof(temporaryType.VarType) + sizeof(temporaryType.Elements) + + sizeof(temporaryType.pTypeName) + sizeof(temporaryType.StructType.Members) + cMembers * sizeof(SVariable)) ); + + memcpy(pHashBuffer, &temporaryType.VarType, sizeof(temporaryType.VarType)); + pHashBuffer += sizeof(temporaryType.VarType); + memcpy(pHashBuffer, &temporaryType.Elements, sizeof(temporaryType.Elements)); + pHashBuffer += sizeof(temporaryType.Elements); + memcpy(pHashBuffer, &temporaryType.pTypeName, sizeof(temporaryType.pTypeName)); + pHashBuffer += sizeof(temporaryType.pTypeName); + memcpy(pHashBuffer, &temporaryType.StructType.Members, sizeof(temporaryType.StructType.Members)); + pHashBuffer += sizeof(temporaryType.StructType.Members); + memcpy(pHashBuffer, temporaryType.StructType.pMembers, cMembers * sizeof(SVariable)); + break; + + default: + D3DXASSERT(0); + VHD( E_FAIL, "Internal loading error: invalid variable type." ); + } + + hash = ComputeHash(&m_HashBuffer[0], m_HashBuffer.GetSize()); + if (FAILED(m_pEffect->m_pTypePool->FindValueWithHash(&temporaryType, hash, &iter))) + { + D3DXASSERT( m_pEffect->m_pPooledHeap != NULL ); + + // allocate real member array, if necessary + if (temporaryType.VarType == EVT_Struct) + { + VN( temporaryType.StructType.pMembers = new(*m_pEffect->m_pPooledHeap) SVariable[temporaryType.StructType.Members] ); + memcpy(temporaryType.StructType.pMembers, pTempMembers, temporaryType.StructType.Members * sizeof(SVariable)); + } + + // allocate real type + VN( (*ppType) = new(*m_pEffect->m_pPooledHeap) SType ); + memcpy(*ppType, &temporaryType, sizeof(temporaryType)); + ZeroMemory(&temporaryType, sizeof(temporaryType)); + VH( m_pEffect->m_pTypePool->AddValueWithHash(*ppType, hash) ); + } + else + { + *ppType = iter.GetData(); + } + +lExit: + SAFE_DELETE_ARRAY(pTempMembers); + return hr; +} + +// Numeric data in annotations are tightly packed (unlike in CBs which follow D3D11 packing rules). This unpacks them. +UINT CEffectLoader::UnpackData(BYTE *pDestData, BYTE *pSrcData, UINT PackedDataSize, SType *pType, UINT *pBytesRead) +{ + UINT bytesRead = 0; + UINT i, j, k; + UINT registers, entries; + HRESULT hr = S_OK; + UINT elementsToCopy = max(pType->Elements, 1); + + switch (pType->VarType) + { + case EVT_Struct: + for (i = 0; i < elementsToCopy; ++ i) + { + for (j = 0; j < pType->StructType.Members; ++ j) + { + UINT br; + D3DXASSERT((UINT_PTR)pType->StructType.pMembers[j].pType == (UINT)(UINT_PTR)pType->StructType.pMembers[j].pType); + D3DXASSERT(PackedDataSize > bytesRead); + + VH( UnpackData(pDestData + pType->StructType.pMembers[j].Data.Offset, + pSrcData + bytesRead, PackedDataSize - bytesRead, + pType->StructType.pMembers[j].pType, &br) ); + + bytesRead += br; + } + pDestData += pType->Stride; + } + break; + + case EVT_Numeric: + if (pType->NumericType.IsPackedArray) + { + // No support for packed arrays + D3DXASSERT(0); + VHD(E_FAIL, "Internal loading error: packed arrays are not supported." ); + } + else + { + UINT bytesToCopy; + + if (pType->NumericType.IsColumnMajor) + { + registers = pType->NumericType.Columns; + entries = pType->NumericType.Rows; + bytesToCopy = entries * registers * SType::c_ScalarSize; + + for (i = 0; i < elementsToCopy; ++ i) + { + for (j = 0; j < registers; ++ j) + { + for (k = 0; k < entries; ++ k) + { + // type cast to an arbitrary scalar + ((UINT*)pDestData)[k] = ((UINT*)pSrcData)[k * registers + j]; + } + pDestData += SType::c_RegisterSize; // advance to next register + } + pSrcData += bytesToCopy; + bytesRead += bytesToCopy; + } + } + else + { + registers = pType->NumericType.Rows; + entries = pType->NumericType.Columns; + bytesToCopy = entries * SType::c_ScalarSize; + + for (i = 0; i < elementsToCopy; ++ i) + { + for (j = 0; j < registers; ++ j) + { + memcpy(pDestData, pSrcData, bytesToCopy); + + pDestData += SType::c_RegisterSize; // advance to next register + pSrcData += bytesToCopy; + bytesRead += bytesToCopy; + } + } + } + } + break; + + default: + // shouldn't be called on non-struct/numeric types + D3DXASSERT(0); + VHD(E_FAIL, "Internal loading error: UnpackData should not be called on non-struct, non-numeric types." ); + } + +lExit: + *pBytesRead = bytesRead; + return hr; +} + +// Read info from the compiled blob and initialize a numeric variable +HRESULT CEffectLoader::LoadNumericVariable(SConstantBuffer *pParentCB) +{ + HRESULT hr = S_OK; + SBinaryNumericVariable *psVar; + SGlobalVariable *pVar; + SType *pType; + void *pDefaultValue; + + // Read variable info + VHD( m_msStructured.Read((void**) &psVar, sizeof(*psVar)), "Invalid pEffectBuffer: cannot read numeric variable." ); + VBD( m_pEffect->m_VariableCount < (m_pHeader->Effect.cObjectVariables + m_pHeader->Effect.cNumericVariables + m_pHeader->cInterfaceVariables), + "Internal loading error: invalid variable counts."); + pVar = &m_pEffect->m_pVariables[m_pEffect->m_VariableCount]; + + // Get type + VH( LoadTypeAndAddToPool(&pType, psVar->oType) ); + + // Make sure the right polymorphic type is created + VH( PlacementNewVariable(pVar, pType, FALSE) ); + + if (psVar->Flags & D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT) + { + pVar->ExplicitBindPoint = psVar->Offset; + } + else + { + pVar->ExplicitBindPoint = -1; + } + + pVar->pEffect = m_pEffect; + pVar->pType = pType; + pVar->pCB = pParentCB; + pVar->Data.pGeneric = pParentCB->pBackingStore + psVar->Offset; + VBD( psVar->Offset + pVar->pType->TotalSize <= pVar->pCB->Size, "Invalid pEffectBuffer: invalid variable offset." ); + + if (pType->VarType == EVT_Struct && pType->StructType.ImplementsInterface && !pParentCB->IsTBuffer) + { + pVar->MemberDataOffsetPlus4 = m_pEffect->m_MemberDataCount * sizeof(SMemberDataPointer) + 4; + m_pEffect->m_MemberDataCount += max(pType->Elements,1); + } + + // Get name & semantic + VHD( GetStringAndAddToReflection(psVar->oName, &pVar->pName), "Invalid pEffectBuffer: cannot read variable name." ); + VHD( GetStringAndAddToReflection(psVar->oSemantic, &pVar->pSemantic), "Invalid pEffectBuffer: cannot read variable semantic." ); + + // Ensure the variable fits in the CBuffer and doesn't overflow + VBD( pType->TotalSize + psVar->Offset <= pParentCB->Size && + pType->TotalSize + psVar->Offset >= pType->TotalSize, "Invalid pEffectBuffer: variable does not fit in CB." ); + + ZeroMemory(pVar->Data.pGeneric, pType->TotalSize); + + // Get default value + if (0 != psVar->oDefaultValue) + { + UINT bytesUnpacked; + VHD( m_msUnstructured.ReadAtOffset(psVar->oDefaultValue, pType->PackedSize, &pDefaultValue), "Invalid pEffectBuffer: cannot read default value." ); + VH( UnpackData((BYTE*) pVar->Data.pGeneric, (BYTE*) pDefaultValue, pType->PackedSize, pType, &bytesUnpacked) ); + VBD( bytesUnpacked == pType->PackedSize, "Invalid pEffectBuffer: invalid type packed size."); + } + + // We need to use offsets until we fixup + pVar->Data.Offset = psVar->Offset; + + // Read annotations + VH( LoadAnnotations(&pVar->AnnotationCount, &pVar->pAnnotations) ); + + m_pEffect->m_VariableCount++; + +lExit: + return hr; +} + +// Read info from the compiled blob and initialize a constant buffer +HRESULT CEffectLoader::LoadCBs() +{ + HRESULT hr = S_OK; + UINT iCB, iVar; + + for (iCB=0; iCB<m_pHeader->Effect.cCBs; iCB++) + { + SBinaryConstantBuffer *psCB; + SConstantBuffer *pCB; + + VHD( m_msStructured.Read((void**) &psCB, sizeof(*psCB)), "Invalid pEffectBuffer: cannot read CB." ); + pCB = &m_pEffect->m_pCBs[iCB]; + + VHD( GetStringAndAddToReflection(psCB->oName, &pCB->pName), "Invalid pEffectBuffer: cannot read CB name." ); + + pCB->IsTBuffer = (psCB->Flags & SBinaryConstantBuffer::c_IsTBuffer) != 0 ? TRUE : FALSE; + pCB->IsSingle = (psCB->Flags & SBinaryConstantBuffer::c_IsSingle) != 0 ? TRUE : FALSE; + pCB->Size = psCB->Size; + pCB->ExplicitBindPoint = psCB->ExplicitBindPoint; + VBD( pCB->Size == AlignToPowerOf2(pCB->Size, SType::c_RegisterSize), "Invalid pEffectBuffer: CB size not a power of 2." ); + VN( pCB->pBackingStore = PRIVATENEW BYTE[pCB->Size] ); + + pCB->MemberDataOffsetPlus4 = m_pEffect->m_MemberDataCount * sizeof(SMemberDataPointer) + 4; + m_pEffect->m_MemberDataCount += 2; + + // point this CB to variables that it owns + pCB->VariableCount = psCB->cVariables; + if (pCB->VariableCount > 0) + { + pCB->pVariables = &m_pEffect->m_pVariables[m_pEffect->m_VariableCount]; + } + else + { + pCB->pVariables = NULL; + } + + // Read annotations + VH( LoadAnnotations(&pCB->AnnotationCount, &pCB->pAnnotations) ); + + for (iVar=0; iVar<psCB->cVariables; iVar++) + { + VH( LoadNumericVariable(pCB) ); + } + } + + m_pEffect->m_CBCount = m_pHeader->Effect.cCBs; + +lExit: + return hr; +} + +// Used by LoadAssignment to initialize members on load +HRESULT CEffectLoader::ExecuteConstantAssignment(SBinaryConstant *pConstant, void *pLHS, D3D10_SHADER_VARIABLE_TYPE lhsType) +{ + HRESULT hr = S_OK; + + switch(pConstant->Type) + { + case EST_UInt: + case EST_Int: + case EST_Bool: + switch(lhsType) + { + case D3D10_SVT_BOOL: + case D3D10_SVT_INT: + case D3D10_SVT_UINT: + *(UINT*) pLHS = pConstant->iValue; + break; + + case D3D10_SVT_UINT8: + *(BYTE*) pLHS = (BYTE) pConstant->iValue; + break; + + case D3D10_SVT_FLOAT: + *(float*) pLHS = (float) pConstant->iValue; + break; + + default: + VHD( E_FAIL, "Internal loading error: invalid left-hand assignment type." ); + } + break; + + case EST_Float: + switch(lhsType) + { + case D3D10_SVT_BOOL: + case D3D10_SVT_INT: + case D3D10_SVT_UINT: + *(UINT*) pLHS = (UINT) pConstant->fValue; + break; + + case D3D10_SVT_UINT8: + *(BYTE*) pLHS = (BYTE) pConstant->fValue; + break; + + case D3D10_SVT_FLOAT: + *(float*) pLHS = pConstant->fValue; + break; + + default: + VHD( E_FAIL, "Internal loading error: invalid left-hand assignment type." ); + } + break; + + default: + VHD( E_FAIL, "Internal loading error: invalid left-hand assignment type." ); + } + +lExit: + return hr; +} + + +// Read info from the compiled blob and initialize a set of assignments +HRESULT CEffectLoader::LoadAssignments( UINT Assignments, SAssignment **ppAssignments, BYTE *pBackingStore, UINT *pRTVAssignments, UINT *pFinalAssignments ) +{ + HRESULT hr = S_OK; + UINT i, j; + + SBinaryAssignment *psAssignments; + UINT finalAssignments = 0; // the number of assignments worth keeping + UINT renderTargetViewAssns = 0; // Number of render target view assns, used by passes since SetRTV is a vararg call + + *pFinalAssignments = 0; + if (pRTVAssignments) + *pRTVAssignments = 0; + + VHD( m_msStructured.Read((void**) &psAssignments, sizeof(*psAssignments) * Assignments), "Invalid pEffectBuffer: cannot read assignments." ); + + // allocate enough room to store all of the assignments (even though some may go unused) + VN( (*ppAssignments) = PRIVATENEW SAssignment[Assignments] ) + + // + // In this loop, we read assignments 1-by-1, keeping some and discarding others. + // We write to the "next" assignment which is given by &(*ppAssignments)[finalAssignments]; + // if an assignment is worth keeping, we increment finalAssignments. + // This means that if you want to keep an assignment, you must be careful to initialize + // all members of SAssignment because old values from preceding discarded assignments might remain. + // + for (i = 0; i < Assignments; ++ i) + { + SGlobalVariable *pVarArray, *pVarIndex, *pVar; + const char *pGlobalVarName; + SAssignment *pAssignment = &(*ppAssignments)[finalAssignments]; + BYTE *pLHS; + + VBD( psAssignments[i].iState < NUM_STATES, "Invalid pEffectBuffer: invalid assignment state." ); + VBD( psAssignments[i].Index < g_lvGeneral[psAssignments[i].iState].m_Indices, "Invalid pEffectBuffer: invalid assignment index." ); + + pAssignment->LhsType = g_lvGeneral[psAssignments[i].iState].m_LhsType; + + // Count RenderTargetView assignments + if (pAssignment->LhsType == ELHS_RenderTargetView) + renderTargetViewAssns++; + + switch (g_lvGeneral[psAssignments[i].iState].m_Type) + { + case D3D10_SVT_UINT8: + D3DXASSERT(g_lvGeneral[psAssignments[i].iState].m_Cols == 1); // BYTE arrays not supported + pAssignment->DataSize = sizeof(BYTE); + // Store an offset for destination instead of a pointer so that it's easy to relocate it later + + break; + + case D3D10_SVT_BOOL: + case D3D10_SVT_INT: + case D3D10_SVT_UINT: + case D3D10_SVT_FLOAT: + pAssignment->DataSize = SType::c_ScalarSize * g_lvGeneral[psAssignments[i].iState].m_Cols; + break; + + case D3D10_SVT_RASTERIZER: + pAssignment->DataSize = sizeof(SRasterizerBlock); + break; + + case D3D10_SVT_DEPTHSTENCIL: + pAssignment->DataSize = sizeof(SDepthStencilBlock); + break; + + case D3D10_SVT_BLEND: + pAssignment->DataSize = sizeof(SBlendBlock); + break; + + case D3D10_SVT_VERTEXSHADER: + case D3D10_SVT_GEOMETRYSHADER: + case D3D10_SVT_PIXELSHADER: + case D3D11_SVT_HULLSHADER: + case D3D11_SVT_DOMAINSHADER: + case D3D11_SVT_COMPUTESHADER: + pAssignment->DataSize = sizeof(SShaderBlock); + break; + + case D3D10_SVT_TEXTURE: + case D3D10_SVT_TEXTURE1D: + case D3D10_SVT_TEXTURE2D: + case D3D10_SVT_TEXTURE2DMS: + case D3D10_SVT_TEXTURE3D: + case D3D10_SVT_TEXTURECUBE: + case D3D10_SVT_TEXTURECUBEARRAY: + case D3D11_SVT_BYTEADDRESS_BUFFER: + case D3D11_SVT_STRUCTURED_BUFFER: + pAssignment->DataSize = sizeof(SShaderResource); + break; + + case D3D10_SVT_RENDERTARGETVIEW: + pAssignment->DataSize = sizeof(SRenderTargetView); + break; + + case D3D10_SVT_DEPTHSTENCILVIEW: + pAssignment->DataSize = sizeof(SDepthStencilView); + break; + + case D3D11_SVT_RWTEXTURE1D: + case D3D11_SVT_RWTEXTURE1DARRAY: + case D3D11_SVT_RWTEXTURE2D: + case D3D11_SVT_RWTEXTURE2DARRAY: + case D3D11_SVT_RWTEXTURE3D: + case D3D11_SVT_RWBUFFER: + case D3D11_SVT_RWBYTEADDRESS_BUFFER: + case D3D11_SVT_RWSTRUCTURED_BUFFER: + case D3D11_SVT_APPEND_STRUCTURED_BUFFER: + case D3D11_SVT_CONSUME_STRUCTURED_BUFFER: + pAssignment->DataSize = sizeof(SUnorderedAccessView); + break; + + case D3D11_SVT_INTERFACE_POINTER: + pAssignment->DataSize = sizeof(SInterface); + break; + + default: + D3DXASSERT(0); + VHD( E_FAIL, "Internal loading error: invalid assignment type."); + } + + UINT lhsStride; + if( g_lvGeneral[psAssignments[i].iState].m_Stride > 0 ) + lhsStride = g_lvGeneral[psAssignments[i].iState].m_Stride; + else + lhsStride = pAssignment->DataSize; + + // Store only the destination offset so that the backing store pointers can be easily fixed up later + pAssignment->Destination.Offset = g_lvGeneral[psAssignments[i].iState].m_Offset + lhsStride * psAssignments[i].Index; + + // As a result, you should use pLHS in this function instead of the destination pointer + pLHS = pBackingStore + pAssignment->Destination.Offset; + + switch (psAssignments[i].AssignmentType) + { + case ECAT_Constant: // e.g. LHS = 1; or LHS = NULL; + UINT *pNumConstants; + SBinaryConstant *pConstants; + + VHD( m_msUnstructured.ReadAtOffset(psAssignments[i].oInitializer, sizeof(UINT), (void**) &pNumConstants), "Invalid pEffectBuffer: cannot read NumConstants." ); + VHD( m_msUnstructured.Read((void **)&pConstants, sizeof(SBinaryConstant) * (*pNumConstants)), "Invalid pEffectBuffer: cannot read constants." ); + + if(pAssignment->IsObjectAssignment()) + { + // make sure this is a NULL assignment + VBD( *pNumConstants == 1 && (pConstants[0].Type == EST_Int || pConstants[0].Type == EST_UInt) && pConstants[0].iValue == 0, + "Invalid pEffectBuffer: non-NULL constant assignment to object."); + + switch (pAssignment->LhsType) + { + case ELHS_DepthStencilBlock: + *((void **)pLHS) = &g_NullDepthStencil; + break; + case ELHS_BlendBlock: + *((void **)pLHS) = &g_NullBlend; + break; + case ELHS_RasterizerBlock: + *((void **)pLHS) = &g_NullRasterizer; + break; + case ELHS_VertexShaderBlock: + *((void **)pLHS) = &g_NullVS; + break; + case ELHS_PixelShaderBlock: + *((void **)pLHS) = &g_NullPS; + break; + case ELHS_GeometryShaderBlock: + *((void **)pLHS) = &g_NullGS; + break; + case ELHS_HullShaderBlock: + *((void **)pLHS) = &g_NullHS; + break; + case ELHS_DomainShaderBlock: + *((void **)pLHS) = &g_NullDS; + break; + case ELHS_ComputeShaderBlock: + *((void **)pLHS) = &g_NullCS; + break; + case ELHS_Texture: + *((void **)pLHS) = &g_NullTexture; + break; + case ELHS_DepthStencilView: + *((void **)pLHS) = &g_NullDepthStencilView; + break; + case ELHS_RenderTargetView: + *((void **)pLHS) = &g_NullRenderTargetView; + break; + default: + D3DXASSERT(0); + } + } + else + { + VBD( *pNumConstants == g_lvGeneral[psAssignments[i].iState].m_Cols, "Internal loading error: mismatch constant count." ); + for (j = 0; j < *pNumConstants; ++ j) + { + VH( ExecuteConstantAssignment(pConstants + j, pLHS, g_lvGeneral[psAssignments[i].iState].m_Type) ); + pLHS += SType::c_ScalarSize; // arrays of constants will always be regular scalar sized, never byte-sized + } + } + + // Can get rid of this assignment + break; + + case ECAT_Variable: // e.g. LHS = myVar; + VHD( m_msUnstructured.ReadAtOffset(psAssignments[i].oInitializer, &pGlobalVarName), "Invalid pEffectBuffer: cannot read variable name." ); + + VBD( pVar = m_pEffect->FindVariableByName(pGlobalVarName), "Loading error: cannot find variable name." ); + + if (pAssignment->IsObjectAssignment()) + { + VBD( pVar->pType->VarType == EVT_Object && + GetSimpleParameterTypeFromObjectType(pVar->pType->ObjectType) == g_lvGeneral[psAssignments[i].iState].m_Type, + "Loading error: invalid variable type or object type." ); + + // Write directly into the state block's backing store + *((void **)pLHS) = pVar->Data.pGeneric; + + // Now we can get rid of this assignment + } + else + { + VBD( pVar->pType->BelongsInConstantBuffer(), "Invalid pEffectBuffer: assignment type mismatch." ); + + pAssignment->DependencyCount = 1; + VN( pAssignment->pDependencies = PRIVATENEW SAssignment::SDependency[pAssignment->DependencyCount] ); + pAssignment->pDependencies->pVariable = pVar; + + // Store an offset for numeric values instead of a pointer so that it's easy to relocate it later + pAssignment->Source.Offset = pVar->Data.Offset; + pAssignment->AssignmentType = ERAT_NumericVariable; + + // Can't get rid of this assignment + ++ finalAssignments; + } + break; + + case ECAT_ConstIndex: // e.g. LHS = myGS[1] + SBinaryAssignment::SConstantIndex *psConstIndex; + + VHD( m_msUnstructured.ReadAtOffset(psAssignments[i].oInitializer, sizeof(*psConstIndex), (void**) &psConstIndex), + "Invalid pEffectBuffer: cannot read assignment initializer." ); + VHD( m_msUnstructured.ReadAtOffset(psConstIndex->oArrayName, &pGlobalVarName), "Invalid pEffectBuffer: cannot read array name." ); + + VBD( pVarArray = m_pEffect->FindVariableByName(pGlobalVarName), "Loading error: cannot find array name." ); + + if (pAssignment->IsObjectAssignment()) + { + VBD( psConstIndex->Index < pVarArray->pType->Elements, "Invalid pEffectBuffer: out of bounds array index." ); + VBD( pVarArray->pType->VarType == EVT_Object && + GetSimpleParameterTypeFromObjectType(pVarArray->pType->ObjectType) == g_lvGeneral[psAssignments[i].iState].m_Type, + "Loading error: invalid variable type or object type." ); + + // Write directly into the state block's backing store + *((void **)pLHS) = GetBlockByIndex(pVarArray->pType->VarType, pVarArray->pType->ObjectType, pVarArray->Data.pGeneric, psConstIndex->Index); + VBD( NULL != *((void **)pLHS), "Internal loading error: invalid block." ); + + // Now we can get rid of this assignment + } + else + { + VBD( pVarArray->pType->BelongsInConstantBuffer(), "Invalid pEffectBuffer: assignment type mismatch." ); + + pAssignment->DependencyCount = 1; + VN( pAssignment->pDependencies = PRIVATENEW SAssignment::SDependency[pAssignment->DependencyCount] ); + pAssignment->pDependencies->pVariable = pVarArray; + + CCheckedDword chkDataLen = psConstIndex->Index; + UINT dataLen; + chkDataLen *= SType::c_ScalarSize; + chkDataLen += pAssignment->DataSize; + VHD( chkDataLen.GetValue(&dataLen), "Overflow: assignment size." ); + VBD( dataLen <= pVarArray->pType->TotalSize, "Internal loading error: assignment size mismatch" ); + + pAssignment->Source.Offset = pVarArray->Data.Offset + psConstIndex->Index * SType::c_ScalarSize; + + // _NumericConstIndex is not used here because _NumericVariable + // does the same stuff in a more general fashion with no perf hit. + pAssignment->AssignmentType = ERAT_NumericVariable; + + // Can't get rid of this assignment + ++ finalAssignments; + } + break; + + case ECAT_VariableIndex: // e.g. LHS = myVar[numLights]; + SBinaryAssignment::SVariableIndex *psVarIndex; + + VHD( m_msUnstructured.ReadAtOffset(psAssignments[i].oInitializer, sizeof(*psVarIndex), (void**) &psVarIndex), + "Invalid pEffectBuffer: cannot read assignment initializer." ); + VHD( m_msUnstructured.ReadAtOffset(psVarIndex->oArrayName, &pGlobalVarName), "Invalid pEffectBuffer: cannot read variable name." ); + VBD( pVarArray = m_pEffect->FindVariableByName(pGlobalVarName), "Loading error: cannot find variable name." ); + + VHD( m_msUnstructured.ReadAtOffset(psVarIndex->oIndexVarName, &pGlobalVarName), "Invalid pEffectBuffer: cannot read index variable name." ); + VBD( pVarIndex = m_pEffect->FindVariableByName(pGlobalVarName), "Loading error: cannot find index variable name." ); + + // Only support integer indices + VBD( pVarIndex->pType->VarType == EVT_Numeric && (pVarIndex->pType->NumericType.ScalarType == EST_Int || pVarIndex->pType->NumericType.ScalarType == EST_UInt), + "Invalid pEffectBuffer: invalid index variable type."); + VBD( pVarArray->pType->Elements > 0, "Invalid pEffectBuffer: array variable is not an array." ); + + pVarIndex->pCB->IsUsedByExpression = TRUE; + + if (pAssignment->IsObjectAssignment()) + { + VBD( pVarArray->pType->VarType == EVT_Object && + GetSimpleParameterTypeFromObjectType(pVarArray->pType->ObjectType) == g_lvGeneral[psAssignments[i].iState].m_Type, + "Loading error: invalid variable type or object type." ); + + // MaxElements is only 16-bits wide + VBD( pVarArray->pType->Elements <= 0xFFFF, "Internal error: array size is too large." ); + pAssignment->MaxElements = pVarArray->pType->Elements; + + pAssignment->DependencyCount = 1; + VN( pAssignment->pDependencies = PRIVATENEW SAssignment::SDependency[pAssignment->DependencyCount] ); + pAssignment->pDependencies[0].pVariable = pVarIndex; + + // Point this assignment to the start of the variable's object array. + // When this assignment is dirty, we write the value of this pointer plus + // the index given by its one dependency directly into the destination + pAssignment->Source = pVarArray->Data; + pAssignment->AssignmentType = ERAT_ObjectVariableIndex; + } + else + { + VBD( pVarArray->pType->BelongsInConstantBuffer(), "Invalid pEffectBuffer: assignment type mismatch." ); + + pAssignment->DependencyCount = 2; + VN( pAssignment->pDependencies = PRIVATENEW SAssignment::SDependency[pAssignment->DependencyCount] ); + pAssignment->pDependencies[0].pVariable = pVarIndex; + pAssignment->pDependencies[1].pVariable = pVarArray; + + // When pVarIndex is updated, we update the source pointer. + // When pVarArray is updated, we copy data from the source to the destination. + pAssignment->Source.pGeneric = NULL; + pAssignment->AssignmentType = ERAT_NumericVariableIndex; + } + + // Can't get rid of this assignment + ++ finalAssignments; + + break; + + case ECAT_ExpressionIndex:// e.g. LHS = myVar[a + b * c]; + case ECAT_Expression: // e.g. LHS = a + b * c; + // we do not support FXLVM + VHD( E_NOTIMPL, "FXLVM Expressions (complex assignments like myVar[i*2]) are not supported in Effects11." ); + break; + + case ECAT_InlineShader: + case ECAT_InlineShader5: + UINT cbShaderBin; + BYTE *pShaderBin; + SShaderBlock *pShaderBlock; + SAnonymousShader *pAnonShader; + union + { + SBinaryAssignment::SInlineShader *psInlineShader; + SBinaryShaderData5 *psInlineShader5; + }; + + // Inline shader assignments must be object types + D3DXASSERT(pAssignment->IsObjectAssignment()); + + C_ASSERT( offsetof(SBinaryAssignment::SInlineShader,oShader) == offsetof(SBinaryShaderData5,oShader) ); + C_ASSERT( offsetof(SBinaryAssignment::SInlineShader,oSODecl) == offsetof(SBinaryShaderData5,oSODecls) ); + if( psAssignments[i].AssignmentType == ECAT_InlineShader ) + { + VHD( m_msUnstructured.ReadAtOffset(psAssignments[i].oInitializer, sizeof(*psInlineShader), (void**) &psInlineShader), + "Invalid pEffectBuffer: cannot read inline shader." ); + } + else + { + VHD( m_msUnstructured.ReadAtOffset(psAssignments[i].oInitializer, sizeof(*psInlineShader5), (void**) &psInlineShader5), + "Invalid pEffectBuffer: cannot read inline shader." ); + } + + VBD( m_pEffect->m_ShaderBlockCount < m_pHeader->cTotalShaders, "Internal loading error: shader count is out incorrect." ); + VBD( m_pEffect->m_AnonymousShaderCount < m_pHeader->cInlineShaders, "Internal loading error: anonymous shader count is out incorrect." ); + + pShaderBlock = &m_pEffect->m_pShaderBlocks[m_pEffect->m_ShaderBlockCount]; + pAnonShader = &m_pEffect->m_pAnonymousShaders[m_pEffect->m_AnonymousShaderCount]; + pAnonShader->pShaderBlock = pShaderBlock; + + ++ m_pEffect->m_ShaderBlockCount; + ++ m_pEffect->m_AnonymousShaderCount; + + // Write directly into the state block's backing store + *((void **)pLHS) = pShaderBlock; + + VHD( GetUnstructuredDataBlock(psInlineShader->oShader, &cbShaderBin, (void **) &pShaderBin), "Invalid pEffectBuffer: cannot read inline shader block." ); + + if (cbShaderBin > 0) + { + VN( pShaderBlock->pReflectionData = PRIVATENEW SShaderBlock::SReflectionData ); + + pShaderBlock->pReflectionData->BytecodeLength = cbShaderBin; + pShaderBlock->pReflectionData->pBytecode = (BYTE*) pShaderBin; + pShaderBlock->pReflectionData->pStreamOutDecls[0] = + pShaderBlock->pReflectionData->pStreamOutDecls[1] = + pShaderBlock->pReflectionData->pStreamOutDecls[2] = + pShaderBlock->pReflectionData->pStreamOutDecls[3] = NULL; + pShaderBlock->pReflectionData->RasterizedStream = 0; + pShaderBlock->pReflectionData->IsNullGS = FALSE; + pShaderBlock->pReflectionData->pReflection = NULL; + pShaderBlock->pReflectionData->InterfaceParameterCount = 0; + pShaderBlock->pReflectionData->pInterfaceParameters = NULL; + } + + switch (pAssignment->LhsType) + { + case ELHS_PixelShaderBlock: + pShaderBlock->pVT = &g_vtPS; + VBD( psInlineShader->oSODecl == NULL, "Internal loading error: pixel shaders cannot have stream out decls." ); + break; + + case ELHS_GeometryShaderBlock: + pShaderBlock->pVT = &g_vtGS; + if( psAssignments[i].AssignmentType == ECAT_InlineShader ) + { + if (psInlineShader->oSODecl) + { + // This is a GS with SO + VHD( GetStringAndAddToReflection(psInlineShader->oSODecl, &pShaderBlock->pReflectionData->pStreamOutDecls[0]), + "Invalid pEffectBuffer: cannot read SO decl." ); + } + } + else + { + // This is a GS with addressable stream out + for( UINT iDecl=0; iDecl < psInlineShader5->cSODecls; ++iDecl ) + { + if (psInlineShader5->oSODecls[iDecl]) + { + VHD( GetStringAndAddToReflection(psInlineShader5->oSODecls[iDecl], &pShaderBlock->pReflectionData->pStreamOutDecls[iDecl]), + "Invalid pEffectBuffer: cannot read SO decl." ); + } + } + pShaderBlock->pReflectionData->RasterizedStream = psInlineShader5->RasterizedStream; + } + break; + + case ELHS_VertexShaderBlock: + pShaderBlock->pVT = &g_vtVS; + VBD( psInlineShader->oSODecl == NULL, "Internal loading error: vertex shaders cannot have stream out decls." ); + break; + + case ELHS_HullShaderBlock: + pShaderBlock->pVT = &g_vtHS; + VBD( psInlineShader->oSODecl == NULL, "Internal loading error: hull shaders cannot have stream out decls." ); + break; + + case ELHS_DomainShaderBlock: + pShaderBlock->pVT = &g_vtDS; + VBD( psInlineShader->oSODecl == NULL, "Internal loading error: domain shaders cannot have stream out decls." ); + break; + + case ELHS_ComputeShaderBlock: + pShaderBlock->pVT = &g_vtCS; + VBD( psInlineShader->oSODecl == NULL, "Internal loading error: compute shaders cannot have stream out decls." ); + break; + + case ELHS_GeometryShaderSO: + D3DXASSERT(0); // Should never happen + + default: + VHD( E_FAIL, "Internal loading error: invalid shader type." ); + } + + if( psAssignments[i].AssignmentType == ECAT_InlineShader5 ) + { + pShaderBlock->pReflectionData->InterfaceParameterCount = psInlineShader5->cInterfaceBindings; + VH( GetInterfaceParametersAndAddToReflection( psInlineShader5->cInterfaceBindings, psInlineShader5->oInterfaceBindings, &pShaderBlock->pReflectionData->pInterfaceParameters ) ); + } + + // Now we can get rid of this assignment + break; + + default: + D3DXASSERT(0); + + } + } + + *pFinalAssignments = finalAssignments; + if (pRTVAssignments) + *pRTVAssignments = renderTargetViewAssns; + +lExit: + return hr; +} + + +// Read info from the compiled blob and initialize an object variable +HRESULT CEffectLoader::LoadObjectVariables() +{ + HRESULT hr = S_OK; + UINT iBlock; + UINT cBlocks; + + cBlocks = m_pHeader->Effect.cObjectVariables; + + for (iBlock=0; iBlock<cBlocks; iBlock++) + { + SBinaryObjectVariable *psBlock; + SGlobalVariable *pVar; + SType *pType; + UINT iElement; + UINT elementsToRead; + CCheckedDword chkElementsTotal; + UINT elementsTotal; + + // Read variable info + VHD( m_msStructured.Read((void**) &psBlock, sizeof(*psBlock)), "Invalid pEffectBuffer: cannot read object variable." ); + VBD( m_pEffect->m_VariableCount < (m_pHeader->Effect.cObjectVariables + m_pHeader->Effect.cNumericVariables + m_pHeader->cInterfaceVariables), + "Internal loading error: variable count mismatch." ); + pVar = &m_pEffect->m_pVariables[m_pEffect->m_VariableCount]; + + // Get type + VH( LoadTypeAndAddToPool(&pType, psBlock->oType) ); + + // Make sure the right polymorphic type is created + VH( PlacementNewVariable(pVar, pType, FALSE) ); + + pVar->pEffect = m_pEffect; + pVar->pType = pType; + pVar->pCB = NULL; + pVar->ExplicitBindPoint = psBlock->ExplicitBindPoint; + + if( pType->IsStateBlockObject() ) + { + pVar->MemberDataOffsetPlus4 = m_pEffect->m_MemberDataCount * sizeof(SMemberDataPointer) + 4; + m_pEffect->m_MemberDataCount += max(pType->Elements,1); + } + + // Get name + VHD( GetStringAndAddToReflection(psBlock->oName, &pVar->pName), "Invalid pEffectBuffer: cannot read object variable name." ); + VHD( GetStringAndAddToReflection(psBlock->oSemantic, &pVar->pSemantic), "Invalid pEffectBuffer: cannot read object variable semantic." ); + + m_pEffect->m_VariableCount++; + elementsToRead = max(1, pType->Elements); + chkElementsTotal = elementsToRead; + + if (pType->IsStateBlockObject()) + { + // State blocks + EBlockType blockType; + UINT *maxBlockCount; + UINT *currentBlockCount; + + switch (pType->ObjectType) + { + case EOT_Blend: + pVar->Data.pBlock = &m_pEffect->m_pBlendBlocks[m_pEffect->m_BlendBlockCount]; + maxBlockCount = &m_pHeader->cBlendStateBlocks; + currentBlockCount = &m_pEffect->m_BlendBlockCount; + blockType = EBT_Blend; + break; + + case EOT_DepthStencil: + pVar->Data.pBlock = &m_pEffect->m_pDepthStencilBlocks[m_pEffect->m_DepthStencilBlockCount]; + maxBlockCount = &m_pHeader->cDepthStencilBlocks; + currentBlockCount = &m_pEffect->m_DepthStencilBlockCount; + blockType = EBT_DepthStencil; + break; + + case EOT_Rasterizer: + pVar->Data.pBlock = &m_pEffect->m_pRasterizerBlocks[m_pEffect->m_RasterizerBlockCount]; + maxBlockCount = &m_pHeader->cRasterizerStateBlocks; + currentBlockCount = &m_pEffect->m_RasterizerBlockCount; + blockType = EBT_Rasterizer; + break; + + default: + VB(pType->IsSampler()); + pVar->Data.pBlock = &m_pEffect->m_pSamplerBlocks[m_pEffect->m_SamplerBlockCount]; + maxBlockCount = &m_pHeader->cSamplers; + currentBlockCount = &m_pEffect->m_SamplerBlockCount; + blockType = EBT_Sampler; + } + + chkElementsTotal += *currentBlockCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: vaiable elements." ); + VBD( elementsTotal <= *maxBlockCount, "Internal loading error: element count overflow." ); + + *currentBlockCount += elementsToRead; + + for (iElement = 0; iElement < elementsToRead; ++ iElement) + { + SBaseBlock *pCurrentBlock; + UINT cAssignments; + + pCurrentBlock = (SBaseBlock *) GetBlockByIndex(pVar->pType->VarType, pVar->pType->ObjectType, pVar->Data.pGeneric, iElement); + VBD( NULL != pCurrentBlock, "Internal loading error: find state block." ); + + pCurrentBlock->BlockType = blockType; + + VHD( m_msStructured.Read(&cAssignments), "Invalid pEffectBuffer: cannot read state block assignments." ); + + VH( LoadAssignments( cAssignments, &pCurrentBlock->pAssignments, (BYTE*)pCurrentBlock, NULL, &pCurrentBlock->AssignmentCount ) ); + } + } + else if (pType->IsShader()) + { + // Shaders + + chkElementsTotal += m_pEffect->m_ShaderBlockCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: shader block count." ); + VBD( elementsTotal <= m_pHeader->cTotalShaders, "Invalid pEffectBuffer: shader count mismatch." ); + + pVar->Data.pShader = &m_pEffect->m_pShaderBlocks[m_pEffect->m_ShaderBlockCount]; + + for (iElement=0; iElement<elementsToRead; iElement++) + { + UINT cbShaderBin; + void *pShaderBin; + SShaderBlock *pShaderBlock; + + union + { + UINT *pOffset; + SBinaryGSSOInitializer *psInlineGSSO4; + SBinaryShaderData5 *psInlineShader5; + }; + + C_ASSERT( offsetof(SBinaryGSSOInitializer,oShader) == 0 ); + C_ASSERT( offsetof(SBinaryShaderData5,oShader) == 0 ); + + + pShaderBlock = &m_pEffect->m_pShaderBlocks[m_pEffect->m_ShaderBlockCount]; + m_pEffect->m_ShaderBlockCount++; + + // Get shader binary + switch (pType->ObjectType) + { + case EOT_VertexShader: + case EOT_GeometryShader: + case EOT_PixelShader: + VHD( m_msStructured.Read((void**)&pOffset, sizeof(*pOffset)), "Invalid pEffectBuffer: cannot read shader block." ); + break; + + case EOT_GeometryShaderSO: + VHD( m_msStructured.Read((void**)&psInlineGSSO4, sizeof(*psInlineGSSO4)), "Invalid pEffectBuffer: cannot read inline GS with SO." ); + break; + + case EOT_VertexShader5: + case EOT_GeometryShader5: + case EOT_HullShader5: + case EOT_DomainShader5: + case EOT_PixelShader5: + case EOT_ComputeShader5: + VHD( m_msStructured.Read((void**)&psInlineShader5, sizeof(*psInlineShader5)), "Invalid pEffectBuffer: cannot read inline shader." ); + break; + + default: + VH( E_FAIL ); + } + + VHD( GetUnstructuredDataBlock(*pOffset, &cbShaderBin, &pShaderBin), "Invalid pEffectBuffer: cannot read shader byte code." ); + + if (cbShaderBin > 0) + { + VN( pShaderBlock->pReflectionData = PRIVATENEW SShaderBlock::SReflectionData ); + + pShaderBlock->pReflectionData->BytecodeLength = cbShaderBin; + pShaderBlock->pReflectionData->pBytecode = (BYTE*) pShaderBin; + pShaderBlock->pReflectionData->pStreamOutDecls[0] = + pShaderBlock->pReflectionData->pStreamOutDecls[1] = + pShaderBlock->pReflectionData->pStreamOutDecls[2] = + pShaderBlock->pReflectionData->pStreamOutDecls[3] = NULL; + pShaderBlock->pReflectionData->RasterizedStream = 0; + pShaderBlock->pReflectionData->IsNullGS = FALSE; + pShaderBlock->pReflectionData->pReflection = NULL; + pShaderBlock->pReflectionData->InterfaceParameterCount = 0; + pShaderBlock->pReflectionData->pInterfaceParameters = NULL; + } + + switch (pType->ObjectType) + { + case EOT_PixelShader: + pShaderBlock->pVT = &g_vtPS; + break; + + case EOT_GeometryShaderSO: + // Get StreamOut decl + //VH( m_msStructured.Read(&dwOffset) ); + if (cbShaderBin > 0) + { + VHD( GetStringAndAddToReflection(psInlineGSSO4->oSODecl, &pShaderBlock->pReflectionData->pStreamOutDecls[0]), + "Invalid pEffectBuffer: cannot read stream out decl." ); + } + pShaderBlock->pVT = &g_vtGS; + break; + + case EOT_VertexShader5: + case EOT_GeometryShader5: + case EOT_HullShader5: + case EOT_DomainShader5: + case EOT_PixelShader5: + case EOT_ComputeShader5: + // Get StreamOut decls + if (cbShaderBin > 0) + { + for( UINT iDecl=0; iDecl < psInlineShader5->cSODecls; ++iDecl ) + { + VHD( GetStringAndAddToReflection(psInlineShader5->oSODecls[iDecl], &pShaderBlock->pReflectionData->pStreamOutDecls[iDecl]), + "Invalid pEffectBuffer: cannot read stream out decls." ); + } + pShaderBlock->pReflectionData->RasterizedStream = psInlineShader5->RasterizedStream; + pShaderBlock->pReflectionData->InterfaceParameterCount = psInlineShader5->cInterfaceBindings; + VH( GetInterfaceParametersAndAddToReflection( psInlineShader5->cInterfaceBindings, psInlineShader5->oInterfaceBindings, &pShaderBlock->pReflectionData->pInterfaceParameters ) ); + } + switch (pType->ObjectType) + { + case EOT_VertexShader5: + pShaderBlock->pVT = &g_vtVS; + break; + case EOT_GeometryShader5: + pShaderBlock->pVT = &g_vtGS; + break; + case EOT_HullShader5: + pShaderBlock->pVT = &g_vtHS; + break; + case EOT_DomainShader5: + pShaderBlock->pVT = &g_vtDS; + break; + case EOT_PixelShader5: + pShaderBlock->pVT = &g_vtPS; + break; + case EOT_ComputeShader5: + pShaderBlock->pVT = &g_vtCS; + break; + default: + VH( E_FAIL ); + } + break; + + case EOT_GeometryShader: + pShaderBlock->pVT = &g_vtGS; + break; + + case EOT_VertexShader: + pShaderBlock->pVT = &g_vtVS; + break; + + default: + VHD( E_FAIL, "Invalid pEffectBuffer: invalid shader type." ); + } + } + } + else if (pType->IsObjectType(EOT_String)) + { + // Strings + + chkElementsTotal += m_pEffect->m_StringCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: string object count." ); + VBD( elementsTotal <= m_pHeader->cStrings, "Invalid pEffectBuffer: string count mismatch." ); + + pVar->Data.pString = &m_pEffect->m_pStrings[m_pEffect->m_StringCount]; + + for (iElement=0; iElement<elementsToRead; iElement++) + { + UINT dwOffset; + SString *pString; + + pString = &m_pEffect->m_pStrings[m_pEffect->m_StringCount]; + m_pEffect->m_StringCount++; + + // Get string + VHD( m_msStructured.Read(&dwOffset), "Invalid pEffectBuffer: cannot read string offset." ); + VHD( GetStringAndAddToReflection(dwOffset, &pString->pString), "Invalid pEffectBuffer: cannot read string." ); + } + } + else if (pType->IsShaderResource()) + { + // Textures/buffers + + chkElementsTotal += m_pEffect->m_ShaderResourceCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: SRV object count." ); + VBD( elementsTotal <= m_pHeader->cShaderResources, "Invalid pEffectBuffer: SRV count mismatch." ); + + pVar->Data.pShaderResource = &m_pEffect->m_pShaderResources[m_pEffect->m_ShaderResourceCount]; + m_pEffect->m_ShaderResourceCount += elementsToRead; + } + else if (pType->IsUnorderedAccessView()) + { + // UnorderedAccessViews + + chkElementsTotal += m_pEffect->m_UnorderedAccessViewCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: UAV object count." ); + VBD( elementsTotal <= m_pHeader->cUnorderedAccessViews, "Invalid pEffectBuffer: UAV count mismatch." ); + + pVar->Data.pUnorderedAccessView = &m_pEffect->m_pUnorderedAccessViews[m_pEffect->m_UnorderedAccessViewCount]; + m_pEffect->m_UnorderedAccessViewCount += elementsToRead; + } + else if (pType->IsRenderTargetView()) + { + // RenderTargets + + chkElementsTotal += m_pEffect->m_RenderTargetViewCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: RTV object count." ); + VBD( elementsTotal <= m_pHeader->cRenderTargetViews, "Invalid pEffectBuffer: RTV count mismatch." ); + + pVar->Data.pRenderTargetView = &m_pEffect->m_pRenderTargetViews[m_pEffect->m_RenderTargetViewCount]; + m_pEffect->m_RenderTargetViewCount += elementsToRead; + } + else if (pType->IsDepthStencilView()) + { + // DepthStencilViews + + chkElementsTotal += m_pEffect->m_DepthStencilViewCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: DSV object count." ); + VBD( elementsTotal <= m_pHeader->cDepthStencilViews, "Invalid pEffectBuffer: DSV count mismatch." ); + + pVar->Data.pDepthStencilView = &m_pEffect->m_pDepthStencilViews[m_pEffect->m_DepthStencilViewCount]; + m_pEffect->m_DepthStencilViewCount += elementsToRead; + } + else + { + VHD( E_FAIL, "Invalid pEffectBuffer: DSV count mismatch." ); + } + + // Read annotations + VH( LoadAnnotations(&pVar->AnnotationCount, &pVar->pAnnotations) ); + } +lExit: + return hr; +} + + +// Read info from the compiled blob and initialize an interface variable +HRESULT CEffectLoader::LoadInterfaceVariables() +{ + HRESULT hr = S_OK; + UINT iBlock; + UINT cBlocks; + + cBlocks = m_pHeader->cInterfaceVariables; + + for (iBlock=0; iBlock<cBlocks; iBlock++) + { + SBinaryInterfaceVariable *psBlock; + SGlobalVariable *pVar; + SType *pType; + UINT elementsToRead; + CCheckedDword chkElementsTotal; + UINT elementsTotal; + void *pDefaultValue; + + // Read variable info + VHD( m_msStructured.Read((void**) &psBlock, sizeof(*psBlock)), "Invalid pEffectBuffer: cannot read interface block." ); + VBD( m_pEffect->m_VariableCount < (m_pHeader->Effect.cObjectVariables + m_pHeader->Effect.cNumericVariables + m_pHeader->cInterfaceVariables), + "Internal loading error: variable count mismatch." ); + pVar = &m_pEffect->m_pVariables[m_pEffect->m_VariableCount]; + + // Get type + VH( LoadTypeAndAddToPool(&pType, psBlock->oType) ); + + // Make sure the right polymorphic type is created + VH( PlacementNewVariable(pVar, pType, FALSE) ); + + pVar->pEffect = m_pEffect; + pVar->pType = pType; + pVar->pCB = NULL; + pVar->ExplicitBindPoint = (UINT)-1; + pVar->pSemantic = NULL; + + // Get name + VHD( GetStringAndAddToReflection(psBlock->oName, &pVar->pName), "Invalid pEffectBuffer: cannot read interface name." ); + + m_pEffect->m_VariableCount++; + elementsToRead = max(1, pType->Elements); + chkElementsTotal = elementsToRead; + + VBD( pType->IsInterface(), "Internal loading error: invlaid type for interface." ); + + chkElementsTotal += m_pEffect->m_InterfaceCount; + VHD( chkElementsTotal.GetValue(&elementsTotal), "Overflow: interface count." ); + VBD( elementsTotal <= m_pHeader->cInterfaceVariableElements, "Invalid pEffectBuffer: interface count mismatch." ); + + pVar->Data.pInterface = &m_pEffect->m_pInterfaces[m_pEffect->m_InterfaceCount]; + m_pEffect->m_InterfaceCount += elementsToRead; + + // Get default value + if (0 != psBlock->oDefaultValue) + { + VHD( m_msUnstructured.ReadAtOffset(psBlock->oDefaultValue, elementsToRead * sizeof(SBinaryInterfaceInitializer), &pDefaultValue), + "Invalid pEffectBuffer: cannot read interface initializer offset." ); + for( UINT i=0; i < elementsToRead; i++ ) + { + SBinaryInterfaceInitializer* pInterfaceInit = &((SBinaryInterfaceInitializer*)pDefaultValue)[i]; + LPCSTR pClassInstanceName; + VHD( m_msUnstructured.ReadAtOffset(pInterfaceInit->oInstanceName, &pClassInstanceName), "Invalid pEffectBuffer: cannot read interface initializer." ); + + SGlobalVariable *pCIVariable = m_pEffect->FindVariableByName(pClassInstanceName); + VBD( pCIVariable != NULL, "Loading error: cannot find class instance for interface initializer." ); + VBD( pCIVariable->pType->IsClassInstance(), "Loading error: variable type mismatch for interface initializer." ); + if( pInterfaceInit->ArrayIndex == (UINT)-1 ) + { + VBD( pCIVariable->pType->Elements == 0, "Loading error: array mismatch for interface initializer." ); + pVar->Data.pInterface[i].pClassInstance = (SClassInstanceGlobalVariable*)pCIVariable; + } + else + { + VBD( pCIVariable->pType->Elements > 0, "Loading error: array mismatch for interface initializer." ); + VBD( pInterfaceInit->ArrayIndex < pCIVariable->pType->Elements, "Loading error: array index out of range." ); + + SMember* pMember = (SMember*)pCIVariable->GetElement( pInterfaceInit->ArrayIndex ); + VBD( pMember->IsValid(), "Loading error: cannot find member by name." ); + VBD( pMember->pType->IsClassInstance(), "Loading error: member type mismatch for interface initializer." ); + pVar->Data.pInterface[i].pClassInstance = (SClassInstanceGlobalVariable*)pMember; + } + } + } + + + // Read annotations + VH( LoadAnnotations(&pVar->AnnotationCount, &pVar->pAnnotations) ); + } +lExit: + return hr; +} + + +// Read info from the compiled blob and initialize a group (and contained techniques and passes) +HRESULT CEffectLoader::LoadGroups() +{ + HRESULT hr = S_OK; + UINT iGroup; + UINT TechniquesInEffect = 0; + + for( iGroup=0; iGroup<m_pHeader->cGroups; iGroup++ ) + { + SGroup *pGroup = &m_pEffect->m_pGroups[iGroup]; + SBinaryGroup *psGroup; + + // Read group info + VHD( m_msStructured.Read((void**) &psGroup, sizeof(*psGroup)), "Invalid pEffectBuffer: cannot read group." ); + pGroup->TechniqueCount = psGroup->cTechniques; + VN( pGroup->pTechniques = PRIVATENEW STechnique[pGroup->TechniqueCount] ); + VHD( GetStringAndAddToReflection(psGroup->oName, &pGroup->pName), "Invalid pEffectBuffer: cannot read group name." ); + + if( pGroup->pName == NULL ) + { + VBD( m_pEffect->m_pNullGroup == NULL, "Internal loading error: multiple NULL groups." ); + m_pEffect->m_pNullGroup = pGroup; + } + + // Read annotations + VH( LoadAnnotations(&pGroup->AnnotationCount, &pGroup->pAnnotations) ); + + UINT iTechnique; + for( iTechnique=0; iTechnique < psGroup->cTechniques; iTechnique++ ) + { + VH( LoadTechnique( &pGroup->pTechniques[iTechnique] ) ); + } + TechniquesInEffect += psGroup->cTechniques; + } + + VBD( TechniquesInEffect == m_pHeader->cTechniques, "Loading error: technique count mismatch." ); + m_pEffect->m_TechniqueCount = m_pHeader->cTechniques; + m_pEffect->m_GroupCount = m_pHeader->cGroups; + +lExit: + return hr; +} + + +// Read info from the compiled blob and initialize a technique (and contained passes) +HRESULT CEffectLoader::LoadTechnique( STechnique* pTech ) +{ + HRESULT hr = S_OK; + UINT iPass; + + SBinaryTechnique *psTech; + + // Read technique info + VHD( m_msStructured.Read((void**) &psTech, sizeof(*psTech)), "Invalid pEffectBuffer: cannot read technique." ); + pTech->PassCount = psTech->cPasses; + VN( pTech->pPasses = PRIVATENEW SPassBlock[pTech->PassCount] ); + VHD( GetStringAndAddToReflection(psTech->oName, &pTech->pName), "Invalid pEffectBuffer: cannot read technique name." ); + + // Read annotations + VH( LoadAnnotations(&pTech->AnnotationCount, &pTech->pAnnotations) ); + + for (iPass=0; iPass<psTech->cPasses; iPass++) + { + SBinaryPass *psPass; + SPassBlock *pPass = &pTech->pPasses[iPass]; + + // Read pass info + VHD( m_msStructured.Read((void**) &psPass, sizeof(SBinaryPass)), "Invalid pEffectBuffer: cannot read pass." ); + VHD( GetStringAndAddToReflection(psPass->oName, &pPass->pName), "Invalid pEffectBuffer: cannot read pass name." ); + + // Read annotations + VH( LoadAnnotations(&pPass->AnnotationCount, &pPass->pAnnotations) ); + + VH( LoadAssignments( psPass->cAssignments, &pPass->pAssignments, (BYTE*)pPass, &pPass->BackingStore.RenderTargetViewCount, &pPass->AssignmentCount ) ); + VBD( pPass->BackingStore.RenderTargetViewCount <= D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, "Invalid pEffectBuffer: too many RTVs in pass." ); + + // Initialize other pass information + pPass->pEffect = m_pEffect; + pPass->BlockType = EBT_Pass; + } + +lExit: + return hr; +} + + +// Read info from the compiled blob and initialize a set of annotations +HRESULT CEffectLoader::LoadAnnotations(UINT *pcAnnotations, SAnnotation **ppAnnotations) +{ + HRESULT hr = S_OK; + UINT cAnnotations, i, oData; + SAnnotation *pAnnotations = NULL; + + VHD( m_msStructured.Read(&cAnnotations), "Invalid pEffectBuffer: cannot read anootation count." ); + + if (cAnnotations) + { + UINT annotationsSize; + CCheckedDword chkAnnotationsSize; + + chkAnnotationsSize = cAnnotations; + chkAnnotationsSize *= sizeof(SAnnotation); + VHD( chkAnnotationsSize.GetValue(&annotationsSize), "Overflow in annotations." ); + + // we allocate raw bytes for annotations because they are polymorphic types that need to be placement new'ed + VN( pAnnotations = (SAnnotation *) PRIVATENEW BYTE[annotationsSize] ); + + for (i=0; i<cAnnotations; i++) + { + SBinaryAnnotation *psAnnotation; + SAnnotation *pAn = &pAnnotations[i]; + SType *pType; + + VHD( m_msStructured.Read((void**) &psAnnotation, sizeof(SBinaryAnnotation)), "Invalid pEffectBuffer: cannot read annotation." ); + + VH( LoadTypeAndAddToPool(&pType, psAnnotation->oType) ); + + // Make sure the right polymorphic type is created + VH( PlacementNewVariable(pAn, pType, TRUE) ); + + pAn->pEffect = m_pEffect; + pAn->pType = pType; + + VHD( GetStringAndAddToReflection(psAnnotation->oName, &pAn->pName), "Invalid pEffectBuffer: cannot read annotation name." ); + + if (pType->IsObjectType(EOT_String)) + { + UINT cElements = max(1, pType->Elements); + UINT j; + VN( pAn->Data.pString = PRIVATENEW SString[cElements] ); + for (j = 0; j < cElements; ++ j) + { + // Read initializer offset + VHD( m_msStructured.Read(&oData), "Invalid pEffectBuffer: cannot read string." ); + VHD( GetStringAndAddToReflection(oData, &pAn->Data.pString[j].pString), "Invalid pEffectBuffer: cannot read string initializer." ); + } + } + else if (pType->BelongsInConstantBuffer()) + { + void *pDefaultValue; + UINT bytesUnpacked; + + // Read initializer offset + VHD( m_msStructured.Read(&oData), "Invalid pEffectBuffer: cannot read annotation." ); + + VBD( oData != 0, "Invalid pEffectBuffer: invalid anotation offset." ); + + VN( pAn->Data.pGeneric = PRIVATENEW BYTE[pType->TotalSize] ); + ZeroMemory(pAn->Data.pGeneric, pType->TotalSize); + VHD( m_msUnstructured.ReadAtOffset(oData, pType->PackedSize, &pDefaultValue), "Invalid pEffectBuffer: cannot read variable default value." ); + VH( UnpackData((BYTE*) pAn->Data.pGeneric, (BYTE*) pDefaultValue, pType->PackedSize, pType, &bytesUnpacked) ); + VBD( bytesUnpacked == pType->PackedSize, "Invalid pEffectBuffer: packed sizes to not match." ); + } + else + { + VHD( E_FAIL, "Invalid pEffectBuffer: invalid annotation type." ); + } + } + } + + *pcAnnotations = cAnnotations; + *ppAnnotations = pAnnotations; +lExit: + + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// Build shader block dependencies from shader metadata +////////////////////////////////////////////////////////////////////////// + +// +// Grabs shader resource dependency information from the bytecode of the shader +// (cbuffer, tbuffer, texture, buffer, sampler, and UAV dependencies), +// and sets up the given SShaderBlock to point to the dependencies within the effect +// +HRESULT CEffectLoader::GrabShaderData(SShaderBlock *pShaderBlock) +{ + HRESULT hr = S_OK; + UINT i, j; + CEffectVector<SRange> vRanges[ER_Count], *pvRange; + SRange *pRange = NULL; + CEffectVector<SConstantBuffer*> vTBuffers; + + ////////////////////////////////////////////////////////////////////////// + // Step 1: iterate through the resource binding structures and build + // an "optimized" list of all of the dependencies + + D3D11_SHADER_DESC ShaderDesc; + pShaderBlock->pReflectionData->pReflection->GetDesc( &ShaderDesc ); + + // Since we have the shader desc, let's find out if this is a NULL GS + if( D3D11_SHVER_GET_TYPE( ShaderDesc.Version ) == D3D11_SHVER_VERTEX_SHADER && pShaderBlock->GetShaderType() == EOT_GeometryShader ) + { + pShaderBlock->pReflectionData->IsNullGS = TRUE; + } + + pShaderBlock->CBDepCount = pShaderBlock->ResourceDepCount = pShaderBlock->TBufferDepCount = pShaderBlock->SampDepCount = 0; + pShaderBlock->UAVDepCount = pShaderBlock->InterfaceDepCount = 0; + + for(i = 0; i < ShaderDesc.BoundResources; i++) + { + LPCSTR pName; + UINT bindPoint, size; + ERanges eRange; + SShaderResource *pShaderResource = NULL; + SUnorderedAccessView *pUnorderedAccessView = NULL; + SSamplerBlock *pSampler = NULL; + SConstantBuffer *pCB = NULL; + SVariable *pVariable = NULL; + BOOL isFX9TextureLoad = FALSE; + D3D11_SHADER_INPUT_BIND_DESC ResourceDesc; + + pShaderBlock->pReflectionData->pReflection->GetResourceBindingDesc( i, &ResourceDesc ); + + // HUGE ASSUMPTION: the bindpoints we read in the shader metadata are sorted; + // i.e. bindpoints are steadily increasing + // If this assumption is not met, then we will hit an assert below + + pName = ResourceDesc.Name; + bindPoint = ResourceDesc.BindPoint; + size = ResourceDesc.BindCount; + + switch( ResourceDesc.Type ) + { + case D3D10_SIT_CBUFFER: + eRange = ER_CBuffer; + + pCB = m_pEffect->FindCB(pName); + VBD( NULL != pCB, "Loading error: cannot find cbuffer." ); + VBD( size == 1, "Loading error: cbuffer arrays are not supported." ); + break; + + case D3D10_SIT_TBUFFER: + eRange = ER_Texture; + + pCB = m_pEffect->FindCB(pName); + VBD( NULL != pCB, "Loading error: cannot find tbuffer." ); + VBD( FALSE != pCB->IsTBuffer, "Loading error: cbuffer found where tbuffer is expected." ); + VBD( size == 1, "Loading error: tbuffer arrays are not supported." ); + pShaderResource = &pCB->TBuffer; + break; + + case D3D10_SIT_TEXTURE: + case D3D11_SIT_STRUCTURED: + case D3D11_SIT_BYTEADDRESS: + eRange = ER_Texture; + + pVariable = m_pEffect->FindVariableByNameWithParsing(pName); + VBD( pVariable != NULL, "Loading error: cannot find SRV variable." ); + UINT elements; + elements = max(1, pVariable->pType->Elements); + VBD( size <= elements, "Loading error: SRV array size mismatch." ); + + if (pVariable->pType->IsShaderResource()) + { + // this is just a straight texture assignment + pShaderResource = pVariable->Data.pShaderResource; + } + else + { + // This is a FX9/HLSL9-style texture load instruction that specifies only a sampler + VBD( pVariable->pType->IsSampler(), "Loading error: shader dependency is neither an SRV nor sampler."); + isFX9TextureLoad = TRUE; + pSampler = pVariable->Data.pSampler; + // validate that all samplers actually used (i.e. based on size, not elements) in this variable have a valid TEXTURE assignment + for (j = 0; j < size; ++ j) + { + if (NULL == pSampler[j].BackingStore.pTexture) + { + // print spew appropriately for samplers vs sampler arrays + if (0 == pVariable->pType->Elements) + { + DPF(0, "%s: Sampler %s does not have a texture bound to it, even though the sampler is used in a DX9-style texture load instruction", g_szEffectLoadArea, pName); + } + else + { + DPF(0, "%s: Sampler %s[%d] does not have a texture bound to it, even though the sampler array is used in a DX9-style texture load instruction", g_szEffectLoadArea, pName, j); + } + + VH( E_FAIL ); + } + } + } + break; + + case D3D11_SIT_UAV_RWTYPED: + case D3D11_SIT_UAV_RWSTRUCTURED: + case D3D11_SIT_UAV_RWBYTEADDRESS: + case D3D11_SIT_UAV_APPEND_STRUCTURED: + case D3D11_SIT_UAV_CONSUME_STRUCTURED: + case D3D11_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: + eRange = ER_UnorderedAccessView; + + pVariable = m_pEffect->FindVariableByNameWithParsing(pName); + VBD( pVariable != NULL, "Loading error: cannot find UAV variable." ); + VBD( size <= max(1, pVariable->pType->Elements), "Loading error: UAV array index out of range." ); + VBD( pVariable->pType->IsUnorderedAccessView(), "Loading error: UAV variable expected." ); + pUnorderedAccessView = pVariable->Data.pUnorderedAccessView; + break; + + case D3D10_SIT_SAMPLER: + eRange = ER_Sampler; + + pVariable = m_pEffect->FindVariableByNameWithParsing(pName); + VBD( pVariable != NULL, "Loading error: cannot find sampler variable." ); + VBD( size <= max(1, pVariable->pType->Elements), "Loading error: sampler array index out of range." ); + VBD( pVariable->pType->IsSampler(), "Loading error: sampler variable expected." ); + pSampler = pVariable->Data.pSampler; + break; + + default: + VHD( E_FAIL, "Internal loading error: unexpected shader dependency type." ); + }; + + // + // Here's where the "optimized" part comes in; whenever there's + // a resource dependency, see if it's located contiguous to + // an existing resource dependency and merge them together + // if possible + // + UINT rangeCount; + pvRange = &vRanges[eRange]; + rangeCount = pvRange->GetSize(); + + if ( rangeCount > 0 ) + { + // Can we continue an existing range? + pRange = &( (*pvRange)[rangeCount - 1] ); + + // Make sure that bind points are strictly increasing, + // otherwise this algorithm breaks and we'd get worse runtime performance + D3DXASSERT(pRange->last <= bindPoint); + + if ( pRange->last != bindPoint ) + { + if( eRange != ER_UnorderedAccessView ) + { + // No we can't. Begin a new range by setting rangeCount to 0 and triggering the next IF + rangeCount = 0; + } + else + { + // UAVs will always be located in one range, as they are more expensive to set + while(pRange->last < bindPoint) + { + VHD( pRange->vResources.Add(&g_NullUnorderedAccessView), "Internal loading error: cannot add UAV to range." ); + pRange->last++; + } + } + } + } + + if ( rangeCount == 0 ) + { + VN( pRange = pvRange->Add() ); + pRange->start = bindPoint; + } + + pRange->last = bindPoint + size; + + switch( ResourceDesc.Type ) + { + case D3D10_SIT_CBUFFER: + VHD( pRange->vResources.Add(pCB), "Internal loading error: cannot add cbuffer to range." ); + break; + case D3D10_SIT_TBUFFER: + VHD( pRange->vResources.Add(pShaderResource), "Internal loading error: cannot add tbuffer to range." ); + VHD( vTBuffers.Add( (SConstantBuffer*)pCB ), "Internal loading error: cannot add tbuffer to vector." ); + break; + case D3D10_SIT_TEXTURE: + case D3D11_SIT_STRUCTURED: + case D3D11_SIT_BYTEADDRESS: + if (isFX9TextureLoad) + { + // grab all of the textures from each sampler + for (j = 0; j < size; ++ j) + { + VHD( pRange->vResources.Add(pSampler[j].BackingStore.pTexture), "Internal loading error: cannot add SRV to range." ); + } + } + else + { + // add the whole array + for (j = 0; j < size; ++ j) + { + VHD( pRange->vResources.Add(pShaderResource + j), "Internal loading error: cannot add SRV to range." ); + } + } + break; + case D3D11_SIT_UAV_RWTYPED: + case D3D11_SIT_UAV_RWSTRUCTURED: + case D3D11_SIT_UAV_RWBYTEADDRESS: + case D3D11_SIT_UAV_APPEND_STRUCTURED: + case D3D11_SIT_UAV_CONSUME_STRUCTURED: + case D3D11_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: + // add the whole array + for (j = 0; j < size; ++ j) + { + VHD( pRange->vResources.Add(pUnorderedAccessView + j), "Internal loading error: cannot add UAV to range." ); + } + break; + case D3D10_SIT_SAMPLER: + // add the whole array + for (j = 0; j < size; ++ j) + { + VHD( pRange->vResources.Add(pSampler + j), "Internal loading error: cannot add sampler to range." ); + } + break; + default: + VHD( E_FAIL, "Internal loading error: unexpected shader dependency type." ); + } + } + + + ////////////////////////////////////////////////////////////////////////// + // Step 2: iterate through the interfaces and build + // an "optimized" list of all of the dependencies + + UINT NumInterfaces = pShaderBlock->pReflectionData->pReflection->GetNumInterfaceSlots(); + UINT CurInterfaceParameter = 0; + if( NumInterfaces > 0 ) + { + D3DXASSERT( ShaderDesc.ConstantBuffers > 0 ); + + for( i=0; i < ShaderDesc.ConstantBuffers; i++ ) + { + ID3D11ShaderReflectionConstantBuffer* pCB = pShaderBlock->pReflectionData->pReflection->GetConstantBufferByIndex(i); + VN( pCB ); + D3D11_SHADER_BUFFER_DESC CBDesc; + VHD( pCB->GetDesc( &CBDesc ), "Internal loading error: cannot get CB desc." ); + if( CBDesc.Type != D3D11_CT_INTERFACE_POINTERS ) + { + continue; + } + + for( UINT iVar=0; iVar < CBDesc.Variables; iVar++ ) + { + ID3D11ShaderReflectionVariable* pInterfaceVar = pCB->GetVariableByIndex( iVar ); + VN( pInterfaceVar ); + D3D11_SHADER_VARIABLE_DESC InterfaceDesc; + pInterfaceVar->GetDesc( &InterfaceDesc ); + + LPCSTR pName; + UINT bindPoint, size; + SGlobalVariable *pVariable = NULL; + SInterface *pInterface = NULL; + UINT VariableElements; + + pName = InterfaceDesc.Name; + bindPoint = InterfaceDesc.StartOffset; + size = InterfaceDesc.Size; + + if( bindPoint == (UINT)-1 ) + { + continue; + } + + D3DXASSERT( InterfaceDesc.uFlags & D3D11_SVF_INTERFACE_POINTER ); + if( InterfaceDesc.uFlags & D3D11_SVF_INTERFACE_PARAMETER ) + { + // This interface pointer is a parameter to the shader + if( pShaderBlock->pReflectionData->InterfaceParameterCount == 0 ) + { + // There may be no interface parameters in this shader if it was compiled but had no interfaced bound to it. + // The shader cannot be set (correctly) in any pass. + continue; + } + else + { + VBD( CurInterfaceParameter < pShaderBlock->pReflectionData->InterfaceParameterCount, + "Internal loading error: interface count mismatch."); + SShaderBlock::SInterfaceParameter* pInterfaceInfo; + pInterfaceInfo = &pShaderBlock->pReflectionData->pInterfaceParameters[CurInterfaceParameter]; + ++CurInterfaceParameter; + SGlobalVariable *pParent = m_pEffect->FindVariableByName(pInterfaceInfo->pName); + VBD( pParent != NULL, "Loading error: cannot find parent type." ); + if( pInterfaceInfo->Index == (UINT)-1 ) + { + pVariable = pParent; + VariableElements = pVariable->pType->Elements; + } + else + { + // We want a specific index of the variable (ex. "MyVar[2]") + VBD( size == 1, "Loading error: interface array type mismatch." ); + pVariable = (SGlobalVariable*)pParent->GetElement( pInterfaceInfo->Index ); + VBD( pVariable->IsValid(), "Loading error: interface array index out of range." ); + VariableElements = 0; + } + } + } + else + { + // This interface pointer is a global interface used in the shader + pVariable = m_pEffect->FindVariableByName(pName); + VBD( pVariable != NULL, "Loading error: cannot find interface variable." ); + VariableElements = pVariable->pType->Elements; + } + VBD( size <= max(1, VariableElements), "Loading error: interface array size mismatch." ); + if( pVariable->pType->IsInterface() ) + { + pInterface = pVariable->Data.pInterface; + } + else if( pVariable->pType->IsClassInstance() ) + { + // For class instances, we create background interfaces which point to the class instance. This is done so + // the shader can always expect SInterface dependencies, rather than a mix of SInterfaces and class instances + VN( pInterface = PRIVATENEW SInterface[size] ); + if( VariableElements == 0 ) + { + D3DXASSERT( size == 1 ); + pInterface[0].pClassInstance = (SClassInstanceGlobalVariable*)pVariable; + m_BackgroundInterfaces.Add( &pInterface[0] ); + } + else + { + // Fill each element of the SInstance array individually + VBD( size == VariableElements, "Loading error: class instance array size mismatch." ); + for( UINT iElement=0; iElement < size; iElement++ ) + { + SGlobalVariable *pElement = (SGlobalVariable*)pVariable->GetElement( iElement ); + VBD( pElement->IsValid(), "Internal loading error: class instance array index out of range." ); + pInterface[iElement].pClassInstance = (SClassInstanceGlobalVariable*)pElement; + m_BackgroundInterfaces.Add( &pInterface[iElement] ); + } + } + } + else + { + VHD( E_FAIL, "Loading error: invalid interface initializer variable type."); + } + + // + // Here's where the "optimized" part comes in; whenever there's + // a resource dependency, see if it's located contiguous to + // an existing resource dependency and merge them together + // if possible + // + UINT rangeCount; + pvRange = &vRanges[ER_Interfaces]; + rangeCount = pvRange->GetSize(); + + VBD( rangeCount <= 1, "Internal loading error: invalid range count." ); + + if ( rangeCount == 0 ) + { + VN( pRange = pvRange->Add() ); + pRange->start = pRange->last = 0; + } + else + { + pRange = &( (*pvRange)[0] ); + } + + if( bindPoint < pRange->last ) + { + // add interfaces into the range that already exists + VBD( bindPoint + size < pRange->last, "Internal loading error: range overlap." ); + for( j = 0; j < size; ++ j ) + { + pRange->vResources[j + bindPoint] = pInterface + j; + } + } + else + { + // add interfaces to the end of the range + + // add missing interface slots, if necessary + while(pRange->last < bindPoint) + { + VHD( pRange->vResources.Add(&g_NullInterface), "Internal loading error: cannot add NULL interface to range." ); + pRange->last++; + } + + D3DXASSERT( bindPoint == pRange->last ); + for( j=0; j < size; ++ j ) + { + VHD( pRange->vResources.Add(pInterface + j), "Internal loading error: cannot at interface to range." ); + } + pRange->last = bindPoint + size; + } + } + + // There is only one interface cbuffer + break; + } + } + + ////////////////////////////////////////////////////////////////////////// + // Step 3: allocate room in pShaderBlock for all of the dependency + // pointers and then hook them up + + pShaderBlock->SampDepCount = vRanges[ ER_Sampler ].GetSize(); + pShaderBlock->CBDepCount = vRanges[ ER_CBuffer ].GetSize(); + pShaderBlock->InterfaceDepCount = vRanges[ ER_Interfaces ].GetSize(); + pShaderBlock->ResourceDepCount = vRanges[ ER_Texture ].GetSize(); + pShaderBlock->UAVDepCount = vRanges[ ER_UnorderedAccessView ].GetSize(); + pShaderBlock->TBufferDepCount = vTBuffers.GetSize(); + + VN( pShaderBlock->pSampDeps = PRIVATENEW SShaderSamplerDependency[pShaderBlock->SampDepCount] ); + VN( pShaderBlock->pCBDeps = PRIVATENEW SShaderCBDependency[pShaderBlock->CBDepCount] ); + VN( pShaderBlock->pInterfaceDeps = PRIVATENEW SInterfaceDependency[pShaderBlock->InterfaceDepCount] ); + VN( pShaderBlock->pResourceDeps = PRIVATENEW SShaderResourceDependency[pShaderBlock->ResourceDepCount] ); + VN( pShaderBlock->pUAVDeps = PRIVATENEW SUnorderedAccessViewDependency[pShaderBlock->UAVDepCount] ); + VN( pShaderBlock->ppTbufDeps = PRIVATENEW SConstantBuffer*[pShaderBlock->TBufferDepCount] ); + + for (i=0; i<pShaderBlock->CBDepCount; ++i) + { + SShaderCBDependency *pDep = &pShaderBlock->pCBDeps[i]; + + pRange = &vRanges[ER_CBuffer][i]; + + pDep->StartIndex = pRange->start; + pDep->Count = pRange->last - pDep->StartIndex; + pDep->ppFXPointers = PRIVATENEW SConstantBuffer*[ pDep->Count ]; + pDep->ppD3DObjects = PRIVATENEW ID3D11Buffer*[ pDep->Count ]; + + D3DXASSERT(pDep->Count == pRange->vResources.GetSize()); + for (j=0; j<pDep->Count; ++j) + { + pDep->ppFXPointers[j] = (SConstantBuffer *)pRange->vResources[j]; + pDep->ppD3DObjects[j] = NULL; + } + } + + for (i=0; i<pShaderBlock->SampDepCount; ++i) + { + SShaderSamplerDependency *pDep = &pShaderBlock->pSampDeps[i]; + + pRange = &vRanges[ER_Sampler][i]; + + pDep->StartIndex = pRange->start; + pDep->Count = pRange->last - pDep->StartIndex; + pDep->ppFXPointers = PRIVATENEW SSamplerBlock*[ pDep->Count ]; + pDep->ppD3DObjects = PRIVATENEW ID3D11SamplerState*[ pDep->Count ]; + + D3DXASSERT(pDep->Count == pRange->vResources.GetSize()); + for (j=0; j<pDep->Count; ++j) + { + pDep->ppFXPointers[j] = (SSamplerBlock *) pRange->vResources[j]; + pDep->ppD3DObjects[j] = NULL; + } + } + + for (i=0; i<pShaderBlock->InterfaceDepCount; ++i) + { + SInterfaceDependency *pDep = &pShaderBlock->pInterfaceDeps[i]; + + pRange = &vRanges[ER_Interfaces][i]; + + pDep->StartIndex = pRange->start; + pDep->Count = pRange->last - pDep->StartIndex; + pDep->ppFXPointers = PRIVATENEW SInterface*[ pDep->Count ]; + pDep->ppD3DObjects = PRIVATENEW ID3D11ClassInstance*[ pDep->Count ]; + + D3DXASSERT(pDep->Count == pRange->vResources.GetSize()); + for (j=0; j<pDep->Count; ++j) + { + pDep->ppFXPointers[j] = (SInterface *) pRange->vResources[j]; + pDep->ppD3DObjects[j] = NULL; + } + } + + for (i=0; i<pShaderBlock->ResourceDepCount; ++i) + { + SShaderResourceDependency *pDep = &pShaderBlock->pResourceDeps[i]; + + pRange = &vRanges[ER_Texture][i]; + + pDep->StartIndex = pRange->start; + pDep->Count = pRange->last - pDep->StartIndex; + pDep->ppFXPointers = PRIVATENEW SShaderResource*[ pDep->Count ]; + pDep->ppD3DObjects = PRIVATENEW ID3D11ShaderResourceView*[ pDep->Count ]; + + D3DXASSERT(pDep->Count == pRange->vResources.GetSize()); + for (j=0; j<pDep->Count; ++j) + { + pDep->ppFXPointers[j] = (SShaderResource *) pRange->vResources[j]; + pDep->ppD3DObjects[j] = NULL; + } + } + + for (i=0; i<pShaderBlock->UAVDepCount; ++i) + { + SUnorderedAccessViewDependency *pDep = &pShaderBlock->pUAVDeps[i]; + + pRange = &vRanges[ER_UnorderedAccessView][i]; + + pDep->StartIndex = pRange->start; + pDep->Count = pRange->last - pDep->StartIndex; + pDep->ppFXPointers = PRIVATENEW SUnorderedAccessView*[ pDep->Count ]; + pDep->ppD3DObjects = PRIVATENEW ID3D11UnorderedAccessView*[ pDep->Count ]; + + D3DXASSERT(pDep->Count == pRange->vResources.GetSize()); + for (j=0; j<pDep->Count; ++j) + { + pDep->ppFXPointers[j] = (SUnorderedAccessView *) pRange->vResources[j]; + pDep->ppD3DObjects[j] = NULL; + } + } + + if (pShaderBlock->TBufferDepCount > 0) + { + memcpy(pShaderBlock->ppTbufDeps, &vTBuffers[0], pShaderBlock->TBufferDepCount * sizeof(SConstantBuffer*)); + } + +lExit: + return hr; +} + +// Create shader reflection interface and grab dependency info +HRESULT CEffectLoader::BuildShaderBlock(SShaderBlock *pShaderBlock) +{ + HRESULT hr = S_OK; + + // unused shader block? that's not right + VBD( pShaderBlock->pVT != NULL, "Internal loading error: NULL shader vtable." ); + + D3DXASSERT(pShaderBlock->pD3DObject == NULL); + + if (NULL == pShaderBlock->pReflectionData) + { + // File contains a shader variable without an assigned shader, or this is a null assignment. + // Usually, this is called by one of these guys: + // SetVertexShader( NULL ); + // or + // vertexshader g_VS = NULL; + return S_OK; + } + + // Initialize the reflection interface + VHD( D3DReflect( pShaderBlock->pReflectionData->pBytecode, pShaderBlock->pReflectionData->BytecodeLength, IID_ID3D11ShaderReflection, (void**)&pShaderBlock->pReflectionData->pReflection ), + "Internal loading error: cannot create shader reflection object." ); + + // Get dependencies + VH( GrabShaderData( pShaderBlock ) ); + + // Grab input signatures for VS + if( EOT_VertexShader == pShaderBlock->GetShaderType() ) + { + D3DXASSERT( pShaderBlock->pInputSignatureBlob == NULL ); + VHD( D3DGetInputSignatureBlob( pShaderBlock->pReflectionData->pBytecode, pShaderBlock->pReflectionData->BytecodeLength, &pShaderBlock->pInputSignatureBlob ), + "Internal loading error: cannot get input signature." ); + } + +lExit: + return hr; +} + +#undef PRIVATENEW + + +////////////////////////////////////////////////////////////////////////// +// Code to relocate data to private heaps (reflection & runtime effect) +// +// Important note about alignment: all reasonable chunks of data are +// machine word aligned (that is, any piece of data moved as a whole is +// aligned as a whole. This means that when computing m_ReflectionMemory +// or m_EffectMemory, each addition is aligned. This also means +// that, when later relocating that same memory, you must call MoveData +// or MoveString on the same chunks that were aligned. This is +// because: Align(a * b) != a * Align(b). +////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////// +// Reflection reallocation code +////////////////////////////////////////////////////////////////////////// + +HRESULT CEffectLoader::CalculateAnnotationSize(UINT cAnnotations, SAnnotation *pAnnotations) +{ + HRESULT hr = S_OK; + UINT i; + + m_ReflectionMemory += AlignToPowerOf2(cAnnotations * sizeof(SAnnotation), c_DataAlignment); + for (i=0; i<cAnnotations; i++) + { + if (pAnnotations[i].pType->BelongsInConstantBuffer()) + { + m_ReflectionMemory += AlignToPowerOf2(pAnnotations[i].pType->TotalSize, c_DataAlignment); + } + else + { + VBD( pAnnotations[i].pType->IsObjectType(EOT_String), "Invalid pEffectBuffer: invalid annotation type." ); + + UINT cElements; + cElements = max(1, pAnnotations[i].pType->Elements); + + m_ReflectionMemory += AlignToPowerOf2(cElements * sizeof(SString), c_DataAlignment); + + } + } + +lExit: + return hr; +} + +HRESULT CEffectLoader::ReallocateAnnotationData(UINT cAnnotations, SAnnotation **ppAnnotations) +{ + HRESULT hr = S_OK; + UINT i; + SAnnotation *pAnnotations; + + VHD( m_pReflection->m_Heap.MoveData((void**) ppAnnotations, cAnnotations * sizeof(SAnnotation)), + "Internal loading error: cannot move annotation data." ); + pAnnotations = *ppAnnotations; + + for (i=0; i<cAnnotations; i++) + { + SAnnotation *pAn = &pAnnotations[i]; + pAn->pEffect = m_pEffect; + + VHD( m_pReflection->m_Heap.MoveString(&pAn->pName), "Internal loading error: cannot move annotation name." ); + + // Reallocate type later + if (pAn->pType->BelongsInConstantBuffer()) + { + VHD( m_pReflection->m_Heap.MoveData( &pAn->Data.pGeneric, pAn->pType->TotalSize ), "Internal loading error: cannot move annotation data." ); + } + else if (pAnnotations[i].pType->IsObjectType(EOT_String)) + { + UINT j; + UINT cElements = max(1, pAn->pType->Elements); + + VHD( m_pReflection->m_Heap.MoveData((void**) &pAn->Data.pString, cElements * sizeof(SString)), "Internal loading error: cannot move annotation string." ); + for (j = 0; j < cElements; ++ j) + { + VHD( m_pReflection->m_Heap.MoveString(&pAn->Data.pString[j].pString), "Internal loading error: cannot move annotation string element." ); + } + } + else + { + VHD( E_FAIL, "Invalid pEffectBuffer: invalid annotation type." ); + } + } + +lExit: + return hr; +} + +HRESULT CEffectLoader::InitializeReflectionDataAndMoveStrings( UINT KnownSize ) +{ + HRESULT hr = S_OK; + UINT i, j, k; + UINT cbStrings; + CEffectHeap *pHeap = &m_pReflection->m_Heap; + + // Get byte counts + cbStrings = m_pEffect->m_StringCount * sizeof( SString ); + + if( KnownSize ) + { + m_ReflectionMemory = KnownSize; + } + else + { + m_ReflectionMemory += AlignToPowerOf2(cbStrings, c_DataAlignment); + + for (i=0; i<m_pEffect->m_CBCount; i++) + { + VH( CalculateAnnotationSize(m_pEffect->m_pCBs[i].AnnotationCount, m_pEffect->m_pCBs[i].pAnnotations) ); + } + + for (i=0; i<m_pEffect->m_VariableCount; i++) + { + VH( CalculateAnnotationSize(m_pEffect->m_pVariables[i].AnnotationCount, m_pEffect->m_pVariables[i].pAnnotations) ); + } + + for (i=0; i<m_pEffect->m_GroupCount; i++) + { + VH( CalculateAnnotationSize(m_pEffect->m_pGroups[i].AnnotationCount, m_pEffect->m_pGroups[i].pAnnotations) ); + + for (j=0; j<m_pEffect->m_pGroups[i].TechniqueCount; j++) + { + VH( CalculateAnnotationSize(m_pEffect->m_pGroups[i].pTechniques[j].AnnotationCount, m_pEffect->m_pGroups[i].pTechniques[j].pAnnotations) ); + + for (k=0; k<m_pEffect->m_pGroups[i].pTechniques[j].PassCount; k++) + { + VH( CalculateAnnotationSize(m_pEffect->m_pGroups[i].pTechniques[j].pPasses[k].AnnotationCount, m_pEffect->m_pGroups[i].pTechniques[j].pPasses[k].pAnnotations) ); + } + } + } + + // Calculate shader reflection data size + for (i=0; i<m_pEffect->m_ShaderBlockCount; i++) + { + if (NULL != m_pEffect->m_pShaderBlocks[i].pReflectionData) + { + m_ReflectionMemory += AlignToPowerOf2(sizeof(SShaderBlock::SReflectionData), c_DataAlignment); + m_ReflectionMemory += AlignToPowerOf2(m_pEffect->m_pShaderBlocks[i].pReflectionData->BytecodeLength, c_DataAlignment); + // stream out decl is handled as a string, and thus its size is already factored because of GetStringAndAddToReflection + } + } + } + + VHD( pHeap->ReserveMemory(m_ReflectionMemory), "Internal loading error: failed to reserve reflection memory." ); + + // Strings are handled separately because we are moving them to reflection + m_pOldStrings = m_pEffect->m_pStrings; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pStrings, cbStrings), "Internal loading error: cannot move string data." ); + for(i=0; i<m_pEffect->m_StringCount; i++) + { + VHD( pHeap->MoveString( &m_pEffect->m_pStrings[i].pString), "Internal loading error: cannot move string pointer." ); + } + +lExit: + return hr; +} + +// Move all reflection data to private heap +HRESULT CEffectLoader::ReallocateReflectionData( bool Cloning ) +{ + HRESULT hr = S_OK; + UINT i, j, k; + CEffectHeap *pHeap = &m_pReflection->m_Heap; + + for(i=0; i<m_pEffect->m_CBCount; i++) + { + VHD( pHeap->MoveString( &m_pEffect->m_pCBs[i].pName ), "Internal loading error: cannot move CB name." ); + VH( ReallocateAnnotationData(m_pEffect->m_pCBs[i].AnnotationCount, &m_pEffect->m_pCBs[i].pAnnotations) ); + } + + for(i=0; i<m_pEffect->m_VariableCount; i++) + { + VHD( pHeap->MoveString( &m_pEffect->m_pVariables[i].pName ), "Internal loading error: cannot move variable name." ); + VHD( pHeap->MoveString( &m_pEffect->m_pVariables[i].pSemantic ), "Internal loading error: cannot move variable semantic." ); + VH( ReallocateAnnotationData(m_pEffect->m_pVariables[i].AnnotationCount, &m_pEffect->m_pVariables[i].pAnnotations) ); + } + + for(i=0; i<m_pEffect->m_GroupCount; i++) + { + VHD( pHeap->MoveString( &m_pEffect->m_pGroups[i].pName ), "Internal loading error: cannot move group name." ); + VH( ReallocateAnnotationData(m_pEffect->m_pGroups[i].AnnotationCount, &m_pEffect->m_pGroups[i].pAnnotations) ); + + for(j=0; j<m_pEffect->m_pGroups[i].TechniqueCount; j++) + { + VHD( pHeap->MoveString( &m_pEffect->m_pGroups[i].pTechniques[j].pName ), "Internal loading error: cannot move technique name." ); + VH( ReallocateAnnotationData(m_pEffect->m_pGroups[i].pTechniques[j].AnnotationCount, &m_pEffect->m_pGroups[i].pTechniques[j].pAnnotations) ); + + for(k=0; k<m_pEffect->m_pGroups[i].pTechniques[j].PassCount; k++) + { + VHD( pHeap->MoveString( &m_pEffect->m_pGroups[i].pTechniques[j].pPasses[k].pName ), "Internal loading error: cannot move pass name." ); + VH( ReallocateAnnotationData(m_pEffect->m_pGroups[i].pTechniques[j].pPasses[k].AnnotationCount, &m_pEffect->m_pGroups[i].pTechniques[j].pPasses[k].pAnnotations) ); + } + } + } + + if( !Cloning ) + { + // When not cloning, every member in m_pMemberInterfaces is from a global variable, so we can take pName and pSemantic + // from the parent variable, which were updated above + for (i = 0; i < m_pEffect->m_pMemberInterfaces.GetSize(); ++ i) + { + SMember* pMember = m_pEffect->m_pMemberInterfaces[i]; + SGlobalVariable* pTopLevelEntity = (SGlobalVariable*)pMember->pTopLevelEntity; + VH( FixupVariablePointer( &pTopLevelEntity ) ); + pMember->pName = pTopLevelEntity->pName; + pMember->pSemantic = pTopLevelEntity->pSemantic; + } + } + + // Move shader bytecode + for (i=0; i<m_pEffect->m_ShaderBlockCount; i++) + { + if (NULL != m_pEffect->m_pShaderBlocks[i].pReflectionData) + { + VHD( pHeap->MoveData((void**)&m_pEffect->m_pShaderBlocks[i].pReflectionData, sizeof(SShaderBlock::SReflectionData)), + "Internal loading error: cannot move shader reflection block." ); + VHD( pHeap->MoveData((void**)&m_pEffect->m_pShaderBlocks[i].pReflectionData->pBytecode, m_pEffect->m_pShaderBlocks[i].pReflectionData->BytecodeLength), + "Internal loading error: cannot move shader bytecode."); + for( UINT iDecl=0; iDecl < D3D11_SO_STREAM_COUNT; ++iDecl ) + { + VHD( pHeap->MoveString(&m_pEffect->m_pShaderBlocks[i].pReflectionData->pStreamOutDecls[iDecl]), "Internal loading error: cannot move SO decl." ); + } + VH( pHeap->MoveInterfaceParameters(m_pEffect->m_pShaderBlocks[i].pReflectionData->InterfaceParameterCount, &m_pEffect->m_pShaderBlocks[i].pReflectionData->pInterfaceParameters ) ); + } + + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// Runtime effect reallocation code +////////////////////////////////////////////////////////////////////////// + +template<class T> HRESULT CEffectLoader::ReallocateBlockAssignments(T* &pBlocks, UINT cBlocks, T* pOldBlocks) +{ + HRESULT hr = S_OK; + CEffectHeap *pHeap = &m_pEffect->m_Heap; + UINT i, j; + + for(i=0; i<cBlocks; i++) + { + T *pBlock = &pBlocks[i]; + VHD( pHeap->MoveData((void**) &pBlock->pAssignments, sizeof(SAssignment)*pBlock->AssignmentCount), "Internal loading error: cannot move assignment count." ); + + for (j=0; j<pBlock->AssignmentCount; j++) + { + SAssignment *pAssignment = &pBlock->pAssignments[j]; + UINT cbDeps; + + // When cloning, convert pointers back into offsets + if( pOldBlocks ) + { + T *pOldBlock = &pOldBlocks[i]; + pAssignment->Destination.Offset = (UINT)( (UINT_PTR)pAssignment->Destination.pGeneric - (UINT_PTR)pOldBlock ) ; + } + + // Convert destination pointers from offset to real pointer + pAssignment->Destination.pGeneric = (BYTE*) pBlock + pAssignment->Destination.Offset; + + // Make sure the data pointer points into the backing store + VBD( pAssignment->Destination.pGeneric >= &pBlock->BackingStore && + pAssignment->Destination.pGeneric < (BYTE*) &pBlock->BackingStore + sizeof(pBlock->BackingStore), + "Internal loading error: assignment destination out of range." ); + + // Fixup dependencies + cbDeps = pAssignment->DependencyCount * sizeof(SAssignment::SDependency); + VHD( pHeap->MoveData((void**) &pAssignment->pDependencies, cbDeps), "Internal loading error: cannot move assignment dependencies." ); + + SGlobalVariable *pOldVariable = NULL; + for(UINT iDep=0; iDep<pAssignment->DependencyCount; iDep++) + { + SAssignment::SDependency *pDep = &pAssignment->pDependencies[iDep]; + // We ignore all but the last variable because below, we only use the last dependency + pOldVariable = pDep->pVariable; + VH( FixupVariablePointer(&pDep->pVariable) ); + } + + // Fixup source pointers + switch(pAssignment->LhsType) + { + case ELHS_VertexShaderBlock: + case ELHS_PixelShaderBlock: + case ELHS_GeometryShaderBlock: + case ELHS_HullShaderBlock: + case ELHS_DomainShaderBlock: + case ELHS_ComputeShaderBlock: + VH( FixupShaderPointer(&pAssignment->Source.pShader) ); + break; + + case ELHS_DepthStencilBlock: + VH( FixupDSPointer((SDepthStencilBlock**)&pAssignment->Source.pBlock) ); + break; + case ELHS_BlendBlock: + VH( FixupABPointer((SBlendBlock**) &pAssignment->Source.pBlock) ); + break; + case ELHS_RasterizerBlock: + VH( FixupRSPointer((SRasterizerBlock**) &pAssignment->Source.pBlock) ); + break; + + case ELHS_Texture: + VH( FixupShaderResourcePointer((SShaderResource**) &pAssignment->Source.pShaderResource) ); + break; + + default: + // Non-object assignment (must have at least one dependency or it would have been pruned by now) + D3DXASSERT( !pAssignment->IsObjectAssignment() && pAssignment->DependencyCount > 0 ); + + // Numeric variables must be relocated before this function is called + + switch (pAssignment->AssignmentType) + { + case ERAT_NumericVariable: + case ERAT_NumericVariableIndex: + // the variable or variable array is always the last dependency in the chain + SGlobalVariable *pVariable; + pVariable = pAssignment->pDependencies[pAssignment->DependencyCount - 1].pVariable; + D3DXASSERT( pVariable->pType->BelongsInConstantBuffer() && NULL != pVariable->pCB ); + + // When cloning, convert pointers back into offsets + if( pOldBlocks ) + { + VBD( pOldVariable != NULL, "Internal loading error: pOldVariable is NULL." ); + pAssignment->Source.Offset = pAssignment->Source.pNumeric - pOldVariable->pCB->pBackingStore; + } + + // Convert from offset to pointer + pAssignment->Source.pNumeric = pVariable->pCB->pBackingStore + pAssignment->Source.Offset; + break; + + default: + // Shouldn't be able to get here + D3DXASSERT(0); + VHD( E_FAIL, "Loading error: invalid assignment type." ); + } + break; + + case ELHS_Invalid: + VHD( E_FAIL, "Loading error: invalid assignment type." ); + } + + D3DXASSERT(m_pEffect->m_LocalTimer > 0); + m_pEffect->EvaluateAssignment(pAssignment); + } + } + +lExit: + return hr; +} + +template<class T> UINT CEffectLoader::CalculateBlockAssignmentSize(T* &pBlocks, UINT cBlocks) +{ + UINT dwSize = 0; + UINT i, j; + + for(i=0; i<cBlocks; i++) + { + SBaseBlock *pBlock = &pBlocks[i]; + dwSize += AlignToPowerOf2(pBlock->AssignmentCount * sizeof(SAssignment), c_DataAlignment); + + for (j=0; j<pBlock->AssignmentCount; j++) + { + SAssignment *pAssignment = &pBlock->pAssignments[j]; + + dwSize += AlignToPowerOf2(pAssignment->DependencyCount * sizeof(SAssignment::SDependency), c_DataAlignment); + } + } + + return dwSize; +} + +HRESULT CEffectLoader::ReallocateShaderBlocks() +{ + HRESULT hr = S_OK; + UINT i, j, k; + CEffectHeap *pHeap = &m_pEffect->m_Heap; + const char* pError = "Internal loading error: cannot move shader data."; + + for (i=0; i<m_pEffect->m_ShaderBlockCount; i++) + { + SShaderBlock *pShader = &m_pEffect->m_pShaderBlocks[i]; + + // pShader->pReflection data and all of its members (bytecode, SO decl, etc.) are handled by ReallocateReflectionData() + VHD( pHeap->MoveData((void**) &pShader->pCBDeps, pShader->CBDepCount * sizeof(SShaderCBDependency)), pError ); + VHD( pHeap->MoveData((void**) &pShader->pSampDeps, pShader->SampDepCount * sizeof(SShaderSamplerDependency)), pError ); + VHD( pHeap->MoveData((void**) &pShader->pInterfaceDeps, pShader->InterfaceDepCount * sizeof(SInterfaceDependency)), pError ); + VHD( pHeap->MoveData((void**) &pShader->pResourceDeps, pShader->ResourceDepCount * sizeof(SShaderResourceDependency)), pError ); + VHD( pHeap->MoveData((void**) &pShader->pUAVDeps, pShader->UAVDepCount * sizeof(SUnorderedAccessViewDependency)), pError ); + VHD( pHeap->MoveData((void**) &pShader->ppTbufDeps, pShader->TBufferDepCount * sizeof(SConstantBuffer*)), pError ); + + for (j=0; j<pShader->CBDepCount; j++) + { + SShaderCBDependency *pCBDeps = &pShader->pCBDeps[j]; + VHD( pHeap->MoveData((void**) &pCBDeps->ppD3DObjects, pCBDeps->Count * sizeof(ID3D11Buffer*)), pError ); + VHD( pHeap->MoveData((void**) &pCBDeps->ppFXPointers, pCBDeps->Count * sizeof(SConstantBuffer*)), pError ); + + for (k=0; k<pCBDeps->Count; k++) + { + VH( FixupCBPointer( &pCBDeps->ppFXPointers[k] ) ); + } + } + + for (j=0; j<pShader->SampDepCount; j++) + { + SShaderSamplerDependency *pSampDeps = &pShader->pSampDeps[j]; + VHD( pHeap->MoveData((void**) &pSampDeps->ppD3DObjects, pSampDeps->Count * sizeof(ID3D11SamplerState*)), pError ); + VHD( pHeap->MoveData((void**) &pSampDeps->ppFXPointers, pSampDeps->Count * sizeof(SSamplerBlock*)), pError ); + + for (k=0; k<pSampDeps->Count; k++) + { + VH( FixupSamplerPointer(&pSampDeps->ppFXPointers[k]) ); + } + } + + for (j=0; j<pShader->InterfaceDepCount; j++) + { + SInterfaceDependency *pInterfaceDeps = &pShader->pInterfaceDeps[j]; + VHD( pHeap->MoveData((void**) &pInterfaceDeps->ppD3DObjects, pInterfaceDeps->Count * sizeof(ID3D11ClassInstance*)), pError ); + VHD( pHeap->MoveData((void**) &pInterfaceDeps->ppFXPointers, pInterfaceDeps->Count * sizeof(SInterface*)), pError ); + + for (k=0; k<pInterfaceDeps->Count; k++) + { + VH( FixupInterfacePointer(&pInterfaceDeps->ppFXPointers[k], true) ); + } + } + + for (j=0; j<pShader->ResourceDepCount; j++) + { + SShaderResourceDependency *pResourceDeps = &pShader->pResourceDeps[j]; + VHD( pHeap->MoveData((void**) &pResourceDeps->ppD3DObjects, pResourceDeps->Count * sizeof(ID3D11ShaderResourceView*)), pError ); + VHD( pHeap->MoveData((void**) &pResourceDeps->ppFXPointers, pResourceDeps->Count * sizeof(SShaderResource*)), pError ); + + for (k=0; k<pResourceDeps->Count; k++) + { + VH( FixupShaderResourcePointer(&pResourceDeps->ppFXPointers[k]) ); + } + } + + for (j=0; j<pShader->UAVDepCount; j++) + { + SUnorderedAccessViewDependency *pUAVDeps = &pShader->pUAVDeps[j]; + VHD( pHeap->MoveData((void**) &pUAVDeps->ppD3DObjects, pUAVDeps->Count * sizeof(ID3D11UnorderedAccessView*)), pError ); + VHD( pHeap->MoveData((void**) &pUAVDeps->ppFXPointers, pUAVDeps->Count * sizeof(SUnorderedAccessView*)), pError ); + + for (k=0; k<pUAVDeps->Count; k++) + { + VH( FixupUnorderedAccessViewPointer(&pUAVDeps->ppFXPointers[k]) ); + } + } + + for (j=0; j<pShader->TBufferDepCount; j++) + { + VH( FixupCBPointer( &pShader->ppTbufDeps[j] ) ); + } + } + +lExit: + return hr; +} + + +UINT CEffectLoader::CalculateShaderBlockSize() +{ + UINT dwSize = 0; + UINT i, j; + + for (i=0; i<m_pEffect->m_ShaderBlockCount; i++) + { + SShaderBlock *pShader = &m_pEffect->m_pShaderBlocks[i]; + + dwSize += AlignToPowerOf2(pShader->CBDepCount * sizeof(SShaderCBDependency), c_DataAlignment); + dwSize += AlignToPowerOf2(pShader->SampDepCount * sizeof(SShaderSamplerDependency), c_DataAlignment); + dwSize += AlignToPowerOf2(pShader->InterfaceDepCount * sizeof(SInterfaceDependency), c_DataAlignment); + dwSize += AlignToPowerOf2(pShader->ResourceDepCount * sizeof(SShaderResourceDependency), c_DataAlignment); + dwSize += AlignToPowerOf2(pShader->UAVDepCount * sizeof(SUnorderedAccessViewDependency), c_DataAlignment); + dwSize += AlignToPowerOf2(pShader->TBufferDepCount * sizeof(SConstantBuffer*), c_DataAlignment); + + for (j=0; j<pShader->CBDepCount; j++) + { + SShaderCBDependency *pCBDeps = &pShader->pCBDeps[j]; + dwSize += AlignToPowerOf2(pCBDeps->Count * sizeof(ID3D11Buffer*), c_DataAlignment); + dwSize += AlignToPowerOf2(pCBDeps->Count * sizeof(SConstantBuffer*), c_DataAlignment); + } + + for (j=0; j<pShader->SampDepCount; j++) + { + SShaderSamplerDependency *pSampDeps = &pShader->pSampDeps[j]; + dwSize += AlignToPowerOf2(pSampDeps->Count * sizeof(ID3D11SamplerState*), c_DataAlignment); + dwSize += AlignToPowerOf2(pSampDeps->Count * sizeof(SSamplerBlock*), c_DataAlignment); + } + + for (j=0; j<pShader->InterfaceDepCount; j++) + { + SInterfaceDependency *pInterfaceDeps = &pShader->pInterfaceDeps[j]; + dwSize += AlignToPowerOf2(pInterfaceDeps->Count * sizeof(ID3D11ClassInstance*), c_DataAlignment); + dwSize += AlignToPowerOf2(pInterfaceDeps->Count * sizeof(SInterface*), c_DataAlignment); + } + + for (j=0; j<pShader->ResourceDepCount; j++) + { + SShaderResourceDependency *pResourceDeps = &pShader->pResourceDeps[j]; + dwSize += AlignToPowerOf2(pResourceDeps->Count * sizeof(ID3D11ShaderResourceView*), c_DataAlignment); + dwSize += AlignToPowerOf2(pResourceDeps->Count * sizeof(SShaderResource*), c_DataAlignment); + } + + for (j=0; j<pShader->UAVDepCount; j++) + { + SUnorderedAccessViewDependency *pUAVDeps = &pShader->pUAVDeps[j]; + dwSize += AlignToPowerOf2(pUAVDeps->Count * sizeof(ID3D11UnorderedAccessView*), c_DataAlignment); + dwSize += AlignToPowerOf2(pUAVDeps->Count * sizeof(SUnorderedAccessView*), c_DataAlignment); + } + } + + return dwSize; +} + +// Move all (non-reflection) effect data to private heap +HRESULT CEffectLoader::ReallocateEffectData( bool Cloning ) +{ + HRESULT hr = S_OK; + UINT i, j; + CEffectHeap *pHeap = &m_pEffect->m_Heap; + UINT cbCBs = sizeof(SConstantBuffer) * m_pEffect->m_CBCount; + UINT cbVariables = sizeof(SGlobalVariable) * m_pEffect->m_VariableCount; + UINT cbGroups = sizeof(STechnique) * m_pEffect->m_GroupCount; + UINT cbShaders = sizeof(SShaderBlock) * m_pEffect->m_ShaderBlockCount; + UINT cbDS = sizeof(SDepthStencilBlock) * m_pEffect->m_DepthStencilBlockCount; + UINT cbAB = sizeof(SBlendBlock) * m_pEffect->m_BlendBlockCount; + UINT cbRS = sizeof(SRasterizerBlock) * m_pEffect->m_RasterizerBlockCount; + UINT cbSamplers = sizeof(SSamplerBlock) * m_pEffect->m_SamplerBlockCount; + UINT cbMemberDatas = sizeof(SMemberDataPointer) * m_pEffect->m_MemberDataCount; + UINT cbInterfaces = sizeof(SInterface) * m_pEffect->m_InterfaceCount; + UINT cbBackgroundInterfaces = sizeof(SInterface) * m_BackgroundInterfaces.GetSize(); + UINT cbShaderResources = sizeof(SShaderResource) * m_pEffect->m_ShaderResourceCount; + UINT cbUnorderedAccessViews = sizeof(SUnorderedAccessView) * m_pEffect->m_UnorderedAccessViewCount; + UINT cbRenderTargetViews = sizeof(SRenderTargetView) * m_pEffect->m_RenderTargetViewCount; + UINT cbDepthStencilViews = sizeof(SDepthStencilView) * m_pEffect->m_DepthStencilViewCount; + UINT cbAnonymousShaders = sizeof(SAnonymousShader) * m_pEffect->m_AnonymousShaderCount; + + // Calculate memory needed + m_EffectMemory += AlignToPowerOf2(cbCBs, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbVariables, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbGroups, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbShaders, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbMemberDatas, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbInterfaces + cbBackgroundInterfaces, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbShaderResources, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbUnorderedAccessViews, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbRenderTargetViews, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbDepthStencilViews, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbDS, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbAB, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbRS, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbSamplers, c_DataAlignment); + m_EffectMemory += AlignToPowerOf2(cbAnonymousShaders, c_DataAlignment); + + m_EffectMemory += CalculateShaderBlockSize(); + + for (i=0; i<m_pEffect->m_CBCount; i++) + { + SConstantBuffer *pCB = &m_pEffect->m_pCBs[i]; + + m_EffectMemory += AlignToPowerOf2(pCB->Size, c_DataAlignment); + } + + for (i=0; i<m_pEffect->m_GroupCount; i++) + { + SGroup *pGroup = &m_pEffect->m_pGroups[i]; + + m_EffectMemory += AlignToPowerOf2(pGroup->TechniqueCount * sizeof(STechnique), c_DataAlignment); + + for (j=0; j<pGroup->TechniqueCount; j++) + { + STechnique *pTech = &pGroup->pTechniques[j]; + + m_EffectMemory += AlignToPowerOf2(pTech->PassCount * sizeof(SPassBlock), c_DataAlignment); + m_EffectMemory += CalculateBlockAssignmentSize(pTech->pPasses, pTech->PassCount); + } + }; + + m_EffectMemory += CalculateBlockAssignmentSize(m_pEffect->m_pBlendBlocks, m_pEffect->m_BlendBlockCount); + m_EffectMemory += CalculateBlockAssignmentSize(m_pEffect->m_pDepthStencilBlocks, m_pEffect->m_DepthStencilBlockCount); + m_EffectMemory += CalculateBlockAssignmentSize(m_pEffect->m_pRasterizerBlocks, m_pEffect->m_RasterizerBlockCount); + m_EffectMemory += CalculateBlockAssignmentSize(m_pEffect->m_pSamplerBlocks, m_pEffect->m_SamplerBlockCount); + + // Reserve memory + VHD( pHeap->ReserveMemory(m_EffectMemory), "Internal loading error: cannot reserve effect memory." ); + + // Move DataMemberPointer blocks + m_pOldMemberDataBlocks = m_pEffect->m_pMemberDataBlocks; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pMemberDataBlocks, cbMemberDatas), "Internal loading error: cannot move member data blocks." ); + + // Move CBs + m_pOldCBs = m_pEffect->m_pCBs; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pCBs, cbCBs), "Internal loading error: cannot move CB count." ); + for (i=0; i<m_pEffect->m_CBCount; i++) + { + SConstantBuffer *pCB = &m_pEffect->m_pCBs[i]; + + VHD( pHeap->MoveData((void**) &pCB->pBackingStore, pCB->Size), "Internal loading error: cannot move CB backing store." ); + + if( !Cloning ) + { + // When creating the effect, MemberDataOffsetPlus4 is used, not pMemberData + if( pCB->MemberDataOffsetPlus4 ) + { + pCB->pMemberData = (SMemberDataPointer*)( (BYTE*)m_pEffect->m_pMemberDataBlocks + ( pCB->MemberDataOffsetPlus4 - 4 ) ); + } + } + else if (pCB->pMemberData) + { + // When cloning an effect, pMemberData points to valid data in the original effect + VH( FixupMemberDataPointer( &pCB->pMemberData ) ); + } + } + + // Move numeric variables; move all variable types + m_pOldVars = m_pEffect->m_pVariables; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pVariables, cbVariables), "Internal loading error: cannot move variable count." ); + for (i=0; i<m_pEffect->m_VariableCount; i++) + { + SGlobalVariable *pVar = &m_pEffect->m_pVariables[i]; + pVar->pEffect = m_pEffect; + + if( Cloning && pVar->pType->BelongsInConstantBuffer()) + { + // Convert pointer back to offset + // pVar->pCB refers to the old CB + pVar->Data.Offset = (UINT_PTR)pVar->Data.pGeneric - (UINT_PTR)pVar->pCB->pBackingStore; + } + + if (pVar->pCB) + { + VH( FixupCBPointer( &pVar->pCB ) ); + } + + if( !Cloning ) + { + // When creating the effect, MemberDataOffsetPlus4 is used, not pMemberData + if( pVar->MemberDataOffsetPlus4 ) + { + pVar->pMemberData = (SMemberDataPointer*)( (BYTE*)m_pEffect->m_pMemberDataBlocks + ( pVar->MemberDataOffsetPlus4 - 4 ) ); + } + } + else if (pVar->pMemberData) + { + // When cloning an effect, pMemberData points to valid data in the original effect + VH( FixupMemberDataPointer( &pVar->pMemberData ) ); + } + + if (pVar->pType->BelongsInConstantBuffer()) + { + // Convert from offsets to pointers + pVar->Data.pGeneric = pVar->pCB->pBackingStore + pVar->Data.Offset; + } + } + + // Fixup each CB's array of child variable pointers + for (i=0; i<m_pEffect->m_CBCount; i++) + { + SConstantBuffer *pCB = &m_pEffect->m_pCBs[i]; + pCB->pEffect = m_pEffect; + + if (pCB->pVariables != NULL) + { + VH( FixupVariablePointer(&pCB->pVariables) ); + } + } + + // Move shaders + m_pOldShaders = m_pEffect->m_pShaderBlocks; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pShaderBlocks, cbShaders), "Internal loading error: cannot move shader count." ); + + // Move interfaces, combining global interfaces and those that were created during shader initialization + m_pOldInterfaces = m_pEffect->m_pInterfaces; + m_OldInterfaceCount = m_pEffect->m_InterfaceCount; + VHD( pHeap->MoveEmptyDataBlock((void**) &m_pEffect->m_pInterfaces, cbInterfaces + cbBackgroundInterfaces), "Internal loading error: cannot move shader." ); + memcpy( m_pEffect->m_pInterfaces, m_pOldInterfaces, cbInterfaces ); + for( i=0; i < m_BackgroundInterfaces.GetSize(); i++ ) + { + D3DXASSERT( m_BackgroundInterfaces[i] != NULL ); + BYTE* pDst = (BYTE*)m_pEffect->m_pInterfaces + ( m_pEffect->m_InterfaceCount * sizeof(SInterface) ); + memcpy( pDst, m_BackgroundInterfaces[i], sizeof(SInterface) ); + m_pEffect->m_InterfaceCount++; + } + + m_pOldShaderResources = m_pEffect->m_pShaderResources; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pShaderResources, cbShaderResources), "Internal loading error: cannot move SRVs." ); + + m_pOldUnorderedAccessViews = m_pEffect->m_pUnorderedAccessViews; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pUnorderedAccessViews, cbUnorderedAccessViews), "Internal loading error: cannot move UAVS." ); + + m_pOldRenderTargetViews = m_pEffect->m_pRenderTargetViews; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pRenderTargetViews, cbRenderTargetViews), "Internal loading error: cannot move RTVs." ); + + m_pOldDepthStencilViews = m_pEffect->m_pDepthStencilViews; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pDepthStencilViews, cbDepthStencilViews), "Internal loading error: cannot move DSVs." ); + + m_pOldDS = m_pEffect->m_pDepthStencilBlocks; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pDepthStencilBlocks, cbDS), "Internal loading error: cannot move depth-stencil state blocks." ); + VH( ReallocateBlockAssignments(m_pEffect->m_pDepthStencilBlocks, m_pEffect->m_DepthStencilBlockCount, Cloning ? m_pOldDS : NULL) ); + + m_pOldAB = m_pEffect->m_pBlendBlocks; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pBlendBlocks, cbAB), "Internal loading error: cannot move blend state blocks." ); + VH( ReallocateBlockAssignments(m_pEffect->m_pBlendBlocks, m_pEffect->m_BlendBlockCount, Cloning ? m_pOldAB : NULL) ); + + m_pOldRS = m_pEffect->m_pRasterizerBlocks; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pRasterizerBlocks, cbRS), "Internal loading error: cannot move rasterizer state blocks." ); + VH( ReallocateBlockAssignments(m_pEffect->m_pRasterizerBlocks, m_pEffect->m_RasterizerBlockCount, Cloning ? m_pOldRS : NULL) ); + + m_pOldSamplers = m_pEffect->m_pSamplerBlocks; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pSamplerBlocks, cbSamplers), "Internal loading error: cannot move samplers." ); + VH( ReallocateBlockAssignments(m_pEffect->m_pSamplerBlocks, m_pEffect->m_SamplerBlockCount, Cloning ? m_pOldSamplers : NULL) ); + + // Fixup sampler backing stores + for (i=0; i<m_pEffect->m_SamplerBlockCount; ++i) + { + VH( FixupShaderResourcePointer(&m_pEffect->m_pSamplerBlocks[i].BackingStore.pTexture) ); + } + + // Fixup each interface's class instance variable pointer + for (i=0; i<m_pEffect->m_InterfaceCount; i++) + { + SInterface *pInterface = &m_pEffect->m_pInterfaces[i]; + + if (pInterface->pClassInstance != NULL) + { + VH( FixupVariablePointer( (SGlobalVariable**)&pInterface->pClassInstance ) ); + } + } + + // Fixup pointers for non-numeric variables + for (i=0; i<m_pEffect->m_VariableCount; i++) + { + SGlobalVariable *pVar = &m_pEffect->m_pVariables[i]; + + if (pVar->pType->IsShader()) + { + VH( FixupShaderPointer(&pVar->Data.pShader) ); + } + else if (pVar->pType->IsShaderResource()) + { + VH( FixupShaderResourcePointer(&pVar->Data.pShaderResource) ); + } + else if (pVar->pType->IsUnorderedAccessView()) + { + VH( FixupUnorderedAccessViewPointer(&pVar->Data.pUnorderedAccessView) ); + } + else if (pVar->pType->IsInterface()) + { + VH( FixupInterfacePointer(&pVar->Data.pInterface, false) ); + } + else if (pVar->pType->IsObjectType(EOT_String)) + { + if( !m_pEffect->IsOptimized() ) + { + VH( FixupStringPointer(&pVar->Data.pString) ); + } + } + else if (pVar->pType->IsStateBlockObject()) + { + switch(pVar->pType->ObjectType) + { + case EOT_DepthStencil: + VH( FixupDSPointer((SDepthStencilBlock**) &pVar->Data.pBlock) ); + break; + case EOT_Blend: + VH( FixupABPointer((SBlendBlock**) &pVar->Data.pBlock) ); + break; + case EOT_Rasterizer: + VH( FixupRSPointer((SRasterizerBlock**) &pVar->Data.pBlock) ); + break; + case EOT_Sampler: + VB(pVar->pType->IsSampler()); + VH( FixupSamplerPointer((SSamplerBlock**) &pVar->Data.pBlock) ); + break; + default: + VH( E_FAIL ); + } + } + else if (pVar->pType->VarType == EVT_Struct || pVar->pType->VarType == EVT_Numeric) + { + if( pVar->pType->IsClassInstance() ) + { + // do nothing + } + else + { + // do nothing + } + } + else if (pVar->pType->IsRenderTargetView()) + { + VH( FixupRenderTargetViewPointer(&pVar->Data.pRenderTargetView) ); + } + else if (pVar->pType->IsDepthStencilView()) + { + VH( FixupDepthStencilViewPointer(&pVar->Data.pDepthStencilView) ); + } + else + { + VHD( E_FAIL, "Internal loading error: Invalid variable type." ); + } + } + + // Fixup created members + for (i = 0; i < m_pEffect->m_pMemberInterfaces.GetSize(); ++ i) + { + SMember* pMember = m_pEffect->m_pMemberInterfaces[i]; + SGlobalVariable** ppTopLevelEntity = (SGlobalVariable**)&pMember->pTopLevelEntity; + VN( *ppTopLevelEntity ); + + // This might be set to false later, for supporting textures inside classes + const bool bGlobalMemberDataBlock = true; + + if( Cloning ) + { + if( pMember->pType->BelongsInConstantBuffer() ) + { + D3DXASSERT( pMember->Data.pGeneric == NULL || (*ppTopLevelEntity)->pEffect->m_Heap.IsInHeap(pMember->Data.pGeneric) ); + pMember->Data.Offset = (UINT)( (BYTE*)pMember->Data.pGeneric - (BYTE*)(*ppTopLevelEntity)->pCB->pBackingStore ); + } + if( bGlobalMemberDataBlock && pMember->pMemberData ) + { + pMember->MemberDataOffsetPlus4 = (UINT)( (BYTE*)pMember->pMemberData - (BYTE*)(*ppTopLevelEntity)->pEffect->m_pMemberDataBlocks ) + 4; + } + } + + VH( FixupVariablePointer( ppTopLevelEntity ) ); + + if (pMember->pType->BelongsInConstantBuffer()) + { + // Convert from offsets to pointers + pMember->Data.pGeneric = (*ppTopLevelEntity)->pCB->pBackingStore + pMember->Data.Offset; + } + if( bGlobalMemberDataBlock && pMember->MemberDataOffsetPlus4 ) + { + pMember->pMemberData = (SMemberDataPointer*)( (BYTE*)m_pEffect->m_pMemberDataBlocks + ( pMember->MemberDataOffsetPlus4 - 4 ) ); + } + } + + // Fixup shader data + VH( ReallocateShaderBlocks() ); + + // Move groups, techniques, and passes + m_pOldGroups = m_pEffect->m_pGroups; + VHD( pHeap->MoveData((void**) &m_pEffect->m_pGroups, cbGroups), "Internal loading error: cannot move groups." ); + for (i=0; i<m_pEffect->m_GroupCount; i++) + { + SGroup *pGroup = &m_pEffect->m_pGroups[i]; + UINT cbTechniques; + + cbTechniques = pGroup->TechniqueCount * sizeof(STechnique); + VHD( pHeap->MoveData((void**) &pGroup->pTechniques, cbTechniques), "Internal loading error: cannot move techniques." ); + + for (j=0; j<pGroup->TechniqueCount; j++) + { + STechnique *pTech = &pGroup->pTechniques[j]; + UINT cbPass; + UINT iPass; + + cbPass = pTech->PassCount * sizeof(SPassBlock); + SPassBlock* pOldPasses = Cloning ? pTech->pPasses : NULL; + VHD( pHeap->MoveData((void**) &pTech->pPasses, cbPass), "Internal loading error: cannot move passes." ); + + for (iPass = 0; iPass < pTech->PassCount; ++ iPass) + { + pTech->pPasses[iPass].pEffect = m_pEffect; + + // Fixup backing store pointers in passes + VH( FixupABPointer((SBlendBlock**) &pTech->pPasses[iPass].BackingStore.pBlendBlock) ); + VH( FixupDSPointer((SDepthStencilBlock**) &pTech->pPasses[iPass].BackingStore.pDepthStencilBlock) ); + VH( FixupRSPointer((SRasterizerBlock**) &pTech->pPasses[iPass].BackingStore.pRasterizerBlock) ); + VH( FixupShaderPointer((SShaderBlock**) &pTech->pPasses[iPass].BackingStore.pVertexShaderBlock) ); + VH( FixupShaderPointer((SShaderBlock**) &pTech->pPasses[iPass].BackingStore.pPixelShaderBlock) ); + VH( FixupShaderPointer((SShaderBlock**) &pTech->pPasses[iPass].BackingStore.pGeometryShaderBlock) ); + VH( FixupShaderPointer((SShaderBlock**) &pTech->pPasses[iPass].BackingStore.pHullShaderBlock) ); + VH( FixupShaderPointer((SShaderBlock**) &pTech->pPasses[iPass].BackingStore.pDomainShaderBlock) ); + VH( FixupShaderPointer((SShaderBlock**) &pTech->pPasses[iPass].BackingStore.pComputeShaderBlock) ); + VH( FixupDepthStencilViewPointer( &pTech->pPasses[iPass].BackingStore.pDepthStencilView) ); + for (UINT iRT = 0; iRT < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; iRT++) + { + VH( FixupRenderTargetViewPointer( &pTech->pPasses[iPass].BackingStore.pRenderTargetViews[iRT] ) ); + } + } + + VH( ReallocateBlockAssignments( pTech->pPasses, pTech->PassCount, pOldPasses ) ); + } + } + VH( FixupGroupPointer( &m_pEffect->m_pNullGroup ) ); + + // Move anonymous shader variables + VHD( pHeap->MoveData((void **) &m_pEffect->m_pAnonymousShaders, cbAnonymousShaders), "Internal loading error: cannot move anonymous shaders." ); + for (i=0; i<m_pEffect->m_AnonymousShaderCount; ++i) + { + SAnonymousShader *pAnonymousShader = m_pEffect->m_pAnonymousShaders + i; + VH( FixupShaderPointer((SShaderBlock**) &pAnonymousShader->pShaderBlock) ); + } + + VBD( pHeap->GetSize() == m_EffectMemory, "Loading error: effect size mismatch." ); + +lExit: + return hr; +} + +} diff --git a/sample/d3d11/Effects11/EffectLoad.h b/sample/d3d11/Effects11/EffectLoad.h new file mode 100644 index 0000000..c5f5dc1 --- /dev/null +++ b/sample/d3d11/Effects11/EffectLoad.h @@ -0,0 +1,149 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectLoad.h +// Content: D3DX11 Effects header for the FX file loader +// A CEffectLoader is created at load time to facilitate loading +// +////////////////////////////////////////////////////////////////////////////// + +#pragma once + +namespace D3DX11Effects +{ + +// Ranges are used for dependency checking during load + +enum ERanges +{ + ER_CBuffer = 0, + ER_Texture, // Includes TBuffers + ER_Sampler, + ER_UnorderedAccessView, + ER_Interfaces, + ER_Count // This should be the size of the enum +}; + +struct SRange +{ + UINT start; + UINT last; + CEffectVector<void *> vResources; // should be (last - start) in length, resource type depends on the range type +}; + +// Used during load to validate assignments +D3D10_SHADER_VARIABLE_TYPE GetSimpleParameterTypeFromObjectType(EObjectType ObjectType); + + +// A class to facilitate loading an Effect. This class is a friend of CEffect. +class CEffectLoader +{ + friend HRESULT CEffect::CloneEffect(UINT Flags, ID3DX11Effect** ppClonedEffect ); + +protected: + // Load-time allocations that eventually get moved happen out of the TempHeap. This heap will grow as needed + CDataBlockStore m_BulkHeap; + + BYTE *m_pData; + SBinaryHeader5 *m_pHeader; + DWORD m_Version; + + CEffect *m_pEffect; + CEffectReflection *m_pReflection; + + D3DX11Core::CMemoryStream m_msStructured; + D3DX11Core::CMemoryStream m_msUnstructured; + + // used to avoid repeated hash buffer allocations in LoadTypeAndAddToPool + CEffectVector<BYTE> m_HashBuffer; + + UINT m_dwBufferSize; // Size of data buffer in bytes + + // List of SInterface blocks created to back class instances bound to shaders + CEffectVector<SInterface*> m_BackgroundInterfaces; + + // Pointers to pre-reallocation data + SGlobalVariable *m_pOldVars; + SShaderBlock *m_pOldShaders; + SDepthStencilBlock *m_pOldDS; + SBlendBlock *m_pOldAB; + SRasterizerBlock *m_pOldRS; + SConstantBuffer *m_pOldCBs; + SSamplerBlock *m_pOldSamplers; + UINT m_OldInterfaceCount; + SInterface *m_pOldInterfaces; + SShaderResource *m_pOldShaderResources; + SUnorderedAccessView *m_pOldUnorderedAccessViews; + SRenderTargetView *m_pOldRenderTargetViews; + SDepthStencilView *m_pOldDepthStencilViews; + SString *m_pOldStrings; + SMemberDataPointer *m_pOldMemberDataBlocks; + CEffectVectorOwner<SMember> *m_pvOldMemberInterfaces; + SGroup *m_pOldGroups; + + UINT m_EffectMemory; // Effect private heap + UINT m_ReflectionMemory; // Reflection private heap + + // Loader helpers + HRESULT LoadCBs(); + HRESULT LoadNumericVariable(SConstantBuffer *pParentCB); + HRESULT LoadObjectVariables(); + HRESULT LoadInterfaceVariables(); + + HRESULT LoadTypeAndAddToPool(SType **ppType, UINT dwOffset); + HRESULT LoadStringAndAddToPool(__out_ecount_full(1) char **ppString, UINT dwOffset); + HRESULT LoadAssignments( UINT Assignments, SAssignment **pAssignments, BYTE *pBackingStore, UINT *pRTVAssignments, UINT *pFinalAssignments ); + HRESULT LoadGroups(); + HRESULT LoadTechnique( STechnique* pTech ); + HRESULT LoadAnnotations(UINT *pcAnnotations, SAnnotation **ppAnnotations); + + HRESULT ExecuteConstantAssignment(SBinaryConstant *pConstant, void *pLHS, D3D10_SHADER_VARIABLE_TYPE lhsType); + UINT UnpackData(BYTE *pDestData, BYTE *pSrcData, UINT PackedDataSize, SType *pType, UINT *pBytesRead); + + // Build shader blocks + HRESULT ConvertRangesToBindings(SShaderBlock *pShaderBlock, CEffectVector<SRange> *pvRanges ); + HRESULT GrabShaderData(SShaderBlock *pShaderBlock); + HRESULT BuildShaderBlock(SShaderBlock *pShaderBlock); + + // Memory compactors + HRESULT InitializeReflectionDataAndMoveStrings( UINT KnownSize = 0 ); + HRESULT ReallocateReflectionData( bool Cloning = false ); + HRESULT ReallocateEffectData( bool Cloning = false ); + HRESULT ReallocateShaderBlocks(); + template<class T> HRESULT ReallocateBlockAssignments(T* &pBlocks, UINT cBlocks, T* pOldBlocks = NULL); + HRESULT ReallocateAnnotationData(UINT cAnnotations, SAnnotation **ppAnnotations); + + HRESULT CalculateAnnotationSize(UINT cAnnotations, SAnnotation *pAnnotations); + UINT CalculateShaderBlockSize(); + template<class T> UINT CalculateBlockAssignmentSize(T* &pBlocks, UINT cBlocks); + + HRESULT FixupCBPointer(SConstantBuffer **ppCB); + HRESULT FixupShaderPointer(SShaderBlock **ppShaderBlock); + HRESULT FixupDSPointer(SDepthStencilBlock **ppDSBlock); + HRESULT FixupABPointer(SBlendBlock **ppABBlock); + HRESULT FixupRSPointer(SRasterizerBlock **ppRSBlock); + HRESULT FixupInterfacePointer(SInterface **ppInterface, bool CheckBackgroundInterfaces); + HRESULT FixupShaderResourcePointer(SShaderResource **ppResource); + HRESULT FixupUnorderedAccessViewPointer(SUnorderedAccessView **ppResource); + HRESULT FixupRenderTargetViewPointer(SRenderTargetView **ppRenderTargetView); + HRESULT FixupDepthStencilViewPointer(SDepthStencilView **ppDepthStencilView); + HRESULT FixupSamplerPointer(SSamplerBlock **ppSampler); + HRESULT FixupVariablePointer(SGlobalVariable **ppVar); + HRESULT FixupStringPointer(SString **ppString); + HRESULT FixupMemberDataPointer(SMemberDataPointer **ppMemberData); + HRESULT FixupGroupPointer(SGroup **ppGroup); + + // Methods to retrieve data from the unstructured block + // (these do not make copies; they simply return pointers into the block) + HRESULT GetStringAndAddToReflection(UINT offset, __out_ecount_full(1) char **ppPointer); // Returns a string from the file string block, updates m_EffectMemory + HRESULT GetUnstructuredDataBlock(UINT offset, UINT *pdwSize, void **ppData); + // This function makes a copy of the array of SInterfaceParameters, but not a copy of the strings + HRESULT GetInterfaceParametersAndAddToReflection( UINT InterfaceCount, UINT offset, __out_ecount_full(1) SShaderBlock::SInterfaceParameter **ppInterfaces ); +public: + + HRESULT LoadEffect(CEffect *pEffect, CONST void *pEffectBuffer, UINT cbEffectBuffer); +}; + + +}
\ No newline at end of file diff --git a/sample/d3d11/Effects11/EffectNonRuntime.cpp b/sample/d3d11/Effects11/EffectNonRuntime.cpp new file mode 100644 index 0000000..5484d50 --- /dev/null +++ b/sample/d3d11/Effects11/EffectNonRuntime.cpp @@ -0,0 +1,2963 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectNonRuntime.cpp +// Content: D3DX11 Effect low-frequency utility functions +// These functions are not intended to be called regularly. They +// are typically called when creating, cloning, or optimizing an +// Effect, or reflecting a variable. +// +////////////////////////////////////////////////////////////////////////////// + +#include "pchfx.h" +#include "SOParser.h" + +namespace D3DX11Effects +{ + +extern SUnorderedAccessView g_NullUnorderedAccessView; + +SBaseBlock::SBaseBlock() +: BlockType(EBT_Invalid) +, IsUserManaged(FALSE) +, AssignmentCount(0) +, pAssignments(NULL) +{ + +} + +SPassBlock::SPassBlock() +{ + pName = NULL; + AnnotationCount = 0; + pAnnotations = NULL; + InitiallyValid = TRUE; + HasDependencies = FALSE; + ZeroMemory(&BackingStore, sizeof(BackingStore)); +} + +STechnique::STechnique() +: pName(NULL) +, PassCount(0) +, pPasses(NULL) +, AnnotationCount(0) +, pAnnotations(NULL) +, InitiallyValid( TRUE ) +, HasDependencies( FALSE ) +{ +} + +SGroup::SGroup() +: pName(NULL) +, TechniqueCount(0) +, pTechniques(NULL) +, AnnotationCount(0) +, pAnnotations(NULL) +, InitiallyValid( TRUE ) +, HasDependencies( FALSE ) +{ +} + +SDepthStencilBlock::SDepthStencilBlock() +{ + pDSObject = NULL; + ZeroMemory(&BackingStore, sizeof(BackingStore)); + IsValid = TRUE; + + BackingStore.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + BackingStore.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + BackingStore.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + BackingStore.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; + BackingStore.DepthEnable = TRUE; + BackingStore.DepthFunc = D3D11_COMPARISON_LESS; + BackingStore.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; + BackingStore.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + BackingStore.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + BackingStore.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + BackingStore.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; + BackingStore.StencilEnable = FALSE; + BackingStore.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; + BackingStore.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; +} + +SBlendBlock::SBlendBlock() +{ + pBlendObject = NULL; + ZeroMemory(&BackingStore, sizeof(BackingStore)); + IsValid = TRUE; + + BackingStore.AlphaToCoverageEnable = FALSE; + BackingStore.IndependentBlendEnable = TRUE; + for( UINT i=0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; i++ ) + { + BackingStore.RenderTarget[i].SrcBlend = D3D11_BLEND_ONE; + BackingStore.RenderTarget[i].DestBlend = D3D11_BLEND_ZERO; + BackingStore.RenderTarget[i].BlendOp = D3D11_BLEND_OP_ADD; + BackingStore.RenderTarget[i].SrcBlendAlpha = D3D11_BLEND_ONE; + BackingStore.RenderTarget[i].DestBlendAlpha = D3D11_BLEND_ZERO; + BackingStore.RenderTarget[i].BlendOpAlpha = D3D11_BLEND_OP_ADD; + memset(&BackingStore.RenderTarget[i].RenderTargetWriteMask, 0x0F, sizeof(BackingStore.RenderTarget[i].RenderTargetWriteMask)); + } +} + +SRasterizerBlock::SRasterizerBlock() +{ + pRasterizerObject = NULL; + ZeroMemory(&BackingStore, sizeof(BackingStore)); + IsValid = TRUE; + + BackingStore.AntialiasedLineEnable = FALSE; + BackingStore.CullMode = D3D11_CULL_BACK; + BackingStore.DepthBias = D3D11_DEFAULT_DEPTH_BIAS; + BackingStore.DepthBiasClamp = D3D11_DEFAULT_DEPTH_BIAS_CLAMP; + BackingStore.FillMode = D3D11_FILL_SOLID; + BackingStore.FrontCounterClockwise = FALSE; + BackingStore.MultisampleEnable = FALSE; + BackingStore.ScissorEnable = FALSE; + BackingStore.SlopeScaledDepthBias = D3D11_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; + BackingStore.DepthClipEnable = TRUE; +} + +SSamplerBlock::SSamplerBlock() +{ + pD3DObject = NULL; + ZeroMemory(&BackingStore, sizeof(BackingStore)); + + BackingStore.SamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; + BackingStore.SamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; + BackingStore.SamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; + BackingStore.SamplerDesc.BorderColor[3] = D3D11_DEFAULT_BORDER_COLOR_COMPONENT; + BackingStore.SamplerDesc.BorderColor[2] = D3D11_DEFAULT_BORDER_COLOR_COMPONENT; + BackingStore.SamplerDesc.BorderColor[1] = D3D11_DEFAULT_BORDER_COLOR_COMPONENT; + BackingStore.SamplerDesc.BorderColor[0] = D3D11_DEFAULT_BORDER_COLOR_COMPONENT; + BackingStore.SamplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; + BackingStore.SamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + BackingStore.SamplerDesc.MaxAnisotropy = (UINT32) D3D11_DEFAULT_MAX_ANISOTROPY; + BackingStore.SamplerDesc.MipLODBias = D3D11_DEFAULT_MIP_LOD_BIAS; + BackingStore.SamplerDesc.MinLOD = -FLT_MAX; + BackingStore.SamplerDesc.MaxLOD = FLT_MAX; +} + +SShaderBlock::SShaderBlock(SD3DShaderVTable *pVirtualTable) +{ + IsValid = TRUE; + + pVT = pVirtualTable; + + pReflectionData = NULL; + + pD3DObject = NULL; + + CBDepCount = 0; + pCBDeps = NULL; + + SampDepCount = 0; + pSampDeps = NULL; + + InterfaceDepCount = 0; + pInterfaceDeps = NULL; + + ResourceDepCount = 0; + pResourceDeps = NULL; + + UAVDepCount = 0; + pUAVDeps = NULL; + + TBufferDepCount = 0; + ppTbufDeps = NULL; + + pInputSignatureBlob = NULL; +} + +HRESULT SShaderBlock::OnDeviceBind() +{ + HRESULT hr = S_OK; + UINT i, j; + + // Update all CB deps + for (i=0; i<CBDepCount; i++) + { + D3DXASSERT(pCBDeps[i].Count); + + for (j=0; j<pCBDeps[i].Count; j++) + { + pCBDeps[i].ppD3DObjects[j] = pCBDeps[i].ppFXPointers[j]->pD3DObject; + + if ( !pCBDeps[i].ppD3DObjects[j] ) + VH( E_FAIL ); + } + } + + // Update all sampler deps + for (i=0; i<SampDepCount; i++) + { + D3DXASSERT(pSampDeps[i].Count); + + for (j=0; j<pSampDeps[i].Count; j++) + { + pSampDeps[i].ppD3DObjects[j] = pSampDeps[i].ppFXPointers[j]->pD3DObject; + + if ( !pSampDeps[i].ppD3DObjects[j] ) + VH( E_FAIL ); + } + } + + // Texture deps will be set automatically on use since they are initially marked dirty. + +lExit: + return hr; +} + +extern SD3DShaderVTable g_vtVS; +extern SD3DShaderVTable g_vtGS; +extern SD3DShaderVTable g_vtPS; +extern SD3DShaderVTable g_vtHS; +extern SD3DShaderVTable g_vtDS; +extern SD3DShaderVTable g_vtCS; + +EObjectType SShaderBlock::GetShaderType() +{ + if (&g_vtVS == pVT) + return EOT_VertexShader; + else if (&g_vtGS == pVT) + return EOT_GeometryShader; + else if (&g_vtPS == pVT) + return EOT_PixelShader; + else if (&g_vtHS == pVT) + return EOT_HullShader5; + else if (&g_vtDS == pVT) + return EOT_DomainShader5; + else if (&g_vtCS == pVT) + return EOT_ComputeShader5; + + return EOT_Invalid; +} + +#define _SET_BIT(bytes, x) (bytes[x / 8] |= (1 << (x % 8))) + +HRESULT SShaderBlock::ComputeStateBlockMask(D3DX11_STATE_BLOCK_MASK *pStateBlockMask) +{ + HRESULT hr = S_OK; + UINT i, j; + BYTE *pSamplerMask = NULL, *pShaderResourceMask = NULL, *pConstantBufferMask = NULL, *pUnorderedAccessViewMask = NULL, *pInterfaceMask = NULL; + + switch (GetShaderType()) + { + case EOT_VertexShader: + case EOT_VertexShader5: + pStateBlockMask->VS = 1; + pSamplerMask = pStateBlockMask->VSSamplers; + pShaderResourceMask = pStateBlockMask->VSShaderResources; + pConstantBufferMask = pStateBlockMask->VSConstantBuffers; + pInterfaceMask = pStateBlockMask->VSInterfaces; + pUnorderedAccessViewMask = NULL; + break; + + case EOT_GeometryShader: + case EOT_GeometryShader5: + pStateBlockMask->GS = 1; + pSamplerMask = pStateBlockMask->GSSamplers; + pShaderResourceMask = pStateBlockMask->GSShaderResources; + pConstantBufferMask = pStateBlockMask->GSConstantBuffers; + pInterfaceMask = pStateBlockMask->GSInterfaces; + pUnorderedAccessViewMask = NULL; + break; + + case EOT_PixelShader: + case EOT_PixelShader5: + pStateBlockMask->PS = 1; + pSamplerMask = pStateBlockMask->PSSamplers; + pShaderResourceMask = pStateBlockMask->PSShaderResources; + pConstantBufferMask = pStateBlockMask->PSConstantBuffers; + pInterfaceMask = pStateBlockMask->PSInterfaces; + pUnorderedAccessViewMask = &pStateBlockMask->PSUnorderedAccessViews; + break; + + case EOT_HullShader5: + pStateBlockMask->HS = 1; + pSamplerMask = pStateBlockMask->HSSamplers; + pShaderResourceMask = pStateBlockMask->HSShaderResources; + pConstantBufferMask = pStateBlockMask->HSConstantBuffers; + pInterfaceMask = pStateBlockMask->HSInterfaces; + pUnorderedAccessViewMask = NULL; + break; + + case EOT_DomainShader5: + pStateBlockMask->DS = 1; + pSamplerMask = pStateBlockMask->DSSamplers; + pShaderResourceMask = pStateBlockMask->DSShaderResources; + pConstantBufferMask = pStateBlockMask->DSConstantBuffers; + pInterfaceMask = pStateBlockMask->DSInterfaces; + pUnorderedAccessViewMask = NULL; + break; + + case EOT_ComputeShader5: + pStateBlockMask->CS = 1; + pSamplerMask = pStateBlockMask->CSSamplers; + pShaderResourceMask = pStateBlockMask->CSShaderResources; + pConstantBufferMask = pStateBlockMask->CSConstantBuffers; + pInterfaceMask = pStateBlockMask->CSInterfaces; + pUnorderedAccessViewMask = &pStateBlockMask->CSUnorderedAccessViews; + break; + + default: + D3DXASSERT(0); + VH(E_FAIL); + } + + for (i = 0; i < SampDepCount; ++ i) + { + for (j = 0; j < pSampDeps[i].Count; ++ j) + { + _SET_BIT(pSamplerMask, (pSampDeps[i].StartIndex + j)); + } + } + + for (i = 0; i < InterfaceDepCount; ++ i) + { + for (j = 0; j < pInterfaceDeps[i].Count; ++ j) + { + _SET_BIT(pInterfaceMask, (pInterfaceDeps[i].StartIndex + j)); + } + } + + for (i = 0; i < ResourceDepCount; ++ i) + { + for (j = 0; j < pResourceDeps[i].Count; ++ j) + { + _SET_BIT(pShaderResourceMask, (pResourceDeps[i].StartIndex + j)); + } + } + + for (i = 0; i < CBDepCount; ++ i) + { + for (j = 0; j < pCBDeps[i].Count; ++ j) + { + _SET_BIT(pConstantBufferMask, (pCBDeps[i].StartIndex + j)); + } + } + + for (i = 0; i < UAVDepCount; ++ i) + { + D3DXASSERT( pUnorderedAccessViewMask != NULL ); + for (j = 0; j < pUAVDeps[i].Count; ++ j) + { + if( pUAVDeps[i].ppFXPointers[j] != &g_NullUnorderedAccessView ) + _SET_BIT(pUnorderedAccessViewMask, (pUAVDeps[i].StartIndex + j)); + } + } + +lExit: + return hr; +} + +#undef _SET_BIT + +HRESULT SShaderBlock::GetShaderDesc(D3DX11_EFFECT_SHADER_DESC *pDesc, BOOL IsInline) +{ + HRESULT hr = S_OK; + + ZeroMemory(pDesc, sizeof(*pDesc)); + + pDesc->pInputSignature = pInputSignatureBlob ? (const BYTE*)pInputSignatureBlob->GetBufferPointer() : NULL; + pDesc->IsInline = IsInline; + + if (NULL != pReflectionData) + { + // initialize these only if present; otherwise leave them NULL or 0 + pDesc->pBytecode = pReflectionData->pBytecode; + pDesc->BytecodeLength = pReflectionData->BytecodeLength; + for( UINT iDecl=0; iDecl < D3D11_SO_STREAM_COUNT; ++iDecl ) + { + pDesc->SODecls[iDecl] = pReflectionData->pStreamOutDecls[iDecl]; + } + pDesc->RasterizedStream = pReflectionData->RasterizedStream; + + // get # of input & output signature entries + D3DXASSERT( pReflectionData->pReflection != NULL ); + + D3D11_SHADER_DESC ShaderDesc; + pReflectionData->pReflection->GetDesc( &ShaderDesc ); + pDesc->NumInputSignatureEntries = ShaderDesc.InputParameters; + pDesc->NumOutputSignatureEntries = ShaderDesc.OutputParameters; + pDesc->NumPatchConstantSignatureEntries = ShaderDesc.PatchConstantParameters; + } +lExit: + return hr; +} + +HRESULT SShaderBlock::GetVertexShader(ID3D11VertexShader **ppVS) +{ + if (EOT_VertexShader == GetShaderType() || + EOT_VertexShader5 == GetShaderType()) + { + *ppVS = (ID3D11VertexShader *) pD3DObject; + SAFE_ADDREF(*ppVS); + return S_OK; + } + else + { + *ppVS = NULL; + DPF(0, "ID3DX11EffectShaderVariable::GetVertexShader: This shader variable is not a vertex shader"); + return D3DERR_INVALIDCALL; + } +} + +HRESULT SShaderBlock::GetGeometryShader(ID3D11GeometryShader **ppGS) +{ + if (EOT_GeometryShader == GetShaderType() || + EOT_GeometryShaderSO == GetShaderType() || + EOT_GeometryShader5 == GetShaderType()) + { + *ppGS = (ID3D11GeometryShader *) pD3DObject; + SAFE_ADDREF(*ppGS); + return S_OK; + } + else + { + *ppGS = NULL; + DPF(0, "ID3DX11EffectShaderVariable::GetGeometryShader: This shader variable is not a geometry shader"); + return D3DERR_INVALIDCALL; + } +} + +HRESULT SShaderBlock::GetPixelShader(ID3D11PixelShader **ppPS) +{ + if (EOT_PixelShader == GetShaderType() || + EOT_PixelShader5 == GetShaderType()) + { + *ppPS = (ID3D11PixelShader *) pD3DObject; + SAFE_ADDREF(*ppPS); + return S_OK; + } + else + { + *ppPS = NULL; + DPF(0, "ID3DX11EffectShaderVariable::GetPixelShader: This shader variable is not a pixel shader"); + return D3DERR_INVALIDCALL; + } +} + +HRESULT SShaderBlock::GetHullShader(ID3D11HullShader **ppHS) +{ + if (EOT_HullShader5 == GetShaderType()) + { + *ppHS = (ID3D11HullShader *) pD3DObject; + SAFE_ADDREF(*ppHS); + return S_OK; + } + else + { + *ppHS = NULL; + DPF(0, "ID3DX11EffectShaderVariable::GetHullShader: This shader variable is not a hull shader"); + return D3DERR_INVALIDCALL; + } +} + +HRESULT SShaderBlock::GetDomainShader(ID3D11DomainShader **ppDS) +{ + if (EOT_DomainShader5 == GetShaderType()) + { + *ppDS = (ID3D11DomainShader *) pD3DObject; + SAFE_ADDREF(*ppDS); + return S_OK; + } + else + { + *ppDS = NULL; + DPF(0, "ID3DX11EffectShaderVariable::GetDomainShader: This shader variable is not a domain shader"); + return D3DERR_INVALIDCALL; + } +} + +HRESULT SShaderBlock::GetComputeShader(ID3D11ComputeShader **ppCS) +{ + if (EOT_ComputeShader5 == GetShaderType()) + { + *ppCS = (ID3D11ComputeShader *) pD3DObject; + SAFE_ADDREF(*ppCS); + return S_OK; + } + else + { + *ppCS = NULL; + DPF(0, "ID3DX11EffectShaderVariable::GetComputeShader: This shader variable is not a compute shader"); + return D3DERR_INVALIDCALL; + } +} + +HRESULT SShaderBlock::GetSignatureElementDesc(ESigType SigType, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName; + switch( SigType ) + { + case ST_Input: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectShaderVariable::GetInputSignatureElementDesc"; + break; + case ST_Output: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectShaderVariable::GetOutputSignatureElementDesc"; + break; + case ST_PatchConstant: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectShaderVariable::GetPatchConstantSignatureElementDesc"; + break; + default: + D3DXASSERT( false ); + return E_FAIL; + }; + + if (NULL != pReflectionData) + { + // get # of signature entries + D3DXASSERT( pReflectionData->pReflection != NULL ); + + D3D11_SHADER_DESC ShaderDesc; + VH( pReflectionData->pReflection->GetDesc( &ShaderDesc ) ); + + D3D11_SIGNATURE_PARAMETER_DESC ParamDesc; + if( pReflectionData->IsNullGS ) + { + switch( SigType ) + { + case ST_Input: + // The input signature for a null-GS is the output signature of the previous VS + SigType = ST_Output; + break; + case ST_PatchConstant: + // GeometryShaders cannot have patch constant signatures + return E_INVALIDARG; + }; + } + + switch( SigType ) + { + case ST_Input: + if( Element >= ShaderDesc.InputParameters ) + { + DPF( 0, "%s: Invalid Element index (%d) specified", pFuncName, Element ); + VH( E_INVALIDARG ); + } + VH( pReflectionData->pReflection->GetInputParameterDesc( Element, &ParamDesc ) ); + break; + case ST_Output: + if( Element >= ShaderDesc.OutputParameters ) + { + DPF( 0, "%s: Invalid Element index (%d) specified", pFuncName, Element ); + VH( E_INVALIDARG ); + } + VH( pReflectionData->pReflection->GetOutputParameterDesc( Element, &ParamDesc ) ); + break; + case ST_PatchConstant: + if( Element >= ShaderDesc.PatchConstantParameters ) + { + DPF( 0, "%s: Invalid Element index (%d) specified", pFuncName, Element ); + VH( E_INVALIDARG ); + } + VH( pReflectionData->pReflection->GetPatchConstantParameterDesc( Element, &ParamDesc ) ); + break; + }; + + pDesc->SemanticName = ParamDesc.SemanticName; + pDesc->SystemValueType = ParamDesc.SystemValueType; + + // Pixel shaders need to be special-cased as they don't technically output SVs + if( pDesc->SystemValueType == D3D10_NAME_UNDEFINED && GetShaderType() == EOT_PixelShader ) + { + if( _stricmp(pDesc->SemanticName, "SV_TARGET") == 0 ) + { + pDesc->SystemValueType = D3D10_NAME_TARGET; + } + else if( _stricmp(pDesc->SemanticName, "SV_DEPTH") == 0 ) + { + pDesc->SystemValueType = D3D10_NAME_DEPTH; + } + else if( _stricmp(pDesc->SemanticName, "SV_COVERAGE") == 0 ) + { + pDesc->SystemValueType = D3D10_NAME_COVERAGE; + } + } + + pDesc->SemanticIndex = ParamDesc.SemanticIndex; + pDesc->Register = ParamDesc.Register; + pDesc->Mask = ParamDesc.Mask; + pDesc->ComponentType = ParamDesc.ComponentType; + pDesc->ReadWriteMask = ParamDesc.ReadWriteMask; + } + else + { + DPF(0, "%s: Cannot get signatures; shader bytecode is not present", pFuncName); + VH( D3DERR_INVALIDCALL ); + } + +lExit: + return hr; +} + +SString::SString() +{ + pString = NULL; +} + +SRenderTargetView::SRenderTargetView() +{ + pRenderTargetView = NULL; +} + +SDepthStencilView::SDepthStencilView() +{ + pDepthStencilView = NULL; +} + +void * GetBlockByIndex(EVarType VarType, EObjectType ObjectType, void *pBaseBlock, UINT Index) +{ + switch( VarType ) + { + case EVT_Interface: + return (SInterface *)pBaseBlock + Index; + case EVT_Object: + switch (ObjectType) + { + case EOT_Blend: + return (SBlendBlock *)pBaseBlock + Index; + case EOT_DepthStencil: + return (SDepthStencilBlock *)pBaseBlock + Index; + case EOT_Rasterizer: + return (SRasterizerBlock *)pBaseBlock + Index; + case EOT_PixelShader: + case EOT_PixelShader5: + case EOT_GeometryShader: + case EOT_GeometryShaderSO: + case EOT_GeometryShader5: + case EOT_VertexShader: + case EOT_VertexShader5: + case EOT_HullShader5: + case EOT_DomainShader5: + case EOT_ComputeShader5: + return (SShaderBlock *)pBaseBlock + Index; + case EOT_String: + return (SString *)pBaseBlock + Index; + case EOT_Sampler: + return (SSamplerBlock *)pBaseBlock + Index; + case EOT_Buffer: + case EOT_Texture: + case EOT_Texture1D: + case EOT_Texture1DArray: + case EOT_Texture2D: + case EOT_Texture2DArray: + case EOT_Texture2DMS: + case EOT_Texture2DMSArray: + case EOT_Texture3D: + case EOT_TextureCube: + case EOT_TextureCubeArray: + case EOT_ByteAddressBuffer: + case EOT_StructuredBuffer: + return (SShaderResource *)pBaseBlock + Index; + case EOT_DepthStencilView: + return (SDepthStencilView *)pBaseBlock + Index; + case EOT_RenderTargetView: + return (SRenderTargetView *)pBaseBlock + Index; + case EOT_RWTexture1D: + case EOT_RWTexture1DArray: + case EOT_RWTexture2D: + case EOT_RWTexture2DArray: + case EOT_RWTexture3D: + case EOT_RWBuffer: + case EOT_RWByteAddressBuffer: + case EOT_RWStructuredBuffer: + case EOT_RWStructuredBufferAlloc: + case EOT_RWStructuredBufferConsume: + case EOT_AppendStructuredBuffer: + case EOT_ConsumeStructuredBuffer: + return (SUnorderedAccessView *)pBaseBlock + Index; + default: + D3DXASSERT(0); + return NULL; + } + default: + D3DXASSERT(0); + return NULL; + } +} + +CEffect::CEffect( UINT Flags ) +{ + m_RefCount = 1; + + m_pVariables = NULL; + m_pAnonymousShaders = NULL; + m_pGroups = NULL; + m_pNullGroup = NULL; + m_pShaderBlocks = NULL; + m_pDepthStencilBlocks = NULL; + m_pBlendBlocks = NULL; + m_pRasterizerBlocks = NULL; + m_pSamplerBlocks = NULL; + m_pCBs = NULL; + m_pStrings = NULL; + m_pMemberDataBlocks = NULL; + m_pInterfaces = NULL; + m_pShaderResources = NULL; + m_pUnorderedAccessViews = NULL; + m_pRenderTargetViews = NULL; + m_pDepthStencilViews = NULL; + m_pDevice = NULL; + m_pClassLinkage = NULL; + m_pContext = NULL; + + m_VariableCount = 0; + m_AnonymousShaderCount = 0; + m_ShaderBlockCount = 0; + m_DepthStencilBlockCount = 0; + m_BlendBlockCount = 0; + m_RasterizerBlockCount = 0; + m_SamplerBlockCount = 0; + m_StringCount = 0; + m_MemberDataCount = 0; + m_InterfaceCount = 0; + m_ShaderResourceCount = 0; + m_UnorderedAccessViewCount = 0; + m_RenderTargetViewCount = 0; + m_DepthStencilViewCount = 0; + m_CBCount = 0; + m_TechniqueCount = 0; + m_GroupCount = 0; + + m_pReflection = NULL; + m_LocalTimer = 1; + m_Flags = Flags; + m_FXLIndex = 0; + + m_pTypePool = NULL; + m_pStringPool = NULL; + m_pPooledHeap = NULL; + m_pOptimizedTypeHeap = NULL; +} + +void CEffect::ReleaseShaderRefection() +{ + for( UINT i = 0; i < m_ShaderBlockCount; ++ i ) + { + SAFE_RELEASE( m_pShaderBlocks[i].pInputSignatureBlob ); + if( m_pShaderBlocks[i].pReflectionData ) + { + SAFE_RELEASE( m_pShaderBlocks[i].pReflectionData->pReflection ); + } + } +} + +CEffect::~CEffect() +{ + ID3D11InfoQueue *pInfoQueue = NULL; + + // Mute debug spew + if (m_pDevice) + m_pDevice->QueryInterface(__uuidof(ID3D11InfoQueue), (void**) &pInfoQueue); + + if (pInfoQueue) + { + D3D11_INFO_QUEUE_FILTER filter; + D3D11_MESSAGE_CATEGORY messageCategory = D3D11_MESSAGE_CATEGORY_STATE_SETTING; + ZeroMemory(&filter, sizeof(filter)); + + filter.DenyList.NumCategories = 1; + filter.DenyList.pCategoryList = &messageCategory; + pInfoQueue->PushStorageFilter(&filter); + } + + UINT i; + + if( NULL != m_pDevice ) + { + // if m_pDevice == NULL, then we failed LoadEffect(), which means ReleaseShaderReflection was already called. + + // Release the shader reflection info, as it was not created on the private heap + // This must be called before we delete m_pReflection + ReleaseShaderRefection(); + } + + SAFE_DELETE( m_pReflection ); + SAFE_DELETE( m_pTypePool ); + SAFE_DELETE( m_pStringPool ); + SAFE_DELETE( m_pPooledHeap ); + SAFE_DELETE( m_pOptimizedTypeHeap ); + + // this code assumes the effect has been loaded & relocated, + // so check for that before freeing the resources + + if (NULL != m_pDevice) + { + // Keep the following in line with AddRefAllForCloning + + D3DXASSERT(NULL == m_pRasterizerBlocks || m_Heap.IsInHeap(m_pRasterizerBlocks)); + for (i = 0; i < m_RasterizerBlockCount; ++ i) + { + SAFE_RELEASE(m_pRasterizerBlocks[i].pRasterizerObject); + } + + D3DXASSERT(NULL == m_pBlendBlocks || m_Heap.IsInHeap(m_pBlendBlocks)); + for (i = 0; i < m_BlendBlockCount; ++ i) + { + SAFE_RELEASE(m_pBlendBlocks[i].pBlendObject); + } + + D3DXASSERT(NULL == m_pDepthStencilBlocks || m_Heap.IsInHeap(m_pDepthStencilBlocks)); + for (i = 0; i < m_DepthStencilBlockCount; ++ i) + { + SAFE_RELEASE(m_pDepthStencilBlocks[i].pDSObject); + } + + D3DXASSERT(NULL == m_pSamplerBlocks || m_Heap.IsInHeap(m_pSamplerBlocks)); + for (i = 0; i < m_SamplerBlockCount; ++ i) + { + SAFE_RELEASE(m_pSamplerBlocks[i].pD3DObject); + } + + D3DXASSERT(NULL == m_pShaderResources || m_Heap.IsInHeap(m_pShaderResources)); + for (i = 0; i < m_ShaderResourceCount; ++ i) + { + SAFE_RELEASE(m_pShaderResources[i].pShaderResource); + } + + D3DXASSERT(NULL == m_pUnorderedAccessViews || m_Heap.IsInHeap(m_pUnorderedAccessViews)); + for (i = 0; i < m_UnorderedAccessViewCount; ++ i) + { + SAFE_RELEASE(m_pUnorderedAccessViews[i].pUnorderedAccessView); + } + + D3DXASSERT(NULL == m_pRenderTargetViews || m_Heap.IsInHeap(m_pRenderTargetViews)); + for (i = 0; i < m_RenderTargetViewCount; ++ i) + { + SAFE_RELEASE(m_pRenderTargetViews[i].pRenderTargetView); + } + + D3DXASSERT(NULL == m_pDepthStencilViews || m_Heap.IsInHeap(m_pDepthStencilViews)); + for (i = 0; i < m_DepthStencilViewCount; ++ i) + { + SAFE_RELEASE(m_pDepthStencilViews[i].pDepthStencilView); + } + + D3DXASSERT(NULL == m_pMemberDataBlocks || m_Heap.IsInHeap(m_pMemberDataBlocks)); + for (i = 0; i < m_MemberDataCount; ++ i) + { + switch( m_pMemberDataBlocks[i].Type ) + { + case MDT_ClassInstance: + SAFE_RELEASE(m_pMemberDataBlocks[i].Data.pD3DClassInstance); + break; + case MDT_BlendState: + SAFE_RELEASE(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedBlendState); + break; + case MDT_DepthStencilState: + SAFE_RELEASE(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedDepthStencilState); + break; + case MDT_RasterizerState: + SAFE_RELEASE(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedRasterizerState); + break; + case MDT_SamplerState: + SAFE_RELEASE(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedSamplerState); + break; + case MDT_Buffer: + SAFE_RELEASE(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedConstantBuffer); + break; + case MDT_ShaderResourceView: + SAFE_RELEASE(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedTextureBuffer); + break; + default: + D3DXASSERT( false ); + } + } + + D3DXASSERT(NULL == m_pCBs || m_Heap.IsInHeap(m_pCBs)); + for (i = 0; i < m_CBCount; ++ i) + { + SAFE_RELEASE(m_pCBs[i].TBuffer.pShaderResource); + SAFE_RELEASE(m_pCBs[i].pD3DObject); + } + + D3DXASSERT(NULL == m_pShaderBlocks || m_Heap.IsInHeap(m_pShaderBlocks)); + for (i = 0; i < m_ShaderBlockCount; ++ i) + { + SAFE_RELEASE(m_pShaderBlocks[i].pD3DObject); + } + + SAFE_RELEASE( m_pDevice ); + } + SAFE_RELEASE( m_pClassLinkage ); + D3DXASSERT( m_pContext == NULL ); + + // Restore debug spew + if (pInfoQueue) + { + pInfoQueue->PopStorageFilter(); + SAFE_RELEASE(pInfoQueue); + } +} + +// AddRef all D3D object when cloning +void CEffect::AddRefAllForCloning( CEffect* pEffectSource ) +{ + UINT i; + + // Keep the following in line with ~CEffect + + D3DXASSERT( m_pDevice != NULL ); + + for( UINT i = 0; i < m_ShaderBlockCount; ++ i ) + { + SAFE_ADDREF( m_pShaderBlocks[i].pInputSignatureBlob ); + if( m_pShaderBlocks[i].pReflectionData ) + { + SAFE_ADDREF( m_pShaderBlocks[i].pReflectionData->pReflection ); + } + } + + D3DXASSERT(NULL == m_pRasterizerBlocks || pEffectSource->m_Heap.IsInHeap(m_pRasterizerBlocks)); + for (i = 0; i < m_RasterizerBlockCount; ++ i) + { + SAFE_ADDREF(m_pRasterizerBlocks[i].pRasterizerObject); + } + + D3DXASSERT(NULL == m_pBlendBlocks || pEffectSource->m_Heap.IsInHeap(m_pBlendBlocks)); + for (i = 0; i < m_BlendBlockCount; ++ i) + { + SAFE_ADDREF(m_pBlendBlocks[i].pBlendObject); + } + + D3DXASSERT(NULL == m_pDepthStencilBlocks || pEffectSource->m_Heap.IsInHeap(m_pDepthStencilBlocks)); + for (i = 0; i < m_DepthStencilBlockCount; ++ i) + { + SAFE_ADDREF(m_pDepthStencilBlocks[i].pDSObject); + } + + D3DXASSERT(NULL == m_pSamplerBlocks || pEffectSource->m_Heap.IsInHeap(m_pSamplerBlocks)); + for (i = 0; i < m_SamplerBlockCount; ++ i) + { + SAFE_ADDREF(m_pSamplerBlocks[i].pD3DObject); + } + + D3DXASSERT(NULL == m_pShaderResources || pEffectSource->m_Heap.IsInHeap(m_pShaderResources)); + for (i = 0; i < m_ShaderResourceCount; ++ i) + { + SAFE_ADDREF(m_pShaderResources[i].pShaderResource); + } + + D3DXASSERT(NULL == m_pUnorderedAccessViews || pEffectSource->m_Heap.IsInHeap(m_pUnorderedAccessViews)); + for (i = 0; i < m_UnorderedAccessViewCount; ++ i) + { + SAFE_ADDREF(m_pUnorderedAccessViews[i].pUnorderedAccessView); + } + + D3DXASSERT(NULL == m_pRenderTargetViews || pEffectSource->m_Heap.IsInHeap(m_pRenderTargetViews)); + for (i = 0; i < m_RenderTargetViewCount; ++ i) + { + SAFE_ADDREF(m_pRenderTargetViews[i].pRenderTargetView); + } + + D3DXASSERT(NULL == m_pDepthStencilViews || pEffectSource->m_Heap.IsInHeap(m_pDepthStencilViews)); + for (i = 0; i < m_DepthStencilViewCount; ++ i) + { + SAFE_ADDREF(m_pDepthStencilViews[i].pDepthStencilView); + } + + D3DXASSERT(NULL == m_pMemberDataBlocks || pEffectSource->m_Heap.IsInHeap(m_pMemberDataBlocks)); + for (i = 0; i < m_MemberDataCount; ++ i) + { + switch( m_pMemberDataBlocks[i].Type ) + { + case MDT_ClassInstance: + SAFE_ADDREF(m_pMemberDataBlocks[i].Data.pD3DClassInstance); + break; + case MDT_BlendState: + SAFE_ADDREF(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedBlendState); + break; + case MDT_DepthStencilState: + SAFE_ADDREF(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedDepthStencilState); + break; + case MDT_RasterizerState: + SAFE_ADDREF(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedRasterizerState); + break; + case MDT_SamplerState: + SAFE_ADDREF(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedSamplerState); + break; + case MDT_Buffer: + SAFE_ADDREF(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedConstantBuffer); + break; + case MDT_ShaderResourceView: + SAFE_ADDREF(m_pMemberDataBlocks[i].Data.pD3DEffectsManagedTextureBuffer); + break; + default: + D3DXASSERT( false ); + } + } + + // There's no need to AddRef CBs, since they are recreated + D3DXASSERT(NULL == m_pCBs || pEffectSource->m_Heap.IsInHeap(m_pCBs)); + for (i = 0; i < m_CBCount; ++ i) + { + SAFE_ADDREF(m_pCBs[i].TBuffer.pShaderResource); + SAFE_ADDREF(m_pCBs[i].pD3DObject); + } + + D3DXASSERT(NULL == m_pShaderBlocks || pEffectSource->m_Heap.IsInHeap(m_pShaderBlocks)); + for (i = 0; i < m_ShaderBlockCount; ++ i) + { + SAFE_ADDREF(m_pShaderBlocks[i].pD3DObject); + } + + SAFE_ADDREF( m_pDevice ); + + SAFE_ADDREF( m_pClassLinkage ); + D3DXASSERT( m_pContext == NULL ); +} + +HRESULT CEffect::QueryInterface(REFIID iid, LPVOID *ppv) +{ + HRESULT hr = S_OK; + + if(NULL == ppv) + { + DPF(0, "ID3DX11Effect::QueryInterface: NULL parameter"); + hr = E_INVALIDARG; + goto EXIT; + } + + *ppv = NULL; + if(IsEqualIID(iid, IID_IUnknown)) + { + *ppv = (IUnknown *) this; + } + else if(IsEqualIID(iid, IID_ID3DX11Effect)) + { + *ppv = (ID3DX11Effect *) this; + } + else + { + return E_NOINTERFACE; + } + + AddRef(); + +EXIT: + return hr; +} + +ULONG CEffect::AddRef() +{ + return ++ m_RefCount; +} + +ULONG CEffect::Release() +{ + if (-- m_RefCount > 0) + { + return m_RefCount; + } + else + { + delete this; + } + + return 0; +} + +// In all shaders, replace pOldBufferBlock with pNewBuffer, if pOldBufferBlock is a dependency +void CEffect::ReplaceCBReference(SConstantBuffer *pOldBufferBlock, ID3D11Buffer *pNewBuffer) +{ + UINT iShaderBlock; + + for (iShaderBlock=0; iShaderBlock<m_ShaderBlockCount; iShaderBlock++) + { + for (UINT iCBDep = 0; iCBDep < m_pShaderBlocks[iShaderBlock].CBDepCount; iCBDep++) + { + for (UINT iCB = 0; iCB < m_pShaderBlocks[iShaderBlock].pCBDeps[iCBDep].Count; iCB++) + { + if (m_pShaderBlocks[iShaderBlock].pCBDeps[iCBDep].ppFXPointers[iCB] == pOldBufferBlock) + m_pShaderBlocks[iShaderBlock].pCBDeps[iCBDep].ppD3DObjects[iCB] = pNewBuffer; + } + } + } +} + +// In all shaders, replace pOldSamplerBlock with pNewSampler, if pOldSamplerBlock is a dependency +void CEffect::ReplaceSamplerReference(SSamplerBlock *pOldSamplerBlock, ID3D11SamplerState *pNewSampler) +{ + UINT iShaderBlock; + + for (iShaderBlock=0; iShaderBlock<m_ShaderBlockCount; iShaderBlock++) + { + for (UINT iSamplerDep = 0; iSamplerDep < m_pShaderBlocks[iShaderBlock].SampDepCount; iSamplerDep++) + { + for (UINT iSampler = 0; iSampler < m_pShaderBlocks[iShaderBlock].pSampDeps[iSamplerDep].Count; iSampler++) + { + if (m_pShaderBlocks[iShaderBlock].pSampDeps[iSamplerDep].ppFXPointers[iSampler] == pOldSamplerBlock) + m_pShaderBlocks[iShaderBlock].pSampDeps[iSamplerDep].ppD3DObjects[iSampler] = pNewSampler; + } + } + } +} + +// Call BindToDevice after the effect has been fully loaded. +// BindToDevice will release all D3D11 objects and create new ones on the new device +HRESULT CEffect::BindToDevice(ID3D11Device *pDevice) +{ + HRESULT hr = S_OK; + + // Set new device + if (pDevice == NULL) + { + DPF(0, "ID3DX11Effect: pDevice must point to a valid D3D11 device"); + return D3DERR_INVALIDCALL; + } + + if (m_pDevice != NULL) + { + DPF(0, "ID3DX11Effect: Internal error, rebinding effects to a new device is not supported"); + return D3DERR_INVALIDCALL; + } + + bool featureLevelGE11 = ( pDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_11_0 ); + + pDevice->AddRef(); + SAFE_RELEASE(m_pDevice); + m_pDevice = pDevice; + VH( m_pDevice->CreateClassLinkage( &m_pClassLinkage ) ); + + // Create all constant buffers + SConstantBuffer *pCB = m_pCBs; + SConstantBuffer *pCBLast = m_pCBs + m_CBCount; + for(; pCB != pCBLast; pCB++) + { + SAFE_RELEASE(pCB->pD3DObject); + SAFE_RELEASE(pCB->TBuffer.pShaderResource); + + // This is a CBuffer + if (pCB->Size > 0) + { + if (pCB->IsTBuffer) + { + D3D11_BUFFER_DESC bufDesc; + // size is always register aligned + bufDesc.ByteWidth = pCB->Size; + bufDesc.Usage = D3D11_USAGE_DEFAULT; + bufDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + bufDesc.CPUAccessFlags = 0; + bufDesc.MiscFlags = 0; + + VH( pDevice->CreateBuffer( &bufDesc, NULL, &pCB->pD3DObject) ); + + D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc; + viewDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; + viewDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; + viewDesc.Buffer.ElementOffset = 0; + viewDesc.Buffer.ElementWidth = pCB->Size / SType::c_RegisterSize; + + VH( pDevice->CreateShaderResourceView( pCB->pD3DObject, &viewDesc, &pCB->TBuffer.pShaderResource) ); + } + else + { + D3D11_BUFFER_DESC bufDesc; + // size is always register aligned + bufDesc.ByteWidth = pCB->Size; + bufDesc.Usage = D3D11_USAGE_DEFAULT; + bufDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + bufDesc.CPUAccessFlags = 0; + bufDesc.MiscFlags = 0; + + VH( pDevice->CreateBuffer( &bufDesc, NULL, &pCB->pD3DObject) ); + pCB->TBuffer.pShaderResource = NULL; + } + + pCB->IsDirty = TRUE; + } + else + { + pCB->IsDirty = FALSE; + } + } + + // Create all RasterizerStates + SRasterizerBlock *pRB = m_pRasterizerBlocks; + SRasterizerBlock *pRBLast = m_pRasterizerBlocks + m_RasterizerBlockCount; + for(; pRB != pRBLast; pRB++) + { + SAFE_RELEASE(pRB->pRasterizerObject); + if( SUCCEEDED( m_pDevice->CreateRasterizerState( &pRB->BackingStore, &pRB->pRasterizerObject) ) ) + pRB->IsValid = TRUE; + else + pRB->IsValid = FALSE; + } + + // Create all DepthStencils + SDepthStencilBlock *pDS = m_pDepthStencilBlocks; + SDepthStencilBlock *pDSLast = m_pDepthStencilBlocks + m_DepthStencilBlockCount; + for(; pDS != pDSLast; pDS++) + { + SAFE_RELEASE(pDS->pDSObject); + if( SUCCEEDED( m_pDevice->CreateDepthStencilState( &pDS->BackingStore, &pDS->pDSObject) ) ) + pDS->IsValid = TRUE; + else + pDS->IsValid = FALSE; + } + + // Create all BlendStates + SBlendBlock *pBlend = m_pBlendBlocks; + SBlendBlock *pBlendLast = m_pBlendBlocks + m_BlendBlockCount; + for(; pBlend != pBlendLast; pBlend++) + { + SAFE_RELEASE(pBlend->pBlendObject); + if( SUCCEEDED( m_pDevice->CreateBlendState( &pBlend->BackingStore, &pBlend->pBlendObject ) ) ) + pBlend->IsValid = TRUE; + else + pBlend->IsValid = FALSE; + } + + // Create all Samplers + SSamplerBlock *pSampler = m_pSamplerBlocks; + SSamplerBlock *pSamplerLast = m_pSamplerBlocks + m_SamplerBlockCount; + for(; pSampler != pSamplerLast; pSampler++) + { + SAFE_RELEASE(pSampler->pD3DObject); + + VH( m_pDevice->CreateSamplerState( &pSampler->BackingStore.SamplerDesc, &pSampler->pD3DObject) ); + } + + // Create all shaders + ID3D11ClassLinkage* neededClassLinkage = featureLevelGE11 ? m_pClassLinkage : NULL; + SShaderBlock *pShader = m_pShaderBlocks; + SShaderBlock *pShaderLast = m_pShaderBlocks + m_ShaderBlockCount; + for(; pShader != pShaderLast; pShader++) + { + SAFE_RELEASE(pShader->pD3DObject); + + if (NULL == pShader->pReflectionData) + { + // NULL shader. It's one of these: + // PixelShader ps; + // or + // SetPixelShader( NULL ); + continue; + } + + if (pShader->pReflectionData->pStreamOutDecls[0] || pShader->pReflectionData->pStreamOutDecls[1] || + pShader->pReflectionData->pStreamOutDecls[2] || pShader->pReflectionData->pStreamOutDecls[3] ) + { + // This is a geometry shader, process it's data + CSOParser soParser; + VH( soParser.Parse(pShader->pReflectionData->pStreamOutDecls) ); + UINT strides[4]; + soParser.GetStrides( strides ); + hr = m_pDevice->CreateGeometryShaderWithStreamOutput((UINT*) pShader->pReflectionData->pBytecode, + pShader->pReflectionData->BytecodeLength, + soParser.GetDeclArray(), + soParser.GetDeclCount(), + strides, + featureLevelGE11 ? 4 : 1, + pShader->pReflectionData->RasterizedStream, + neededClassLinkage, + (ID3D11GeometryShader**) &pShader->pD3DObject); + if (FAILED(hr)) + { + DPF(1, "ID3DX11Effect::Load - failed to create GeometryShader with StreamOutput decl: \"%s\"", soParser.GetErrorString() ); + pShader->IsValid = FALSE; + hr = S_OK; + } + } + else + { + // This is a regular shader + if( pShader->pReflectionData->RasterizedStream == D3D11_SO_NO_RASTERIZED_STREAM ) + pShader->IsValid = FALSE; + else + { + if( FAILED( (m_pDevice->*(pShader->pVT->pCreateShader))( (UINT *) pShader->pReflectionData->pBytecode, pShader->pReflectionData->BytecodeLength, neededClassLinkage, &pShader->pD3DObject) ) ) + { + DPF(1, "ID3DX11Effect::Load - failed to create shader" ); + pShader->IsValid = FALSE; + } + } + } + + // Update all dependency pointers + VH( pShader->OnDeviceBind() ); + } + + // Initialize the member data pointers for all variables + UINT CurMemberData = 0; + for (UINT i = 0; i < m_VariableCount; ++ i) + { + if( m_pVariables[i].pMemberData ) + { + if( m_pVariables[i].pType->IsClassInstance() ) + { + for (UINT j = 0; j < max(m_pVariables[i].pType->Elements,1); ++j) + { + D3DXASSERT( CurMemberData < m_MemberDataCount ); + ID3D11ClassInstance** ppCI = &(m_pVariables[i].pMemberData + j)->Data.pD3DClassInstance; + (m_pVariables[i].pMemberData + j)->Type = MDT_ClassInstance; + (m_pVariables[i].pMemberData + j)->Data.pD3DClassInstance = NULL; + if( m_pVariables[i].pType->TotalSize > 0 ) + { + // ignore failures in GetClassInstance; + m_pClassLinkage->GetClassInstance( m_pVariables[i].pName, j, ppCI ); + } + else + { + // The HLSL compiler optimizes out zero-sized classes, so we have to create class instances from scratch + if( FAILED( m_pClassLinkage->CreateClassInstance( m_pVariables[i].pType->pTypeName, 0, 0, 0, 0, ppCI ) ) ) + { + DPF(0, "ID3DX11Effect: Out of memory while trying to create new class instance interface"); + } + } + CurMemberData++; + } + } + else if( m_pVariables[i].pType->IsStateBlockObject() ) + { + for (UINT j = 0; j < max(m_pVariables[i].pType->Elements,1); ++j) + { + switch( m_pVariables[i].pType->ObjectType ) + { + case EOT_Blend: + (m_pVariables[i].pMemberData + j)->Type = MDT_BlendState; + (m_pVariables[i].pMemberData + j)->Data.pD3DEffectsManagedBlendState = NULL; + break; + case EOT_Rasterizer: + (m_pVariables[i].pMemberData + j)->Type = MDT_RasterizerState; + (m_pVariables[i].pMemberData + j)->Data.pD3DEffectsManagedRasterizerState = NULL; + break; + case EOT_DepthStencil: + (m_pVariables[i].pMemberData + j)->Type = MDT_DepthStencilState; + (m_pVariables[i].pMemberData + j)->Data.pD3DEffectsManagedDepthStencilState = NULL; + break; + case EOT_Sampler: + (m_pVariables[i].pMemberData + j)->Type = MDT_SamplerState; + (m_pVariables[i].pMemberData + j)->Data.pD3DEffectsManagedSamplerState = NULL; + break; + default: + VB( FALSE ); + } + CurMemberData++; + } + } + else + { + VB( FALSE ); + } + } + } + for(pCB = m_pCBs; pCB != pCBLast; pCB++) + { + (pCB->pMemberData + 0)->Type = MDT_Buffer; + (pCB->pMemberData + 0)->Data.pD3DEffectsManagedConstantBuffer = NULL; + CurMemberData++; + (pCB->pMemberData + 1)->Type = MDT_ShaderResourceView; + (pCB->pMemberData + 1)->Data.pD3DEffectsManagedTextureBuffer = NULL; + CurMemberData++; + } + + + // Determine which techniques and passes are known to be invalid + for( UINT iGroup=0; iGroup < m_GroupCount; iGroup++ ) + { + SGroup* pGroup = &m_pGroups[iGroup]; + pGroup->InitiallyValid = TRUE; + + for( UINT iTech=0; iTech < pGroup->TechniqueCount; iTech++ ) + { + STechnique* pTechnique = &pGroup->pTechniques[iTech]; + pTechnique->InitiallyValid = TRUE; + + for( UINT iPass = 0; iPass < pTechnique->PassCount; iPass++ ) + { + SPassBlock* pPass = &pTechnique->pPasses[iPass]; + pPass->InitiallyValid = TRUE; + + if( pPass->BackingStore.pBlendBlock != NULL && !pPass->BackingStore.pBlendBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pDepthStencilBlock != NULL && !pPass->BackingStore.pDepthStencilBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pRasterizerBlock != NULL && !pPass->BackingStore.pRasterizerBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pVertexShaderBlock != NULL && !pPass->BackingStore.pVertexShaderBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pPixelShaderBlock != NULL && !pPass->BackingStore.pPixelShaderBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pGeometryShaderBlock != NULL && !pPass->BackingStore.pGeometryShaderBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pHullShaderBlock != NULL && !pPass->BackingStore.pHullShaderBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pDomainShaderBlock != NULL && !pPass->BackingStore.pDomainShaderBlock->IsValid ) + pPass->InitiallyValid = FALSE; + if( pPass->BackingStore.pComputeShaderBlock != NULL && !pPass->BackingStore.pComputeShaderBlock->IsValid ) + pPass->InitiallyValid = FALSE; + + pTechnique->InitiallyValid &= pPass->InitiallyValid; + } + pGroup->InitiallyValid &= pTechnique->InitiallyValid; + } + } + +lExit: + return hr; +} + +// FindVariableByName, plus an understanding of literal indices +// This code handles A[i]. +// It does not handle anything else, like A.B, A[B[i]], A[B] +SVariable * CEffect::FindVariableByNameWithParsing(LPCSTR pName) +{ + SGlobalVariable *pVariable; + const UINT MAX_PARSABLE_NAME_LENGTH = 256; + char pScratchString[MAX_PARSABLE_NAME_LENGTH]; + + const char* pSource = pName; + char* pDest = pScratchString; + char* pEnd = pScratchString + MAX_PARSABLE_NAME_LENGTH; + + pVariable = NULL; + + while( *pSource != 0 ) + { + if( pDest == pEnd ) + { + pVariable = FindLocalVariableByName(pName); + if( pVariable == NULL ) + { + DPF( 0, "Name %s is too long to parse", &pName ); + } + return pVariable; + } + + if( *pSource == '[' ) + { + // parse previous variable name + *pDest = 0; + D3DXASSERT( pVariable == NULL ); + pVariable = FindLocalVariableByName(pScratchString); + if( pVariable == NULL ) + { + return NULL; + } + pDest = pScratchString; + } + else if( *pSource == ']' ) + { + // parse integer + *pDest = 0; + UINT index = atoi(pScratchString); + D3DXASSERT( pVariable != NULL ); + pVariable = (SGlobalVariable*)pVariable->GetElement(index); + if( pVariable && !pVariable->IsValid() ) + { + pVariable = NULL; + } + return pVariable; + } + else + { + // add character + *pDest = *pSource; + pDest++; + } + pSource++; + } + + if( pDest != pScratchString ) + { + // parse the variable name (there was no [i]) + *pDest = 0; + D3DXASSERT( pVariable == NULL ); + pVariable = FindLocalVariableByName(pScratchString); + } + + return pVariable; +} + +SGlobalVariable * CEffect::FindVariableByName(LPCSTR pName) +{ + SGlobalVariable *pVariable; + + pVariable = FindLocalVariableByName(pName); + + return pVariable; +} + +SGlobalVariable * CEffect::FindLocalVariableByName(LPCSTR pName) +{ + SGlobalVariable *pVariable, *pVariableEnd; + + pVariableEnd = m_pVariables + m_VariableCount; + for (pVariable = m_pVariables; pVariable != pVariableEnd; pVariable++) + { + if (strcmp( pVariable->pName, pName) == 0) + { + return pVariable; + } + } + + return NULL; +} + + +// +// Checks to see if two types are equivalent (either at runtime +// or during the type-pooling load process) +// +// Major assumption: if both types are structures, then their +// member types & names should already have been added to the pool, +// in which case their member type & name pointers should be equal. +// +// This is true because complex data types (structures) have all +// sub-types translated before the containing type is translated, +// which means that simple sub-types (numeric types) have already +// been pooled. +// +BOOL SType::IsEqual(SType *pOtherType) CONST +{ + if (VarType != pOtherType->VarType || Elements != pOtherType->Elements + || strcmp(pTypeName, pOtherType->pTypeName) != 0) + { + return FALSE; + } + + switch (VarType) + { + case EVT_Struct: + { + if (StructType.Members != pOtherType->StructType.Members) + { + return FALSE; + } + D3DXASSERT(StructType.pMembers != NULL && pOtherType->StructType.pMembers != NULL); + + UINT i; + for (i = 0; i < StructType.Members; ++ i) + { + // names for types must exist (not true for semantics) + D3DXASSERT(StructType.pMembers[i].pName != NULL && pOtherType->StructType.pMembers[i].pName != NULL); + + if (StructType.pMembers[i].pType != pOtherType->StructType.pMembers[i].pType || + StructType.pMembers[i].Data.Offset != pOtherType->StructType.pMembers[i].Data.Offset || + StructType.pMembers[i].pName != pOtherType->StructType.pMembers[i].pName || + StructType.pMembers[i].pSemantic != pOtherType->StructType.pMembers[i].pSemantic) + { + return FALSE; + } + } + } + break; + + case EVT_Object: + { + if (ObjectType != pOtherType->ObjectType) + { + return FALSE; + } + } + break; + + case EVT_Numeric: + { + if (NumericType.Rows != pOtherType->NumericType.Rows || + NumericType.Columns != pOtherType->NumericType.Columns || + NumericType.ScalarType != pOtherType->NumericType.ScalarType || + NumericType.NumericLayout != pOtherType->NumericType.NumericLayout || + NumericType.IsColumnMajor != pOtherType->NumericType.IsColumnMajor || + NumericType.IsPackedArray != pOtherType->NumericType.IsPackedArray) + { + return FALSE; + } + } + break; + + case EVT_Interface: + { + // VarType and pTypeName handled above + } + break; + + default: + { + D3DXASSERT(0); + return FALSE; + } + break; + } + + D3DXASSERT(TotalSize == pOtherType->TotalSize && Stride == pOtherType->Stride && PackedSize == pOtherType->PackedSize); + + return TRUE; +} + +UINT SType::GetTotalUnpackedSize(BOOL IsSingleElement) CONST +{ + if (VarType == EVT_Object) + { + return 0; + } + else if (VarType == EVT_Interface) + { + return 0; + } + else if (Elements > 0 && IsSingleElement) + { + D3DXASSERT( ( TotalSize == 0 && Stride == 0 ) || + ( (TotalSize > (Stride * (Elements - 1))) && (TotalSize <= (Stride * Elements)) ) ); + return TotalSize - Stride * (Elements - 1); + } + else + { + return TotalSize; + } +} + +UINT SType::GetTotalPackedSize(BOOL IsSingleElement) CONST +{ + if (Elements > 0 && IsSingleElement) + { + D3DXASSERT(PackedSize % Elements == 0); + return PackedSize / Elements; + } + else + { + return PackedSize; + } +} + +SConstantBuffer *CEffect::FindCB(LPCSTR pName) +{ + UINT i; + + for (i=0; i<m_CBCount; i++) + { + if (!strcmp(m_pCBs[i].pName, pName)) + { + return &m_pCBs[i]; + } + } + + return NULL; +} + +inline UINT PtrToDword(void *pPtr) +{ + return (UINT)(UINT_PTR) pPtr; +} + +BOOL CEffect::IsOptimized() +{ + if ((m_Flags & D3DX11_EFFECT_OPTIMIZED) != 0) + { + D3DXASSERT(NULL == m_pReflection); + return TRUE; + } + else + { + D3DXASSERT(NULL != m_pReflection); + return FALSE; + } +} + +// Replace *ppType with the corresponding value in pMappingTable +// pMappingTable table describes how to map old type pointers to new type pointers +static HRESULT RemapType(SType **ppType, CPointerMappingTable *pMappingTable) +{ + HRESULT hr = S_OK; + + SPointerMapping ptrMapping; + CPointerMappingTable::CIterator iter; + ptrMapping.pOld = *ppType; + VH( pMappingTable->FindValueWithHash(ptrMapping, ptrMapping.Hash(), &iter) ); + *ppType = (SType *) iter.GetData().pNew; + +lExit: + return hr; +} + +// Replace *ppString with the corresponding value in pMappingTable +// pMappingTable table describes how to map old string pointers to new string pointers +static HRESULT RemapString(__in char **ppString, CPointerMappingTable *pMappingTable) +{ + HRESULT hr = S_OK; + + SPointerMapping ptrMapping; + CPointerMappingTable::CIterator iter; + ptrMapping.pOld = *ppString; + VH( pMappingTable->FindValueWithHash(ptrMapping, ptrMapping.Hash(), &iter) ); + *ppString = (char *) iter.GetData().pNew; + +lExit: + return hr; +} + +// Used in cloning, copy m_pMemberInterfaces from pEffectSource to this +HRESULT CEffect::CopyMemberInterfaces( CEffect* pEffectSource ) +{ + HRESULT hr = S_OK; + UINT i; // after a failure, this holds the failing index + + UINT Members = pEffectSource->m_pMemberInterfaces.GetSize(); + m_pMemberInterfaces.AddRange(Members); + for( i=0; i < Members; i++ ) + { + SMember* pOldMember = pEffectSource->m_pMemberInterfaces[i]; + if( pOldMember == NULL ) + { + // During Optimization, m_pMemberInterfaces[i] was set to NULL because it was an annotation + m_pMemberInterfaces[i] = NULL; + continue; + } + + SMember *pNewMember; + D3DXASSERT( pOldMember->pTopLevelEntity != NULL ); + + if (NULL == (pNewMember = CreateNewMember((SType*)pOldMember->pType, FALSE))) + { + DPF(0, "ID3DX11Effect: Out of memory while trying to create new member variable interface"); + VN( pNewMember ); + } + + pNewMember->pType = pOldMember->pType; + pNewMember->pName = pOldMember->pName; + pNewMember->pSemantic = pOldMember->pSemantic; + pNewMember->Data.pGeneric = pOldMember->Data.pGeneric; + pNewMember->IsSingleElement = pOldMember->IsSingleElement; + pNewMember->pTopLevelEntity = pOldMember->pTopLevelEntity; + pNewMember->pMemberData = pOldMember->pMemberData; + + m_pMemberInterfaces[i] = pNewMember; + } + +lExit: + if( FAILED(hr) ) + { + D3DXASSERT( i < Members ); + ZeroMemory( &m_pMemberInterfaces[i], sizeof(SMember) * ( Members - i ) ); + } + return hr; +} + +// Used in cloning, copy the string pool from pEffectSource to this and build mappingTable +// for use in RemapString +HRESULT CEffect::CopyStringPool( CEffect* pEffectSource, CPointerMappingTable& mappingTable ) +{ + HRESULT hr = S_OK; + D3DXASSERT( m_pPooledHeap != NULL ); + VN( m_pStringPool = NEW CEffect::CStringHashTable ); + m_pStringPool->SetPrivateHeap(m_pPooledHeap); + VH( m_pStringPool->AutoGrow() ); + + CStringHashTable::CIterator stringIter; + + // move strings over, build mapping table + for (pEffectSource->m_pStringPool->GetFirstEntry(&stringIter); !pEffectSource->m_pStringPool->PastEnd(&stringIter); pEffectSource->m_pStringPool->GetNextEntry(&stringIter)) + { + SPointerMapping ptrMapping; + char *pString; + + const char* pOldString = stringIter.GetData(); + ptrMapping.pOld = (void*)pOldString; + UINT len = (UINT)strlen(pOldString); + UINT hash = ptrMapping.Hash(); + VN( pString = new(*m_pPooledHeap) char[len + 1] ); + ptrMapping.pNew = (void*)pString; + memcpy(ptrMapping.pNew, ptrMapping.pOld, len + 1); + VH( m_pStringPool->AddValueWithHash(pString, hash) ); + + VH( mappingTable.AddValueWithHash(ptrMapping, hash) ); + } + + // Uncomment to print string mapping + /* + CPointerMappingTable::CIterator mapIter; + for (mappingTable.GetFirstEntry(&mapIter); !mappingTable.PastEnd(&mapIter); mappingTable.GetNextEntry(&mapIter)) + { + SPointerMapping ptrMapping = mapIter.GetData(); + DPF(0, "string: 0x%x : 0x%x %s", (UINT_PTR)ptrMapping.pOld, (UINT_PTR)ptrMapping.pNew, (char*)ptrMapping.pNew ); + }*/ + +lExit: + return hr; +} + +// Used in cloning, copy the unoptimized type pool from pEffectSource to this and build mappingTableTypes +// for use in RemapType. mappingTableStrings is the mapping table previously filled when copying strings. +HRESULT CEffect::CopyTypePool( CEffect* pEffectSource, CPointerMappingTable& mappingTableTypes, CPointerMappingTable& mappingTableStrings ) +{ + HRESULT hr = S_OK; + D3DXASSERT( m_pPooledHeap != NULL ); + VN( m_pTypePool = NEW CEffect::CTypeHashTable ); + m_pTypePool->SetPrivateHeap(m_pPooledHeap); + VH( m_pTypePool->AutoGrow() ); + + CTypeHashTable::CIterator typeIter; + CPointerMappingTable::CIterator mapIter; + + // first pass: move types over, build mapping table + for (pEffectSource->m_pTypePool->GetFirstEntry(&typeIter); !pEffectSource->m_pTypePool->PastEnd(&typeIter); pEffectSource->m_pTypePool->GetNextEntry(&typeIter)) + { + SPointerMapping ptrMapping; + SType *pType; + + ptrMapping.pOld = typeIter.GetData(); + UINT hash = ptrMapping.Hash(); + VN( (ptrMapping.pNew) = new(*m_pPooledHeap) SType ); + memcpy(ptrMapping.pNew, ptrMapping.pOld, sizeof(SType)); + + pType = (SType *) ptrMapping.pNew; + + // if this is a struct, move its members to the newly allocated space + if (EVT_Struct == pType->VarType) + { + SVariable* pOldMembers = pType->StructType.pMembers; + VN( pType->StructType.pMembers = new(*m_pPooledHeap) SVariable[pType->StructType.Members] ); + memcpy(pType->StructType.pMembers, pOldMembers, pType->StructType.Members * sizeof(SVariable)); + } + + VH( m_pTypePool->AddValueWithHash(pType, hash) ); + VH( mappingTableTypes.AddValueWithHash(ptrMapping, hash) ); + } + + // second pass: fixup structure member & name pointers + for (mappingTableTypes.GetFirstEntry(&mapIter); !mappingTableTypes.PastEnd(&mapIter); mappingTableTypes.GetNextEntry(&mapIter)) + { + SPointerMapping ptrMapping = mapIter.GetData(); + + // Uncomment to print type mapping + //DPF(0, "type: 0x%x : 0x%x", (UINT_PTR)ptrMapping.pOld, (UINT_PTR)ptrMapping.pNew ); + + SType *pType = (SType *) ptrMapping.pNew; + + if( pType->pTypeName ) + { + VH( RemapString(&pType->pTypeName, &mappingTableStrings) ); + } + + // if this is a struct, fix up its members' pointers + if (EVT_Struct == pType->VarType) + { + for (UINT i = 0; i < pType->StructType.Members; ++ i) + { + VH( RemapType((SType**)&pType->StructType.pMembers[i].pType, &mappingTableTypes) ); + if( pType->StructType.pMembers[i].pName ) + { + VH( RemapString(&pType->StructType.pMembers[i].pName, &mappingTableStrings) ); + } + if( pType->StructType.pMembers[i].pSemantic ) + { + VH( RemapString(&pType->StructType.pMembers[i].pSemantic, &mappingTableStrings) ); + } + } + } + } + +lExit: + return hr; +} + +// Used in cloning, copy the unoptimized type pool from pEffectSource to this and build mappingTableTypes +// for use in RemapType. mappingTableStrings is the mapping table previously filled when copying strings. +HRESULT CEffect::CopyOptimizedTypePool( CEffect* pEffectSource, CPointerMappingTable& mappingTableTypes ) +{ + HRESULT hr = S_OK; + CEffectHeap* pOptimizedTypeHeap = NULL; + + D3DXASSERT( pEffectSource->m_pOptimizedTypeHeap != NULL ); + D3DXASSERT( m_pTypePool == NULL ); + D3DXASSERT( m_pStringPool == NULL ); + D3DXASSERT( m_pPooledHeap == NULL ); + + VN( pOptimizedTypeHeap = NEW CEffectHeap ); + VH( pOptimizedTypeHeap->ReserveMemory( pEffectSource->m_pOptimizedTypeHeap->GetSize() ) ); + CPointerMappingTable::CIterator mapIter; + + // first pass: move types over, build mapping table + BYTE* pReadTypes = pEffectSource->m_pOptimizedTypeHeap->GetDataStart(); + while( pEffectSource->m_pOptimizedTypeHeap->IsInHeap( pReadTypes ) ) + { + SPointerMapping ptrMapping; + SType *pType; + UINT moveSize; + + ptrMapping.pOld = ptrMapping.pNew = pReadTypes; + moveSize = sizeof(SType); + VH( pOptimizedTypeHeap->MoveData(&ptrMapping.pNew, moveSize) ); + pReadTypes += moveSize; + + pType = (SType *) ptrMapping.pNew; + + // if this is a struct, move its members to the newly allocated space + if (EVT_Struct == pType->VarType) + { + moveSize = pType->StructType.Members * sizeof(SVariable); + VH( pOptimizedTypeHeap->MoveData((void **)&pType->StructType.pMembers, moveSize) ); + pReadTypes += moveSize; + } + + VH( mappingTableTypes.AddValueWithHash(ptrMapping, ptrMapping.Hash()) ); + } + + // second pass: fixup structure member & name pointers + for (mappingTableTypes.GetFirstEntry(&mapIter); !mappingTableTypes.PastEnd(&mapIter); mappingTableTypes.GetNextEntry(&mapIter)) + { + SPointerMapping ptrMapping = mapIter.GetData(); + + // Uncomment to print type mapping + //DPF(0, "type: 0x%x : 0x%x", (UINT_PTR)ptrMapping.pOld, (UINT_PTR)ptrMapping.pNew ); + + SType *pType = (SType *) ptrMapping.pNew; + + // if this is a struct, fix up its members' pointers + if (EVT_Struct == pType->VarType) + { + for (UINT i = 0; i < pType->StructType.Members; ++ i) + { + VH( RemapType((SType**)&pType->StructType.pMembers[i].pType, &mappingTableTypes) ); + } + } + } + +lExit: + return hr; +} + +// Used in cloning, create new ID3D11ConstantBuffers for each non-single CB +HRESULT CEffect::RecreateCBs() +{ + HRESULT hr = S_OK; + UINT i; // after a failure, this holds the failing index + + for (i = 0; i < m_CBCount; ++ i) + { + SConstantBuffer* pCB = &m_pCBs[i]; + + pCB->IsNonUpdatable = pCB->IsUserManaged || pCB->ClonedSingle(); + + if( pCB->Size > 0 && !pCB->ClonedSingle() ) + { + ID3D11Buffer** ppOriginalBuffer; + ID3D11ShaderResourceView** ppOriginalTBufferView; + + if( pCB->IsUserManaged ) + { + ppOriginalBuffer = &pCB->pMemberData[0].Data.pD3DEffectsManagedConstantBuffer; + ppOriginalTBufferView = &pCB->pMemberData[1].Data.pD3DEffectsManagedTextureBuffer; + } + else + { + ppOriginalBuffer = &pCB->pD3DObject; + ppOriginalTBufferView = &pCB->TBuffer.pShaderResource; + } + + VN( *ppOriginalBuffer ); + D3D11_BUFFER_DESC bufDesc; + (*ppOriginalBuffer)->GetDesc( &bufDesc ); + ID3D11Buffer* pNewBuffer = NULL; + VH( m_pDevice->CreateBuffer( &bufDesc, NULL, &pNewBuffer ) ); + (*ppOriginalBuffer)->Release(); + (*ppOriginalBuffer) = pNewBuffer; + pNewBuffer = NULL; + + if( pCB->IsTBuffer ) + { + VN( *ppOriginalTBufferView ); + D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc; + (*ppOriginalTBufferView)->GetDesc( &viewDesc ); + ID3D11ShaderResourceView* pNewView = NULL; + VH( m_pDevice->CreateShaderResourceView( (*ppOriginalBuffer), &viewDesc, &pNewView) ); + (*ppOriginalTBufferView)->Release(); + (*ppOriginalTBufferView) = pNewView; + pNewView = NULL; + } + else + { + D3DXASSERT( *ppOriginalTBufferView == NULL ); + ReplaceCBReference( pCB, (*ppOriginalBuffer) ); + } + + pCB->IsDirty = TRUE; + } + } + +lExit: + return hr; +} + +// Move Name and Semantic strings using mappingTableStrings +HRESULT CEffect::FixupMemberInterface( SMember* pMember, CEffect* pEffectSource, CPointerMappingTable& mappingTableStrings ) +{ + HRESULT hr = S_OK; + + if( pMember->pName ) + { + if( pEffectSource->m_pReflection && pEffectSource->m_pReflection->m_Heap.IsInHeap(pMember->pName) ) + { + pMember->pName = (char*)((UINT_PTR)pMember->pName - (UINT_PTR)pEffectSource->m_pReflection->m_Heap.GetDataStart() + (UINT_PTR)m_pReflection->m_Heap.GetDataStart()); + } + else + { + VH( RemapString(&pMember->pName, &mappingTableStrings) ); + } + } + if( pMember->pSemantic ) + { + if( pEffectSource->m_pReflection && pEffectSource->m_pReflection->m_Heap.IsInHeap(pMember->pSemantic) ) + { + pMember->pSemantic = (char*)((UINT_PTR)pMember->pSemantic - (UINT_PTR)pEffectSource->m_pReflection->m_Heap.GetDataStart() + (UINT_PTR)m_pReflection->m_Heap.GetDataStart()); + } + else + { + VH( RemapString(&pMember->pSemantic, &mappingTableStrings) ); + } + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// Public API to create a copy of this effect +HRESULT CEffect::CloneEffect(UINT Flags, ID3DX11Effect** ppClonedEffect ) +{ + HRESULT hr = S_OK; + CPointerMappingTable mappingTableTypes; + CPointerMappingTable mappingTableStrings; + + CEffectLoader loader; + CEffect* pNewEffect = NULL; + CDataBlockStore* pTempHeap = NULL; + + + VN( pNewEffect = NEW CEffect( m_Flags ) ); + if( Flags & D3DX11_EFFECT_CLONE_FORCE_NONSINGLE ) + { + // The effect is cloned as if there was no original, so don't mark it as cloned + pNewEffect->m_Flags &= ~(UINT)D3DX11_EFFECT_CLONE; + } + else + { + pNewEffect->m_Flags |= D3DX11_EFFECT_CLONE; + } + + pNewEffect->m_VariableCount = m_VariableCount; + pNewEffect->m_pVariables = m_pVariables; + pNewEffect->m_AnonymousShaderCount = m_AnonymousShaderCount; + pNewEffect->m_pAnonymousShaders = m_pAnonymousShaders; + pNewEffect->m_TechniqueCount = m_TechniqueCount; + pNewEffect->m_GroupCount = m_GroupCount; + pNewEffect->m_pGroups = m_pGroups; + pNewEffect->m_pNullGroup = m_pNullGroup; + pNewEffect->m_ShaderBlockCount = m_ShaderBlockCount; + pNewEffect->m_pShaderBlocks = m_pShaderBlocks; + pNewEffect->m_DepthStencilBlockCount = m_DepthStencilBlockCount; + pNewEffect->m_pDepthStencilBlocks = m_pDepthStencilBlocks; + pNewEffect->m_BlendBlockCount = m_BlendBlockCount; + pNewEffect->m_pBlendBlocks = m_pBlendBlocks; + pNewEffect->m_RasterizerBlockCount = m_RasterizerBlockCount; + pNewEffect->m_pRasterizerBlocks = m_pRasterizerBlocks; + pNewEffect->m_SamplerBlockCount = m_SamplerBlockCount; + pNewEffect->m_pSamplerBlocks = m_pSamplerBlocks; + pNewEffect->m_MemberDataCount = m_MemberDataCount; + pNewEffect->m_pMemberDataBlocks = m_pMemberDataBlocks; + pNewEffect->m_InterfaceCount = m_InterfaceCount; + pNewEffect->m_pInterfaces = m_pInterfaces; + pNewEffect->m_CBCount = m_CBCount; + pNewEffect->m_pCBs = m_pCBs; + pNewEffect->m_StringCount = m_StringCount; + pNewEffect->m_pStrings = m_pStrings; + pNewEffect->m_ShaderResourceCount = m_ShaderResourceCount; + pNewEffect->m_pShaderResources = m_pShaderResources; + pNewEffect->m_UnorderedAccessViewCount = m_UnorderedAccessViewCount; + pNewEffect->m_pUnorderedAccessViews = m_pUnorderedAccessViews; + pNewEffect->m_RenderTargetViewCount = m_RenderTargetViewCount; + pNewEffect->m_pRenderTargetViews = m_pRenderTargetViews; + pNewEffect->m_DepthStencilViewCount = m_DepthStencilViewCount; + pNewEffect->m_pDepthStencilViews = m_pDepthStencilViews; + pNewEffect->m_LocalTimer = m_LocalTimer; + pNewEffect->m_FXLIndex = m_FXLIndex; + pNewEffect->m_pDevice = m_pDevice; + pNewEffect->m_pClassLinkage = m_pClassLinkage; + + pNewEffect->AddRefAllForCloning( this ); + + + // m_pMemberInterfaces is a vector of cbuffer members that were created when the user called GetMemberBy* or GetElement + // or during Effect loading when an interface is initialized to a global class variable elment. + VH( pNewEffect->CopyMemberInterfaces( this ) ); + + loader.m_pvOldMemberInterfaces = &m_pMemberInterfaces; + loader.m_pEffect = pNewEffect; + loader.m_EffectMemory = loader.m_ReflectionMemory = 0; + + + // Move data from current effect to new effect + if( !IsOptimized() ) + { + VN( pNewEffect->m_pReflection = NEW CEffectReflection() ); + loader.m_pReflection = pNewEffect->m_pReflection; + + // make sure strings are moved before ReallocateEffectData + VH( loader.InitializeReflectionDataAndMoveStrings( m_pReflection->m_Heap.GetSize() ) ); + } + VH( loader.ReallocateEffectData( true ) ); + if( !IsOptimized() ) + { + VH( loader.ReallocateReflectionData( true ) ); + } + + + // Data structures for remapping type pointers and string pointers + VN( pTempHeap = NEW CDataBlockStore ); + pTempHeap->EnableAlignment(); + mappingTableTypes.SetPrivateHeap(pTempHeap); + mappingTableStrings.SetPrivateHeap(pTempHeap); + VH( mappingTableTypes.AutoGrow() ); + VH( mappingTableStrings.AutoGrow() ); + + if( !IsOptimized() ) + { + // Let's re-create the type pool and string pool + VN( pNewEffect->m_pPooledHeap = NEW CDataBlockStore ); + pNewEffect->m_pPooledHeap->EnableAlignment(); + + VH( pNewEffect->CopyStringPool( this, mappingTableStrings ) ); + VH( pNewEffect->CopyTypePool( this, mappingTableTypes, mappingTableStrings ) ); + } + else + { + // There's no string pool after optimizing. Let's re-create the type pool + VH( pNewEffect->CopyOptimizedTypePool( this, mappingTableTypes ) ); + } + + // fixup this effect's variable's types + VH( pNewEffect->OptimizeTypes(&mappingTableTypes, true) ); + VH( pNewEffect->RecreateCBs() ); + + + for (UINT i = 0; i < pNewEffect->m_pMemberInterfaces.GetSize(); ++ i) + { + SMember* pMember = pNewEffect->m_pMemberInterfaces[i]; + VH( pNewEffect->FixupMemberInterface( pMember, this, mappingTableStrings ) ); + } + + +lExit: + SAFE_DELETE( pTempHeap ); + if( FAILED( hr ) ) + { + SAFE_DELETE( pNewEffect ); + } + *ppClonedEffect = pNewEffect; + return hr; +} + +// Move all type pointers using pMappingTable. +// This is called after creating the optimized type pool or during cloning. +HRESULT CEffect::OptimizeTypes(CPointerMappingTable *pMappingTable, bool Cloning) +{ + HRESULT hr = S_OK; + UINT i; + + // find all child types, point them to the new location + for (i = 0; i < m_VariableCount; ++ i) + { + VH( RemapType((SType**)&m_pVariables[i].pType, pMappingTable) ); + } + + UINT Members = m_pMemberInterfaces.GetSize(); + for( i=0; i < Members; i++ ) + { + if( m_pMemberInterfaces[i] != NULL ) + { + VH( RemapType((SType**)&m_pMemberInterfaces[i]->pType, pMappingTable) ); + } + } + + // when cloning, there may be annotations + if( Cloning ) + { + for (UINT iVar = 0; iVar < m_VariableCount; ++ iVar) + { + for(i = 0; i < m_pVariables[iVar].AnnotationCount; ++ i ) + { + VH( RemapType((SType**)&m_pVariables[iVar].pAnnotations[i].pType, pMappingTable) ); + } + } + for (UINT iCB = 0; iCB < m_CBCount; ++ iCB) + { + for(i = 0; i < m_pCBs[iCB].AnnotationCount; ++ i ) + { + VH( RemapType((SType**)&m_pCBs[iCB].pAnnotations[i].pType, pMappingTable) ); + } + } + for (UINT iGroup = 0; iGroup < m_GroupCount; ++ iGroup) + { + for(i = 0; i < m_pGroups[iGroup].AnnotationCount; ++ i ) + { + VH( RemapType((SType**)&m_pGroups[iGroup].pAnnotations[i].pType, pMappingTable) ); + } + for(UINT iTech = 0; iTech < m_pGroups[iGroup].TechniqueCount; ++ iTech ) + { + for(i = 0; i < m_pGroups[iGroup].pTechniques[iTech].AnnotationCount; ++ i ) + { + VH( RemapType((SType**)&m_pGroups[iGroup].pTechniques[iTech].pAnnotations[i].pType, pMappingTable) ); + } + for(UINT iPass = 0; iPass < m_pGroups[iGroup].pTechniques[iTech].PassCount; ++ iPass ) + { + for(i = 0; i < m_pGroups[iGroup].pTechniques[iTech].pPasses[iPass].AnnotationCount; ++ i ) + { + VH( RemapType((SType**)&m_pGroups[iGroup].pTechniques[iTech].pPasses[iPass].pAnnotations[i].pType, pMappingTable) ); + } + } + } + } + } +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// Public API to shed this effect of its reflection data +HRESULT CEffect::Optimize() +{ + HRESULT hr = S_OK; + UINT i, j, k; + CEffectHeap *pOptimizedTypeHeap = NULL; + + if (IsOptimized()) + { + DPF(0, "ID3DX11Effect::Optimize: Effect has already been Optimize()'ed"); + return S_OK; + } + + // Delete annotations, names, semantics, and string data on variables + + for (i = 0; i < m_VariableCount; ++ i) + { + m_pVariables[i].AnnotationCount = 0; + m_pVariables[i].pAnnotations = NULL; + m_pVariables[i].pName = NULL; + m_pVariables[i].pSemantic = NULL; + + // 2) Point string variables to NULL + if (m_pVariables[i].pType->IsObjectType(EOT_String)) + { + D3DXASSERT(NULL != m_pVariables[i].Data.pString); + m_pVariables[i].Data.pString = NULL; + } + } + + // Delete annotations and names on CBs + + for (i = 0; i < m_CBCount; ++ i) + { + m_pCBs[i].AnnotationCount = 0; + m_pCBs[i].pAnnotations = NULL; + m_pCBs[i].pName = NULL; + m_pCBs[i].IsEffectOptimized = TRUE; + } + + // Delete annotations and names on techniques and passes + + for (i = 0; i < m_GroupCount; ++ i) + { + m_pGroups[i].AnnotationCount = 0; + m_pGroups[i].pAnnotations = NULL; + m_pGroups[i].pName = NULL; + + for (j = 0; j < m_pGroups[i].TechniqueCount; ++ j) + { + m_pGroups[i].pTechniques[j].AnnotationCount = 0; + m_pGroups[i].pTechniques[j].pAnnotations = NULL; + m_pGroups[i].pTechniques[j].pName = NULL; + + for (k = 0; k < m_pGroups[i].pTechniques[j].PassCount; ++ k) + { + m_pGroups[i].pTechniques[j].pPasses[k].AnnotationCount = 0; + m_pGroups[i].pTechniques[j].pPasses[k].pAnnotations = NULL; + m_pGroups[i].pTechniques[j].pPasses[k].pName = NULL; + } + } + }; + + // 2) Remove shader bytecode & stream out decls + // (all are contained within pReflectionData) + + for (i = 0; i < m_ShaderBlockCount; ++ i) + { + if( m_pShaderBlocks[i].pReflectionData ) + { + // pReflection was not created with PRIVATENEW + SAFE_RELEASE( m_pShaderBlocks[i].pReflectionData->pReflection ); + + m_pShaderBlocks[i].pReflectionData = NULL; + } + } + + UINT Members = m_pMemberInterfaces.GetSize(); + for( i=0; i < Members; i++ ) + { + D3DXASSERT( m_pMemberInterfaces[i] != NULL ); + if( IsReflectionData(m_pMemberInterfaces[i]->pTopLevelEntity) ) + { + D3DXASSERT( IsReflectionData(m_pMemberInterfaces[i]->Data.pGeneric) ); + + // This is checked when cloning (so we don't clone Optimized-out member variables) + m_pMemberInterfaces[i] = NULL; + } + else + { + m_pMemberInterfaces[i]->pName = NULL; + m_pMemberInterfaces[i]->pSemantic = NULL; + } + } + + + + // get rid of the name/type hash tables and string data, + // then reallocate the type data and fix up this effect + CPointerMappingTable mappingTable; + CTypeHashTable::CIterator typeIter; + CPointerMappingTable::CIterator mapIter; + CCheckedDword chkSpaceNeeded = 0; + UINT spaceNeeded; + + // first pass: compute needed space + for (m_pTypePool->GetFirstEntry(&typeIter); !m_pTypePool->PastEnd(&typeIter); m_pTypePool->GetNextEntry(&typeIter)) + { + SType *pType = typeIter.GetData(); + + chkSpaceNeeded += AlignToPowerOf2(sizeof(SType), c_DataAlignment); + + // if this is a struct, allocate room for its members + if (EVT_Struct == pType->VarType) + { + chkSpaceNeeded += AlignToPowerOf2(pType->StructType.Members * sizeof(SVariable), c_DataAlignment); + } + } + + VH( chkSpaceNeeded.GetValue(&spaceNeeded) ); + + D3DXASSERT(NULL == m_pOptimizedTypeHeap); + VN( pOptimizedTypeHeap = NEW CEffectHeap ); + VH( pOptimizedTypeHeap->ReserveMemory(spaceNeeded)); + + // use the private heap that we're about to destroy as scratch space for the mapping table + mappingTable.SetPrivateHeap(m_pPooledHeap); + VH( mappingTable.AutoGrow() ); + + // second pass: move types over, build mapping table + for (m_pTypePool->GetFirstEntry(&typeIter); !m_pTypePool->PastEnd(&typeIter); m_pTypePool->GetNextEntry(&typeIter)) + { + SPointerMapping ptrMapping; + SType *pType; + + ptrMapping.pOld = ptrMapping.pNew = typeIter.GetData(); + VH( pOptimizedTypeHeap->MoveData(&ptrMapping.pNew, sizeof(SType)) ); + + pType = (SType *) ptrMapping.pNew; + + // if this is a struct, move its members to the newly allocated space + if (EVT_Struct == pType->VarType) + { + VH( pOptimizedTypeHeap->MoveData((void **)&pType->StructType.pMembers, pType->StructType.Members * sizeof(SVariable)) ); + } + + VH( mappingTable.AddValueWithHash(ptrMapping, ptrMapping.Hash()) ); + } + + // third pass: fixup structure member & name pointers + for (mappingTable.GetFirstEntry(&mapIter); !mappingTable.PastEnd(&mapIter); mappingTable.GetNextEntry(&mapIter)) + { + SPointerMapping ptrMapping = mapIter.GetData(); + SType *pType = (SType *) ptrMapping.pNew; + + pType->pTypeName = NULL; + + // if this is a struct, fix up its members' pointers + if (EVT_Struct == pType->VarType) + { + for (i = 0; i < pType->StructType.Members; ++ i) + { + VH( RemapType((SType**)&pType->StructType.pMembers[i].pType, &mappingTable) ); + pType->StructType.pMembers[i].pName = NULL; + pType->StructType.pMembers[i].pSemantic = NULL; + } + } + } + + // fixup this effect's variable's types + VH( OptimizeTypes(&mappingTable) ); + + m_pOptimizedTypeHeap = pOptimizedTypeHeap; + pOptimizedTypeHeap = NULL; + +#ifdef D3DX11_FX_PRINT_HASH_STATS + DPF(0, "Compiler string pool hash table statistics:"); + m_pTypePool->PrintHashTableStats(); + DPF(0, "Compiler type pool hash table statistics:"); + m_pStringPool->PrintHashTableStats(); +#endif // D3DX11_FX_PRINT_HASH_STATS + + SAFE_DELETE(m_pTypePool); + SAFE_DELETE(m_pStringPool); + SAFE_DELETE(m_pPooledHeap); + + DPF(0, "ID3DX11Effect::Optimize: %d bytes of reflection data freed.", m_pReflection->m_Heap.GetSize()); + SAFE_DELETE(m_pReflection); + m_Flags |= D3DX11_EFFECT_OPTIMIZED; + +lExit: + SAFE_DELETE(pOptimizedTypeHeap); + return hr; +} + +SMember * CreateNewMember(SType *pType, BOOL IsAnnotation) +{ + switch (pType->VarType) + { + case EVT_Struct: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SNumericAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SNumericAnnotationMember; + } + else if (pType->StructType.ImplementsInterface) + { + D3DXASSERT(sizeof(SClassInstanceGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SClassInstanceGlobalVariableMember; + } + else + { + D3DXASSERT(sizeof(SNumericGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SNumericGlobalVariableMember; + } + break; + case EVT_Interface: + D3DXASSERT(sizeof(SInterfaceGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SInterfaceGlobalVariableMember; + break; + case EVT_Object: + switch (pType->ObjectType) + { + case EOT_String: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SStringAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SStringAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SStringGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SStringGlobalVariableMember; + } + + break; + case EOT_Texture: + case EOT_Texture1D: + case EOT_Texture1DArray: + case EOT_Texture2D: + case EOT_Texture2DArray: + case EOT_Texture2DMS: + case EOT_Texture2DMSArray: + case EOT_Texture3D: + case EOT_TextureCube: + case EOT_TextureCubeArray: + case EOT_Buffer: + case EOT_ByteAddressBuffer: + case EOT_StructuredBuffer: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SShaderResourceGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SShaderResourceGlobalVariableMember; + break; + case EOT_RWTexture1D: + case EOT_RWTexture1DArray: + case EOT_RWTexture2D: + case EOT_RWTexture2DArray: + case EOT_RWTexture3D: + case EOT_RWBuffer: + case EOT_RWByteAddressBuffer: + case EOT_RWStructuredBuffer: + case EOT_RWStructuredBufferAlloc: + case EOT_RWStructuredBufferConsume: + case EOT_AppendStructuredBuffer: + case EOT_ConsumeStructuredBuffer: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SUnorderedAccessViewGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SUnorderedAccessViewGlobalVariableMember; + break; + case EOT_VertexShader: + case EOT_VertexShader5: + case EOT_GeometryShader: + case EOT_GeometryShaderSO: + case EOT_GeometryShader5: + case EOT_PixelShader: + case EOT_PixelShader5: + case EOT_HullShader5: + case EOT_DomainShader5: + case EOT_ComputeShader5: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SShaderGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SShaderGlobalVariableMember; + break; + case EOT_Blend: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SBlendGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SBlendGlobalVariableMember; + break; + case EOT_Rasterizer: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SRasterizerGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SRasterizerGlobalVariableMember; + break; + case EOT_DepthStencil: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SDepthStencilGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SDepthStencilGlobalVariableMember; + break; + case EOT_Sampler: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SSamplerGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SSamplerGlobalVariableMember; + break; + case EOT_DepthStencilView: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SDepthStencilViewGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SDepthStencilViewGlobalVariableMember; + break; + case EOT_RenderTargetView: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SRenderTargetViewGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SRenderTargetViewGlobalVariableMember; + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal error: invalid object type." ); + return NULL; + break; + } + break; + case EVT_Numeric: + switch (pType->NumericType.NumericLayout) + { + case ENL_Matrix: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SMatrixAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SMatrixAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SMatrixGlobalVariableMember) == sizeof(SMember)); + D3DXASSERT(sizeof(SMatrix4x4ColumnMajorGlobalVariableMember) == sizeof(SMember)); + D3DXASSERT(sizeof(SMatrix4x4RowMajorGlobalVariableMember) == sizeof(SMember)); + + if (pType->NumericType.Rows == 4 && pType->NumericType.Columns == 4) + { + if (pType->NumericType.IsColumnMajor) + { + return (SMember*) NEW SMatrix4x4ColumnMajorGlobalVariableMember; + } + else + { + return (SMember*) NEW SMatrix4x4RowMajorGlobalVariableMember; + } + } + else + { + return (SMember*) NEW SMatrixGlobalVariableMember; + } + } + break; + case ENL_Vector: + switch (pType->NumericType.ScalarType) + { + case EST_Float: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SFloatVectorAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SFloatVectorAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SFloatVectorGlobalVariableMember) == sizeof(SMember)); + D3DXASSERT(sizeof(SFloatVector4GlobalVariableMember) == sizeof(SMember)); + + if (pType->NumericType.Columns == 4) + { + return (SMember*) NEW SFloatVector4GlobalVariableMember; + } + else + { + return (SMember*) NEW SFloatVectorGlobalVariableMember; + } + } + break; + case EST_Bool: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SBoolVectorAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SBoolVectorAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SBoolVectorGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SBoolVectorGlobalVariableMember; + } + break; + case EST_UInt: + case EST_Int: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SIntVectorAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SIntVectorAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SIntVectorGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SIntVectorGlobalVariableMember; + } + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal loading error: invalid vector type." ); + break; + } + break; + case ENL_Scalar: + switch (pType->NumericType.ScalarType) + { + case EST_Float: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SFloatScalarAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SFloatScalarAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SFloatScalarGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SFloatScalarGlobalVariableMember; + } + break; + case EST_UInt: + case EST_Int: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SIntScalarAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SIntScalarAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SIntScalarGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SIntScalarGlobalVariableMember; + } + break; + case EST_Bool: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SBoolScalarAnnotationMember) == sizeof(SMember)); + return (SMember*) NEW SBoolScalarAnnotationMember; + } + else + { + D3DXASSERT(sizeof(SBoolScalarGlobalVariableMember) == sizeof(SMember)); + return (SMember*) NEW SBoolScalarGlobalVariableMember; + } + break; + default: + DPF( 0, "Internal loading error: invalid scalar type." ); + D3DXASSERT(0); + break; + } + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal loading error: invalid numeric type." ); + break; + } + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal loading error: invalid variable type." ); + break; + } + return NULL; +} + +// Global variables are created in place because storage for them was allocated during LoadEffect +HRESULT PlacementNewVariable(void *pVar, SType *pType, BOOL IsAnnotation) +{ + switch (pType->VarType) + { + case EVT_Struct: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SNumericAnnotation) == sizeof(SAnnotation)); + new(pVar) SNumericAnnotation(); + } + else if (pType->StructType.ImplementsInterface) + { + D3DXASSERT(sizeof(SClassInstanceGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SClassInstanceGlobalVariable; + } + else + { + D3DXASSERT(sizeof(SNumericGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SNumericGlobalVariable; + } + break; + case EVT_Interface: + D3DXASSERT(sizeof(SInterfaceGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SInterfaceGlobalVariable; + break; + case EVT_Object: + switch (pType->ObjectType) + { + case EOT_String: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SStringAnnotation) == sizeof(SAnnotation)); + new(pVar) SStringAnnotation; + } + else + { + D3DXASSERT(sizeof(SStringGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SStringGlobalVariable; + } + + break; + case EOT_Texture: + case EOT_Texture1D: + case EOT_Texture1DArray: + case EOT_Texture2D: + case EOT_Texture2DArray: + case EOT_Texture2DMS: + case EOT_Texture2DMSArray: + case EOT_Texture3D: + case EOT_TextureCube: + case EOT_TextureCubeArray: + case EOT_Buffer: + case EOT_ByteAddressBuffer: + case EOT_StructuredBuffer: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SShaderResourceGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SShaderResourceGlobalVariable; + break; + case EOT_RWTexture1D: + case EOT_RWTexture1DArray: + case EOT_RWTexture2D: + case EOT_RWTexture2DArray: + case EOT_RWTexture3D: + case EOT_RWBuffer: + case EOT_RWByteAddressBuffer: + case EOT_RWStructuredBuffer: + case EOT_RWStructuredBufferAlloc: + case EOT_RWStructuredBufferConsume: + case EOT_AppendStructuredBuffer: + case EOT_ConsumeStructuredBuffer: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SUnorderedAccessViewGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SUnorderedAccessViewGlobalVariable; + break; + case EOT_VertexShader: + case EOT_VertexShader5: + case EOT_GeometryShader: + case EOT_GeometryShaderSO: + case EOT_GeometryShader5: + case EOT_PixelShader: + case EOT_PixelShader5: + case EOT_HullShader5: + case EOT_DomainShader5: + case EOT_ComputeShader5: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SShaderGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SShaderGlobalVariable; + break; + case EOT_Blend: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SBlendGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SBlendGlobalVariable; + break; + case EOT_Rasterizer: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SRasterizerGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SRasterizerGlobalVariable; + break; + case EOT_DepthStencil: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SDepthStencilGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SDepthStencilGlobalVariable; + break; + case EOT_Sampler: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SSamplerGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SSamplerGlobalVariable; + break; + case EOT_RenderTargetView: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SRenderTargetViewGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SRenderTargetViewGlobalVariable; + break; + case EOT_DepthStencilView: + D3DXASSERT(!IsAnnotation); + D3DXASSERT(sizeof(SDepthStencilViewGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SDepthStencilViewGlobalVariable; + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal loading error: invalid object type." ); + return E_FAIL; + break; + } + break; + case EVT_Numeric: + switch (pType->NumericType.NumericLayout) + { + case ENL_Matrix: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SMatrixAnnotation) == sizeof(SAnnotation)); + new(pVar) SMatrixAnnotation; + } + else + { + D3DXASSERT(sizeof(SMatrixGlobalVariable) == sizeof(SGlobalVariable)); + D3DXASSERT(sizeof(SMatrix4x4ColumnMajorGlobalVariable) == sizeof(SGlobalVariable)); + D3DXASSERT(sizeof(SMatrix4x4RowMajorGlobalVariable) == sizeof(SGlobalVariable)); + + if (pType->NumericType.Rows == 4 && pType->NumericType.Columns == 4) + { + if (pType->NumericType.IsColumnMajor) + { + new(pVar) SMatrix4x4ColumnMajorGlobalVariable; + } + else + { + new(pVar) SMatrix4x4RowMajorGlobalVariable; + } + } + else + { + new(pVar) SMatrixGlobalVariable; + } + } + break; + case ENL_Vector: + switch (pType->NumericType.ScalarType) + { + case EST_Float: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SFloatVectorAnnotation) == sizeof(SAnnotation)); + new(pVar) SFloatVectorAnnotation; + } + else + { + D3DXASSERT(sizeof(SFloatVectorGlobalVariable) == sizeof(SGlobalVariable)); + D3DXASSERT(sizeof(SFloatVector4GlobalVariable) == sizeof(SGlobalVariable)); + + if (pType->NumericType.Columns == 4) + { + new(pVar) SFloatVector4GlobalVariable; + } + else + { + new(pVar) SFloatVectorGlobalVariable; + } + } + break; + case EST_Bool: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SBoolVectorAnnotation) == sizeof(SAnnotation)); + new(pVar) SBoolVectorAnnotation; + } + else + { + D3DXASSERT(sizeof(SBoolVectorGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SBoolVectorGlobalVariable; + } + break; + case EST_UInt: + case EST_Int: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SIntVectorAnnotation) == sizeof(SAnnotation)); + new(pVar) SIntVectorAnnotation; + } + else + { + D3DXASSERT(sizeof(SIntVectorGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SIntVectorGlobalVariable; + } + break; + } + break; + case ENL_Scalar: + switch (pType->NumericType.ScalarType) + { + case EST_Float: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SFloatScalarAnnotation) == sizeof(SAnnotation)); + new(pVar) SFloatScalarAnnotation; + } + else + { + D3DXASSERT(sizeof(SFloatScalarGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SFloatScalarGlobalVariable; + } + break; + case EST_UInt: + case EST_Int: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SIntScalarAnnotation) == sizeof(SAnnotation)); + new(pVar) SIntScalarAnnotation; + } + else + { + D3DXASSERT(sizeof(SIntScalarGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SIntScalarGlobalVariable; + } + break; + case EST_Bool: + if (IsAnnotation) + { + D3DXASSERT(sizeof(SBoolScalarAnnotation) == sizeof(SAnnotation)); + new(pVar) SBoolScalarAnnotation; + } + else + { + D3DXASSERT(sizeof(SBoolScalarGlobalVariable) == sizeof(SGlobalVariable)); + new(pVar) SBoolScalarGlobalVariable; + } + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal loading error: invalid scalar type." ); + return E_FAIL; + break; + } + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal loading error: invalid numeric type." ); + return E_FAIL; + break; + } + break; + default: + D3DXASSERT(0); + DPF( 0, "Internal loading error: invalid variable type." ); + return E_FAIL; + break; + } + return S_OK; +} + +} diff --git a/sample/d3d11/Effects11/EffectReflection.cpp b/sample/d3d11/Effects11/EffectReflection.cpp new file mode 100644 index 0000000..138447b --- /dev/null +++ b/sample/d3d11/Effects11/EffectReflection.cpp @@ -0,0 +1,2151 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectReflection.cpp +// Content: D3DX11 Effects public reflection APIs +// +////////////////////////////////////////////////////////////////////////////// + +#include "pchfx.h" + +namespace D3DX11Effects +{ + +SEffectInvalidType g_InvalidType; + +SEffectInvalidScalarVariable g_InvalidScalarVariable; +SEffectInvalidVectorVariable g_InvalidVectorVariable; +SEffectInvalidMatrixVariable g_InvalidMatrixVariable; +SEffectInvalidStringVariable g_InvalidStringVariable; +SEffectInvalidClassInstanceVariable g_InvalidClassInstanceVariable; +SEffectInvalidInterfaceVariable g_InvalidInterfaceVariable; +SEffectInvalidShaderResourceVariable g_InvalidShaderResourceVariable; +SEffectInvalidUnorderedAccessViewVariable g_InvalidUnorderedAccessViewVariable; +SEffectInvalidRenderTargetViewVariable g_InvalidRenderTargetViewVariable; +SEffectInvalidDepthStencilViewVariable g_InvalidDepthStencilViewVariable; +SEffectInvalidConstantBuffer g_InvalidConstantBuffer; +SEffectInvalidShaderVariable g_InvalidShaderVariable; +SEffectInvalidBlendVariable g_InvalidBlendVariable; +SEffectInvalidDepthStencilVariable g_InvalidDepthStencilVariable; +SEffectInvalidRasterizerVariable g_InvalidRasterizerVariable; +SEffectInvalidSamplerVariable g_InvalidSamplerVariable; + +SEffectInvalidPass g_InvalidPass; +SEffectInvalidTechnique g_InvalidTechnique; +SEffectInvalidGroup g_InvalidGroup; + + +////////////////////////////////////////////////////////////////////////// +// Helper routine implementations +////////////////////////////////////////////////////////////////////////// + +ID3DX11EffectConstantBuffer * NoParentCB() +{ + DPF(0, "ID3DX11EffectVariable::GetParentConstantBuffer: Variable does not have a parent constant buffer"); + // have to typecast because the type of g_InvalidScalarVariable has not been declared yet + return &g_InvalidConstantBuffer; +} + +ID3DX11EffectVariable * GetAnnotationByIndexHelper(const char *pClassName, UINT Index, UINT AnnotationCount, SAnnotation *pAnnotations) +{ + if (Index >= AnnotationCount) + { + DPF(0, "%s::GetAnnotationByIndex: Invalid index (%d, total: %d)", pClassName, Index, AnnotationCount); + return &g_InvalidScalarVariable; + } + + return pAnnotations + Index; +} + +ID3DX11EffectVariable * GetAnnotationByNameHelper(const char *pClassName, LPCSTR Name, UINT AnnotationCount, SAnnotation *pAnnotations) +{ + UINT i; + for (i = 0; i < AnnotationCount; ++ i) + { + if (strcmp(pAnnotations[i].pName, Name) == 0) + { + return pAnnotations + i; + } + } + + DPF(0, "%s::GetAnnotationByName: Annotation [%s] not found", pClassName, Name); + return &g_InvalidScalarVariable; +} + +////////////////////////////////////////////////////////////////////////// +// Effect routines to pool interfaces +////////////////////////////////////////////////////////////////////////// + +ID3DX11EffectType * CEffect::CreatePooledSingleElementTypeInterface(SType *pType) +{ + UINT i; + + if (IsOptimized()) + { + DPF(0, "ID3DX11Effect: Cannot create new type interfaces since the effect has been Optimize()'ed"); + return &g_InvalidType; + } + + for (i = 0; i < m_pTypeInterfaces.GetSize(); ++ i) + { + if (m_pTypeInterfaces[i]->pType == pType) + { + return (SSingleElementType*)m_pTypeInterfaces[i]; + } + } + SSingleElementType *pNewType; + if (NULL == (pNewType = NEW SSingleElementType)) + { + DPF(0, "ID3DX11Effect: Out of memory while trying to create new type interface"); + return &g_InvalidType; + } + + pNewType->pType = pType; + m_pTypeInterfaces.Add(pNewType); + + return pNewType; +} + +// Create a member variable (via GetMemberBy* or GetElement) +ID3DX11EffectVariable * CEffect::CreatePooledVariableMemberInterface(TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity, SVariable *pMember, UDataPointer Data, BOOL IsSingleElement, UINT Index) +{ + BOOL IsAnnotation; + UINT i; + + if (IsOptimized()) + { + DPF(0, "ID3DX11Effect: Cannot create new variable interfaces since the effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + for (i = 0; i < m_pMemberInterfaces.GetSize(); ++ i) + { + if (m_pMemberInterfaces[i]->pType == pMember->pType && + m_pMemberInterfaces[i]->pName == pMember->pName && + m_pMemberInterfaces[i]->pSemantic == pMember->pSemantic && + m_pMemberInterfaces[i]->Data.pGeneric == Data.pGeneric && + m_pMemberInterfaces[i]->IsSingleElement == IsSingleElement && + ((SMember*)m_pMemberInterfaces[i])->pTopLevelEntity == pTopLevelEntity) + { + return (ID3DX11EffectVariable *) m_pMemberInterfaces[i]; + } + } + + // is this annotation or runtime data? + if( pTopLevelEntity->pEffect->IsReflectionData(pTopLevelEntity) ) + { + D3DXASSERT( pTopLevelEntity->pEffect->IsReflectionData(Data.pGeneric) ); + IsAnnotation = TRUE; + } + else + { + // if the heap is empty, we are still loading the Effect, and thus creating a member for a variable initializer + // ex. Interface myInt = myClassArray[2]; + if( pTopLevelEntity->pEffect->m_Heap.GetSize() > 0 ) + { + D3DXASSERT( pTopLevelEntity->pEffect->IsRuntimeData(pTopLevelEntity) ); + if (!pTopLevelEntity->pType->IsObjectType(EOT_String)) + { + // strings are funny; their data is reflection data, so ignore those + D3DXASSERT( pTopLevelEntity->pEffect->IsRuntimeData(Data.pGeneric) ); + } + } + IsAnnotation = FALSE; + } + + SMember *pNewMember; + + if (NULL == (pNewMember = CreateNewMember((SType*)pMember->pType, IsAnnotation))) + { + DPF(0, "ID3DX11Effect: Out of memory while trying to create new member variable interface"); + return &g_InvalidScalarVariable; + } + + pNewMember->pType = pMember->pType; + pNewMember->pName = pMember->pName; + pNewMember->pSemantic = pMember->pSemantic; + pNewMember->Data.pGeneric = Data.pGeneric; + pNewMember->IsSingleElement = IsSingleElement; + pNewMember->pTopLevelEntity = pTopLevelEntity; + + if( IsSingleElement && pMember->pMemberData ) + { + D3DXASSERT( !IsAnnotation ); + // This is an element of a global variable array + pNewMember->pMemberData = pMember->pMemberData + Index; + } + + if (FAILED(m_pMemberInterfaces.Add(pNewMember))) + { + SAFE_DELETE(pNewMember); + DPF(0, "ID3DX11Effect: Out of memory while trying to create new member variable interface"); + return &g_InvalidScalarVariable; + } + + return (ID3DX11EffectVariable *) pNewMember; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectType (SType, SSingleElementType implementations) +////////////////////////////////////////////////////////////////////////// + +static ID3DX11EffectType * GetTypeByIndexHelper(UINT Index, UINT VariableCount, + SVariable *pVariables, UINT SizeOfVariableType) +{ + LPCSTR pFuncName = "ID3DX11EffectType::GetMemberTypeByIndex"; + + if (Index >= VariableCount) + { + DPF(0, "%s: Invalid index (%d, total: %d)", pFuncName, Index, VariableCount); + return &g_InvalidType; + } + + SVariable *pVariable = (SVariable *)((BYTE *)pVariables + Index * SizeOfVariableType); + if (NULL == pVariable->pName) + { + DPF(0, "%s: Cannot get member types; Effect has been Optimize()'ed", pFuncName); + return &g_InvalidType; + } + + return (ID3DX11EffectType *) pVariable->pType; +} + +static ID3DX11EffectType * GetTypeByNameHelper(LPCSTR Name, UINT VariableCount, + SVariable *pVariables, UINT SizeOfVariableType) +{ + LPCSTR pFuncName = "ID3DX11EffectType::GetMemberTypeByName"; + + if (NULL == Name) + { + DPF(0, "%s: Parameter Name was NULL.", pFuncName); + return &g_InvalidType; + } + + UINT i; + SVariable *pVariable; + + for (i = 0; i < VariableCount; ++ i) + { + pVariable = (SVariable *)((BYTE *)pVariables + i * SizeOfVariableType); + if (NULL == pVariable->pName) + { + DPF(0, "%s: Cannot get member types; Effect has been Optimize()'ed", pFuncName); + return &g_InvalidType; + } + if (strcmp(pVariable->pName, Name) == 0) + { + return (ID3DX11EffectType *) pVariable->pType; + } + } + + DPF(0, "%s: Member type [%s] not found", pFuncName, Name); + return &g_InvalidType; +} + + +static ID3DX11EffectType * GetTypeBySemanticHelper(LPCSTR Semantic, UINT VariableCount, + SVariable *pVariables, UINT SizeOfVariableType) +{ + LPCSTR pFuncName = "ID3DX11EffectType::GetMemberTypeBySemantic"; + + if (NULL == Semantic) + { + DPF(0, "%s: Parameter Semantic was NULL.", pFuncName); + return &g_InvalidType; + } + + UINT i; + SVariable *pVariable; + + for (i = 0; i < VariableCount; ++ i) + { + pVariable = (SVariable *)((BYTE *)pVariables + i * SizeOfVariableType); + if (NULL == pVariable->pName) + { + DPF(0, "%s: Cannot get member types; Effect has been Optimize()'ed", pFuncName); + return &g_InvalidType; + } + if (NULL != pVariable->pSemantic && + _stricmp(pVariable->pSemantic, Semantic) == 0) + { + return (ID3DX11EffectType *) pVariable->pType; + } + } + + DPF(0, "%s: Member type with semantic [%s] not found", pFuncName, Semantic); + return &g_InvalidType; +} + +ID3DX11EffectType * SType::GetMemberTypeByIndex(UINT Index) +{ + if (VarType != EVT_Struct) + { + DPF(0, "ID3DX11EffectType::GetMemberTypeByIndex: This interface does not refer to a structure"); + return &g_InvalidType; + } + + return GetTypeByIndexHelper(Index, StructType.Members, StructType.pMembers, sizeof(SVariable)); +} + +ID3DX11EffectType * SType::GetMemberTypeByName(LPCSTR Name) +{ + if (VarType != EVT_Struct) + { + DPF(0, "ID3DX11EffectType::GetMemberTypeByName: This interface does not refer to a structure"); + return &g_InvalidType; + } + + return GetTypeByNameHelper(Name, StructType.Members, StructType.pMembers, sizeof(SVariable)); +} + +ID3DX11EffectType * SType::GetMemberTypeBySemantic(LPCSTR Semantic) +{ + if (VarType != EVT_Struct) + { + DPF(0, "ID3DX11EffectType::GetMemberTypeBySemantic: This interface does not refer to a structure"); + return &g_InvalidType; + } + + return GetTypeBySemanticHelper(Semantic, StructType.Members, StructType.pMembers, sizeof(SVariable)); +} + +LPCSTR SType::GetMemberName(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectType::GetMemberName"; + + if (VarType != EVT_Struct) + { + DPF(0, "%s: This interface does not refer to a structure", pFuncName); + return NULL; + } + + if (Index >= StructType.Members) + { + DPF(0, "%s: Invalid index (%d, total: %d)", pFuncName, Index, StructType.Members); + return NULL; + } + + SVariable *pVariable = StructType.pMembers + Index; + + if (NULL == pVariable->pName) + { + DPF(0, "%s: Cannot get member names; Effect has been Optimize()'ed", pFuncName); + return NULL; + } + + return pVariable->pName; +} + +LPCSTR SType::GetMemberSemantic(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectType::GetMemberSemantic"; + + if (VarType != EVT_Struct) + { + DPF(0, "%s: This interface does not refer to a structure", pFuncName); + return NULL; + } + + if (Index >= StructType.Members) + { + DPF(0, "%s: Invalid index (%d, total: %d)", pFuncName, Index, StructType.Members); + return NULL; + } + + SVariable *pVariable = StructType.pMembers + Index; + + if (NULL == pVariable->pName) + { + DPF(0, "%s: Cannot get member semantics; Effect has been Optimize()'ed", pFuncName); + return NULL; + } + + return pVariable->pSemantic; +} + +HRESULT SType::GetDescHelper(D3DX11_EFFECT_TYPE_DESC *pDesc, BOOL IsSingleElement) const +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectType::GetDesc"; + + VERIFYPARAMETER(pDesc); + + pDesc->TypeName = pTypeName; + + // intentionally return 0 so they know it's not a single element array + pDesc->Elements = IsSingleElement ? 0 : Elements; + pDesc->PackedSize = GetTotalPackedSize(IsSingleElement); + pDesc->UnpackedSize = GetTotalUnpackedSize(IsSingleElement); + pDesc->Stride = Stride; + + switch (VarType) + { + case EVT_Numeric: + switch (NumericType.NumericLayout) + { + case ENL_Matrix: + if (NumericType.IsColumnMajor) + { + pDesc->Class = D3D10_SVC_MATRIX_COLUMNS; + } + else + { + pDesc->Class = D3D10_SVC_MATRIX_ROWS; + } + break; + case ENL_Vector: + pDesc->Class = D3D10_SVC_VECTOR; + break; + case ENL_Scalar: + pDesc->Class = D3D10_SVC_SCALAR; + break; + default: + D3DXASSERT(0); + } + + switch (NumericType.ScalarType) + { + case EST_Bool: + pDesc->Type = D3D10_SVT_BOOL; + break; + case EST_Int: + pDesc->Type = D3D10_SVT_INT; + break; + case EST_UInt: + pDesc->Type = D3D10_SVT_UINT; + break; + case EST_Float: + pDesc->Type = D3D10_SVT_FLOAT; + break; + default: + D3DXASSERT(0); + } + + pDesc->Rows = NumericType.Rows; + pDesc->Columns = NumericType.Columns; + pDesc->Members = 0; + + break; + + case EVT_Struct: + pDesc->Rows = 0; + pDesc->Columns = 0; + pDesc->Members = StructType.Members; + if( StructType.ImplementsInterface ) + { + pDesc->Class = D3D11_SVC_INTERFACE_CLASS; + } + else + { + pDesc->Class = D3D10_SVC_STRUCT; + } + pDesc->Type = D3D10_SVT_VOID; + break; + + case EVT_Interface: + pDesc->Rows = 0; + pDesc->Columns = 0; + pDesc->Members = 0; + pDesc->Class = D3D11_SVC_INTERFACE_POINTER; + pDesc->Type = D3D11_SVT_INTERFACE_POINTER; + break; + + case EVT_Object: + pDesc->Rows = 0; + pDesc->Columns = 0; + pDesc->Members = 0; + pDesc->Class = D3D10_SVC_OBJECT; + + switch (ObjectType) + { + case EOT_String: + pDesc->Type = D3D10_SVT_STRING; + break; + case EOT_Blend: + pDesc->Type = D3D10_SVT_BLEND; + break; + case EOT_DepthStencil: + pDesc->Type = D3D10_SVT_DEPTHSTENCIL; + break; + case EOT_Rasterizer: + pDesc->Type = D3D10_SVT_RASTERIZER; + break; + case EOT_PixelShader: + case EOT_PixelShader5: + pDesc->Type = D3D10_SVT_PIXELSHADER; + break; + case EOT_VertexShader: + case EOT_VertexShader5: + pDesc->Type = D3D10_SVT_VERTEXSHADER; + break; + case EOT_GeometryShader: + case EOT_GeometryShaderSO: + case EOT_GeometryShader5: + pDesc->Type = D3D10_SVT_GEOMETRYSHADER; + break; + case EOT_HullShader5: + pDesc->Type = D3D11_SVT_HULLSHADER; + break; + case EOT_DomainShader5: + pDesc->Type = D3D11_SVT_DOMAINSHADER; + break; + case EOT_ComputeShader5: + pDesc->Type = D3D11_SVT_COMPUTESHADER; + break; + case EOT_Texture: + pDesc->Type = D3D10_SVT_TEXTURE; + break; + case EOT_Texture1D: + pDesc->Type = D3D10_SVT_TEXTURE1D; + break; + case EOT_Texture1DArray: + pDesc->Type = D3D10_SVT_TEXTURE1DARRAY; + break; + case EOT_Texture2D: + pDesc->Type = D3D10_SVT_TEXTURE2D; + break; + case EOT_Texture2DArray: + pDesc->Type = D3D10_SVT_TEXTURE2DARRAY; + break; + case EOT_Texture2DMS: + pDesc->Type = D3D10_SVT_TEXTURE2DMS; + break; + case EOT_Texture2DMSArray: + pDesc->Type = D3D10_SVT_TEXTURE2DMSARRAY; + break; + case EOT_Texture3D: + pDesc->Type = D3D10_SVT_TEXTURE3D; + break; + case EOT_TextureCube: + pDesc->Type = D3D10_SVT_TEXTURECUBE; + break; + case EOT_TextureCubeArray: + pDesc->Type = D3D10_SVT_TEXTURECUBEARRAY; + break; + case EOT_Buffer: + pDesc->Type = D3D10_SVT_BUFFER; + break; + case EOT_Sampler: + pDesc->Type = D3D10_SVT_SAMPLER; + break; + case EOT_RenderTargetView: + pDesc->Type = D3D10_SVT_RENDERTARGETVIEW; + break; + case EOT_DepthStencilView: + pDesc->Type = D3D10_SVT_DEPTHSTENCILVIEW; + break; + case EOT_RWTexture1D: + pDesc->Type = D3D11_SVT_RWTEXTURE1D; + break; + case EOT_RWTexture1DArray: + pDesc->Type = D3D11_SVT_RWTEXTURE1DARRAY; + break; + case EOT_RWTexture2D: + pDesc->Type = D3D11_SVT_RWTEXTURE2D; + break; + case EOT_RWTexture2DArray: + pDesc->Type = D3D11_SVT_RWTEXTURE2DARRAY; + break; + case EOT_RWTexture3D: + pDesc->Type = D3D11_SVT_RWTEXTURE3D; + break; + case EOT_RWBuffer: + pDesc->Type = D3D11_SVT_RWBUFFER; + break; + case EOT_ByteAddressBuffer: + pDesc->Type = D3D11_SVT_BYTEADDRESS_BUFFER; + break; + case EOT_RWByteAddressBuffer: + pDesc->Type = D3D11_SVT_RWBYTEADDRESS_BUFFER; + break; + case EOT_StructuredBuffer: + pDesc->Type = D3D11_SVT_STRUCTURED_BUFFER; + break; + case EOT_RWStructuredBuffer: + case EOT_RWStructuredBufferAlloc: + case EOT_RWStructuredBufferConsume: + pDesc->Type = D3D11_SVT_RWSTRUCTURED_BUFFER; + break; + case EOT_AppendStructuredBuffer: + pDesc->Type = D3D11_SVT_APPEND_STRUCTURED_BUFFER; + break; + case EOT_ConsumeStructuredBuffer: + pDesc->Type = D3D11_SVT_CONSUME_STRUCTURED_BUFFER; + break; + + default: + D3DXASSERT(0); + } + break; + + default: + D3DXASSERT(0); + } + +lExit: + return hr; + +} + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderVariable (SAnonymousShader implementation) +//////////////////////////////////////////////////////////////////////////////// + +SAnonymousShader::SAnonymousShader(SShaderBlock *pBlock) +{ + pShaderBlock = pBlock; +} + +BOOL SAnonymousShader::IsValid() +{ + return pShaderBlock && pShaderBlock->IsValid; +} + +ID3DX11EffectType * SAnonymousShader::GetType() +{ + return (ID3DX11EffectType *) this; +} + +HRESULT SAnonymousShader::GetDesc(D3DX11_EFFECT_VARIABLE_DESC *pDesc) +{ + pDesc->Annotations = 0; + pDesc->Flags = 0; + + pDesc->Name = "$Anonymous"; + pDesc->Semantic = NULL; + pDesc->BufferOffset = 0; + + return S_OK; +} + +ID3DX11EffectVariable * SAnonymousShader::GetAnnotationByIndex(UINT Index) +{ + DPF(0, "ID3DX11EffectVariable::GetAnnotationByIndex: Anonymous shaders cannot have annotations"); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectVariable * SAnonymousShader::GetAnnotationByName(LPCSTR Name) +{ + DPF(0, "ID3DX11EffectVariable::GetAnnotationByName: Anonymous shaders cannot have annotations"); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectVariable * SAnonymousShader::GetMemberByIndex(UINT Index) +{ + DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Variable is not a structure"); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectVariable * SAnonymousShader::GetMemberByName(LPCSTR Name) +{ + DPF(0, "ID3DX11EffectVariable::GetMemberByName: Variable is not a structure"); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectVariable * SAnonymousShader::GetMemberBySemantic(LPCSTR Semantic) +{ + DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Variable is not a structure"); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectVariable * SAnonymousShader::GetElement(UINT Index) +{ + DPF(0, "ID3DX11EffectVariable::GetElement: Anonymous shaders cannot have elements"); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectConstantBuffer * SAnonymousShader::GetParentConstantBuffer() +{ + return NoParentCB(); +} + +ID3DX11EffectShaderVariable * SAnonymousShader::AsShader() +{ + return (ID3DX11EffectShaderVariable *) this; +} + +HRESULT SAnonymousShader::SetRawValue(CONST void *pData, UINT Offset, UINT Count) +{ + return ObjectSetRawValue(); +} + +HRESULT SAnonymousShader::GetRawValue(__out_bcount(Count) void *pData, UINT Offset, UINT Count) +{ + return ObjectGetRawValue(); +} + +#define ANONYMOUS_SHADER_INDEX_CHECK() \ + HRESULT hr = S_OK; \ + if (0 != ShaderIndex) \ + { \ + DPF(0, "%s: Invalid index specified", pFuncName); \ + VH(E_INVALIDARG); \ + } \ + +HRESULT SAnonymousShader::GetShaderDesc(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetShaderDesc"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + pShaderBlock->GetShaderDesc(pDesc, TRUE); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetVertexShader(UINT ShaderIndex, ID3D11VertexShader **ppVS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetVertexShader"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetVertexShader(ppVS) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetGeometryShader(UINT ShaderIndex, ID3D11GeometryShader **ppGS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetGeometryShader"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetGeometryShader(ppGS) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetPixelShader(UINT ShaderIndex, ID3D11PixelShader **ppPS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPixelShader"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetPixelShader(ppPS) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetHullShader(UINT ShaderIndex, ID3D11HullShader **ppHS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetHullShader"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetHullShader(ppHS) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetDomainShader(UINT ShaderIndex, ID3D11DomainShader **ppCS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetDomainShader"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetDomainShader(ppCS) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetComputeShader(UINT ShaderIndex, ID3D11ComputeShader **ppCS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetComputeShader"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetComputeShader(ppCS) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetInputSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetInputSignatureElementDesc"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetSignatureElementDesc(SShaderBlock::ST_Input, Element, pDesc) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetOutputSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetOutputSignatureElementDesc"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetSignatureElementDesc(SShaderBlock::ST_Output, Element, pDesc) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetPatchConstantSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPatchConstantSignatureElementDesc"; + + ANONYMOUS_SHADER_INDEX_CHECK(); + + VH( pShaderBlock->GetSignatureElementDesc(SShaderBlock::ST_PatchConstant, Element, pDesc) ); + +lExit: + return hr; +} + +HRESULT SAnonymousShader::GetDesc(D3DX11_EFFECT_TYPE_DESC *pDesc) +{ + pDesc->Class = D3D10_SVC_OBJECT; + + switch (pShaderBlock->GetShaderType()) + { + case EOT_VertexShader: + case EOT_VertexShader5: + pDesc->TypeName = "vertexshader"; + pDesc->Type = D3D10_SVT_VERTEXSHADER; + break; + case EOT_GeometryShader: + case EOT_GeometryShader5: + pDesc->TypeName = "geometryshader"; + pDesc->Type = D3D10_SVT_GEOMETRYSHADER; + break; + case EOT_PixelShader: + case EOT_PixelShader5: + pDesc->TypeName = "pixelshader"; + pDesc->Type = D3D10_SVT_PIXELSHADER; + break; + case EOT_HullShader5: + pDesc->TypeName = "Hullshader"; + pDesc->Type = D3D11_SVT_HULLSHADER; + break; + case EOT_DomainShader5: + pDesc->TypeName = "Domainshader"; + pDesc->Type = D3D11_SVT_DOMAINSHADER; + break; + case EOT_ComputeShader5: + pDesc->TypeName = "Computeshader"; + pDesc->Type = D3D11_SVT_COMPUTESHADER; + break; + } + + pDesc->Elements = 0; + pDesc->Members = 0; + pDesc->Rows = 0; + pDesc->Columns = 0; + pDesc->PackedSize = 0; + pDesc->UnpackedSize = 0; + pDesc->Stride = 0; + + return S_OK; +} + +ID3DX11EffectType * SAnonymousShader::GetMemberTypeByIndex(UINT Index) +{ + DPF(0, "ID3DX11EffectType::GetMemberTypeByIndex: This interface does not refer to a structure"); + return &g_InvalidType; +} + +ID3DX11EffectType * SAnonymousShader::GetMemberTypeByName(LPCSTR Name) +{ + DPF(0, "ID3DX11EffectType::GetMemberTypeByName: This interface does not refer to a structure"); + return &g_InvalidType; +} + +ID3DX11EffectType * SAnonymousShader::GetMemberTypeBySemantic(LPCSTR Semantic) +{ + DPF(0, "ID3DX11EffectType::GetMemberTypeBySemantic: This interface does not refer to a structure"); + return &g_InvalidType; +} + +LPCSTR SAnonymousShader::GetMemberName(UINT Index) +{ + DPF(0, "ID3DX11EffectType::GetMemberName: This interface does not refer to a structure"); + return NULL; +} + +LPCSTR SAnonymousShader::GetMemberSemantic(UINT Index) +{ + DPF(0, "ID3DX11EffectType::GetMemberSemantic: This interface does not refer to a structure"); + return NULL; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectConstantBuffer (SConstantBuffer implementation) +////////////////////////////////////////////////////////////////////////// + +BOOL SConstantBuffer::IsValid() +{ + return TRUE; +} + +ID3DX11EffectType * SConstantBuffer::GetType() +{ + return (ID3DX11EffectType *) this; +} + +HRESULT SConstantBuffer::GetDesc(D3DX11_EFFECT_VARIABLE_DESC *pDesc) +{ + pDesc->Annotations = AnnotationCount; + pDesc->Flags = 0; + + pDesc->Name = pName; + pDesc->Semantic = NULL; + pDesc->BufferOffset = 0; + + if (ExplicitBindPoint != -1) + { + pDesc->ExplicitBindPoint = ExplicitBindPoint; + pDesc->Flags |= D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT; + } + else + { + pDesc->ExplicitBindPoint = 0; + } + + return S_OK; +} + +ID3DX11EffectVariable * SConstantBuffer::GetAnnotationByIndex(UINT Index) +{ + return GetAnnotationByIndexHelper("ID3DX11EffectVariable", Index, AnnotationCount, pAnnotations); +} + +ID3DX11EffectVariable * SConstantBuffer::GetAnnotationByName(LPCSTR Name) +{ + return GetAnnotationByNameHelper("ID3DX11EffectVariable", Name, AnnotationCount, pAnnotations); +} + +ID3DX11EffectVariable * SConstantBuffer::GetMemberByIndex(UINT Index) +{ + SGlobalVariable *pMember; + UDataPointer dataPtr; + + if (IsEffectOptimized) + { + DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Cannot get members; effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + if (!GetVariableByIndexHelper<SGlobalVariable>(Index, VariableCount, (SGlobalVariable*)pVariables, + NULL, &pMember, &dataPtr.pGeneric)) + { + return &g_InvalidScalarVariable; + } + + return (ID3DX11EffectVariable *) pMember; +} + +ID3DX11EffectVariable * SConstantBuffer::GetMemberByName(LPCSTR Name) +{ + SGlobalVariable *pMember; + UDataPointer dataPtr; + UINT index; + + if (IsEffectOptimized) + { + DPF(0, "ID3DX11EffectVariable::GetMemberByName: Cannot get members; effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + if (!GetVariableByNameHelper<SGlobalVariable>(Name, VariableCount, (SGlobalVariable*)pVariables, + NULL, &pMember, &dataPtr.pGeneric, &index)) + { + return &g_InvalidScalarVariable; + } + + return (ID3DX11EffectVariable *) pMember; +} + +ID3DX11EffectVariable * SConstantBuffer::GetMemberBySemantic(LPCSTR Semantic) +{ + SGlobalVariable *pMember; + UDataPointer dataPtr; + UINT index; + + if (IsEffectOptimized) + { + DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Cannot get members; effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + if (!GetVariableBySemanticHelper<SGlobalVariable>(Semantic, VariableCount, (SGlobalVariable*)pVariables, + NULL, &pMember, &dataPtr.pGeneric, &index)) + { + return &g_InvalidScalarVariable; + } + + return (ID3DX11EffectVariable *) pMember; +} + +ID3DX11EffectVariable * SConstantBuffer::GetElement(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::GetElement"; + DPF(0, "%s: This interface does not refer to an array", pFuncName); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectConstantBuffer * SConstantBuffer::GetParentConstantBuffer() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::GetParentConstantBuffer"; + DPF(0, "%s: Constant buffers do not have parent constant buffers", pFuncName); + return &g_InvalidConstantBuffer; +} + +ID3DX11EffectConstantBuffer * SConstantBuffer::AsConstantBuffer() +{ + return (ID3DX11EffectConstantBuffer *) this; +} + +HRESULT SConstantBuffer::GetDesc(D3DX11_EFFECT_TYPE_DESC *pDesc) +{ + pDesc->TypeName = IsTBuffer ? "tbuffer" : "cbuffer"; + pDesc->Class = D3D10_SVC_OBJECT; + pDesc->Type = IsTBuffer ? D3D10_SVT_TBUFFER : D3D10_SVT_CBUFFER; + + pDesc->Elements = 0; + pDesc->Members = VariableCount; + pDesc->Rows = 0; + pDesc->Columns = 0; + + UINT i; + pDesc->PackedSize = 0; + for (i = 0; i < VariableCount; ++ i) + { + pDesc->PackedSize += pVariables[i].pType->PackedSize; + } + + pDesc->UnpackedSize = Size; + D3DXASSERT(pDesc->UnpackedSize >= pDesc->PackedSize); + + pDesc->Stride = AlignToPowerOf2(pDesc->UnpackedSize, SType::c_RegisterSize); + + return S_OK; +} + +ID3DX11EffectType * SConstantBuffer::GetMemberTypeByIndex(UINT Index) +{ + return GetTypeByIndexHelper(Index, VariableCount, pVariables, sizeof (SGlobalVariable)); +} + +ID3DX11EffectType * SConstantBuffer::GetMemberTypeByName(LPCSTR Name) +{ + return GetTypeByNameHelper(Name, VariableCount, pVariables, sizeof (SGlobalVariable)); +} + +ID3DX11EffectType * SConstantBuffer::GetMemberTypeBySemantic(LPCSTR Semantic) +{ + return GetTypeBySemanticHelper(Semantic, VariableCount, pVariables, sizeof (SGlobalVariable)); +} + +LPCSTR SConstantBuffer::GetMemberName(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectType::GetMemberName"; + + if (IsEffectOptimized) + { + DPF(0, "%s: Cannot get member names; Effect has been Optimize()'ed", pFuncName); + return NULL; + } + + if (Index >= VariableCount) + { + DPF(0, "%s: Invalid index (%d, total: %d)", pFuncName, Index, VariableCount); + return NULL; + } + + return pVariables[Index].pName; +} + +LPCSTR SConstantBuffer::GetMemberSemantic(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectType::GetMemberSemantic"; + + if (IsEffectOptimized) + { + DPF(0, "%s: Cannot get member semantics; Effect has been Optimize()'ed", pFuncName); + return NULL; + } + + if (Index >= VariableCount) + { + DPF(0, "%s: Invalid index (%d, total: %d)", pFuncName, Index, VariableCount); + return NULL; + } + + return pVariables[Index].pSemantic; +} + +HRESULT SConstantBuffer::SetRawValue(CONST void *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectVariable::SetRawValue"; + + VERIFYPARAMETER(pData); + + if ((Offset + Count < Offset) || + (Count + (BYTE*)pData < (BYTE*)pData) || + ((Offset + Count) > Size)) + { + // overflow of some kind + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + if (IsUsedByExpression) + { + UINT i; + for (i = 0; i < VariableCount; ++ i) + { + ((SGlobalVariable*)pVariables)[i].DirtyVariable(); + } + } + else + { + IsDirty = TRUE; + } + + memcpy(pBackingStore + Offset, pData, Count); + +lExit: + return hr; +} + +HRESULT SConstantBuffer::GetRawValue(__out_bcount(Count) void *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectVariable::GetRawValue"; + + VERIFYPARAMETER(pData); + + if ((Offset + Count < Offset) || + (Count + (BYTE*)pData < (BYTE*)pData) || + ((Offset + Count) > Size)) + { + // overflow of some kind + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + memcpy(pData, pBackingStore + Offset, Count); + +lExit: + return hr; +} + +bool SConstantBuffer::ClonedSingle() const +{ + return IsSingle && ( pEffect->m_Flags & D3DX11_EFFECT_CLONE ); +} + +HRESULT SConstantBuffer::SetConstantBuffer(ID3D11Buffer *pConstantBuffer) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectConstantBuffer::SetConstantBuffer"; + + if (IsTBuffer) + { + DPF(0, "%s: This is a texture buffer; use SetTextureBuffer instead", pFuncName); + VH(D3DERR_INVALIDCALL); + } + + // Replace all references to the old shader block with this one + pEffect->ReplaceCBReference(this, pConstantBuffer); + + if( !IsUserManaged ) + { + // Save original cbuffer in case we UndoSet + D3DXASSERT( pMemberData[0].Type == MDT_Buffer ); + VB( pMemberData[0].Data.pD3DEffectsManagedConstantBuffer == NULL ); + pMemberData[0].Data.pD3DEffectsManagedConstantBuffer = pD3DObject; + pD3DObject = NULL; + IsUserManaged = TRUE; + IsNonUpdatable = TRUE; + } + + SAFE_ADDREF( pConstantBuffer ); + SAFE_RELEASE( pD3DObject ); + pD3DObject = pConstantBuffer; + +lExit: + return hr; +} + +HRESULT SConstantBuffer::GetConstantBuffer(ID3D11Buffer **ppConstantBuffer) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectConstantBuffer::GetConstantBuffer"; + + VERIFYPARAMETER(ppConstantBuffer); + + if (IsTBuffer) + { + DPF(0, "%s: This is a texture buffer; use GetTextureBuffer instead", pFuncName); + VH(D3DERR_INVALIDCALL); + } + + *ppConstantBuffer = pD3DObject; + SAFE_ADDREF(*ppConstantBuffer); + +lExit: + return hr; +} + +HRESULT SConstantBuffer::UndoSetConstantBuffer() +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectConstantBuffer::UndoSetConstantBuffer"; + + if (IsTBuffer) + { + DPF(0, "%s: This is a texture buffer; use UndoSetTextureBuffer instead", pFuncName); + VH(D3DERR_INVALIDCALL); + } + + if( !IsUserManaged ) + { + return S_FALSE; + } + + // Replace all references to the old shader block with this one + pEffect->ReplaceCBReference(this, pMemberData[0].Data.pD3DEffectsManagedConstantBuffer); + + // Revert to original cbuffer + SAFE_RELEASE( pD3DObject ); + pD3DObject = pMemberData[0].Data.pD3DEffectsManagedConstantBuffer; + pMemberData[0].Data.pD3DEffectsManagedConstantBuffer = NULL; + IsUserManaged = FALSE; + IsNonUpdatable = ClonedSingle(); + +lExit: + return hr; +} + +HRESULT SConstantBuffer::SetTextureBuffer(ID3D11ShaderResourceView *pTextureBuffer) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectConstantBuffer::SetTextureBuffer"; + + if (!IsTBuffer) + { + DPF(0, "%s: This is a constant buffer; use SetConstantBuffer instead", pFuncName); + VH(D3DERR_INVALIDCALL); + } + + if( !IsUserManaged ) + { + // Save original cbuffer and tbuffer in case we UndoSet + D3DXASSERT( pMemberData[0].Type == MDT_Buffer ); + VB( pMemberData[0].Data.pD3DEffectsManagedConstantBuffer == NULL ); + pMemberData[0].Data.pD3DEffectsManagedConstantBuffer = pD3DObject; + pD3DObject = NULL; + D3DXASSERT( pMemberData[1].Type == MDT_ShaderResourceView ); + VB( pMemberData[1].Data.pD3DEffectsManagedTextureBuffer == NULL ); + pMemberData[1].Data.pD3DEffectsManagedTextureBuffer = TBuffer.pShaderResource; + TBuffer.pShaderResource = NULL; + IsUserManaged = TRUE; + IsNonUpdatable = TRUE; + } + + SAFE_ADDREF( pTextureBuffer ); + SAFE_RELEASE(pD3DObject); // won't be needing this anymore... + SAFE_RELEASE( TBuffer.pShaderResource ); + TBuffer.pShaderResource = pTextureBuffer; + +lExit: + return hr; +} + +HRESULT SConstantBuffer::GetTextureBuffer(ID3D11ShaderResourceView **ppTextureBuffer) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectConstantBuffer::GetTextureBuffer"; + + VERIFYPARAMETER(ppTextureBuffer); + + if (!IsTBuffer) + { + DPF(0, "%s: This is a constant buffer; use GetConstantBuffer instead", pFuncName); + VH(D3DERR_INVALIDCALL); + } + + *ppTextureBuffer = TBuffer.pShaderResource; + SAFE_ADDREF(*ppTextureBuffer); + +lExit: + return hr; +} + +HRESULT SConstantBuffer::UndoSetTextureBuffer() +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectConstantBuffer::UndoSetTextureBuffer"; + + if (!IsTBuffer) + { + DPF(0, "%s: This is a texture buffer; use UndoSetConstantBuffer instead", pFuncName); + VH(D3DERR_INVALIDCALL); + } + + if( !IsUserManaged ) + { + return S_FALSE; + } + + // Revert to original cbuffer + SAFE_RELEASE( pD3DObject ); + pD3DObject = pMemberData[0].Data.pD3DEffectsManagedConstantBuffer; + pMemberData[0].Data.pD3DEffectsManagedConstantBuffer = NULL; + SAFE_RELEASE( TBuffer.pShaderResource ); + TBuffer.pShaderResource = pMemberData[1].Data.pD3DEffectsManagedTextureBuffer; + pMemberData[1].Data.pD3DEffectsManagedTextureBuffer = NULL; + IsUserManaged = FALSE; + IsNonUpdatable = ClonedSingle(); + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectPass (CEffectPass implementation) +////////////////////////////////////////////////////////////////////////// + +BOOL SPassBlock::IsValid() +{ + if( HasDependencies ) + return pEffect->ValidatePassBlock( this ); + return InitiallyValid; +} + +HRESULT SPassBlock::GetDesc(D3DX11_PASS_DESC *pDesc) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectPass::GetDesc"; + + VERIFYPARAMETER(pDesc); + + ZeroMemory(pDesc, sizeof(*pDesc)); + + pDesc->Name = pName; + pDesc->Annotations = AnnotationCount; + + SAssignment *pAssignment; + SAssignment *pLastAssn; + + pEffect->IncrementTimer(); + + pAssignment = pAssignments; + pLastAssn = pAssignments + AssignmentCount; + + for(; pAssignment < pLastAssn; pAssignment++) + { + pEffect->EvaluateAssignment(pAssignment); + } + + if( BackingStore.pVertexShaderBlock && BackingStore.pVertexShaderBlock->pInputSignatureBlob ) + { + // pInputSignatureBlob can be null if we're setting a NULL VS "SetVertexShader( NULL )" + pDesc->pIAInputSignature = (BYTE*)BackingStore.pVertexShaderBlock->pInputSignatureBlob->GetBufferPointer(); + pDesc->IAInputSignatureSize = BackingStore.pVertexShaderBlock->pInputSignatureBlob->GetBufferSize(); + } + + pDesc->StencilRef = BackingStore.StencilRef; + pDesc->SampleMask = BackingStore.SampleMask; + pDesc->BlendFactor[0] = BackingStore.BlendFactor[0]; + pDesc->BlendFactor[1] = BackingStore.BlendFactor[1]; + pDesc->BlendFactor[2] = BackingStore.BlendFactor[2]; + pDesc->BlendFactor[3] = BackingStore.BlendFactor[3]; + +lExit: + return hr; +} + +extern SShaderBlock g_NullVS; +extern SShaderBlock g_NullGS; +extern SShaderBlock g_NullPS; +extern SShaderBlock g_NullHS; +extern SShaderBlock g_NullDS; +extern SShaderBlock g_NullCS; + +SAnonymousShader g_AnonymousNullVS(&g_NullVS); +SAnonymousShader g_AnonymousNullGS(&g_NullGS); +SAnonymousShader g_AnonymousNullPS(&g_NullPS); +SAnonymousShader g_AnonymousNullHS(&g_NullHS); +SAnonymousShader g_AnonymousNullDS(&g_NullDS); +SAnonymousShader g_AnonymousNullCS(&g_NullCS); + +template<EObjectType EShaderType> +HRESULT SPassBlock::GetShaderDescHelper(D3DX11_PASS_SHADER_DESC *pDesc) +{ + HRESULT hr = S_OK; + UINT i; + LPCSTR pFuncName = NULL; + SShaderBlock *pShaderBlock = NULL; + + ApplyPassAssignments(); + + switch (EShaderType) + { + case EOT_VertexShader: + case EOT_VertexShader5: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectPass::GetVertexShaderDesc"; + pShaderBlock = BackingStore.pVertexShaderBlock; + break; + case EOT_PixelShader: + case EOT_PixelShader5: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectPass::GetPixelShaderDesc"; + pShaderBlock = BackingStore.pPixelShaderBlock; + break; + case EOT_GeometryShader: + case EOT_GeometryShader5: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectPass::GetGeometryShaderDesc"; + pShaderBlock = BackingStore.pGeometryShaderBlock; + break; + case EOT_HullShader5: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectPass::GetHullShaderDesc"; + pShaderBlock = BackingStore.pHullShaderBlock; + break; + case EOT_DomainShader5: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectPass::GetDomainShaderDesc"; + pShaderBlock = BackingStore.pDomainShaderBlock; + break; + case EOT_ComputeShader5: +#pragma prefast(suppress:__WARNING_UNUSED_POINTER_ASSIGNMENT, "pFuncName used in DPF") + pFuncName = "ID3DX11EffectPass::GetComputeShaderDesc"; + pShaderBlock = BackingStore.pComputeShaderBlock; + break; + default: + D3DXASSERT(0); + } + + VERIFYPARAMETER(pDesc); + + // in case of error (or in case the assignment doesn't exist), return something reasonable + pDesc->pShaderVariable = &g_InvalidShaderVariable; + pDesc->ShaderIndex = 0; + + if (NULL != pShaderBlock) + { + UINT elements, varCount, anonymousShaderCount; + SGlobalVariable *pVariables; + SAnonymousShader *pAnonymousShaders; + + if (pShaderBlock == &g_NullVS) + { + pDesc->pShaderVariable = &g_AnonymousNullVS; + pDesc->ShaderIndex = 0; + // we're done + goto lExit; + } + else if (pShaderBlock == &g_NullGS) + { + pDesc->pShaderVariable = &g_AnonymousNullGS; + pDesc->ShaderIndex = 0; + // we're done + goto lExit; + } + else if (pShaderBlock == &g_NullPS) + { + pDesc->pShaderVariable = &g_AnonymousNullPS; + pDesc->ShaderIndex = 0; + // we're done + goto lExit; + } + else if (pShaderBlock == &g_NullHS) + { + pDesc->pShaderVariable = &g_AnonymousNullHS; + pDesc->ShaderIndex = 0; + // we're done + goto lExit; + } + else if (pShaderBlock == &g_NullDS) + { + pDesc->pShaderVariable = &g_AnonymousNullDS; + pDesc->ShaderIndex = 0; + // we're done + goto lExit; + } + else if (pShaderBlock == &g_NullCS) + { + pDesc->pShaderVariable = &g_AnonymousNullCS; + pDesc->ShaderIndex = 0; + // we're done + goto lExit; + } + else + { + VB( pEffect->IsRuntimeData(pShaderBlock) ); + varCount = pEffect->m_VariableCount; + pVariables = pEffect->m_pVariables; + anonymousShaderCount = pEffect->m_AnonymousShaderCount; + pAnonymousShaders = pEffect->m_pAnonymousShaders; + } + + for (i = 0; i < varCount; ++ i) + { + elements = max(1, pVariables[i].pType->Elements); + // make sure the variable type matches, and don't forget about GeometryShaderSO's + if (pVariables[i].pType->IsShader()) + { + if (pShaderBlock >= pVariables[i].Data.pShader && pShaderBlock < pVariables[i].Data.pShader + elements) + { + pDesc->pShaderVariable = (ID3DX11EffectShaderVariable *)(pVariables + i); + pDesc->ShaderIndex = (UINT)(UINT_PTR)(pShaderBlock - pVariables[i].Data.pShader); + // we're done + goto lExit; + } + } + } + + for (i = 0; i < anonymousShaderCount; ++ i) + { + if (pShaderBlock == pAnonymousShaders[i].pShaderBlock) + { + VB(EShaderType == pAnonymousShaders[i].pShaderBlock->GetShaderType()) + pDesc->pShaderVariable = (pAnonymousShaders + i); + pDesc->ShaderIndex = 0; + // we're done + goto lExit; + } + } + + DPF(0, "%s: Internal error; shader not found", pFuncName); + VH( E_FAIL ); + } + +lExit: + return hr; +} + +HRESULT SPassBlock::GetVertexShaderDesc(D3DX11_PASS_SHADER_DESC *pDesc) +{ + return GetShaderDescHelper<EOT_VertexShader>(pDesc); +} + +HRESULT SPassBlock::GetPixelShaderDesc(D3DX11_PASS_SHADER_DESC *pDesc) +{ + return GetShaderDescHelper<EOT_PixelShader>(pDesc); +} + +HRESULT SPassBlock::GetGeometryShaderDesc(D3DX11_PASS_SHADER_DESC *pDesc) +{ + return GetShaderDescHelper<EOT_GeometryShader>(pDesc); +} + +HRESULT SPassBlock::GetHullShaderDesc(D3DX11_PASS_SHADER_DESC *pDesc) +{ + return GetShaderDescHelper<EOT_HullShader5>(pDesc); +} + +HRESULT SPassBlock::GetDomainShaderDesc(D3DX11_PASS_SHADER_DESC *pDesc) +{ + return GetShaderDescHelper<EOT_DomainShader5>(pDesc); +} + +HRESULT SPassBlock::GetComputeShaderDesc(D3DX11_PASS_SHADER_DESC *pDesc) +{ + return GetShaderDescHelper<EOT_ComputeShader5>(pDesc); +} + +ID3DX11EffectVariable * SPassBlock::GetAnnotationByIndex(UINT Index) +{ + return GetAnnotationByIndexHelper("ID3DX11EffectPass", Index, AnnotationCount, pAnnotations); +} + +ID3DX11EffectVariable * SPassBlock::GetAnnotationByName(LPCSTR Name) +{ + return GetAnnotationByNameHelper("ID3DX11EffectPass", Name, AnnotationCount, pAnnotations); +} + +HRESULT SPassBlock::Apply(UINT Flags, ID3D11DeviceContext* pContext) +{ + HRESULT hr = S_OK; + + // TODO: Flags are not yet implemented + + D3DXASSERT( pEffect->m_pContext == NULL ); + pEffect->m_pContext = pContext; + pEffect->ApplyPassBlock(this); + pEffect->m_pContext = NULL; + +lExit: + return hr; +} + +HRESULT SPassBlock::ComputeStateBlockMask(D3DX11_STATE_BLOCK_MASK *pStateBlockMask) +{ + HRESULT hr = S_OK; + UINT i, j; + + // flags indicating whether the following shader types were caught by assignment checks or not + BOOL bVS = FALSE, bGS = FALSE, bPS = FALSE, bHS = FALSE, bDS = FALSE, bCS = FALSE; + + for (i = 0; i < AssignmentCount; ++ i) + { + BOOL bShader = FALSE; + + switch (pAssignments[i].LhsType) + { + case ELHS_VertexShaderBlock: + bVS = TRUE; + bShader = TRUE; + break; + case ELHS_GeometryShaderBlock: + bGS = TRUE; + bShader = TRUE; + break; + case ELHS_PixelShaderBlock: + bPS = TRUE; + bShader = TRUE; + break; + case ELHS_HullShaderBlock: + bHS = TRUE; + bShader = TRUE; + break; + case ELHS_DomainShaderBlock: + bDS = TRUE; + bShader = TRUE; + break; + case ELHS_ComputeShaderBlock: + bCS = TRUE; + bShader = TRUE; + break; + + case ELHS_RasterizerBlock: + pStateBlockMask->RSRasterizerState = 1; + break; + case ELHS_BlendBlock: + pStateBlockMask->OMBlendState = 1; + break; + case ELHS_DepthStencilBlock: + pStateBlockMask->OMDepthStencilState = 1; + break; + + default: + // ignore this assignment (must be a scalar/vector assignment associated with a state object) + break; + } + + if (bShader) + { + for (j = 0; j < pAssignments[i].MaxElements; ++ j) + { + // compute state block mask for the union of ALL shaders + VH( pAssignments[i].Source.pShader[j].ComputeStateBlockMask(pStateBlockMask) ); + } + } + } + + // go over the state block objects in case there was no corresponding assignment + if (NULL != BackingStore.pRasterizerBlock) + { + pStateBlockMask->RSRasterizerState = 1; + } + if (NULL != BackingStore.pBlendBlock) + { + pStateBlockMask->OMBlendState = 1; + } + if (NULL != BackingStore.pDepthStencilBlock) + { + pStateBlockMask->OMDepthStencilState = 1; + } + + // go over the shaders only if an assignment didn't already catch them + if (FALSE == bVS && NULL != BackingStore.pVertexShaderBlock) + { + VH( BackingStore.pVertexShaderBlock->ComputeStateBlockMask(pStateBlockMask) ); + } + if (FALSE == bGS && NULL != BackingStore.pGeometryShaderBlock) + { + VH( BackingStore.pGeometryShaderBlock->ComputeStateBlockMask(pStateBlockMask) ); + } + if (FALSE == bPS && NULL != BackingStore.pPixelShaderBlock) + { + VH( BackingStore.pPixelShaderBlock->ComputeStateBlockMask(pStateBlockMask) ); + } + if (FALSE == bHS && NULL != BackingStore.pHullShaderBlock) + { + VH( BackingStore.pHullShaderBlock->ComputeStateBlockMask(pStateBlockMask) ); + } + if (FALSE == bDS && NULL != BackingStore.pDomainShaderBlock) + { + VH( BackingStore.pDomainShaderBlock->ComputeStateBlockMask(pStateBlockMask) ); + } + if (FALSE == bCS && NULL != BackingStore.pComputeShaderBlock) + { + VH( BackingStore.pComputeShaderBlock->ComputeStateBlockMask(pStateBlockMask) ); + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectTechnique (STechnique implementation) +////////////////////////////////////////////////////////////////////////// + +BOOL STechnique::IsValid() +{ + if( HasDependencies ) + { + for( UINT i = 0; i < PassCount; i++ ) + { + if( !((SPassBlock*)pPasses)[i].IsValid() ) + return FALSE; + } + return TRUE; + } + return InitiallyValid; +} + +HRESULT STechnique::GetDesc(D3DX11_TECHNIQUE_DESC *pDesc) +{ + HRESULT hr = S_OK; + + LPCSTR pFuncName = "ID3DX11EffectTechnique::GetDesc"; + + VERIFYPARAMETER(pDesc); + + pDesc->Name = pName; + pDesc->Annotations = AnnotationCount; + pDesc->Passes = PassCount; + +lExit: + return hr; +} + +ID3DX11EffectVariable * STechnique::GetAnnotationByIndex(UINT Index) +{ + return GetAnnotationByIndexHelper("ID3DX11EffectTechnique", Index, AnnotationCount, pAnnotations); +} + +ID3DX11EffectVariable * STechnique::GetAnnotationByName(LPCSTR Name) +{ + return GetAnnotationByNameHelper("ID3DX11EffectTechnique", Name, AnnotationCount, pAnnotations); +} + +ID3DX11EffectPass * STechnique::GetPassByIndex(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectTechnique::GetPassByIndex"; + + if (Index >= PassCount) + { + DPF(0, "%s: Invalid pass index (%d, total: %d)", pFuncName, Index, PassCount); + return &g_InvalidPass; + } + + return (ID3DX11EffectPass *)(pPasses + Index); +} + +ID3DX11EffectPass * STechnique::GetPassByName(LPCSTR Name) +{ + LPCSTR pFuncName = "ID3DX11EffectTechnique::GetPassByName"; + + UINT i; + + for (i = 0; i < PassCount; ++ i) + { + if (NULL != pPasses[i].pName && + strcmp(pPasses[i].pName, Name) == 0) + { + break; + } + } + + if (i == PassCount) + { + DPF(0, "%s: Pass [%s] not found", pFuncName, Name); + return &g_InvalidPass; + } + + return (ID3DX11EffectPass *)(pPasses + i); +} + +HRESULT STechnique::ComputeStateBlockMask(D3DX11_STATE_BLOCK_MASK *pStateBlockMask) +{ + HRESULT hr = S_OK; + UINT i; + + for (i = 0; i < PassCount; ++ i) + { + VH( ((SPassBlock*)pPasses)[i].ComputeStateBlockMask(pStateBlockMask) ); + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectGroup (SGroup implementation) +////////////////////////////////////////////////////////////////////////// + +BOOL SGroup::IsValid() +{ + if( HasDependencies ) + { + for( UINT i = 0; i < TechniqueCount; i++ ) + { + if( !((STechnique*)pTechniques)[i].IsValid() ) + return FALSE; + } + return TRUE; + } + return InitiallyValid; +} + +HRESULT SGroup::GetDesc(D3DX11_GROUP_DESC *pDesc) +{ + HRESULT hr = S_OK; + + LPCSTR pFuncName = "ID3DX11EffectGroup::GetDesc"; + + VERIFYPARAMETER(pDesc); + + pDesc->Name = pName; + pDesc->Annotations = AnnotationCount; + pDesc->Techniques = TechniqueCount; + +lExit: + return hr; +} + +ID3DX11EffectVariable * SGroup::GetAnnotationByIndex(UINT Index) +{ + return GetAnnotationByIndexHelper("ID3DX11EffectGroup", Index, AnnotationCount, pAnnotations); +} + +ID3DX11EffectVariable * SGroup::GetAnnotationByName(LPCSTR Name) +{ + return GetAnnotationByNameHelper("ID3DX11EffectGroup", Name, AnnotationCount, pAnnotations); +} + +ID3DX11EffectTechnique * SGroup::GetTechniqueByIndex(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectGroup::GetTechniqueByIndex"; + + if (Index >= TechniqueCount) + { + DPF(0, "%s: Invalid pass index (%d, total: %d)", pFuncName, Index, TechniqueCount); + return &g_InvalidTechnique; + } + + return (ID3DX11EffectTechnique *)(pTechniques + Index); +} + +ID3DX11EffectTechnique * SGroup::GetTechniqueByName(LPCSTR Name) +{ + LPCSTR pFuncName = "ID3DX11EffectGroup::GetTechniqueByName"; + + UINT i; + + for (i = 0; i < TechniqueCount; ++ i) + { + if (NULL != pTechniques[i].pName && + strcmp(pTechniques[i].pName, Name) == 0) + { + break; + } + } + + if (i == TechniqueCount) + { + DPF(0, "%s: Technique [%s] not found", pFuncName, Name); + return &g_InvalidTechnique; + } + + return (ID3DX11EffectTechnique *)(pTechniques + i); +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11Effect Public Reflection APIs (CEffect) +////////////////////////////////////////////////////////////////////////// + +HRESULT CEffect::GetDevice(ID3D11Device **ppDevice) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11Effect::GetDevice"; + VERIFYPARAMETER(ppDevice); + + m_pDevice->AddRef(); + *ppDevice = m_pDevice; + +lExit: + return hr; +} + +HRESULT CEffect::GetDesc(D3DX11_EFFECT_DESC *pDesc) +{ + HRESULT hr = S_OK; + + LPCSTR pFuncName = "ID3DX11Effect::GetDesc"; + + VERIFYPARAMETER(pDesc); + + pDesc->ConstantBuffers = m_CBCount; + pDesc->GlobalVariables = m_VariableCount; + pDesc->Techniques = m_TechniqueCount; + pDesc->Groups = m_GroupCount; + pDesc->InterfaceVariables = m_InterfaceCount; + +lExit: + return hr; +} + +ID3DX11EffectConstantBuffer * CEffect::GetConstantBufferByIndex(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11Effect::GetConstantBufferByIndex"; + + if (Index < m_CBCount) + { + return m_pCBs + Index; + } + + DPF(0, "%s: Invalid constant buffer index", pFuncName); + return &g_InvalidConstantBuffer; +} + +ID3DX11EffectConstantBuffer * CEffect::GetConstantBufferByName(LPCSTR Name) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11Effect::GetConstantBufferByName"; + + if (IsOptimized()) + { + DPF(0, "%s: Cannot get constant buffer interfaces by name since the effect has been Optimize()'ed", pFuncName); + return &g_InvalidConstantBuffer; + } + + if (NULL == Name) + { + DPF(0, "%s: Parameter Name was NULL.", pFuncName); + return &g_InvalidConstantBuffer; + } + + UINT i; + + for (i = 0; i < m_CBCount; ++ i) + { + if (strcmp(m_pCBs[i].pName, Name) == 0) + { + return m_pCBs + i; + } + } + + DPF(0, "%s: Constant Buffer [%s] not found", pFuncName, Name); + return &g_InvalidConstantBuffer; +} + +ID3DX11EffectVariable * CEffect::GetVariableByIndex(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11Effect::GetVariableByIndex"; + + if (Index < m_VariableCount) + { + return m_pVariables + Index; + } + + DPF(0, "%s: Invalid variable index", pFuncName); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectVariable * CEffect::GetVariableByName(LPCSTR Name) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11Effect::GetVariableByName"; + + if (IsOptimized()) + { + DPF(0, "%s: Cannot get variable interfaces by name since the effect has been Optimize()'ed", pFuncName); + return &g_InvalidScalarVariable; + } + + if (NULL == Name) + { + DPF(0, "%s: Parameter Name was NULL.", pFuncName); + return &g_InvalidScalarVariable; + } + + UINT i; + + for (i = 0; i < m_VariableCount; ++ i) + { + if (strcmp(m_pVariables[i].pName, Name) == 0) + { + return m_pVariables + i; + } + } + + DPF(0, "%s: Variable [%s] not found", pFuncName, Name); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectVariable * CEffect::GetVariableBySemantic(LPCSTR Semantic) +{ + LPCSTR pFuncName = "ID3DX11Effect::GetVariableBySemantic"; + + if (IsOptimized()) + { + DPF(0, "%s: Cannot get variable interfaces by semantic since the effect has been Optimize()'ed", pFuncName); + return &g_InvalidScalarVariable; + } + + if (NULL == Semantic) + { + DPF(0, "%s: Parameter Semantic was NULL.", pFuncName); + return &g_InvalidScalarVariable; + } + + UINT i; + + for (i = 0; i < m_VariableCount; ++ i) + { + if (NULL != m_pVariables[i].pSemantic && + _stricmp(m_pVariables[i].pSemantic, Semantic) == 0) + { + return (ID3DX11EffectVariable *)(m_pVariables + i); + } + } + + DPF(0, "%s: Variable with semantic [%s] not found", pFuncName, Semantic); + return &g_InvalidScalarVariable; +} + +ID3DX11EffectTechnique * CEffect::GetTechniqueByIndex(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11Effect::GetTechniqueByIndex"; + + if( Index < m_TechniqueCount ) + { + UINT i; + for( i=0; i < m_GroupCount; i++ ) + { + if( Index < m_pGroups[i].TechniqueCount ) + { + return (ID3DX11EffectTechnique *)(m_pGroups[i].pTechniques + Index); + } + Index -= m_pGroups[i].TechniqueCount; + } + D3DXASSERT( FALSE ); + } + DPF(0, "%s: Invalid technique index (%d)", pFuncName, Index); + return &g_InvalidTechnique; +} + +ID3DX11EffectTechnique * CEffect::GetTechniqueByName(LPCSTR Name) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11Effect::GetTechniqueByName"; + const UINT MAX_GROUP_TECHNIQUE_SIZE = 256; + char NameCopy[MAX_GROUP_TECHNIQUE_SIZE]; + + if (IsOptimized()) + { + DPF(0, "ID3DX11Effect::GetTechniqueByName: Cannot get technique interfaces by name since the effect has been Optimize()'ed"); + return &g_InvalidTechnique; + } + + if (NULL == Name) + { + DPF(0, "%s: Parameter Name was NULL.", pFuncName); + return &g_InvalidTechnique; + } + + if( FAILED( StringCchCopyA( NameCopy, MAX_GROUP_TECHNIQUE_SIZE, Name ) ) ) + { + DPF( 0, "Group|Technique name has a length greater than %d.", MAX_GROUP_TECHNIQUE_SIZE ); + return &g_InvalidTechnique; + } + + char* pDelimiter = strchr( NameCopy, '|' ); + if( pDelimiter == NULL ) + { + if ( m_pNullGroup == NULL ) + { + DPF( 0, "The effect contains no default group." ); + return &g_InvalidTechnique; + } + + return m_pNullGroup->GetTechniqueByName( Name ); + } + + // separate group name and technique name + *pDelimiter = 0; + + return GetGroupByName( NameCopy )->GetTechniqueByName( pDelimiter + 1 ); +} + +ID3D11ClassLinkage * CEffect::GetClassLinkage() +{ + SAFE_ADDREF( m_pClassLinkage ); + return m_pClassLinkage; +} + +ID3DX11EffectGroup * CEffect::GetGroupByIndex(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11Effect::GetGroupByIndex"; + + if( Index < m_GroupCount ) + { + return (ID3DX11EffectGroup *)(m_pGroups + Index); + } + DPF(0, "%s: Invalid group index (%d)", pFuncName, Index); + return &g_InvalidGroup; +} + +ID3DX11EffectGroup * CEffect::GetGroupByName(LPCSTR Name) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11Effect::GetGroupByName"; + + if (IsOptimized()) + { + DPF(0, "ID3DX11Effect::GetGroupByName: Cannot get group interfaces by name since the effect has been Optimize()'ed"); + return &g_InvalidGroup; + } + + if (NULL == Name || Name[0] == 0 ) + { + return m_pNullGroup ? (ID3DX11EffectGroup *)m_pNullGroup : &g_InvalidGroup; + } + + UINT i; + + for (i = 0; i < m_GroupCount; ++ i) + { + if (NULL != m_pGroups[i].pName && + strcmp(m_pGroups[i].pName, Name) == 0) + { + break; + } + } + + if (i == m_GroupCount) + { + DPF(0, "%s: Group [%s] not found", pFuncName, Name); + return &g_InvalidGroup; + } + + return (ID3DX11EffectGroup *)(m_pGroups + i); +} + +} diff --git a/sample/d3d11/Effects11/EffectRuntime.cpp b/sample/d3d11/Effects11/EffectRuntime.cpp new file mode 100644 index 0000000..c09dc84 --- /dev/null +++ b/sample/d3d11/Effects11/EffectRuntime.cpp @@ -0,0 +1,694 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectRuntime.cpp +// Content: D3DX11 Effect runtime routines (performance critical) +// These functions are expected to be called at high frequency +// (when applying a pass). +// +////////////////////////////////////////////////////////////////////////////// + +#include "pchfx.h" + +namespace D3DX11Effects +{ + // D3D11_KEEP_UNORDERED_ACCESS_VIEWS == (UINT)-1 + UINT g_pNegativeOnes[8] = { D3D11_KEEP_UNORDERED_ACCESS_VIEWS, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, + D3D11_KEEP_UNORDERED_ACCESS_VIEWS, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, + D3D11_KEEP_UNORDERED_ACCESS_VIEWS, D3D11_KEEP_UNORDERED_ACCESS_VIEWS }; + +BOOL SBaseBlock::ApplyAssignments(CEffect *pEffect) +{ + SAssignment *pAssignment = pAssignments; + SAssignment *pLastAssn = pAssignments + AssignmentCount; + BOOL bRecreate = FALSE; + + for(; pAssignment < pLastAssn; pAssignment++) + { + bRecreate |= pEffect->EvaluateAssignment(pAssignment); + } + + return bRecreate; +} + +void SPassBlock::ApplyPassAssignments() +{ + SAssignment *pAssignment = pAssignments; + SAssignment *pLastAssn = pAssignments + AssignmentCount; + + pEffect->IncrementTimer(); + + for(; pAssignment < pLastAssn; pAssignment++) + { + pEffect->EvaluateAssignment(pAssignment); + } +} + +// Returns TRUE if the shader uses global interfaces (since these interfaces can be updated through SetClassInstance) +BOOL SPassBlock::CheckShaderDependencies( SShaderBlock* pBlock ) +{ + if( pBlock->InterfaceDepCount > 0 ) + { + D3DXASSERT( pBlock->InterfaceDepCount == 1 ); + for( UINT i=0; i < pBlock->pInterfaceDeps[0].Count; i++ ) + { + SInterface* pInterfaceDep = pBlock->pInterfaceDeps[0].ppFXPointers[i]; + if( pInterfaceDep > pEffect->m_pInterfaces && pInterfaceDep < (pEffect->m_pInterfaces + pEffect->m_InterfaceCount) ) + { + // This is a global interface pointer (as opposed to an SInterface created in a BindInterface call + return TRUE; + } + } + } + return FALSE; +} + +// Returns TRUE if the pass (and sets HasDependencies) if the pass sets objects whose backing stores can be updated +BOOL SPassBlock::CheckDependencies() +{ + if( HasDependencies ) + return TRUE; + + for( UINT i=0; i < AssignmentCount; i++ ) + { + if( pAssignments[i].DependencyCount > 0 ) + return HasDependencies = TRUE; + } + if( BackingStore.pBlendBlock && BackingStore.pBlendBlock->AssignmentCount > 0 ) + { + for( UINT i=0; i < BackingStore.pBlendBlock->AssignmentCount; i++ ) + { + if( BackingStore.pBlendBlock->pAssignments[i].DependencyCount > 0 ) + return HasDependencies = TRUE; + } + } + if( BackingStore.pDepthStencilBlock && BackingStore.pDepthStencilBlock->AssignmentCount > 0 ) + { + for( UINT i=0; i < BackingStore.pDepthStencilBlock->AssignmentCount; i++ ) + { + if( BackingStore.pDepthStencilBlock->pAssignments[i].DependencyCount > 0 ) + return HasDependencies = TRUE; + } + } + if( BackingStore.pRasterizerBlock && BackingStore.pRasterizerBlock->AssignmentCount > 0 ) + { + for( UINT i=0; i < BackingStore.pRasterizerBlock->AssignmentCount; i++ ) + { + if( BackingStore.pRasterizerBlock->pAssignments[i].DependencyCount > 0 ) + return HasDependencies = TRUE; + } + } + if( BackingStore.pVertexShaderBlock && CheckShaderDependencies( BackingStore.pVertexShaderBlock ) ) + { + return HasDependencies = TRUE; + } + if( BackingStore.pGeometryShaderBlock && CheckShaderDependencies( BackingStore.pGeometryShaderBlock ) ) + { + return HasDependencies = TRUE; + } + if( BackingStore.pPixelShaderBlock && CheckShaderDependencies( BackingStore.pPixelShaderBlock ) ) + { + return HasDependencies = TRUE; + } + if( BackingStore.pHullShaderBlock && CheckShaderDependencies( BackingStore.pHullShaderBlock ) ) + { + return HasDependencies = TRUE; + } + if( BackingStore.pDomainShaderBlock && CheckShaderDependencies( BackingStore.pDomainShaderBlock ) ) + { + return HasDependencies = TRUE; + } + if( BackingStore.pComputeShaderBlock && CheckShaderDependencies( BackingStore.pComputeShaderBlock ) ) + { + return HasDependencies = TRUE; + } + + return HasDependencies; +} + + +// Update constant buffer contents if necessary +D3DX11INLINE void CheckAndUpdateCB_FX(ID3D11DeviceContext *pContext, SConstantBuffer *pCB) +{ + if (pCB->IsDirty && !pCB->IsNonUpdatable) + { + // CB out of date; rebuild it + pContext->UpdateSubresource(pCB->pD3DObject, 0, NULL, pCB->pBackingStore, pCB->Size, pCB->Size); + pCB->IsDirty = FALSE; + } +} + + +// Set the shader and dependent state (SRVs, samplers, UAVs, interfaces) +void CEffect::ApplyShaderBlock(SShaderBlock *pBlock) +{ + UINT i; + + SD3DShaderVTable *pVT = pBlock->pVT; + + // Apply constant buffers first (tbuffers are done later) + SShaderCBDependency *pCBDep = pBlock->pCBDeps; + SShaderCBDependency *pLastCBDep = pBlock->pCBDeps + pBlock->CBDepCount; + + for (; pCBDep<pLastCBDep; pCBDep++) + { + D3DXASSERT(pCBDep->ppFXPointers); + + for (i = 0; i < pCBDep->Count; ++ i) + { + CheckAndUpdateCB_FX(m_pContext, (SConstantBuffer*)pCBDep->ppFXPointers[i]); + } + + (m_pContext->*(pVT->pSetConstantBuffers))(pCBDep->StartIndex, pCBDep->Count, pCBDep->ppD3DObjects); + } + + // Next, apply samplers + SShaderSamplerDependency *pSampDep = pBlock->pSampDeps; + SShaderSamplerDependency *pLastSampDep = pBlock->pSampDeps + pBlock->SampDepCount; + + for (; pSampDep<pLastSampDep; pSampDep++) + { + D3DXASSERT(pSampDep->ppFXPointers); + + for (i=0; i<pSampDep->Count; i++) + { + if ( ApplyRenderStateBlock(pSampDep->ppFXPointers[i]) ) + { + // If the sampler was updated, its pointer will have changed + pSampDep->ppD3DObjects[i] = pSampDep->ppFXPointers[i]->pD3DObject; + } + } + (m_pContext->*(pVT->pSetSamplers))(pSampDep->StartIndex, pSampDep->Count, pSampDep->ppD3DObjects); + } + + // Set the UAVs + // UAV ranges were combined in EffectLoad. This code remains unchanged, however, so that ranges can be easily split + D3DXASSERT( pBlock->UAVDepCount < 2 ); + if( pBlock->UAVDepCount > 0 ) + { + SUnorderedAccessViewDependency *pUAVDep = pBlock->pUAVDeps; + D3DXASSERT(pUAVDep->ppFXPointers); + + for (i=0; i<pUAVDep->Count; i++) + { + pUAVDep->ppD3DObjects[i] = pUAVDep->ppFXPointers[i]->pUnorderedAccessView; + } + + if( EOT_ComputeShader5 == pBlock->GetShaderType() ) + { + m_pContext->CSSetUnorderedAccessViews( pUAVDep->StartIndex, pUAVDep->Count, pUAVDep->ppD3DObjects, g_pNegativeOnes ); + } + else + { + // This call could be combined with the call to set render targets if both exist in the pass + m_pContext->OMSetRenderTargetsAndUnorderedAccessViews( D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL, NULL, NULL, pUAVDep->StartIndex, pUAVDep->Count, pUAVDep->ppD3DObjects, g_pNegativeOnes ); + } + } + + // TBuffers are funny: + // We keep two references to them. One is in as a standard texture dep, and that gets used for all sets + // The other is as a part of the TBufferDeps array, which tells us to rebuild the matching CBs. + // These two refs could be rolled into one, but then we would have to predicate on each CB or each texture. + SConstantBuffer **ppTB = pBlock->ppTbufDeps; + SConstantBuffer **ppLastTB = ppTB + pBlock->TBufferDepCount; + + for (; ppTB<ppLastTB; ppTB++) + { + CheckAndUpdateCB_FX(m_pContext, (SConstantBuffer*)*ppTB); + } + + // Set the textures + SShaderResourceDependency *pResourceDep = pBlock->pResourceDeps; + SShaderResourceDependency *pLastResourceDep = pBlock->pResourceDeps + pBlock->ResourceDepCount; + + for (; pResourceDep<pLastResourceDep; pResourceDep++) + { + D3DXASSERT(pResourceDep->ppFXPointers); + + for (i=0; i<pResourceDep->Count; i++) + { + pResourceDep->ppD3DObjects[i] = pResourceDep->ppFXPointers[i]->pShaderResource; + } + + (m_pContext->*(pVT->pSetShaderResources))(pResourceDep->StartIndex, pResourceDep->Count, pResourceDep->ppD3DObjects); + } + + // Update Interface dependencies + UINT Interfaces = 0; + ID3D11ClassInstance** ppClassInstances = NULL; + D3DXASSERT( pBlock->InterfaceDepCount < 2 ); + if( pBlock->InterfaceDepCount > 0 ) + { + SInterfaceDependency *pInterfaceDep = pBlock->pInterfaceDeps; + D3DXASSERT(pInterfaceDep->ppFXPointers); + + ppClassInstances = pInterfaceDep->ppD3DObjects; + Interfaces = pInterfaceDep->Count; + for (i=0; i<pInterfaceDep->Count; i++) + { + SClassInstanceGlobalVariable* pCI = pInterfaceDep->ppFXPointers[i]->pClassInstance; + if( pCI ) + { + D3DXASSERT( pCI->pMemberData != NULL ); + pInterfaceDep->ppD3DObjects[i] = pCI->pMemberData->Data.pD3DClassInstance; + } + else + { + pInterfaceDep->ppD3DObjects[i] = NULL; + } + } + } + + // Now set the shader + (m_pContext->*(pVT->pSetShader))(pBlock->pD3DObject, ppClassInstances, Interfaces); +} + +// Returns TRUE if the block D3D data was recreated +BOOL CEffect::ApplyRenderStateBlock(SBaseBlock *pBlock) +{ + if( pBlock->IsUserManaged ) + { + return FALSE; + } + + BOOL bRecreate = pBlock->ApplyAssignments(this); + + if (bRecreate) + { + switch (pBlock->BlockType) + { + case EBT_Sampler: + { + SSamplerBlock *pSBlock = pBlock->AsSampler(); + + D3DXASSERT(NULL != pSBlock->pD3DObject); + pSBlock->pD3DObject->Release(); + + m_pDevice->CreateSamplerState( &pSBlock->BackingStore.SamplerDesc, &pSBlock->pD3DObject ); + + } + break; + + case EBT_DepthStencil: + { + SDepthStencilBlock *pDSBlock = pBlock->AsDepthStencil(); + + D3DXASSERT(NULL != pDSBlock->pDSObject); + SAFE_RELEASE( pDSBlock->pDSObject ); + if( SUCCEEDED( m_pDevice->CreateDepthStencilState( &pDSBlock->BackingStore, &pDSBlock->pDSObject ) ) ) + pDSBlock->IsValid = TRUE; + else + pDSBlock->IsValid = FALSE; + } + break; + + case EBT_Blend: + { + SBlendBlock *pBBlock = pBlock->AsBlend(); + + D3DXASSERT(NULL != pBBlock->pBlendObject); + SAFE_RELEASE( pBBlock->pBlendObject ); + if( SUCCEEDED( m_pDevice->CreateBlendState( &pBBlock->BackingStore, &pBBlock->pBlendObject ) ) ) + pBBlock->IsValid = TRUE; + else + pBBlock->IsValid = FALSE; + } + break; + + case EBT_Rasterizer: + { + SRasterizerBlock *pRBlock = pBlock->AsRasterizer(); + + D3DXASSERT(NULL != pRBlock->pRasterizerObject); + + SAFE_RELEASE( pRBlock->pRasterizerObject ); + if( SUCCEEDED( m_pDevice->CreateRasterizerState( &pRBlock->BackingStore, &pRBlock->pRasterizerObject ) ) ) + pRBlock->IsValid = TRUE; + else + pRBlock->IsValid = FALSE; + } + break; + + default: + D3DXASSERT(0); + } + } + + return bRecreate; +} + +void CEffect::ValidateIndex(UINT Elements) +{ + if (m_FXLIndex >= Elements) + { + DPF(0, "ID3DX11Effect: Overindexing variable array (size: %d, index: %d), using index = 0 instead", Elements, m_FXLIndex); + m_FXLIndex = 0; + } +} + +// Returns TRUE if the assignment was changed +BOOL CEffect::EvaluateAssignment(SAssignment *pAssignment) +{ + BOOL bNeedUpdate = FALSE; + SGlobalVariable *pVarDep0, *pVarDep1; + + switch (pAssignment->AssignmentType) + { + case ERAT_NumericVariable: + D3DXASSERT(pAssignment->DependencyCount == 1); + if (pAssignment->pDependencies[0].pVariable->LastModifiedTime >= pAssignment->LastRecomputedTime) + { + dwordMemcpy(pAssignment->Destination.pNumeric, pAssignment->Source.pNumeric, pAssignment->DataSize); + bNeedUpdate = TRUE; + } + break; + + case ERAT_NumericVariableIndex: + D3DXASSERT(pAssignment->DependencyCount == 2); + pVarDep0 = pAssignment->pDependencies[0].pVariable; + pVarDep1 = pAssignment->pDependencies[1].pVariable; + + if (pVarDep0->LastModifiedTime >= pAssignment->LastRecomputedTime) + { + m_FXLIndex = *pVarDep0->Data.pNumericDword; + + ValidateIndex(pVarDep1->pType->Elements); + + // Array index variable is dirty, update the pointer + pAssignment->Source.pNumeric = pVarDep1->Data.pNumeric + pVarDep1->pType->Stride * m_FXLIndex; + + // Copy the new data + dwordMemcpy(pAssignment->Destination.pNumeric, pAssignment->Source.pNumeric, pAssignment->DataSize); + bNeedUpdate = TRUE; + } + else if (pVarDep1->LastModifiedTime >= pAssignment->LastRecomputedTime) + { + // Only the array variable is dirty, copy the new data + dwordMemcpy(pAssignment->Destination.pNumeric, pAssignment->Source.pNumeric, pAssignment->DataSize); + bNeedUpdate = TRUE; + } + break; + + case ERAT_ObjectVariableIndex: + D3DXASSERT(pAssignment->DependencyCount == 1); + pVarDep0 = pAssignment->pDependencies[0].pVariable; + if (pVarDep0->LastModifiedTime >= pAssignment->LastRecomputedTime) + { + m_FXLIndex = *pVarDep0->Data.pNumericDword; + ValidateIndex(pAssignment->MaxElements); + + // Array index variable is dirty, update the destination pointer + *((void **)pAssignment->Destination.pGeneric) = pAssignment->Source.pNumeric + + pAssignment->DataSize * m_FXLIndex; + bNeedUpdate = TRUE; + } + break; + + default: + //case ERAT_Constant: -- These are consumed and discarded + //case ERAT_ObjectVariable: -- These are consumed and discarded + //case ERAT_ObjectConstIndex: -- These are consumed and discarded + //case ERAT_ObjectInlineShader: -- These are consumed and discarded + //case ERAT_NumericConstIndex: -- ERAT_NumericVariable should be generated instead + D3DXASSERT(0); + break; + } + + // Mark the assignment as not dirty + pAssignment->LastRecomputedTime = m_LocalTimer; + + return bNeedUpdate; +} + +// Returns FALSE if this shader has interface dependencies which are NULL (SetShader will fail). +BOOL CEffect::ValidateShaderBlock( SShaderBlock* pBlock ) +{ + if( !pBlock->IsValid ) + return FALSE; + if( pBlock->InterfaceDepCount > 0 ) + { + D3DXASSERT( pBlock->InterfaceDepCount == 1 ); + for( UINT i=0; i < pBlock->pInterfaceDeps[0].Count; i++ ) + { + SInterface* pInterfaceDep = pBlock->pInterfaceDeps[0].ppFXPointers[i]; + D3DXASSERT( pInterfaceDep != NULL ); + if( pInterfaceDep->pClassInstance == NULL ) + { + return FALSE; + } + } + } + return TRUE; +} + +// Returns FALSE if any state in the pass is invalid +BOOL CEffect::ValidatePassBlock( SPassBlock* pBlock ) +{ + pBlock->ApplyPassAssignments(); + + if (NULL != pBlock->BackingStore.pBlendBlock) + { + ApplyRenderStateBlock(pBlock->BackingStore.pBlendBlock); + pBlock->BackingStore.pBlendState = pBlock->BackingStore.pBlendBlock->pBlendObject; + if( !pBlock->BackingStore.pBlendBlock->IsValid ) + return FALSE; + } + + if( NULL != pBlock->BackingStore.pDepthStencilBlock ) + { + ApplyRenderStateBlock( pBlock->BackingStore.pDepthStencilBlock ); + pBlock->BackingStore.pDepthStencilState = pBlock->BackingStore.pDepthStencilBlock->pDSObject; + if( !pBlock->BackingStore.pDepthStencilBlock->IsValid ) + return FALSE; + } + + if( NULL != pBlock->BackingStore.pRasterizerBlock ) + { + ApplyRenderStateBlock( pBlock->BackingStore.pRasterizerBlock ); + if( !pBlock->BackingStore.pRasterizerBlock->IsValid ) + return FALSE; + } + + if( NULL != pBlock->BackingStore.pVertexShaderBlock && !ValidateShaderBlock(pBlock->BackingStore.pVertexShaderBlock) ) + return FALSE; + + if( NULL != pBlock->BackingStore.pGeometryShaderBlock && !ValidateShaderBlock(pBlock->BackingStore.pGeometryShaderBlock) ) + return FALSE; + + if( NULL != pBlock->BackingStore.pPixelShaderBlock ) + { + if( !ValidateShaderBlock(pBlock->BackingStore.pPixelShaderBlock) ) + return FALSE; + else if( pBlock->BackingStore.pPixelShaderBlock->UAVDepCount > 0 && + pBlock->BackingStore.RenderTargetViewCount > pBlock->BackingStore.pPixelShaderBlock->pUAVDeps[0].StartIndex ) + { + return FALSE; + } + } + + if( NULL != pBlock->BackingStore.pHullShaderBlock && !ValidateShaderBlock(pBlock->BackingStore.pHullShaderBlock) ) + return FALSE; + + if( NULL != pBlock->BackingStore.pDomainShaderBlock && !ValidateShaderBlock(pBlock->BackingStore.pDomainShaderBlock) ) + return FALSE; + + if( NULL != pBlock->BackingStore.pComputeShaderBlock && !ValidateShaderBlock(pBlock->BackingStore.pComputeShaderBlock) ) + return FALSE; + + return TRUE; +} + +// Set all state defined in the pass +void CEffect::ApplyPassBlock(SPassBlock *pBlock) +{ + pBlock->ApplyPassAssignments(); + + if (NULL != pBlock->BackingStore.pBlendBlock) + { + ApplyRenderStateBlock(pBlock->BackingStore.pBlendBlock); +#ifdef FXDEBUG + if( !pBlock->BackingStore.pBlendBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid BlendState." ); +#endif + pBlock->BackingStore.pBlendState = pBlock->BackingStore.pBlendBlock->pBlendObject; + m_pContext->OMSetBlendState(pBlock->BackingStore.pBlendState, + pBlock->BackingStore.BlendFactor, + pBlock->BackingStore.SampleMask); + } + + if (NULL != pBlock->BackingStore.pDepthStencilBlock) + { + ApplyRenderStateBlock(pBlock->BackingStore.pDepthStencilBlock); +#ifdef FXDEBUG + if( !pBlock->BackingStore.pDepthStencilBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid DepthStencilState." ); +#endif + pBlock->BackingStore.pDepthStencilState = pBlock->BackingStore.pDepthStencilBlock->pDSObject; + m_pContext->OMSetDepthStencilState(pBlock->BackingStore.pDepthStencilState, + pBlock->BackingStore.StencilRef); + } + + if (NULL != pBlock->BackingStore.pRasterizerBlock) + { + ApplyRenderStateBlock(pBlock->BackingStore.pRasterizerBlock); +#ifdef FXDEBUG + if( !pBlock->BackingStore.pRasterizerBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid RasterizerState." ); +#endif + m_pContext->RSSetState(pBlock->BackingStore.pRasterizerBlock->pRasterizerObject); + } + + if (NULL != pBlock->BackingStore.pRenderTargetViews[0]) + { + // Grab all render targets + ID3D11RenderTargetView *pRTV[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT]; + + D3DXASSERT(pBlock->BackingStore.RenderTargetViewCount <= D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT); + __analysis_assume(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT >= pBlock->BackingStore.RenderTargetViewCount); + + for (UINT i=0; i<pBlock->BackingStore.RenderTargetViewCount; i++) + { + pRTV[i] = pBlock->BackingStore.pRenderTargetViews[i]->pRenderTargetView; + } + + // This call could be combined with the call to set PS UAVs if both exist in the pass + m_pContext->OMSetRenderTargetsAndUnorderedAccessViews( pBlock->BackingStore.RenderTargetViewCount, pRTV, pBlock->BackingStore.pDepthStencilView->pDepthStencilView, 7, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, NULL, NULL ); + } + + if (NULL != pBlock->BackingStore.pVertexShaderBlock) + { +#ifdef FXDEBUG + if( !pBlock->BackingStore.pVertexShaderBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid vertex shader." ); +#endif + ApplyShaderBlock(pBlock->BackingStore.pVertexShaderBlock); + } + + if (NULL != pBlock->BackingStore.pPixelShaderBlock) + { +#ifdef FXDEBUG + if( !pBlock->BackingStore.pPixelShaderBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid pixel shader." ); +#endif + ApplyShaderBlock(pBlock->BackingStore.pPixelShaderBlock); + } + + if (NULL != pBlock->BackingStore.pGeometryShaderBlock) + { +#ifdef FXDEBUG + if( !pBlock->BackingStore.pGeometryShaderBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid geometry shader." ); +#endif + ApplyShaderBlock(pBlock->BackingStore.pGeometryShaderBlock); + } + + if (NULL != pBlock->BackingStore.pHullShaderBlock) + { +#ifdef FXDEBUG + if( !pBlock->BackingStore.pHullShaderBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid hull shader." ); +#endif + ApplyShaderBlock(pBlock->BackingStore.pHullShaderBlock); + } + + if (NULL != pBlock->BackingStore.pDomainShaderBlock) + { +#ifdef FXDEBUG + if( !pBlock->BackingStore.pDomainShaderBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid domain shader." ); +#endif + ApplyShaderBlock(pBlock->BackingStore.pDomainShaderBlock); + } + + if (NULL != pBlock->BackingStore.pComputeShaderBlock) + { +#ifdef FXDEBUG + if( !pBlock->BackingStore.pComputeShaderBlock->IsValid ) + DPF( 0, "Pass::Apply - warning: applying invalid compute shader." ); +#endif + ApplyShaderBlock(pBlock->BackingStore.pComputeShaderBlock); + } +} + +void CEffect::IncrementTimer() +{ + m_LocalTimer++; + +#ifndef _WIN64 +#if _DEBUG && FXDEBUG + if (m_LocalTimer > g_TimerRolloverCount) + { + DPF(0, "Rolling over timer (current time: %d, rollover cap: %d).", m_LocalTimer, g_TimerRolloverCount); +#else // else !(_DEBUG && FXDEBUG) + if (m_LocalTimer >= 0x80000000) // check to see if we've exceeded ~2 billion + { +#endif // _DEBUG && FXDEBUG + HandleLocalTimerRollover(); + + m_LocalTimer = 1; + } +#endif // _WIN64 +} + +// This function resets all timers, rendering all assignments dirty +// This is clearly bad for performance, but should only happen every few billion ticks +void CEffect::HandleLocalTimerRollover() +{ + UINT i, j, k; + + // step 1: update variables + for (i = 0; i < m_VariableCount; ++ i) + { + m_pVariables[i].LastModifiedTime = 0; + } + + // step 2: update assignments on all blocks (pass, depth stencil, rasterizer, blend, sampler) + for (UINT iGroup = 0; iGroup < m_GroupCount; ++ iGroup) + { + for (i = 0; i < m_pGroups[iGroup].TechniqueCount; ++ i) + { + for (j = 0; j < m_pGroups[iGroup].pTechniques[i].PassCount; ++ j) + { + for (k = 0; k < m_pGroups[iGroup].pTechniques[i].pPasses[j].AssignmentCount; ++ k) + { + m_pGroups[iGroup].pTechniques[i].pPasses[j].pAssignments[k].LastRecomputedTime = 0; + } + } + } + } + + for (i = 0; i < m_DepthStencilBlockCount; ++ i) + { + for (j = 0; j < m_pDepthStencilBlocks[i].AssignmentCount; ++ j) + { + m_pDepthStencilBlocks[i].pAssignments[j].LastRecomputedTime = 0; + } + } + + for (i = 0; i < m_RasterizerBlockCount; ++ i) + { + for (j = 0; j < m_pRasterizerBlocks[i].AssignmentCount; ++ j) + { + m_pRasterizerBlocks[i].pAssignments[j].LastRecomputedTime = 0; + } + } + + for (i = 0; i < m_BlendBlockCount; ++ i) + { + for (j = 0; j < m_pBlendBlocks[i].AssignmentCount; ++ j) + { + m_pBlendBlocks[i].pAssignments[j].LastRecomputedTime = 0; + } + } + + for (i = 0; i < m_SamplerBlockCount; ++ i) + { + for (j = 0; j < m_pSamplerBlocks[i].AssignmentCount; ++ j) + { + m_pSamplerBlocks[i].pAssignments[j].LastRecomputedTime = 0; + } + } +} + +} diff --git a/sample/d3d11/Effects11/EffectVariable.inl b/sample/d3d11/Effects11/EffectVariable.inl new file mode 100644 index 0000000..4a8f4b7 --- /dev/null +++ b/sample/d3d11/Effects11/EffectVariable.inl @@ -0,0 +1,4573 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: EffectVariable.inl +// Content: D3DX11 Effects Variable reflection template +// These templates define the many Effect variable types. +// +////////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////// +// Invalid variable forward defines +////////////////////////////////////////////////////////////////////////// + +struct SEffectInvalidScalarVariable; +struct SEffectInvalidVectorVariable; +struct SEffectInvalidMatrixVariable; +struct SEffectInvalidStringVariable; +struct SEffectInvalidClassInstanceVariable; +struct SEffectInvalidInterfaceVariable; +struct SEffectInvalidShaderResourceVariable; +struct SEffectInvalidUnorderedAccessViewVariable; +struct SEffectInvalidRenderTargetViewVariable; +struct SEffectInvalidDepthStencilViewVariable; +struct SEffectInvalidConstantBuffer; +struct SEffectInvalidShaderVariable; +struct SEffectInvalidBlendVariable; +struct SEffectInvalidDepthStencilVariable; +struct SEffectInvalidRasterizerVariable; +struct SEffectInvalidSamplerVariable; +struct SEffectInvalidTechnique; +struct SEffectInvalidPass; +struct SEffectInvalidType; + +extern SEffectInvalidScalarVariable g_InvalidScalarVariable; +extern SEffectInvalidVectorVariable g_InvalidVectorVariable; +extern SEffectInvalidMatrixVariable g_InvalidMatrixVariable; +extern SEffectInvalidStringVariable g_InvalidStringVariable; +extern SEffectInvalidClassInstanceVariable g_InvalidClassInstanceVariable; +extern SEffectInvalidInterfaceVariable g_InvalidInterfaceVariable; +extern SEffectInvalidShaderResourceVariable g_InvalidShaderResourceVariable; +extern SEffectInvalidUnorderedAccessViewVariable g_InvalidUnorderedAccessViewVariable; +extern SEffectInvalidRenderTargetViewVariable g_InvalidRenderTargetViewVariable; +extern SEffectInvalidDepthStencilViewVariable g_InvalidDepthStencilViewVariable; +extern SEffectInvalidConstantBuffer g_InvalidConstantBuffer; +extern SEffectInvalidShaderVariable g_InvalidShaderVariable; +extern SEffectInvalidBlendVariable g_InvalidBlendVariable; +extern SEffectInvalidDepthStencilVariable g_InvalidDepthStencilVariable; +extern SEffectInvalidRasterizerVariable g_InvalidRasterizerVariable; +extern SEffectInvalidSamplerVariable g_InvalidSamplerVariable; +extern SEffectInvalidTechnique g_InvalidTechnique; +extern SEffectInvalidPass g_InvalidPass; +extern SEffectInvalidType g_InvalidType; + +enum ETemplateVarType +{ + ETVT_Bool, + ETVT_Int, + ETVT_Float +}; + +////////////////////////////////////////////////////////////////////////// +// Invalid effect variable struct definitions +////////////////////////////////////////////////////////////////////////// + +struct SEffectInvalidType : public ID3DX11EffectType +{ + STDMETHOD_(BOOL, IsValid)() { return FALSE; } + STDMETHOD(GetDesc)(D3DX11_EFFECT_TYPE_DESC *pDesc) { return E_FAIL; } + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(UINT Index) { return &g_InvalidType; } + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(LPCSTR Name) { return &g_InvalidType; } + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(LPCSTR Semanti) { return &g_InvalidType; } + STDMETHOD_(LPCSTR, GetMemberName)(UINT Index) { return NULL; } + STDMETHOD_(LPCSTR, GetMemberSemantic)(UINT Index) { return NULL; } +}; + +template<typename IBaseInterface> +struct TEffectInvalidVariable : public IBaseInterface +{ +public: + STDMETHOD_(BOOL, IsValid)() { return FALSE; } + STDMETHOD_(ID3DX11EffectType*, GetType)() { return &g_InvalidType; } + STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) { return E_FAIL; } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(UINT Index) { return &g_InvalidScalarVariable; } + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(LPCSTR Semantic) { return &g_InvalidScalarVariable; } + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(UINT Index) { return &g_InvalidScalarVariable; } + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() { return &g_InvalidConstantBuffer; } + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)() { return &g_InvalidScalarVariable; } + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)() { return &g_InvalidVectorVariable; } + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)() { return &g_InvalidMatrixVariable; } + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)() { return &g_InvalidStringVariable; } + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)() { return &g_InvalidClassInstanceVariable; } + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)() { return &g_InvalidInterfaceVariable; } + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)() { return &g_InvalidShaderResourceVariable; } + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)() { return &g_InvalidUnorderedAccessViewVariable; } + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)() { return &g_InvalidRenderTargetViewVariable; } + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)() { return &g_InvalidDepthStencilViewVariable; } + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)() { return &g_InvalidConstantBuffer; } + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)() { return &g_InvalidShaderVariable; } + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)() { return &g_InvalidBlendVariable; } + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)() { return &g_InvalidDepthStencilVariable; } + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)() { return &g_InvalidRasterizerVariable; } + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)() { return &g_InvalidSamplerVariable; } + + STDMETHOD(SetRawValue)(CONST void *pData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetRawValue)(void *pData, UINT Offset, UINT Count) { return E_FAIL; } +}; + +struct SEffectInvalidScalarVariable : public TEffectInvalidVariable<ID3DX11EffectScalarVariable> +{ +public: + + STDMETHOD(SetFloat)(CONST float Value) { return E_FAIL; } + STDMETHOD(GetFloat)(float *pValue) { return E_FAIL; } + + STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; } + + STDMETHOD(SetInt)(CONST int Value) { return E_FAIL; } + STDMETHOD(GetInt)(int *pValue) { return E_FAIL; } + + STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count) { return E_FAIL; } + + STDMETHOD(SetBool)(CONST BOOL Value) { return E_FAIL; } + STDMETHOD(GetBool)(BOOL *pValue) { return E_FAIL; } + + STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; } +}; + + +struct SEffectInvalidVectorVariable : public TEffectInvalidVariable<ID3DX11EffectVectorVariable> +{ +public: + STDMETHOD(SetFloatVector)(CONST float *pData) { return E_FAIL; }; + STDMETHOD(SetIntVector)(CONST int *pData) { return E_FAIL; }; + STDMETHOD(SetBoolVector)(CONST BOOL *pData) { return E_FAIL; }; + + STDMETHOD(GetFloatVector)(float *pData) { return E_FAIL; }; + STDMETHOD(GetIntVector)(int *pData) { return E_FAIL; }; + STDMETHOD(GetBoolVector)(BOOL *pData) { return E_FAIL; }; + + STDMETHOD(SetBoolVectorArray) (CONST BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; }; + STDMETHOD(SetIntVectorArray) (CONST int *pData, UINT Offset, UINT Count) { return E_FAIL; }; + STDMETHOD(SetFloatVectorArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; }; + + STDMETHOD(GetBoolVectorArray) (BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; }; + STDMETHOD(GetIntVectorArray) (int *pData, UINT Offset, UINT Count) { return E_FAIL; }; + STDMETHOD(GetFloatVectorArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; }; + +}; + +struct SEffectInvalidMatrixVariable : public TEffectInvalidVariable<ID3DX11EffectMatrixVariable> +{ +public: + + STDMETHOD(SetMatrix)(CONST float *pData) { return E_FAIL; } + STDMETHOD(GetMatrix)(float *pData) { return E_FAIL; } + + STDMETHOD(SetMatrixArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetMatrixArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; } + + STDMETHOD(SetMatrixPointerArray)(CONST float **ppData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetMatrixPointerArray)(float **ppData, UINT Offset, UINT Count) { return E_FAIL; } + + STDMETHOD(SetMatrixTranspose)(CONST float *pData) { return E_FAIL; } + STDMETHOD(GetMatrixTranspose)(float *pData) { return E_FAIL; } + + STDMETHOD(SetMatrixTransposeArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetMatrixTransposeArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; } + + STDMETHOD(SetMatrixTransposePointerArray)(CONST float **ppData, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetMatrixTransposePointerArray)(float **ppData, UINT Offset, UINT Count) { return E_FAIL; } +}; + +struct SEffectInvalidStringVariable : public TEffectInvalidVariable<ID3DX11EffectStringVariable> +{ +public: + + STDMETHOD(GetString)(LPCSTR *ppString) { return E_FAIL; } + STDMETHOD(GetStringArray)(LPCSTR *ppStrings, UINT Offset, UINT Count) { return E_FAIL; } +}; + +struct SEffectInvalidClassInstanceVariable : public TEffectInvalidVariable<ID3DX11EffectClassInstanceVariable> +{ +public: + + STDMETHOD(GetClassInstance)(ID3D11ClassInstance **ppClassInstance) { return E_FAIL; } +}; + + +struct SEffectInvalidInterfaceVariable : public TEffectInvalidVariable<ID3DX11EffectInterfaceVariable> +{ +public: + + STDMETHOD(SetClassInstance)(ID3DX11EffectClassInstanceVariable *pEffectClassInstance) { return E_FAIL; } + STDMETHOD(GetClassInstance)(ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) { return E_FAIL; } +}; + + +struct SEffectInvalidShaderResourceVariable : public TEffectInvalidVariable<ID3DX11EffectShaderResourceVariable> +{ +public: + + STDMETHOD(SetResource)(ID3D11ShaderResourceView *pResource) { return E_FAIL; } + STDMETHOD(GetResource)(ID3D11ShaderResourceView **ppResource) { return E_FAIL; } + + STDMETHOD(SetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } +}; + + +struct SEffectInvalidUnorderedAccessViewVariable : public TEffectInvalidVariable<ID3DX11EffectUnorderedAccessViewVariable> +{ +public: + + STDMETHOD(SetUnorderedAccessView)(ID3D11UnorderedAccessView *pResource) { return E_FAIL; } + STDMETHOD(GetUnorderedAccessView)(ID3D11UnorderedAccessView **ppResource) { return E_FAIL; } + + STDMETHOD(SetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } +}; + + +struct SEffectInvalidRenderTargetViewVariable : public TEffectInvalidVariable<ID3DX11EffectRenderTargetViewVariable> +{ +public: + + STDMETHOD(SetRenderTarget)(ID3D11RenderTargetView *pResource) { return E_FAIL; } + STDMETHOD(GetRenderTarget)(ID3D11RenderTargetView **ppResource) { return E_FAIL; } + + STDMETHOD(SetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } +}; + + +struct SEffectInvalidDepthStencilViewVariable : public TEffectInvalidVariable<ID3DX11EffectDepthStencilViewVariable> +{ +public: + + STDMETHOD(SetDepthStencil)(ID3D11DepthStencilView *pResource) { return E_FAIL; } + STDMETHOD(GetDepthStencil)(ID3D11DepthStencilView **ppResource) { return E_FAIL; } + + STDMETHOD(SetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } + STDMETHOD(GetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } +}; + + +struct SEffectInvalidConstantBuffer : public TEffectInvalidVariable<ID3DX11EffectConstantBuffer> +{ +public: + + STDMETHOD(SetConstantBuffer)(ID3D11Buffer *pConstantBuffer) { return E_FAIL; } + STDMETHOD(GetConstantBuffer)(ID3D11Buffer **ppConstantBuffer) { return E_FAIL; } + STDMETHOD(UndoSetConstantBuffer)() { return E_FAIL; } + + STDMETHOD(SetTextureBuffer)(ID3D11ShaderResourceView *pTextureBuffer) { return E_FAIL; } + STDMETHOD(GetTextureBuffer)(ID3D11ShaderResourceView **ppTextureBuffer) { return E_FAIL; } + STDMETHOD(UndoSetTextureBuffer)() { return E_FAIL; } +}; + +struct SEffectInvalidShaderVariable : public TEffectInvalidVariable<ID3DX11EffectShaderVariable> +{ +public: + + STDMETHOD(GetShaderDesc)(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc) { return E_FAIL; } + + STDMETHOD(GetVertexShader)(UINT ShaderIndex, ID3D11VertexShader **ppVS) { return E_FAIL; } + STDMETHOD(GetGeometryShader)(UINT ShaderIndex, ID3D11GeometryShader **ppGS) { return E_FAIL; } + STDMETHOD(GetPixelShader)(UINT ShaderIndex, ID3D11PixelShader **ppPS) { return E_FAIL; } + STDMETHOD(GetHullShader)(UINT ShaderIndex, ID3D11HullShader **ppPS) { return E_FAIL; } + STDMETHOD(GetDomainShader)(UINT ShaderIndex, ID3D11DomainShader **ppPS) { return E_FAIL; } + STDMETHOD(GetComputeShader)(UINT ShaderIndex, ID3D11ComputeShader **ppPS) { return E_FAIL; } + + STDMETHOD(GetInputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { return E_FAIL; } + STDMETHOD(GetOutputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { return E_FAIL; } + STDMETHOD(GetPatchConstantSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { return E_FAIL; } +}; + +struct SEffectInvalidBlendVariable : public TEffectInvalidVariable<ID3DX11EffectBlendVariable> +{ +public: + + STDMETHOD(GetBlendState)(UINT Index, ID3D11BlendState **ppBlendState) { return E_FAIL; } + STDMETHOD(SetBlendState)(UINT Index, ID3D11BlendState *pBlendState) { return E_FAIL; } + STDMETHOD(UndoSetBlendState)(UINT Index) { return E_FAIL; } + STDMETHOD(GetBackingStore)(UINT Index, D3D11_BLEND_DESC *pBlendDesc) { return E_FAIL; } +}; + +struct SEffectInvalidDepthStencilVariable : public TEffectInvalidVariable<ID3DX11EffectDepthStencilVariable> +{ +public: + + STDMETHOD(GetDepthStencilState)(UINT Index, ID3D11DepthStencilState **ppDepthStencilState) { return E_FAIL; } + STDMETHOD(SetDepthStencilState)(UINT Index, ID3D11DepthStencilState *pDepthStencilState) { return E_FAIL; } + STDMETHOD(UndoSetDepthStencilState)(UINT Index) { return E_FAIL; } + STDMETHOD(GetBackingStore)(UINT Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc) { return E_FAIL; } +}; + +struct SEffectInvalidRasterizerVariable : public TEffectInvalidVariable<ID3DX11EffectRasterizerVariable> +{ +public: + + STDMETHOD(GetRasterizerState)(UINT Index, ID3D11RasterizerState **ppRasterizerState) { return E_FAIL; } + STDMETHOD(SetRasterizerState)(UINT Index, ID3D11RasterizerState *pRasterizerState) { return E_FAIL; } + STDMETHOD(UndoSetRasterizerState)(UINT Index) { return E_FAIL; } + STDMETHOD(GetBackingStore)(UINT Index, D3D11_RASTERIZER_DESC *pRasterizerDesc) { return E_FAIL; } +}; + +struct SEffectInvalidSamplerVariable : public TEffectInvalidVariable<ID3DX11EffectSamplerVariable> +{ +public: + + STDMETHOD(GetSampler)(UINT Index, ID3D11SamplerState **ppSampler) { return E_FAIL; } + STDMETHOD(SetSampler)(UINT Index, ID3D11SamplerState *pSampler) { return E_FAIL; } + STDMETHOD(UndoSetSampler)(UINT Index) { return E_FAIL; } + STDMETHOD(GetBackingStore)(UINT Index, D3D11_SAMPLER_DESC *pSamplerDesc) { return E_FAIL; } +}; + +struct SEffectInvalidPass : public ID3DX11EffectPass +{ +public: + STDMETHOD_(BOOL, IsValid)() { return FALSE; } + STDMETHOD(GetDesc)(D3DX11_PASS_DESC *pDesc) { return E_FAIL; } + + STDMETHOD(GetVertexShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } + STDMETHOD(GetGeometryShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } + STDMETHOD(GetPixelShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } + STDMETHOD(GetHullShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } + STDMETHOD(GetDomainShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } + STDMETHOD(GetComputeShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } + + STDMETHOD(Apply)(UINT Flags, ID3D11DeviceContext* pContext) { return E_FAIL; } + STDMETHOD(ComputeStateBlockMask)(D3DX11_STATE_BLOCK_MASK *pStateBlockMask) { return E_FAIL; } +}; + +struct SEffectInvalidTechnique : public ID3DX11EffectTechnique +{ +public: + STDMETHOD_(BOOL, IsValid)() { return FALSE; } + STDMETHOD(GetDesc)(D3DX11_TECHNIQUE_DESC *pDesc) { return E_FAIL; } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } + + STDMETHOD_(ID3DX11EffectPass*, GetPassByIndex)(UINT Index) { return &g_InvalidPass; } + STDMETHOD_(ID3DX11EffectPass*, GetPassByName)(LPCSTR Name) { return &g_InvalidPass; } + + STDMETHOD(ComputeStateBlockMask)(D3DX11_STATE_BLOCK_MASK *pStateBlockMask) { return E_FAIL; } +}; + +struct SEffectInvalidGroup : public ID3DX11EffectGroup +{ +public: + STDMETHOD_(BOOL, IsValid)() { return FALSE; } + STDMETHOD(GetDesc)(D3DX11_GROUP_DESC *pDesc) { return E_FAIL; } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } + + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(UINT Index) { return &g_InvalidTechnique; } + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(LPCSTR Name) { return &g_InvalidTechnique; } +}; + +////////////////////////////////////////////////////////////////////////// +// Helper routines +////////////////////////////////////////////////////////////////////////// + +// This is an annoying warning that pops up in retail builds because +// the code that jumps to "lExit" is conditionally not compiled. +// The only alternative is more #ifdefs in every function +#pragma warning( disable : 4102 ) // 'label' : unreferenced label + +#define VERIFYPARAMETER(x) \ +{ if (!(x)) { DPF(0, "%s: Parameter " #x " was NULL.", pFuncName); \ + __BREAK_ON_FAIL; hr = E_INVALIDARG; goto lExit; } } + +static HRESULT AnnotationInvalidSetCall(LPCSTR pFuncName) +{ + DPF(0, "%s: Annotations are readonly", pFuncName); + return D3DERR_INVALIDCALL; +} + +static HRESULT ObjectSetRawValue() +{ + DPF(0, "ID3DX11EffectVariable::SetRawValue: Objects do not support ths call; please use the specific object accessors instead."); + return D3DERR_INVALIDCALL; +} + +static HRESULT ObjectGetRawValue() +{ + DPF(0, "ID3DX11EffectVariable::GetRawValue: Objects do not support ths call; please use the specific object accessors instead."); + return D3DERR_INVALIDCALL; +} + +ID3DX11EffectConstantBuffer * NoParentCB(); + +ID3DX11EffectVariable * GetAnnotationByIndexHelper(const char *pClassName, UINT Index, UINT AnnotationCount, SAnnotation *pAnnotations); + +ID3DX11EffectVariable * GetAnnotationByNameHelper(const char *pClassName, LPCSTR Name, UINT AnnotationCount, SAnnotation *pAnnotations); + +template<typename SVarType> +BOOL GetVariableByIndexHelper(UINT Index, UINT VariableCount, SVarType *pVariables, + BYTE *pBaseAddress, SVarType **ppMember, void **ppDataPtr) +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberByIndex"; + + if (Index >= VariableCount) + { + DPF(0, "%s: Invalid index (%d, total: %d)", pFuncName, Index, VariableCount); + return FALSE; + } + + *ppMember = pVariables + Index; + *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; + return TRUE; +} + +template<typename SVarType> +BOOL GetVariableByNameHelper(LPCSTR Name, UINT VariableCount, SVarType *pVariables, + BYTE *pBaseAddress, SVarType **ppMember, void **ppDataPtr, UINT* pIndex) +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberByName"; + + if (NULL == Name) + { + DPF(0, "%s: Parameter Name was NULL.", pFuncName); + return FALSE; + } + + UINT i; + bool bHasSuper = false; + + for (i = 0; i < VariableCount; ++ i) + { + *ppMember = pVariables + i; + D3DXASSERT(NULL != (*ppMember)->pName); + if (strcmp((*ppMember)->pName, Name) == 0) + { + *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; + *pIndex = i; + return TRUE; + } + else if (i == 0 && + (*ppMember)->pName[0] == '$' && + strcmp((*ppMember)->pName, "$super") == 0) + { + bHasSuper = true; + } + } + + if (bHasSuper) + { + SVarType* pSuper = pVariables; + + return GetVariableByNameHelper<SVarType>(Name, + pSuper->pType->StructType.Members, + (SVarType*)pSuper->pType->StructType.pMembers, + pBaseAddress + pSuper->Data.Offset, + ppMember, + ppDataPtr, + pIndex); + } + + DPF(0, "%s: Variable [%s] not found", pFuncName, Name); + return FALSE; +} + +template<typename SVarType> +BOOL GetVariableBySemanticHelper(LPCSTR Semantic, UINT VariableCount, SVarType *pVariables, + BYTE *pBaseAddress, SVarType **ppMember, void **ppDataPtr, UINT* pIndex) +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberBySemantic"; + + if (NULL == Semantic) + { + DPF(0, "%s: Parameter Semantic was NULL.", pFuncName); + return FALSE; + } + + UINT i; + + for (i = 0; i < VariableCount; ++ i) + { + *ppMember = pVariables + i; + if (NULL != (*ppMember)->pSemantic && + _stricmp((*ppMember)->pSemantic, Semantic) == 0) + { + *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; + *pIndex = i; + return TRUE; + } + } + + DPF(0, "%s: Variable with semantic [%s] not found", pFuncName, Semantic); + return FALSE; +} + +D3DX11INLINE BOOL AreBoundsValid(UINT Offset, UINT Count, CONST void *pData, CONST SType *pType, UINT TotalUnpackedSize) +{ + if (Count == 0) return TRUE; + UINT singleElementSize = pType->GetTotalUnpackedSize(TRUE); + D3DXASSERT(singleElementSize <= pType->Stride); + + return ((Offset + Count >= Offset) && + ((Offset + Count) < ((UINT)-1) / pType->Stride) && + (Count * pType->Stride + (BYTE*)pData >= (BYTE*)pData) && + ((Offset + Count - 1) * pType->Stride + singleElementSize <= TotalUnpackedSize)); +} + +// Note that the branches in this code is based on template parameters and will be compiled out +template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, BOOL ValidatePtr> +__forceinline HRESULT CopyScalarValue(SRC_TYPE SrcValue, void *pDest, const char *pFuncName) +{ + HRESULT hr = S_OK; +#ifdef _DEBUG + if (ValidatePtr) + VERIFYPARAMETER(pDest); +#endif + + switch (SourceType) + { + case ETVT_Bool: + switch (DestType) + { + case ETVT_Bool: + *(int*)pDest = (SrcValue != 0) ? -1 : 0; + break; + + case ETVT_Int: + *(int*)pDest = SrcValue ? 1 : 0; + break; + + case ETVT_Float: + *(float*)pDest = SrcValue ? 1.0f : 0.0f; + break; + + default: + D3DXASSERT(0); + } + break; + + + case ETVT_Int: + switch (DestType) + { + case ETVT_Bool: + *(int*)pDest = (SrcValue != 0) ? -1 : 0; + break; + + case ETVT_Int: + *(int*)pDest = (int) SrcValue; + break; + + case ETVT_Float: + *(float*)pDest = (float)(SrcValue); + break; + + default: + D3DXASSERT(0); + } + break; + + case ETVT_Float: + switch (DestType) + { + case ETVT_Bool: + *(int*)pDest = (SrcValue != 0.0f) ? -1 : 0; + break; + + case ETVT_Int: + *(int*)pDest = (int) (SrcValue); + break; + + case ETVT_Float: + *(float*)pDest = (float) SrcValue; + break; + + default: + D3DXASSERT(0); + } + break; + + default: + D3DXASSERT(0); + } + +lExit: + return S_OK; +} + +template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, typename DEST_TYPE> +D3DX11INLINE HRESULT SetScalarArray(CONST SRC_TYPE *pSrcValues, DEST_TYPE *pDestValues, UINT Offset, UINT Count, + SType *pType, UINT TotalUnpackedSize, const char *pFuncName) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + VERIFYPARAMETER(pSrcValues); + + if (!AreBoundsValid(Offset, Count, pSrcValues, pType, TotalUnpackedSize)) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + UINT i, j, delta = pType->NumericType.IsPackedArray ? 1 : SType::c_ScalarsPerRegister; + pDestValues += Offset * delta; + for (i = 0, j = 0; j < Count; i += delta, ++ j) + { + // pDestValues[i] = (DEST_TYPE)pSrcValues[j]; + CopyScalarValue<SourceType, DestType, SRC_TYPE, FALSE>(pSrcValues[j], &pDestValues[i], "SetScalarArray"); + } + +lExit: + return hr; +} + +template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, typename DEST_TYPE> +D3DX11INLINE HRESULT GetScalarArray(SRC_TYPE *pSrcValues, DEST_TYPE *pDestValues, UINT Offset, UINT Count, + SType *pType, UINT TotalUnpackedSize, const char *pFuncName) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + VERIFYPARAMETER(pDestValues); + + if (!AreBoundsValid(Offset, Count, pDestValues, pType, TotalUnpackedSize)) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + UINT i, j, delta = pType->NumericType.IsPackedArray ? 1 : SType::c_ScalarsPerRegister; + pSrcValues += Offset * delta; + for (i = 0, j = 0; j < Count; i += delta, ++ j) + { + // pDestValues[j] = (DEST_TYPE)pSrcValues[i]; + CopyScalarValue<SourceType, DestType, SRC_TYPE, FALSE>(pSrcValues[i], &pDestValues[j], "GetScalarArray"); + } + +lExit: + return hr; +} + + +////////////////////////////////////////////////////////////////////////// +// TVariable - implements type casting and member/element retrieval +////////////////////////////////////////////////////////////////////////// + +// requires that IBaseInterface contain SVariable's fields and support ID3DX11EffectVariable +template<typename IBaseInterface> +struct TVariable : public IBaseInterface +{ + STDMETHOD_(BOOL, IsValid)() { return TRUE; } + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(UINT Index) + { + SVariable *pMember; + UDataPointer dataPtr; + TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); + + if (((ID3DX11Effect*)pTopLevelEntity->pEffect)->IsOptimized()) + { + DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Cannot get members; effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + if (pType->VarType != EVT_Struct) + { + DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Variable is not a structure"); + return &g_InvalidScalarVariable; + } + + if (!GetVariableByIndexHelper<SVariable>(Index, pType->StructType.Members, pType->StructType.pMembers, + Data.pNumeric, &pMember, &dataPtr.pGeneric)) + { + return &g_InvalidScalarVariable; + } + + return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, pMember, dataPtr, FALSE, Index); + } + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(LPCSTR Name) + { + SVariable *pMember; + UDataPointer dataPtr; + UINT index; + TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); + + if (pTopLevelEntity->pEffect->IsOptimized()) + { + DPF(0, "ID3DX11EffectVariable::GetMemberByName: Cannot get members; effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + if (pType->VarType != EVT_Struct) + { + DPF(0, "ID3DX11EffectVariable::GetMemberByName: Variable is not a structure"); + return &g_InvalidScalarVariable; + } + + if (!GetVariableByNameHelper<SVariable>(Name, pType->StructType.Members, pType->StructType.pMembers, + Data.pNumeric, &pMember, &dataPtr.pGeneric, &index)) + { + return &g_InvalidScalarVariable; + + } + + return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, pMember, dataPtr, FALSE, index); + } + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(LPCSTR Semantic) + { + SVariable *pMember; + UDataPointer dataPtr; + UINT index; + TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); + + if (pTopLevelEntity->pEffect->IsOptimized()) + { + DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Cannot get members; effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + if (pType->VarType != EVT_Struct) + { + DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Variable is not a structure"); + return &g_InvalidScalarVariable; + } + + if (!GetVariableBySemanticHelper<SVariable>(Semantic, pType->StructType.Members, pType->StructType.pMembers, + Data.pNumeric, &pMember, &dataPtr.pGeneric, &index)) + { + return &g_InvalidScalarVariable; + + } + + return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, pMember, dataPtr, FALSE, index); + } + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(UINT Index) + { + LPCSTR pFuncName = "ID3DX11EffectVariable::GetElement"; + TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); + UDataPointer dataPtr; + + if (pTopLevelEntity->pEffect->IsOptimized()) + { + DPF(0, "ID3DX11EffectVariable::GetElement: Cannot get element; effect has been Optimize()'ed"); + return &g_InvalidScalarVariable; + } + + if (!IsArray()) + { + DPF(0, "%s: This interface does not refer to an array", pFuncName); + return &g_InvalidScalarVariable; + } + + if (Index >= pType->Elements) + { + DPF(0, "%s: Invalid element index (%d, total: %d)", pFuncName, Index, pType->Elements); + return &g_InvalidScalarVariable; + } + + if (pType->BelongsInConstantBuffer()) + { + dataPtr.pGeneric = Data.pNumeric + pType->Stride * Index; + } + else + { + dataPtr.pGeneric = GetBlockByIndex(pType->VarType, pType->ObjectType, Data.pGeneric, Index); + if (NULL == dataPtr.pGeneric) + { + DPF(0, "%s: Internal error", pFuncName); + return &g_InvalidScalarVariable; + } + } + + return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, (SVariable *) this, dataPtr, TRUE, Index); + } + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsScalar"; + + if (pType->VarType != EVT_Numeric || + pType->NumericType.NumericLayout != ENL_Scalar) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidScalarVariable; + } + + return (ID3DX11EffectScalarVariable *) this; + } + + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsVector"; + + if (pType->VarType != EVT_Numeric || + pType->NumericType.NumericLayout != ENL_Vector) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidVectorVariable; + } + + return (ID3DX11EffectVectorVariable *) this; + } + + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsMatrix"; + + if (pType->VarType != EVT_Numeric || + pType->NumericType.NumericLayout != ENL_Matrix) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidMatrixVariable; + } + + return (ID3DX11EffectMatrixVariable *) this; + } + + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsString"; + + if (!pType->IsObjectType(EOT_String)) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidStringVariable; + } + + return (ID3DX11EffectStringVariable *) this; + } + + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsClassInstance"; + + if (!pType->IsClassInstance() ) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidClassInstanceVariable; + } + else if( pMemberData == NULL ) + { + DPF(0, "%s: Non-global class instance variables (members of structs or classes) and class instances " + "inside tbuffers are not supported.", pFuncName ); + return &g_InvalidClassInstanceVariable; + } + + return (ID3DX11EffectClassInstanceVariable *) this; + } + + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsInterface"; + + if (!pType->IsInterface()) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidInterfaceVariable; + } + + return (ID3DX11EffectInterfaceVariable *) this; + } + + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsShaderResource"; + + if (!pType->IsShaderResource()) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidShaderResourceVariable; + } + + return (ID3DX11EffectShaderResourceVariable *) this; + } + + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsUnorderedAccessView"; + + if (!pType->IsUnorderedAccessView()) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidUnorderedAccessViewVariable; + } + + return (ID3DX11EffectUnorderedAccessViewVariable *) this; + } + + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsRenderTargetView"; + + if (!pType->IsRenderTargetView()) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidRenderTargetViewVariable; + } + + return (ID3DX11EffectRenderTargetViewVariable *) this; + } + + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencilView"; + + if (!pType->IsDepthStencilView()) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidDepthStencilViewVariable; + } + + return (ID3DX11EffectDepthStencilViewVariable *) this; + } + + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsConstantBuffer"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidConstantBuffer; + } + + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsShader"; + + if (!pType->IsShader()) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidShaderVariable; + } + + return (ID3DX11EffectShaderVariable *) this; + } + + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsBlend"; + + if (!pType->IsObjectType(EOT_Blend)) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidBlendVariable; + } + + return (ID3DX11EffectBlendVariable *) this; + } + + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencil"; + + if (!pType->IsObjectType(EOT_DepthStencil)) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidDepthStencilVariable; + } + + return (ID3DX11EffectDepthStencilVariable *) this; + } + + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsRasterizer"; + + if (!pType->IsObjectType(EOT_Rasterizer)) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidRasterizerVariable; + } + + return (ID3DX11EffectRasterizerVariable *) this; + } + + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)() + { + LPCSTR pFuncName = "ID3DX11EffectVariable::AsSampler"; + + if (!pType->IsSampler()) + { + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidSamplerVariable; + } + + return (ID3DX11EffectSamplerVariable *) this; + } + + // Numeric variables should override this + STDMETHOD(SetRawValue)(CONST void *pData, UINT Offset, UINT Count) { return ObjectSetRawValue(); } + STDMETHOD(GetRawValue)(void *pData, UINT Offset, UINT Count) { return ObjectGetRawValue(); } +}; + +////////////////////////////////////////////////////////////////////////// +// TTopLevelVariable - functionality for annotations and global variables +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TTopLevelVariable : public SVariable, public IBaseInterface +{ + // Required to create member/element variable interfaces + CEffect *pEffect; + + CEffect* GetEffect() + { + return pEffect; + } + + TTopLevelVariable() + { + pEffect = NULL; + } + + UINT GetTotalUnpackedSize() + { + return ((SType*)pType)->GetTotalUnpackedSize(FALSE); + } + + STDMETHOD_(ID3DX11EffectType*, GetType)() + { + return (ID3DX11EffectType*)(SType*)pType; + } + + TTopLevelVariable<ID3DX11EffectVariable> * GetTopLevelEntity() + { + return (TTopLevelVariable<ID3DX11EffectVariable> *)this; + } + + BOOL IsArray() + { + return (pType->Elements > 0); + } + +}; + +////////////////////////////////////////////////////////////////////////// +// TMember - functionality for structure/array members of other variables +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TMember : public SVariable, public IBaseInterface +{ + // Indicates that this is a single element of a containing array + UINT IsSingleElement : 1; + + // Required to create member/element variable interfaces + TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity; + + TMember() + { + IsSingleElement = FALSE; + pTopLevelEntity = NULL; + } + + CEffect* GetEffect() + { + return pTopLevelEntity->pEffect; + } + + UINT GetTotalUnpackedSize() + { + return pType->GetTotalUnpackedSize(IsSingleElement); + } + + STDMETHOD_(ID3DX11EffectType*, GetType)() + { + if (IsSingleElement) + { + return pTopLevelEntity->pEffect->CreatePooledSingleElementTypeInterface( pType ); + } + else + { + return (ID3DX11EffectType*) pType; + } + } + + STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) + { + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; + + VERIFYPARAMETER(pDesc != NULL); + + pDesc->Name = pName; + pDesc->Semantic = pSemantic; + pDesc->Flags = 0; + + if (pTopLevelEntity->pEffect->IsReflectionData(pTopLevelEntity)) + { + // Is part of an annotation + D3DXASSERT(pTopLevelEntity->pEffect->IsReflectionData(Data.pGeneric)); + pDesc->Annotations = 0; + pDesc->BufferOffset = 0; + pDesc->Flags |= D3DX11_EFFECT_VARIABLE_ANNOTATION; + } + else + { + // Is part of a global variable + D3DXASSERT(pTopLevelEntity->pEffect->IsRuntimeData(pTopLevelEntity)); + if (!pTopLevelEntity->pType->IsObjectType(EOT_String)) + { + // strings are funny; their data is reflection data, so ignore those + D3DXASSERT(pTopLevelEntity->pEffect->IsRuntimeData(Data.pGeneric)); + } + + pDesc->Annotations = ((TGlobalVariable<ID3DX11Effect>*)pTopLevelEntity)->AnnotationCount; + + SConstantBuffer *pCB = ((TGlobalVariable<ID3DX11Effect>*)pTopLevelEntity)->pCB; + + if (pType->BelongsInConstantBuffer()) + { + D3DXASSERT(pCB != NULL); + UINT_PTR offset = Data.pNumeric - pCB->pBackingStore; + D3DXASSERT(offset == (UINT)offset); + pDesc->BufferOffset = (UINT)offset; + D3DXASSERT(pDesc->BufferOffset >= 0 && pDesc->BufferOffset + GetTotalUnpackedSize() <= pCB->Size); + } + else + { + D3DXASSERT(pCB == NULL); + pDesc->BufferOffset = 0; + } + } + +lExit: + return hr; + } + + TTopLevelVariable<ID3DX11EffectVariable> * GetTopLevelEntity() + { + return pTopLevelEntity; + } + + BOOL IsArray() + { + return (pType->Elements > 0 && !IsSingleElement); + } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) + { return pTopLevelEntity->GetAnnotationByIndex(Index); } + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) + { return pTopLevelEntity->GetAnnotationByName(Name); } + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() + { return pTopLevelEntity->GetParentConstantBuffer(); } + + // Annotations should never be able to go down this codepath + void DirtyVariable() + { + // make sure to call the global variable's version of dirty variable + ((TGlobalVariable<ID3DX11EffectVariable>*)pTopLevelEntity)->DirtyVariable(); + } +}; + +////////////////////////////////////////////////////////////////////////// +// TAnnotation - functionality for top level annotations +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TAnnotation : public TVariable<TTopLevelVariable<IBaseInterface> > +{ + STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) + { + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; + + VERIFYPARAMETER(pDesc != NULL); + + pDesc->Name = pName; + pDesc->Semantic = pSemantic; + pDesc->Flags = D3DX11_EFFECT_VARIABLE_ANNOTATION; + pDesc->Annotations = 0; + pDesc->BufferOffset = 0; + pDesc->ExplicitBindPoint = 0; + +lExit: + return hr; + + } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) + { + LPCSTR pFuncName = "ID3DX11EffectVariable::GetAnnotationByIndex"; + DPF(0, "%s: Only variables may have annotations", pFuncName); + return &g_InvalidScalarVariable; + } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) + { + LPCSTR pFuncName = "ID3DX11EffectVariable::GetAnnotationByName"; + DPF(0, "%s: Only variables may have annotations", pFuncName); + return &g_InvalidScalarVariable; + } + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() + { return NoParentCB(); } + + void DirtyVariable() + { + D3DXASSERT(0); + } +}; + +////////////////////////////////////////////////////////////////////////// +// TGlobalVariable - functionality for top level global variables +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TGlobalVariable : public TVariable<TTopLevelVariable<IBaseInterface> > +{ + Timer LastModifiedTime; + + // if numeric, pointer to the constant buffer where this variable lives + SConstantBuffer *pCB; + + UINT AnnotationCount; + SAnnotation *pAnnotations; + + TGlobalVariable() + { + LastModifiedTime = 0; + pCB = NULL; + AnnotationCount = 0; + pAnnotations = NULL; + } + + STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) + { + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; + + VERIFYPARAMETER(pDesc != NULL); + + pDesc->Name = pName; + pDesc->Semantic = pSemantic; + pDesc->Flags = 0; + pDesc->Annotations = AnnotationCount; + + if (pType->BelongsInConstantBuffer()) + { + D3DXASSERT(pCB != NULL); + UINT_PTR offset = Data.pNumeric - pCB->pBackingStore; + D3DXASSERT(offset == (UINT)offset); + pDesc->BufferOffset = (UINT)offset; + D3DXASSERT(pDesc->BufferOffset >= 0 && pDesc->BufferOffset + GetTotalUnpackedSize() <= pCB->Size ); + } + else + { + D3DXASSERT(pCB == NULL); + pDesc->BufferOffset = 0; + } + + if (ExplicitBindPoint != -1) + { + pDesc->ExplicitBindPoint = ExplicitBindPoint; + pDesc->Flags |= D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT; + } + else + { + pDesc->ExplicitBindPoint = 0; + } + +lExit: + return hr; + } + + // these are all well defined for global vars + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) + { + return GetAnnotationByIndexHelper("ID3DX11EffectVariable", Index, AnnotationCount, pAnnotations); + } + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) + { + return GetAnnotationByNameHelper("ID3DX11EffectVariable", Name, AnnotationCount, pAnnotations); + } + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() + { + if (NULL != pCB) + { + D3DXASSERT(pType->BelongsInConstantBuffer()); + return (ID3DX11EffectConstantBuffer*)pCB; + } + else + { + D3DXASSERT(!pType->BelongsInConstantBuffer()); + return &g_InvalidConstantBuffer; + } + } + + D3DX11INLINE void DirtyVariable() + { + D3DXASSERT(NULL != pCB); + pCB->IsDirty = TRUE; + LastModifiedTime = pEffect->GetCurrentTime(); + } + +}; + +////////////////////////////////////////////////////////////////////////// +// TNumericVariable - implements raw set/get functionality +////////////////////////////////////////////////////////////////////////// + +// IMPORTANT NOTE: All of these numeric & object aspect classes MUST NOT +// add data members to the base variable classes. Otherwise type sizes +// will disagree between object & numeric variables and we cannot eaily +// create arrays of global variables using SGlobalVariable + +// Requires that IBaseInterface have SVariable's members, GetTotalUnpackedSize() and DirtyVariable() +template<typename IBaseInterface, BOOL IsAnnotation> +struct TNumericVariable : public IBaseInterface +{ + STDMETHOD(SetRawValue)(CONST void *pData, UINT ByteOffset, UINT ByteCount) + { + if (IsAnnotation) + { + return AnnotationInvalidSetCall("ID3DX11EffectVariable::SetRawValue"); + } + else + { + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectVariable::SetRawValue"; + + VERIFYPARAMETER(pData); + + if ((ByteOffset + ByteCount < ByteOffset) || + (ByteCount + (BYTE*)pData < (BYTE*)pData) || + ((ByteOffset + ByteCount) > GetTotalUnpackedSize())) + { + // overflow of some kind + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + DirtyVariable(); + memcpy(Data.pNumeric + ByteOffset, pData, ByteCount); + +lExit: + return hr; + } + } + + STDMETHOD(GetRawValue)(__out_bcount(ByteCount) void *pData, UINT ByteOffset, UINT ByteCount) + { + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectVariable::GetRawValue"; + + VERIFYPARAMETER(pData); + + if ((ByteOffset + ByteCount < ByteOffset) || + (ByteCount + (BYTE*)pData < (BYTE*)pData) || + ((ByteOffset + ByteCount) > GetTotalUnpackedSize())) + { + // overflow of some kind + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + memcpy(pData, Data.pNumeric + ByteOffset, ByteCount); + +lExit: + return hr; + } +}; + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectScalarVariable (TFloatScalarVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface, BOOL IsAnnotation> +struct TFloatScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> +{ + STDMETHOD(SetFloat)(CONST float Value); + STDMETHOD(GetFloat)(float *pValue); + + STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count); + + STDMETHOD(SetInt)(CONST int Value); + STDMETHOD(GetInt)(int *pValue); + + STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count); + STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count); + + STDMETHOD(SetBool)(CONST BOOL Value); + STDMETHOD(GetBool)(BOOL *pValue); + + STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count); + STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count); +}; + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Float, ETVT_Float, float, FALSE>(Value, Data.pNumericFloat, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) +{ + return CopyScalarValue<ETVT_Float, ETVT_Float, float, TRUE>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetFloat"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(CONST float *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Float, ETVT_Float, float, float>(pData, Data.pNumericFloat, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Float, ETVT_Float, float, float>(Data.pNumericFloat, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetInt(CONST int Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Int, ETVT_Float, int, FALSE>(Value, Data.pNumericFloat, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) +{ + return CopyScalarValue<ETVT_Float, ETVT_Int, float, TRUE>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetInt"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(CONST int *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Int, ETVT_Float, int, float>(pData, Data.pNumericFloat, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Float, ETVT_Int, float, int>(Data.pNumericFloat, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetBool(CONST BOOL Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Bool, ETVT_Float, BOOL, FALSE>(Value, Data.pNumericFloat, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetBool(BOOL *pValue) +{ + return CopyScalarValue<ETVT_Float, ETVT_Bool, float, TRUE>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetBool"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(CONST BOOL *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Bool, ETVT_Float, BOOL, float>(pData, Data.pNumericFloat, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(BOOL *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Float, ETVT_Bool, float, BOOL>(Data.pNumericFloat, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectScalarVariable (TIntScalarVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface, BOOL IsAnnotation> +struct TIntScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> +{ + STDMETHOD(SetFloat)(CONST float Value); + STDMETHOD(GetFloat)(float *pValue); + + STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count); + + STDMETHOD(SetInt)(CONST int Value); + STDMETHOD(GetInt)(int *pValue); + + STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count); + STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count); + + STDMETHOD(SetBool)(CONST BOOL Value); + STDMETHOD(GetBool)(BOOL *pValue); + + STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count); + STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count); +}; + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Float, ETVT_Int, float, FALSE>(Value, Data.pNumericInt, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) +{ + return CopyScalarValue<ETVT_Int, ETVT_Float, int, TRUE>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetFloat"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(CONST float *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Float, ETVT_Int, float, int>(pData, Data.pNumericInt, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Int, ETVT_Float, int, float>(Data.pNumericInt, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetInt(CONST int Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Int, ETVT_Int, int, FALSE>(Value, Data.pNumericInt, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) +{ + return CopyScalarValue<ETVT_Int, ETVT_Int, int, TRUE>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetInt"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(CONST int *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Int, ETVT_Int, int, int>(pData, Data.pNumericInt, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Int, ETVT_Int, int, int>(Data.pNumericInt, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetBool(CONST BOOL Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Bool, ETVT_Int, BOOL, FALSE>(Value, Data.pNumericInt, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetBool(BOOL *pValue) +{ + return CopyScalarValue<ETVT_Int, ETVT_Bool, int, TRUE>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetBool"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(CONST BOOL *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Bool, ETVT_Int, BOOL, int>(pData, Data.pNumericInt, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(BOOL *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Int, ETVT_Bool, int, BOOL>(Data.pNumericInt, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectScalarVariable (TBoolScalarVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface, BOOL IsAnnotation> +struct TBoolScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> +{ + STDMETHOD(SetFloat)(CONST float Value); + STDMETHOD(GetFloat)(float *pValue); + + STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count); + + STDMETHOD(SetInt)(CONST int Value); + STDMETHOD(GetInt)(int *pValue); + + STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count); + STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count); + + STDMETHOD(SetBool)(CONST BOOL Value); + STDMETHOD(GetBool)(BOOL *pValue); + + STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count); + STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count); +}; + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Float, ETVT_Bool, float, FALSE>(Value, Data.pNumericBool, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) +{ + return CopyScalarValue<ETVT_Bool, ETVT_Float, BOOL, TRUE>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetFloat"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(CONST float *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Float, ETVT_Bool, float, BOOL>(pData, Data.pNumericBool, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Bool, ETVT_Float, BOOL, float>(Data.pNumericBool, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetInt(CONST int Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Int, ETVT_Bool, int, FALSE>(Value, Data.pNumericBool, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) +{ + return CopyScalarValue<ETVT_Bool, ETVT_Int, BOOL, TRUE>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetInt"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(CONST int *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Int, ETVT_Bool, int, BOOL>(pData, Data.pNumericBool, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Bool, ETVT_Int, BOOL, int>(Data.pNumericBool, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetBool(CONST BOOL Value) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return CopyScalarValue<ETVT_Bool, ETVT_Bool, BOOL, FALSE>(Value, Data.pNumericBool, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetBool(BOOL *pValue) +{ + return CopyScalarValue<ETVT_Bool, ETVT_Bool, BOOL, TRUE>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetBool"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(CONST BOOL *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return SetScalarArray<ETVT_Bool, ETVT_Bool, BOOL, BOOL>(pData, Data.pNumericBool, Offset, Count, + pType, GetTotalUnpackedSize(), pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(BOOL *pData, UINT Offset, UINT Count) +{ + return GetScalarArray<ETVT_Bool, ETVT_Bool, BOOL, BOOL>(Data.pNumericBool, pData, Offset, Count, + pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectVectorVariable (TVectorVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType > +struct TVectorVariable : public TNumericVariable<IBaseInterface, IsAnnotation> +{ + STDMETHOD(SetBoolVector) (CONST BOOL *pData); + STDMETHOD(SetIntVector) (CONST int *pData); + STDMETHOD(SetFloatVector)(CONST float *pData); + + STDMETHOD(GetBoolVector) (BOOL *pData); + STDMETHOD(GetIntVector) (int *pData); + STDMETHOD(GetFloatVector)(float *pData); + + + STDMETHOD(SetBoolVectorArray) (CONST BOOL *pData, UINT Offset, UINT Count); + STDMETHOD(SetIntVectorArray) (CONST int *pData, UINT Offset, UINT Count); + STDMETHOD(SetFloatVectorArray)(CONST float *pData, UINT Offset, UINT Count); + + STDMETHOD(GetBoolVectorArray) (BOOL *pData, UINT Offset, UINT Count); + STDMETHOD(GetIntVectorArray) (int *pData, UINT Offset, UINT Count); + STDMETHOD(GetFloatVectorArray)(float *pData, UINT Offset, UINT Count); +}; + +// Note that branches in this code is based on template parameters and will be compiled out +template <ETemplateVarType DestType, ETemplateVarType SourceType> +void __forceinline CopyDataWithTypeConversion(__out_bcount(vecCount * dstVecSize * sizeof(UINT)) void *pDest, CONST void *pSource, UINT dstVecSize, UINT srcVecSize, UINT elementCount, UINT vecCount) +{ + UINT i, j; + + switch (SourceType) + { + case ETVT_Bool: + switch (DestType) + { + case ETVT_Bool: + for (j=0; j<vecCount; j++) + { + dwordMemcpy(pDest, pSource, elementCount * SType::c_ScalarSize); + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + case ETVT_Int: + for (j=0; j<vecCount; j++) + { + for (i=0; i<elementCount; i++) + ((int*)pDest)[i] = ((BOOL*)pSource)[i] ? -1 : 0; + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + case ETVT_Float: + for (j=0; j<vecCount; j++) + { + for (i=0; i<elementCount; i++) + ((float*)pDest)[i] = ((BOOL*)pSource)[i] ? -1.0f : 0.0f; + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + default: + D3DXASSERT(0); + } + break; + + + case ETVT_Int: + switch (DestType) + { + case ETVT_Bool: + for (j=0; j<vecCount; j++) + { + for (i=0; i<elementCount; i++) + ((int*)pDest)[i] = (((int*)pSource)[i] != 0) ? -1 : 0; + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + case ETVT_Int: + for (j=0; j<vecCount; j++) + { + dwordMemcpy(pDest, pSource, elementCount * SType::c_ScalarSize); + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + case ETVT_Float: + for (j=0; j<vecCount; j++) + { + for (i=0; i<elementCount; i++) + ((float*)pDest)[i] = (float)(((int*)pSource)[i]); + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + default: + D3DXASSERT(0); + } + break; + + case ETVT_Float: + switch (DestType) + { + case ETVT_Bool: + for (j=0; j<vecCount; j++) + { + for (i=0; i<elementCount; i++) + ((int*)pDest)[i] = (((float*)pSource)[i] != 0.0f) ? -1 : 0; + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + case ETVT_Int: + for (j=0; j<vecCount; j++) + { + for (i=0; i<elementCount; i++) + ((int*)pDest)[i] = (int)((float*)pSource)[i]; + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + case ETVT_Float: + for (i=0; i<vecCount; i++) + { + dwordMemcpy( pDest, pSource, elementCount * SType::c_ScalarSize); + + pDest = ((float*) pDest) + dstVecSize; + pSource = ((float*) pSource) + srcVecSize; + } + break; + + default: + D3DXASSERT(0); + } + break; + + default: + D3DXASSERT(0); + } +} + +// Float Vector + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetFloatVector(CONST float *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + CopyDataWithTypeConversion<BaseType, ETVT_Float>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetFloatVector(float *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + CopyDataWithTypeConversion<ETVT_Float, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); + +lExit: + return hr; +} + +// Int Vector + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetIntVector(CONST int *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetIntVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + CopyDataWithTypeConversion<BaseType, ETVT_Int>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetIntVector(int *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetIntVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + CopyDataWithTypeConversion<ETVT_Int, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); + +lExit: + return hr; +} + +// Bool Vector + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetBoolVector(CONST BOOL *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetBoolVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + CopyDataWithTypeConversion<BaseType, ETVT_Bool>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetBoolVector(BOOL *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetBoolVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + CopyDataWithTypeConversion<ETVT_Bool, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); + +lExit: + return hr; +} + +// Vector Arrays ///////////////////////////////////////////////////////// + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetFloatVectorArray(CONST float *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + // ensure we don't write over the padding at the end of the vector array + CopyDataWithTypeConversion<BaseType, ETVT_Float>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetFloatVectorArray(float *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + // ensure we don't read past the end of the vector array + CopyDataWithTypeConversion<ETVT_Float, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); + +lExit: + return hr; +} + +// int + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetIntVectorArray(CONST int *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetIntVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + // ensure we don't write over the padding at the end of the vector array + CopyDataWithTypeConversion<BaseType, ETVT_Int>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetIntVectorArray(int *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetIntVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + // ensure we don't read past the end of the vector array + CopyDataWithTypeConversion<ETVT_Int, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); + +lExit: + return hr; +} + +// bool + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetBoolVectorArray(CONST BOOL *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetBoolVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + // ensure we don't write over the padding at the end of the vector array + CopyDataWithTypeConversion<BaseType, ETVT_Bool>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> +HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetBoolVectorArray(BOOL *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetBoolVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + // ensure we don't read past the end of the vector array + CopyDataWithTypeConversion<ETVT_Bool, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectVector4Variable (TVectorVariable implementation) [OPTIMIZED] +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TVector4Variable : public TVectorVariable<IBaseInterface, FALSE, ETVT_Float> +{ + STDMETHOD(SetFloatVector)(CONST float *pData); + STDMETHOD(GetFloatVector)(float *pData); + + STDMETHOD(SetFloatVectorArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetFloatVectorArray)(float *pData, UINT Offset, UINT Count); +}; + +template<typename IBaseInterface> +HRESULT TVector4Variable<IBaseInterface>::SetFloatVector(CONST float *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + DirtyVariable(); + Data.pVector[0] = ((CEffectVector4*) pData)[0]; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TVector4Variable<IBaseInterface>::GetFloatVector(float *pData) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVector"; + +#ifdef _DEBUG + VERIFYPARAMETER(pData); +#endif + + dwordMemcpy(pData, Data.pVector, pType->NumericType.Columns * SType::c_ScalarSize); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TVector4Variable<IBaseInterface>::SetFloatVectorArray(CONST float *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + DirtyVariable(); + // ensure we don't write over the padding at the end of the vector array + dwordMemcpy(Data.pVector + Offset, pData, min((Offset + Count) * sizeof(CEffectVector4), pType->TotalSize)); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TVector4Variable<IBaseInterface>::GetFloatVectorArray(float *pData, UINT Offset, UINT Count) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVectorArray"; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + // ensure we don't read past the end of the vector array + dwordMemcpy(pData, Data.pVector + Offset, min((Offset + Count) * sizeof(CEffectVector4), pType->TotalSize)); + +lExit: + return hr; +} + + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectMatrixVariable (TMatrixVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface, BOOL IsAnnotation> +struct TMatrixVariable : public TNumericVariable<IBaseInterface, IsAnnotation> +{ + STDMETHOD(SetMatrix)(CONST float *pData); + STDMETHOD(GetMatrix)(float *pData); + + STDMETHOD(SetMatrixArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetMatrixArray)(float *pData, UINT Offset, UINT Count); + + STDMETHOD(SetMatrixPointerArray)(CONST float **ppData, UINT Offset, UINT Count); + STDMETHOD(GetMatrixPointerArray)(float **ppData, UINT Offset, UINT Count); + + STDMETHOD(SetMatrixTranspose)(CONST float *pData); + STDMETHOD(GetMatrixTranspose)(float *pData); + + STDMETHOD(SetMatrixTransposeArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetMatrixTransposeArray)(float *pData, UINT Offset, UINT Count); + + STDMETHOD(SetMatrixTransposePointerArray)(CONST float **ppData, UINT Offset, UINT Count); + STDMETHOD(GetMatrixTransposePointerArray)(float **ppData, UINT Offset, UINT Count); +}; + +template<BOOL Transpose> +static void SetMatrixTransposeHelper(SType *pType, __out_bcount(64) BYTE *pDestData, CONST float* pMatrix) +{ + UINT i, j; + UINT registers, entries; + + if (Transpose) + { + // row major + registers = pType->NumericType.Rows; + entries = pType->NumericType.Columns; + } + else + { + // column major + registers = pType->NumericType.Columns; + entries = pType->NumericType.Rows; + } + __analysis_assume( registers <= 4 ); + __analysis_assume( entries <= 4 ); + + for (i = 0; i < registers; ++ i) + { + for (j = 0; j < entries; ++ j) + { +#pragma prefast(suppress:__WARNING_UNRELATED_LOOP_TERMINATION, "regs / entries <= 4") + ((float*)pDestData)[j] = ((float*)pMatrix)[j * 4 + i]; + } + pDestData += SType::c_RegisterSize; + } +} + +template<BOOL Transpose> +static void GetMatrixTransposeHelper(SType *pType, __in_bcount(64) BYTE *pSrcData, __out_ecount(16) float* pMatrix) +{ + UINT i, j; + UINT registers, entries; + + if (Transpose) + { + // row major + registers = pType->NumericType.Rows; + entries = pType->NumericType.Columns; + } + else + { + // column major + registers = pType->NumericType.Columns; + entries = pType->NumericType.Rows; + } + __analysis_assume( registers <= 4 ); + __analysis_assume( entries <= 4 ); + + for (i = 0; i < registers; ++ i) + { + for (j = 0; j < entries; ++ j) + { + ((float*)pMatrix)[j * 4 + i] = ((float*)pSrcData)[j]; + } + pSrcData += SType::c_RegisterSize; + } +} + +template<BOOL Transpose, BOOL IsSetting, BOOL ExtraIndirection> +HRESULT DoMatrixArrayInternal(SType *pType, UINT TotalUnpackedSize, BYTE *pEffectData, void *pMatrixData, UINT Offset, UINT Count, LPCSTR pFuncName) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pMatrixData, pType, TotalUnpackedSize)) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } +#endif + + UINT i; + + if ((pType->NumericType.IsColumnMajor && Transpose) || (!pType->NumericType.IsColumnMajor && !Transpose)) + { + // fast path + UINT dataSize; + if (Transpose) + { + dataSize = ((pType->NumericType.Columns - 1) * 4 + pType->NumericType.Rows) * SType::c_ScalarSize; + } + else + { + dataSize = ((pType->NumericType.Rows - 1) * 4 + pType->NumericType.Columns) * SType::c_ScalarSize; + } + + for (i = 0; i < Count; ++ i) + { + CEffectMatrix *pMatrix; + if (ExtraIndirection) + { + pMatrix = ((CEffectMatrix **)pMatrixData)[i]; + if (!pMatrix) + { + continue; + } + } + else + { + pMatrix = ((CEffectMatrix *)pMatrixData) + i; + } + + if (IsSetting) + { + dwordMemcpy(pEffectData + pType->Stride * (i + Offset), pMatrix, dataSize); + } + else + { + dwordMemcpy(pMatrix, pEffectData + pType->Stride * (i + Offset), dataSize); + } + } + } + else + { + // slow path + for (i = 0; i < Count; ++ i) + { + CEffectMatrix *pMatrix; + if (ExtraIndirection) + { + pMatrix = ((CEffectMatrix **)pMatrixData)[i]; + if (!pMatrix) + { + continue; + } + } + else + { + pMatrix = ((CEffectMatrix *)pMatrixData) + i; + } + + if (IsSetting) + { + SetMatrixTransposeHelper<Transpose>(pType, pEffectData + pType->Stride * (i + Offset), (float*) pMatrix); + } + else + { + GetMatrixTransposeHelper<Transpose>(pType, pEffectData + pType->Stride * (i + Offset), (float*) pMatrix); + } + } + } + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrix(CONST float *pData) +{ + LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrix"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return DoMatrixArrayInternal<FALSE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, const_cast<float*>(pData), 0, 1, pFuncName); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrix(float *pData) +{ + return DoMatrixArrayInternal<FALSE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, pData, 0, 1, "ID3DX11EffectMatrixVariable::GetMatrix"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixArray(CONST float *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return DoMatrixArrayInternal<FALSE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, const_cast<float*>(pData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixArray(float *pData, UINT Offset, UINT Count) +{ + return DoMatrixArrayInternal<FALSE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, pData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixPointerArray(CONST float **ppData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixPointerArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return DoMatrixArrayInternal<FALSE, TRUE, TRUE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, const_cast<float**>(ppData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixPointerArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixPointerArray(float **ppData, UINT Offset, UINT Count) +{ + return DoMatrixArrayInternal<FALSE, FALSE, TRUE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, ppData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixPointerArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTranspose(CONST float *pData) +{ + LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTranspose"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return DoMatrixArrayInternal<TRUE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, const_cast<float*>(pData), 0, 1, "ID3DX11EffectMatrixVariable::SetMatrixTranspose"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTranspose(float *pData) +{ + return DoMatrixArrayInternal<TRUE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, pData, 0, 1, "ID3DX11EffectMatrixVariable::GetMatrixTranspose"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTransposeArray(CONST float *pData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return DoMatrixArrayInternal<TRUE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, const_cast<float*>(pData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTransposeArray(float *pData, UINT Offset, UINT Count) +{ + return DoMatrixArrayInternal<TRUE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, pData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixTransposeArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTransposePointerArray(CONST float **ppData, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTransposePointerArray"; + if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); + DirtyVariable(); + return DoMatrixArrayInternal<TRUE, TRUE, TRUE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, const_cast<float**>(ppData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixTransposePointerArray"); +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTransposePointerArray(float **ppData, UINT Offset, UINT Count) +{ + return DoMatrixArrayInternal<TRUE, FALSE, TRUE>(pType, GetTotalUnpackedSize(), + Data.pNumeric, ppData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixTransposePointerArray"); +} + +// Optimize commonly used fast paths +// (non-annotations only!) +template<typename IBaseInterface, BOOL IsColumnMajor> +struct TMatrix4x4Variable : public TMatrixVariable<IBaseInterface, FALSE> +{ + STDMETHOD(SetMatrix)(CONST float *pData); + STDMETHOD(GetMatrix)(float *pData); + + STDMETHOD(SetMatrixArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetMatrixArray)(float *pData, UINT Offset, UINT Count); + + STDMETHOD(SetMatrixTranspose)(CONST float *pData); + STDMETHOD(GetMatrixTranspose)(float *pData); + + STDMETHOD(SetMatrixTransposeArray)(CONST float *pData, UINT Offset, UINT Count); + STDMETHOD(GetMatrixTransposeArray)(float *pData, UINT Offset, UINT Count); +}; + +D3DX11INLINE static void Matrix4x4TransposeHelper(CONST void *pSrc, void *pDst) +{ + BYTE *pDestData = (BYTE*)pDst; + UINT *pMatrix = (UINT*)pSrc; + + ((UINT*)pDestData)[0 * 4 + 0] = pMatrix[0 * 4 + 0]; + ((UINT*)pDestData)[0 * 4 + 1] = pMatrix[1 * 4 + 0]; + ((UINT*)pDestData)[0 * 4 + 2] = pMatrix[2 * 4 + 0]; + ((UINT*)pDestData)[0 * 4 + 3] = pMatrix[3 * 4 + 0]; + + ((UINT*)pDestData)[1 * 4 + 0] = pMatrix[0 * 4 + 1]; + ((UINT*)pDestData)[1 * 4 + 1] = pMatrix[1 * 4 + 1]; + ((UINT*)pDestData)[1 * 4 + 2] = pMatrix[2 * 4 + 1]; + ((UINT*)pDestData)[1 * 4 + 3] = pMatrix[3 * 4 + 1]; + + ((UINT*)pDestData)[2 * 4 + 0] = pMatrix[0 * 4 + 2]; + ((UINT*)pDestData)[2 * 4 + 1] = pMatrix[1 * 4 + 2]; + ((UINT*)pDestData)[2 * 4 + 2] = pMatrix[2 * 4 + 2]; + ((UINT*)pDestData)[2 * 4 + 3] = pMatrix[3 * 4 + 2]; + + ((UINT*)pDestData)[3 * 4 + 0] = pMatrix[0 * 4 + 3]; + ((UINT*)pDestData)[3 * 4 + 1] = pMatrix[1 * 4 + 3]; + ((UINT*)pDestData)[3 * 4 + 2] = pMatrix[2 * 4 + 3]; + ((UINT*)pDestData)[3 * 4 + 3] = pMatrix[3 * 4 + 3]; +} + +D3DX11INLINE static void Matrix4x4Copy(CONST void *pSrc, void *pDst) +{ +#if 1 + // In tests, this path ended up generating faster code both on x86 and x64 + // T1 - Matrix4x4Copy - this path + // T2 - Matrix4x4Transpose + // T1: 1.88 T2: 1.92 - with 32 bit copies + // T1: 1.85 T2: 1.80 - with 64 bit copies + + UINT64 *pDestData = (UINT64*)pDst; + UINT64 *pMatrix = (UINT64*)pSrc; + + pDestData[0 * 4 + 0] = pMatrix[0 * 4 + 0]; + pDestData[0 * 4 + 1] = pMatrix[0 * 4 + 1]; + pDestData[0 * 4 + 2] = pMatrix[0 * 4 + 2]; + pDestData[0 * 4 + 3] = pMatrix[0 * 4 + 3]; + + pDestData[1 * 4 + 0] = pMatrix[1 * 4 + 0]; + pDestData[1 * 4 + 1] = pMatrix[1 * 4 + 1]; + pDestData[1 * 4 + 2] = pMatrix[1 * 4 + 2]; + pDestData[1 * 4 + 3] = pMatrix[1 * 4 + 3]; +#else + UINT *pDestData = (UINT*)pDst; + UINT *pMatrix = (UINT*)pSrc; + + pDestData[0 * 4 + 0] = pMatrix[0 * 4 + 0]; + pDestData[0 * 4 + 1] = pMatrix[0 * 4 + 1]; + pDestData[0 * 4 + 2] = pMatrix[0 * 4 + 2]; + pDestData[0 * 4 + 3] = pMatrix[0 * 4 + 3]; + + pDestData[1 * 4 + 0] = pMatrix[1 * 4 + 0]; + pDestData[1 * 4 + 1] = pMatrix[1 * 4 + 1]; + pDestData[1 * 4 + 2] = pMatrix[1 * 4 + 2]; + pDestData[1 * 4 + 3] = pMatrix[1 * 4 + 3]; + + pDestData[2 * 4 + 0] = pMatrix[2 * 4 + 0]; + pDestData[2 * 4 + 1] = pMatrix[2 * 4 + 1]; + pDestData[2 * 4 + 2] = pMatrix[2 * 4 + 2]; + pDestData[2 * 4 + 3] = pMatrix[2 * 4 + 3]; + + pDestData[3 * 4 + 0] = pMatrix[3 * 4 + 0]; + pDestData[3 * 4 + 1] = pMatrix[3 * 4 + 1]; + pDestData[3 * 4 + 2] = pMatrix[3 * 4 + 2]; + pDestData[3 * 4 + 3] = pMatrix[3 * 4 + 3]; +#endif +} + + +// Note that branches in this code is based on template parameters and will be compiled out +template<BOOL IsColumnMajor, BOOL Transpose, BOOL IsSetting> +D3DX11INLINE HRESULT DoMatrix4x4ArrayInternal(BYTE *pEffectData, void *pMatrixData, UINT Offset, UINT Count + +#ifdef _DEBUG + , SType *pType, UINT TotalUnpackedSize, LPCSTR pFuncName) +#else + ) +#endif +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + if (!AreBoundsValid(Offset, Count, pMatrixData, pType, TotalUnpackedSize)) + { + DPF(0, "%s: Invalid range specified", pFuncName); + VH(E_INVALIDARG); + } + + D3DXASSERT(pType->NumericType.IsColumnMajor == IsColumnMajor && pType->Stride == (4 * SType::c_RegisterSize)); +#endif + + UINT i; + + if ((IsColumnMajor && Transpose) || (!IsColumnMajor && !Transpose)) + { + // fast path + for (i = 0; i < Count; ++ i) + { + CEffectMatrix *pMatrix = ((CEffectMatrix *)pMatrixData) + i; + + if (IsSetting) + { + Matrix4x4Copy(pMatrix, pEffectData + 4 * SType::c_RegisterSize * (i + Offset)); + } + else + { + Matrix4x4Copy(pEffectData + 4 * SType::c_RegisterSize * (i + Offset), pMatrix); + } + } + } + else + { + // slow path + for (i = 0; i < Count; ++ i) + { + CEffectMatrix *pMatrix = ((CEffectMatrix *)pMatrixData) + i; + + if (IsSetting) + { + Matrix4x4TransposeHelper((float*) pMatrix, pEffectData + 4 * SType::c_RegisterSize * (i + Offset)); + } + else + { + Matrix4x4TransposeHelper(pEffectData + 4 * SType::c_RegisterSize * (i + Offset), (float*) pMatrix); + } + } + } + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrix(CONST float *pData) +{ + DirtyVariable(); + return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, TRUE>(Data.pNumeric, const_cast<float*>(pData), 0, 1 +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrix"); +#else + ); +#endif +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrix(float *pData) +{ + return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, FALSE>(Data.pNumeric, pData, 0, 1 +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrix"); +#else + ); +#endif +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixArray(CONST float *pData, UINT Offset, UINT Count) +{ + DirtyVariable(); + return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, TRUE>(Data.pNumeric, const_cast<float*>(pData), Offset, Count +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixArray"); +#else + ); +#endif +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixArray(float *pData, UINT Offset, UINT Count) +{ + return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, FALSE>(Data.pNumeric, pData, Offset, Count +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixArray"); +#else + ); +#endif +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixTranspose(CONST float *pData) +{ + DirtyVariable(); + return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, TRUE>(Data.pNumeric, const_cast<float*>(pData), 0, 1 +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixTranspose"); +#else + ); +#endif +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixTranspose(float *pData) +{ + return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, FALSE>(Data.pNumeric, pData, 0, 1 +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixTranspose"); +#else + ); +#endif +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixTransposeArray(CONST float *pData, UINT Offset, UINT Count) +{ + DirtyVariable(); + return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, TRUE>(Data.pNumeric, const_cast<float*>(pData), Offset, Count +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"); +#else + ); +#endif +} + +template<typename IBaseInterface, BOOL IsColumnMajor> +HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixTransposeArray(float *pData, UINT Offset, UINT Count) +{ + return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, FALSE>(Data.pNumeric, pData, Offset, Count +#ifdef _DEBUG + , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixTransposeArray"); +#else + ); +#endif +} + +#ifdef _DEBUG + +// Useful object macro to check bounds and parameters +#define CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, Pointer) \ + HRESULT hr = S_OK; \ + VERIFYPARAMETER(Pointer) \ + UINT elements = IsArray() ? pType->Elements : 1; \ + \ + if ((Offset + Count < Offset) || (elements < Offset + Count)) \ + { \ + DPF(0, "%s: Invalid range specified", pFuncName); \ + VH(E_INVALIDARG); \ + } \ + +#define CHECK_OBJECT_SCALAR_BOUNDS(Index, Pointer) \ + HRESULT hr = S_OK; \ + VERIFYPARAMETER(Pointer) \ + UINT elements = IsArray() ? pType->Elements : 1; \ + \ + if (Index >= elements) \ + { \ + DPF(0, "%s: Invalid index specified", pFuncName); \ + VH(E_INVALIDARG); \ + } \ + +#define CHECK_SCALAR_BOUNDS(Index) \ + HRESULT hr = S_OK; \ + UINT elements = IsArray() ? pType->Elements : 1; \ + \ + if (Index >= elements) \ +{ \ + DPF(0, "%s: Invalid index specified", pFuncName); \ + VH(E_INVALIDARG); \ +} \ + +#else // _DEBUG + +#define CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, Pointer) \ + HRESULT hr = S_OK; \ + +#define CHECK_OBJECT_SCALAR_BOUNDS(Index, Pointer) \ + HRESULT hr = S_OK; \ + +#define CHECK_SCALAR_BOUNDS(Index) \ + HRESULT hr = S_OK; \ + +#endif // _DEBUG + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectStringVariable (TStringVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface, BOOL IsAnnotation> +struct TStringVariable : public IBaseInterface +{ + STDMETHOD(GetString)(LPCSTR *ppString); + STDMETHOD(GetStringArray)( __out_ecount(Count) LPCSTR *ppStrings, UINT Offset, UINT Count ); +}; + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TStringVariable<IBaseInterface, IsAnnotation>::GetString(LPCSTR *ppString) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectStringVariable::GetString"; + + VERIFYPARAMETER(ppString); + + if (GetTopLevelEntity()->pEffect->IsOptimized()) + { + DPF(0, "%s: Effect has been Optimize()'ed; all string/reflection data has been deleted", pFuncName); + return D3DERR_INVALIDCALL; + } + + D3DXASSERT(NULL != Data.pString); + + *ppString = Data.pString->pString; + +lExit: + return hr; +} + +template<typename IBaseInterface, BOOL IsAnnotation> +HRESULT TStringVariable<IBaseInterface, IsAnnotation>::GetStringArray( __out_ecount(Count) LPCSTR *ppStrings, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectStringVariable::GetStringArray"; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppStrings); + + if (GetTopLevelEntity()->pEffect->IsOptimized()) + { + DPF(0, "%s: Effect has been Optimize()'ed; all string/reflection data has been deleted", pFuncName); + return D3DERR_INVALIDCALL; + } + + D3DXASSERT(NULL != Data.pString); + + UINT i; + for (i = 0; i < Count; ++ i) + { + ppStrings[i] = (Data.pString + Offset + i)->pString; + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectClassInstanceVariable (TClassInstanceVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TClassInstanceVariable : public IBaseInterface +{ + STDMETHOD(GetClassInstance)(ID3D11ClassInstance **ppClassInstance); +}; + +template<typename IBaseClassInstance> +HRESULT TClassInstanceVariable<IBaseClassInstance>::GetClassInstance(ID3D11ClassInstance** ppClassInstance) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectClassInstanceVariable::GetClassInstance"; + + D3DXASSERT( pMemberData != NULL ); + *ppClassInstance = pMemberData->Data.pD3DClassInstance; + SAFE_ADDREF(*ppClassInstance); + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectInterfaceeVariable (TInterfaceVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TInterfaceVariable : public IBaseInterface +{ + STDMETHOD(SetClassInstance)(ID3DX11EffectClassInstanceVariable *pEffectClassInstance); + STDMETHOD(GetClassInstance)(ID3DX11EffectClassInstanceVariable **ppEffectClassInstance); +}; + +template<typename IBaseInterface> +HRESULT TInterfaceVariable<IBaseInterface>::SetClassInstance(ID3DX11EffectClassInstanceVariable *pEffectClassInstance) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectInterfaceVariable::SetClassInstance"; + + // Note that we don't check if the types are compatible. The debug layer will complain if it is. + // IsValid() will not catch type mismatches. + SClassInstanceGlobalVariable* pCI = (SClassInstanceGlobalVariable*)pEffectClassInstance; + Data.pInterface->pClassInstance = pCI; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TInterfaceVariable<IBaseInterface>::GetClassInstance(ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) +{ + HRESULT hr = S_OK; + LPCSTR pFuncName = "ID3DX11EffectInterfaceVariable::GetClassInstance"; + +#ifdef _DEBUG + VERIFYPARAMETER(ppEffectClassInstance); +#endif + + *ppEffectClassInstance = Data.pInterface->pClassInstance; + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderResourceVariable (TShaderResourceVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TShaderResourceVariable : public IBaseInterface +{ + STDMETHOD(SetResource)(ID3D11ShaderResourceView *pResource); + STDMETHOD(GetResource)(ID3D11ShaderResourceView **ppResource); + + STDMETHOD(SetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count); + STDMETHOD(GetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count); +}; + +static LPCSTR GetTextureTypeNameFromEnum(EObjectType ObjectType) +{ + switch (ObjectType) + { + case EOT_Buffer: + return "Buffer"; + case EOT_Texture: + return "texture"; + case EOT_Texture1D: + case EOT_Texture1DArray: + return "Texture1D"; + case EOT_Texture2DMS: + case EOT_Texture2DMSArray: + return "Texture2DMS"; + case EOT_Texture2D: + case EOT_Texture2DArray: + return "Texture2D"; + case EOT_Texture3D: + return "Texture3D"; + case EOT_TextureCube: + return "TextureCube"; + case EOT_TextureCubeArray: + return "TextureCubeArray"; + case EOT_RWTexture1D: + case EOT_RWTexture1DArray: + return "RWTexture1D"; + case EOT_RWTexture2D: + case EOT_RWTexture2DArray: + return "RWTexture2D"; + case EOT_RWTexture3D: + return "RWTexture3D"; + case EOT_RWBuffer: + return "RWBuffer"; + case EOT_ByteAddressBuffer: + return "ByteAddressBuffer"; + case EOT_RWByteAddressBuffer: + return "RWByteAddressBuffer"; + case EOT_StructuredBuffer: + return "StructuredBuffe"; + case EOT_RWStructuredBuffer: + return "RWStructuredBuffer"; + case EOT_RWStructuredBufferAlloc: + return "RWStructuredBufferAlloc"; + case EOT_RWStructuredBufferConsume: + return "RWStructuredBufferConsume"; + case EOT_AppendStructuredBuffer: + return "AppendStructuredBuffer"; + case EOT_ConsumeStructuredBuffer: + return "ConsumeStructuredBuffer"; + } + return "<unknown texture format>"; +} + +static LPCSTR GetResourceDimensionNameFromEnum(D3D11_RESOURCE_DIMENSION ResourceDimension) +{ + switch (ResourceDimension) + { + case D3D11_RESOURCE_DIMENSION_BUFFER: + return "Buffer"; + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + return "Texture1D"; + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: + return "Texture2D"; + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: + return "Texture3D"; + } + return "<unknown texture format>"; +} + +static LPCSTR GetSRVDimensionNameFromEnum(D3D11_SRV_DIMENSION ViewDimension) +{ + switch (ViewDimension) + { + case D3D11_SRV_DIMENSION_BUFFER: + case D3D11_SRV_DIMENSION_BUFFEREX: + return "Buffer"; + case D3D11_SRV_DIMENSION_TEXTURE1D: + return "Texture1D"; + case D3D11_SRV_DIMENSION_TEXTURE1DARRAY: + return "Texture1DArray"; + case D3D11_SRV_DIMENSION_TEXTURE2D: + return "Texture2D"; + case D3D11_SRV_DIMENSION_TEXTURE2DARRAY: + return "Texture2DArray"; + case D3D11_SRV_DIMENSION_TEXTURE2DMS: + return "Texture2DMS"; + case D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: + return "Texture2DMSArray"; + case D3D11_SRV_DIMENSION_TEXTURE3D: + return "Texture3D"; + case D3D11_SRV_DIMENSION_TEXTURECUBE: + return "TextureCube"; + } + return "<unknown texture format>"; +} + +static LPCSTR GetUAVDimensionNameFromEnum(D3D11_UAV_DIMENSION ViewDimension) +{ + switch (ViewDimension) + { + case D3D11_UAV_DIMENSION_BUFFER: + return "Buffer"; + case D3D11_UAV_DIMENSION_TEXTURE1D: + return "RWTexture1D"; + case D3D11_UAV_DIMENSION_TEXTURE1DARRAY: + return "RWTexture1DArray"; + case D3D11_UAV_DIMENSION_TEXTURE2D: + return "RWTexture2D"; + case D3D11_UAV_DIMENSION_TEXTURE2DARRAY: + return "RWTexture2DArray"; + case D3D11_UAV_DIMENSION_TEXTURE3D: + return "RWTexture3D"; + } + return "<unknown texture format>"; +} + +static LPCSTR GetRTVDimensionNameFromEnum(D3D11_RTV_DIMENSION ViewDimension) +{ + switch (ViewDimension) + { + case D3D11_RTV_DIMENSION_BUFFER: + return "Buffer"; + case D3D11_RTV_DIMENSION_TEXTURE1D: + return "Texture1D"; + case D3D11_RTV_DIMENSION_TEXTURE1DARRAY: + return "Texture1DArray"; + case D3D11_RTV_DIMENSION_TEXTURE2D: + return "Texture2D"; + case D3D11_RTV_DIMENSION_TEXTURE2DARRAY: + return "Texture2DArray"; + case D3D11_RTV_DIMENSION_TEXTURE2DMS: + return "Texture2DMS"; + case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY: + return "Texture2DMSArray"; + case D3D11_RTV_DIMENSION_TEXTURE3D: + return "Texture3D"; + } + return "<unknown texture format>"; +} + +static LPCSTR GetDSVDimensionNameFromEnum(D3D11_DSV_DIMENSION ViewDimension) +{ + switch (ViewDimension) + { + case D3D11_DSV_DIMENSION_TEXTURE1D: + return "Texture1D"; + case D3D11_DSV_DIMENSION_TEXTURE1DARRAY: + return "Texture1DArray"; + case D3D11_DSV_DIMENSION_TEXTURE2D: + return "Texture2D"; + case D3D11_DSV_DIMENSION_TEXTURE2DARRAY: + return "Texture2DArray"; + case D3D11_DSV_DIMENSION_TEXTURE2DMS: + return "Texture2DMS"; + case D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY: + return "Texture2DMSArray"; + } + return "<unknown texture format>"; +} + +static HRESULT ValidateTextureType(ID3D11ShaderResourceView *pView, EObjectType ObjectType, LPCSTR pFuncName) +{ + if (NULL != pView) + { + D3D11_SHADER_RESOURCE_VIEW_DESC desc; + pView->GetDesc(&desc); + switch (ObjectType) + { + case EOT_Texture: + if (desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFER && desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFEREX) + return S_OK; + break; + case EOT_Buffer: + if (desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFER && desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFEREX) + break; + if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX && (desc.BufferEx.Flags & D3D11_BUFFEREX_SRV_FLAG_RAW)) + { + DPF(0, "%s: Resource type mismatch; %s expected, ByteAddressBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + else + { + ID3D11Buffer* pBuffer = NULL; + pView->GetResource( (ID3D11Resource**)&pBuffer ); + D3DXASSERT( pBuffer != NULL ); + D3D11_BUFFER_DESC BufDesc; + pBuffer->GetDesc( &BufDesc ); + SAFE_RELEASE( pBuffer ); + if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) + { + DPF(0, "%s: Resource type mismatch; %s expected, StructuredBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + else + { + return S_OK; + } + } + break; + case EOT_Texture1D: + case EOT_Texture1DArray: + if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE1D || + desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE1DARRAY) + return S_OK; + break; + case EOT_Texture2D: + case EOT_Texture2DArray: + if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2D || + desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DARRAY) + return S_OK; + break; + case EOT_Texture2DMS: + case EOT_Texture2DMSArray: + if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DMS || + desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY) + return S_OK; + break; + case EOT_Texture3D: + if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE3D) + return S_OK; + break; + case EOT_TextureCube: + case EOT_TextureCubeArray: + if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBE || + desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBEARRAY) + return S_OK; + break; + case EOT_ByteAddressBuffer: + if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX && (desc.BufferEx.Flags & D3D11_BUFFEREX_SRV_FLAG_RAW)) + return S_OK; + break; + case EOT_StructuredBuffer: + if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX || desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFER) + { + ID3D11Buffer* pBuffer = NULL; + pView->GetResource( (ID3D11Resource**)&pBuffer ); + D3DXASSERT( pBuffer != NULL ); + D3D11_BUFFER_DESC BufDesc; + pBuffer->GetDesc( &BufDesc ); + SAFE_RELEASE( pBuffer ); + if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) + { + return S_OK; + } + else + { + DPF(0, "%s: Resource type mismatch; %s expected, non-structured Buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + } + break; + default: + D3DXASSERT(0); // internal error, should never get here + return E_FAIL; + } + + + DPF(0, "%s: Resource type mismatch; %s expected, %s provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType), GetSRVDimensionNameFromEnum(desc.ViewDimension)); + return E_INVALIDARG; + } + return S_OK; +} + +template<typename IBaseInterface> +HRESULT TShaderResourceVariable<IBaseInterface>::SetResource(ID3D11ShaderResourceView *pResource) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::SetResource"; + + VH(ValidateTextureType(pResource, pType->ObjectType, pFuncName)); +#endif + + // Texture variables don't need to be dirtied. + SAFE_ADDREF(pResource); + SAFE_RELEASE(Data.pShaderResource->pShaderResource); + Data.pShaderResource->pShaderResource = pResource; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderResourceVariable<IBaseInterface>::GetResource(ID3D11ShaderResourceView **ppResource) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::GetResource"; + + VERIFYPARAMETER(ppResource); +#endif + + *ppResource = Data.pShaderResource->pShaderResource; + SAFE_ADDREF(*ppResource); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderResourceVariable<IBaseInterface>::SetResourceArray(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::SetResourceArray"; + UINT i; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + +#ifdef _DEBUG + for (i = 0; i < Count; ++ i) + { + VH(ValidateTextureType(ppResources[i], pType->ObjectType, pFuncName)); + } +#endif + + // Texture variables don't need to be dirtied. + for (i = 0; i < Count; ++ i) + { + SShaderResource *pResourceBlock = Data.pShaderResource + Offset + i; + SAFE_ADDREF(ppResources[i]); + SAFE_RELEASE(pResourceBlock->pShaderResource); + pResourceBlock->pShaderResource = ppResources[i]; + } + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderResourceVariable<IBaseInterface>::GetResourceArray(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::GetResourceArray"; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + + UINT i; + for (i = 0; i < Count; ++ i) + { + ppResources[i] = (Data.pShaderResource + Offset + i)->pShaderResource; + SAFE_ADDREF(ppResources[i]); + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectUnorderedAccessViewVariable (TUnorderedAccessViewVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TUnorderedAccessViewVariable : public IBaseInterface +{ + STDMETHOD(SetUnorderedAccessView)(ID3D11UnorderedAccessView *pResource); + STDMETHOD(GetUnorderedAccessView)(ID3D11UnorderedAccessView **ppResource); + + STDMETHOD(SetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count); + STDMETHOD(GetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count); +}; + +static HRESULT ValidateTextureType(ID3D11UnorderedAccessView *pView, EObjectType ObjectType, LPCSTR pFuncName) +{ + if (NULL != pView) + { + D3D11_UNORDERED_ACCESS_VIEW_DESC desc; + pView->GetDesc(&desc); + switch (ObjectType) + { + case EOT_RWBuffer: + if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) + break; + if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_RAW) + { + DPF(0, "%s: Resource type mismatch; %s expected, RWByteAddressBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + else + { + ID3D11Buffer* pBuffer = NULL; + pView->GetResource( (ID3D11Resource**)&pBuffer ); + D3DXASSERT( pBuffer != NULL ); + D3D11_BUFFER_DESC BufDesc; + pBuffer->GetDesc( &BufDesc ); + SAFE_RELEASE( pBuffer ); + if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) + { + DPF(0, "%s: Resource type mismatch; %s expected, an RWStructuredBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + else + { + return S_OK; + } + } + break; + case EOT_RWTexture1D: + case EOT_RWTexture1DArray: + if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE1D || + desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE1DARRAY) + return S_OK; + break; + case EOT_RWTexture2D: + case EOT_RWTexture2DArray: + if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE2D || + desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE2DARRAY) + return S_OK; + break; + case EOT_RWTexture3D: + if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE3D) + return S_OK; + break; + case EOT_RWByteAddressBuffer: + if (desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER && (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_RAW)) + return S_OK; + break; + case EOT_RWStructuredBuffer: + if (desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER) + { + ID3D11Buffer* pBuffer = NULL; + pView->GetResource( (ID3D11Resource**)&pBuffer ); + D3DXASSERT( pBuffer != NULL ); + D3D11_BUFFER_DESC BufDesc; + pBuffer->GetDesc( &BufDesc ); + SAFE_RELEASE( pBuffer ); + if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) + { + return S_OK; + } + else + { + DPF(0, "%s: Resource type mismatch; %s expected, non-structured Buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + } + break; + case EOT_RWStructuredBufferAlloc: + case EOT_RWStructuredBufferConsume: + if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) + break; + if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_COUNTER) + { + return S_OK; + } + else + { + DPF(0, "%s: Resource type mismatch; %s expected, non-Counter buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + break; + case EOT_AppendStructuredBuffer: + case EOT_ConsumeStructuredBuffer: + if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) + break; + if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_APPEND) + { + return S_OK; + } + else + { + DPF(0, "%s: Resource type mismatch; %s expected, non-Append buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); + return E_INVALIDARG; + } + break; + default: + D3DXASSERT(0); // internal error, should never get here + return E_FAIL; + } + + + DPF(0, "%s: Resource type mismatch; %s expected, %s provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType), GetUAVDimensionNameFromEnum(desc.ViewDimension)); + return E_INVALIDARG; + } + return S_OK; +} + +template<typename IBaseInterface> +HRESULT TUnorderedAccessViewVariable<IBaseInterface>::SetUnorderedAccessView(ID3D11UnorderedAccessView *pResource) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::SetUnorderedAccessView"; + + VH(ValidateTextureType(pResource, pType->ObjectType, pFuncName)); +#endif + + // UAV variables don't need to be dirtied. + SAFE_ADDREF(pResource); + SAFE_RELEASE(Data.pUnorderedAccessView->pUnorderedAccessView); + Data.pUnorderedAccessView->pUnorderedAccessView = pResource; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TUnorderedAccessViewVariable<IBaseInterface>::GetUnorderedAccessView(ID3D11UnorderedAccessView **ppResource) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::GetUnorderedAccessView"; + + VERIFYPARAMETER(ppResource); +#endif + + *ppResource = Data.pUnorderedAccessView->pUnorderedAccessView; + SAFE_ADDREF(*ppResource); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TUnorderedAccessViewVariable<IBaseInterface>::SetUnorderedAccessViewArray(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::SetUnorderedAccessViewArray"; + UINT i; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + +#ifdef _DEBUG + for (i = 0; i < Count; ++ i) + { + VH(ValidateTextureType(ppResources[i], pType->ObjectType, pFuncName)); + } +#endif + + // Texture variables don't need to be dirtied. + for (i = 0; i < Count; ++ i) + { + SUnorderedAccessView *pResourceBlock = Data.pUnorderedAccessView + Offset + i; + SAFE_ADDREF(ppResources[i]); + SAFE_RELEASE(pResourceBlock->pUnorderedAccessView); + pResourceBlock->pUnorderedAccessView = ppResources[i]; + } + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TUnorderedAccessViewVariable<IBaseInterface>::GetUnorderedAccessViewArray(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::GetUnorderedAccessViewArray"; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + + UINT i; + for (i = 0; i < Count; ++ i) + { + ppResources[i] = (Data.pUnorderedAccessView + Offset + i)->pUnorderedAccessView; + SAFE_ADDREF(ppResources[i]); + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectRenderTargetViewVariable (TRenderTargetViewVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TRenderTargetViewVariable : public IBaseInterface +{ + STDMETHOD(SetRenderTarget)(ID3D11RenderTargetView *pResource); + STDMETHOD(GetRenderTarget)(ID3D11RenderTargetView **ppResource); + + STDMETHOD(SetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count); + STDMETHOD(GetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count); +}; + + +template<typename IBaseInterface> +HRESULT TRenderTargetViewVariable<IBaseInterface>::SetRenderTarget(ID3D11RenderTargetView *pResource) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::SetRenderTarget"; + +#endif + + // Texture variables don't need to be dirtied. + SAFE_ADDREF(pResource); + SAFE_RELEASE(Data.pRenderTargetView->pRenderTargetView); + Data.pRenderTargetView->pRenderTargetView = pResource; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TRenderTargetViewVariable<IBaseInterface>::GetRenderTarget(ID3D11RenderTargetView **ppResource) +{ + HRESULT hr = S_OK; + + *ppResource = Data.pRenderTargetView->pRenderTargetView; + SAFE_ADDREF(*ppResource); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TRenderTargetViewVariable<IBaseInterface>::SetRenderTargetArray(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::SetRenderTargetArray"; + UINT i; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + + // Texture variables don't need to be dirtied. + for (i = 0; i < Count; ++ i) + { + SRenderTargetView *pResourceBlock = Data.pRenderTargetView + Offset + i; + SAFE_ADDREF(ppResources[i]); + SAFE_RELEASE(pResourceBlock->pRenderTargetView); + pResourceBlock->pRenderTargetView = ppResources[i]; + } + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TRenderTargetViewVariable<IBaseInterface>::GetRenderTargetArray(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::GetRenderTargetArray"; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + + UINT i; + for (i = 0; i < Count; ++ i) + { + ppResources[i] = (Data.pRenderTargetView + Offset + i)->pRenderTargetView; + SAFE_ADDREF(ppResources[i]); + } + +lExit: + return hr; +} + +////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectDepthStencilViewVariable (TDepthStencilViewVariable implementation) +////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TDepthStencilViewVariable : public IBaseInterface +{ + STDMETHOD(SetDepthStencil)(ID3D11DepthStencilView *pResource); + STDMETHOD(GetDepthStencil)(ID3D11DepthStencilView **ppResource); + + STDMETHOD(SetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count); + STDMETHOD(GetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count); +}; + + +template<typename IBaseInterface> +HRESULT TDepthStencilViewVariable<IBaseInterface>::SetDepthStencil(ID3D11DepthStencilView *pResource) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::SetDepthStencil"; + +#endif + + // Texture variables don't need to be dirtied. + SAFE_ADDREF(pResource); + SAFE_RELEASE(Data.pDepthStencilView->pDepthStencilView); + Data.pDepthStencilView->pDepthStencilView = pResource; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TDepthStencilViewVariable<IBaseInterface>::GetDepthStencil(ID3D11DepthStencilView **ppResource) +{ + HRESULT hr = S_OK; + +#ifdef _DEBUG + LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::GetDepthStencil"; + + VERIFYPARAMETER(ppResource); +#endif + + *ppResource = Data.pDepthStencilView->pDepthStencilView; + SAFE_ADDREF(*ppResource); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TDepthStencilViewVariable<IBaseInterface>::SetDepthStencilArray(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::SetDepthStencilArray"; + UINT i; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + + // Texture variables don't need to be dirtied. + for (i = 0; i < Count; ++ i) + { + SDepthStencilView *pResourceBlock = Data.pDepthStencilView + Offset + i; + SAFE_ADDREF(ppResources[i]); + SAFE_RELEASE(pResourceBlock->pDepthStencilView); + pResourceBlock->pDepthStencilView = ppResources[i]; + } + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TDepthStencilViewVariable<IBaseInterface>::GetDepthStencilArray(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) +{ + LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::GetDepthStencilArray"; + + CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); + + UINT i; + for (i = 0; i < Count; ++ i) + { + ppResources[i] = (Data.pDepthStencilView + Offset + i)->pDepthStencilView; + SAFE_ADDREF(ppResources[i]); + } + +lExit: + return hr; +} + + + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderVariable (TShaderVariable implementation) +//////////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TShaderVariable : public IBaseInterface +{ + STDMETHOD(GetShaderDesc)(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc); + + STDMETHOD(GetVertexShader)(UINT ShaderIndex, ID3D11VertexShader **ppVS); + STDMETHOD(GetGeometryShader)(UINT ShaderIndex, ID3D11GeometryShader **ppGS); + STDMETHOD(GetPixelShader)(UINT ShaderIndex, ID3D11PixelShader **ppPS); + STDMETHOD(GetHullShader)(UINT ShaderIndex, ID3D11HullShader **ppPS); + STDMETHOD(GetDomainShader)(UINT ShaderIndex, ID3D11DomainShader **ppPS); + STDMETHOD(GetComputeShader)(UINT ShaderIndex, ID3D11ComputeShader **ppPS); + + STDMETHOD(GetInputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); + STDMETHOD(GetOutputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); + STDMETHOD(GetPatchConstantSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); + + STDMETHOD_(BOOL, IsValid)(); +}; + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetShaderDesc(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetShaderDesc"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); + + Data.pShader[ShaderIndex].GetShaderDesc(pDesc, FALSE); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetVertexShader(UINT ShaderIndex, ID3D11VertexShader **ppVS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetVertexShader"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppVS); + + VH( Data.pShader[ShaderIndex].GetVertexShader(ppVS) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetGeometryShader(UINT ShaderIndex, ID3D11GeometryShader **ppGS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetGeometryShader"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppGS); + + VH( Data.pShader[ShaderIndex].GetGeometryShader(ppGS) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetPixelShader(UINT ShaderIndex, ID3D11PixelShader **ppPS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPixelShader"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppPS); + + VH( Data.pShader[ShaderIndex].GetPixelShader(ppPS) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetHullShader(UINT ShaderIndex, ID3D11HullShader **ppHS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetHullShader"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppHS); + + VH( Data.pShader[ShaderIndex].GetHullShader(ppHS) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetDomainShader(UINT ShaderIndex, ID3D11DomainShader **ppDS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetDomainShader"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppDS); + + VH( Data.pShader[ShaderIndex].GetDomainShader(ppDS) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetComputeShader(UINT ShaderIndex, ID3D11ComputeShader **ppCS) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetComputeShader"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppCS); + + VH( Data.pShader[ShaderIndex].GetComputeShader(ppCS) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetInputSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetInputSignatureElementDesc"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); + + VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_Input, Element, pDesc) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetOutputSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetOutputSignatureElementDesc"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); + + VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_Output, Element, pDesc) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TShaderVariable<IBaseInterface>::GetPatchConstantSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPatchConstantSignatureElementDesc"; + + CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); + + VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_PatchConstant, Element, pDesc) ); + +lExit: + return hr; +} + +template<typename IBaseInterface> +BOOL TShaderVariable<IBaseInterface>::IsValid() +{ + UINT numElements = IsArray()? pType->Elements : 1; + BOOL valid = TRUE; + while( numElements > 0 && ( valid = Data.pShader[ numElements-1 ].IsValid ) ) + numElements--; + return valid; +} + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectBlendVariable (TBlendVariable implementation) +//////////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TBlendVariable : public IBaseInterface +{ +public: + STDMETHOD(GetBlendState)(UINT Index, ID3D11BlendState **ppBlendState); + STDMETHOD(SetBlendState)(UINT Index, ID3D11BlendState *pBlendState); + STDMETHOD(UndoSetBlendState)(UINT Index); + STDMETHOD(GetBackingStore)(UINT Index, D3D11_BLEND_DESC *pBlendDesc); + STDMETHOD_(BOOL, IsValid)(); +}; + +template<typename IBaseInterface> +HRESULT TBlendVariable<IBaseInterface>::GetBlendState(UINT Index, ID3D11BlendState **ppBlendState) +{ + LPCSTR pFuncName = "ID3DX11EffectBlendVariable::GetBlendState"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, ppBlendState); + + *ppBlendState = Data.pBlend[Index].pBlendObject; + SAFE_ADDREF(*ppBlendState); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TBlendVariable<IBaseInterface>::SetBlendState(UINT Index, ID3D11BlendState *pBlendState) +{ + LPCSTR pFuncName = "ID3DX11EffectBlendState::SetBlendState"; + + CHECK_SCALAR_BOUNDS(Index); + + if( !Data.pBlend[Index].IsUserManaged ) + { + // Save original state object in case we UndoSet + D3DXASSERT( pMemberData[Index].Type == MDT_BlendState ); + VB( pMemberData[Index].Data.pD3DEffectsManagedBlendState == NULL ); + pMemberData[Index].Data.pD3DEffectsManagedBlendState = Data.pBlend[Index].pBlendObject; + Data.pBlend[Index].pBlendObject = NULL; + Data.pBlend[Index].IsUserManaged = TRUE; + } + + SAFE_ADDREF( pBlendState ); + SAFE_RELEASE( Data.pBlend[Index].pBlendObject ); + Data.pBlend[Index].pBlendObject = pBlendState; + Data.pBlend[Index].IsValid = TRUE; +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TBlendVariable<IBaseInterface>::UndoSetBlendState(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectBlendState::UndoSetBlendState"; + + CHECK_SCALAR_BOUNDS(Index); + + if( !Data.pBlend[Index].IsUserManaged ) + { + return S_FALSE; + } + + // Revert to original state object + SAFE_RELEASE( Data.pBlend[Index].pBlendObject ); + Data.pBlend[Index].pBlendObject = pMemberData[Index].Data.pD3DEffectsManagedBlendState; + pMemberData[Index].Data.pD3DEffectsManagedBlendState = NULL; + Data.pBlend[Index].IsUserManaged = FALSE; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TBlendVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_BLEND_DESC *pBlendDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectBlendVariable::GetBackingStore"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, pBlendDesc); + + if( Data.pBlend[Index].IsUserManaged ) + { + if( Data.pBlend[Index].pBlendObject ) + { + Data.pBlend[Index].pBlendObject->GetDesc( pBlendDesc ); + } + else + { + *pBlendDesc = CD3D11_BLEND_DESC( D3D11_DEFAULT ); + } + } + else + { + SBlendBlock *pBlock = Data.pBlend + Index; + if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) + { + pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called + } + + memcpy( pBlendDesc, &pBlock->BackingStore, sizeof(D3D11_BLEND_DESC) ); + } + +lExit: + return hr; +} + +template<typename IBaseInterface> +BOOL TBlendVariable<IBaseInterface>::IsValid() +{ + UINT numElements = IsArray()? pType->Elements : 1; + BOOL valid = TRUE; + while( numElements > 0 && ( valid = Data.pBlend[ numElements-1 ].IsValid ) ) + numElements--; + return valid; +} + + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectDepthStencilVariable (TDepthStencilVariable implementation) +//////////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TDepthStencilVariable : public IBaseInterface +{ +public: + STDMETHOD(GetDepthStencilState)(UINT Index, ID3D11DepthStencilState **ppDepthStencilState); + STDMETHOD(SetDepthStencilState)(UINT Index, ID3D11DepthStencilState *pDepthStencilState); + STDMETHOD(UndoSetDepthStencilState)(UINT Index); + STDMETHOD(GetBackingStore)(UINT Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc); + STDMETHOD_(BOOL, IsValid)(); +}; + +template<typename IBaseInterface> +HRESULT TDepthStencilVariable<IBaseInterface>::GetDepthStencilState(UINT Index, ID3D11DepthStencilState **ppDepthStencilState) +{ + LPCSTR pFuncName = "ID3DX11EffectDepthStencilVariable::GetDepthStencilState"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, ppDepthStencilState); + + *ppDepthStencilState = Data.pDepthStencil[Index].pDSObject; + SAFE_ADDREF(*ppDepthStencilState); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TDepthStencilVariable<IBaseInterface>::SetDepthStencilState(UINT Index, ID3D11DepthStencilState *pDepthStencilState) +{ + LPCSTR pFuncName = "ID3DX11EffectDepthStencilState::SetDepthStencilState"; + + CHECK_SCALAR_BOUNDS(Index); + + if( !Data.pDepthStencil[Index].IsUserManaged ) + { + // Save original state object in case we UndoSet + D3DXASSERT( pMemberData[Index].Type == MDT_DepthStencilState ); + VB( pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState == NULL ); + pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState = Data.pDepthStencil[Index].pDSObject; + Data.pDepthStencil[Index].pDSObject = NULL; + Data.pDepthStencil[Index].IsUserManaged = TRUE; + } + + SAFE_ADDREF( pDepthStencilState ); + SAFE_RELEASE( Data.pDepthStencil[Index].pDSObject ); + Data.pDepthStencil[Index].pDSObject = pDepthStencilState; + Data.pDepthStencil[Index].IsValid = TRUE; +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TDepthStencilVariable<IBaseInterface>::UndoSetDepthStencilState(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectDepthStencilState::UndoSetDepthStencilState"; + + CHECK_SCALAR_BOUNDS(Index); + + if( !Data.pDepthStencil[Index].IsUserManaged ) + { + return S_FALSE; + } + + // Revert to original state object + SAFE_RELEASE( Data.pDepthStencil[Index].pDSObject ); + Data.pDepthStencil[Index].pDSObject = pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState; + pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState = NULL; + Data.pDepthStencil[Index].IsUserManaged = FALSE; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TDepthStencilVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectDepthStencilVariable::GetBackingStore"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, pDepthStencilDesc); + + if( Data.pDepthStencil[Index].IsUserManaged ) + { + if( Data.pDepthStencil[Index].pDSObject ) + { + Data.pDepthStencil[Index].pDSObject->GetDesc( pDepthStencilDesc ); + } + else + { + *pDepthStencilDesc = CD3D11_DEPTH_STENCIL_DESC( D3D11_DEFAULT ); + } + } + else + { + SDepthStencilBlock *pBlock = Data.pDepthStencil + Index; + if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) + { + pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called + } + + memcpy(pDepthStencilDesc, &pBlock->BackingStore, sizeof(D3D11_DEPTH_STENCIL_DESC)); + } + +lExit: + return hr; +} + +template<typename IBaseInterface> +BOOL TDepthStencilVariable<IBaseInterface>::IsValid() +{ + UINT numElements = IsArray()? pType->Elements : 1; + BOOL valid = TRUE; + while( numElements > 0 && ( valid = Data.pDepthStencil[ numElements-1 ].IsValid ) ) + numElements--; + return valid; +} + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectRasterizerVariable (TRasterizerVariable implementation) +//////////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TRasterizerVariable : public IBaseInterface +{ +public: + + STDMETHOD(GetRasterizerState)(UINT Index, ID3D11RasterizerState **ppRasterizerState); + STDMETHOD(SetRasterizerState)(UINT Index, ID3D11RasterizerState *pRasterizerState); + STDMETHOD(UndoSetRasterizerState)(UINT Index); + STDMETHOD(GetBackingStore)(UINT Index, D3D11_RASTERIZER_DESC *pRasterizerDesc); + STDMETHOD_(BOOL, IsValid)(); +}; + +template<typename IBaseInterface> +HRESULT TRasterizerVariable<IBaseInterface>::GetRasterizerState(UINT Index, ID3D11RasterizerState **ppRasterizerState) +{ + LPCSTR pFuncName = "ID3DX11EffectRasterizerVariable::GetRasterizerState"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, ppRasterizerState); + + *ppRasterizerState = Data.pRasterizer[Index].pRasterizerObject; + SAFE_ADDREF(*ppRasterizerState); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TRasterizerVariable<IBaseInterface>::SetRasterizerState(UINT Index, ID3D11RasterizerState *pRasterizerState) +{ + LPCSTR pFuncName = "ID3DX11EffectRasterizerState::SetRasterizerState"; + + CHECK_SCALAR_BOUNDS(Index); + + if( !Data.pRasterizer[Index].IsUserManaged ) + { + // Save original state object in case we UndoSet + D3DXASSERT( pMemberData[Index].Type == MDT_RasterizerState ); + VB( pMemberData[Index].Data.pD3DEffectsManagedRasterizerState == NULL ); + pMemberData[Index].Data.pD3DEffectsManagedRasterizerState = Data.pRasterizer[Index].pRasterizerObject; + Data.pRasterizer[Index].pRasterizerObject = NULL; + Data.pRasterizer[Index].IsUserManaged = TRUE; + } + + SAFE_ADDREF( pRasterizerState ); + SAFE_RELEASE( Data.pRasterizer[Index].pRasterizerObject ); + Data.pRasterizer[Index].pRasterizerObject = pRasterizerState; + Data.pRasterizer[Index].IsValid = TRUE; +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TRasterizerVariable<IBaseInterface>::UndoSetRasterizerState(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectRasterizerState::UndoSetRasterizerState"; + + CHECK_SCALAR_BOUNDS(Index); + + if( !Data.pRasterizer[Index].IsUserManaged ) + { + return S_FALSE; + } + + // Revert to original state object + SAFE_RELEASE( Data.pRasterizer[Index].pRasterizerObject ); + Data.pRasterizer[Index].pRasterizerObject = pMemberData[Index].Data.pD3DEffectsManagedRasterizerState; + pMemberData[Index].Data.pD3DEffectsManagedRasterizerState = NULL; + Data.pRasterizer[Index].IsUserManaged = FALSE; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TRasterizerVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_RASTERIZER_DESC *pRasterizerDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectRasterizerVariable::GetBackingStore"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, pRasterizerDesc); + + if( Data.pRasterizer[Index].IsUserManaged ) + { + if( Data.pRasterizer[Index].pRasterizerObject ) + { + Data.pRasterizer[Index].pRasterizerObject->GetDesc( pRasterizerDesc ); + } + else + { + *pRasterizerDesc = CD3D11_RASTERIZER_DESC( D3D11_DEFAULT ); + } + } + else + { + SRasterizerBlock *pBlock = Data.pRasterizer + Index; + if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) + { + pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called + } + + memcpy(pRasterizerDesc, &pBlock->BackingStore, sizeof(D3D11_RASTERIZER_DESC)); + } + +lExit: + return hr; +} + +template<typename IBaseInterface> +BOOL TRasterizerVariable<IBaseInterface>::IsValid() +{ + UINT numElements = IsArray()? pType->Elements : 1; + BOOL valid = TRUE; + while( numElements > 0 && ( valid = Data.pRasterizer[ numElements-1 ].IsValid ) ) + numElements--; + return valid; +} + +//////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectSamplerVariable (TSamplerVariable implementation) +//////////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TSamplerVariable : public IBaseInterface +{ +public: + + STDMETHOD(GetSampler)(UINT Index, ID3D11SamplerState **ppSampler); + STDMETHOD(SetSampler)(UINT Index, ID3D11SamplerState *pSampler); + STDMETHOD(UndoSetSampler)(UINT Index); + STDMETHOD(GetBackingStore)(UINT Index, D3D11_SAMPLER_DESC *pSamplerDesc); +}; + +template<typename IBaseInterface> +HRESULT TSamplerVariable<IBaseInterface>::GetSampler(UINT Index, ID3D11SamplerState **ppSampler) +{ + LPCSTR pFuncName = "ID3DX11EffectSamplerVariable::GetSampler"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, ppSampler); + + *ppSampler = Data.pSampler[Index].pD3DObject; + SAFE_ADDREF(*ppSampler); + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TSamplerVariable<IBaseInterface>::SetSampler(UINT Index, ID3D11SamplerState *pSampler) +{ + LPCSTR pFuncName = "ID3DX11EffectSamplerState::SetSampler"; + + CHECK_SCALAR_BOUNDS(Index); + + // Replace all references to the old shader block with this one + GetEffect()->ReplaceSamplerReference(&Data.pSampler[Index], pSampler); + + if( !Data.pSampler[Index].IsUserManaged ) + { + // Save original state object in case we UndoSet + D3DXASSERT( pMemberData[Index].Type == MDT_SamplerState ); + VB( pMemberData[Index].Data.pD3DEffectsManagedSamplerState == NULL ); + pMemberData[Index].Data.pD3DEffectsManagedSamplerState = Data.pSampler[Index].pD3DObject; + Data.pSampler[Index].pD3DObject = NULL; + Data.pSampler[Index].IsUserManaged = TRUE; + } + + SAFE_ADDREF( pSampler ); + SAFE_RELEASE( Data.pSampler[Index].pD3DObject ); + Data.pSampler[Index].pD3DObject = pSampler; +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TSamplerVariable<IBaseInterface>::UndoSetSampler(UINT Index) +{ + LPCSTR pFuncName = "ID3DX11EffectSamplerState::UndoSetSampler"; + + CHECK_SCALAR_BOUNDS(Index); + + if( !Data.pSampler[Index].IsUserManaged ) + { + return S_FALSE; + } + + // Replace all references to the old shader block with this one + GetEffect()->ReplaceSamplerReference(&Data.pSampler[Index], pMemberData[Index].Data.pD3DEffectsManagedSamplerState); + + // Revert to original state object + SAFE_RELEASE( Data.pSampler[Index].pD3DObject ); + Data.pSampler[Index].pD3DObject = pMemberData[Index].Data.pD3DEffectsManagedSamplerState; + pMemberData[Index].Data.pD3DEffectsManagedSamplerState = NULL; + Data.pSampler[Index].IsUserManaged = FALSE; + +lExit: + return hr; +} + +template<typename IBaseInterface> +HRESULT TSamplerVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_SAMPLER_DESC *pSamplerDesc) +{ + LPCSTR pFuncName = "ID3DX11EffectSamplerVariable::GetBackingStore"; + + CHECK_OBJECT_SCALAR_BOUNDS(Index, pSamplerDesc); + + if( Data.pSampler[Index].IsUserManaged ) + { + if( Data.pSampler[Index].pD3DObject ) + { + Data.pSampler[Index].pD3DObject->GetDesc( pSamplerDesc ); + } + else + { + *pSamplerDesc = CD3D11_SAMPLER_DESC( D3D11_DEFAULT ); + } + } + else + { + SSamplerBlock *pBlock = Data.pSampler + Index; + if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) + { + pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called + } + + memcpy(pSamplerDesc, &pBlock->BackingStore.SamplerDesc, sizeof(D3D11_SAMPLER_DESC)); + } + +lExit: + return hr; +} + +//////////////////////////////////////////////////////////////////////////////// +// TUncastableVariable +//////////////////////////////////////////////////////////////////////////////// + +template<typename IBaseInterface> +struct TUncastableVariable : public IBaseInterface +{ + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(); + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(); + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(); + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(); + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(); + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(); + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(); + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(); + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(); + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(); + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(); + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(); + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(); + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(); + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(); + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(); +}; + +template<typename IBaseInterface> +ID3DX11EffectScalarVariable * TUncastableVariable<IBaseInterface>::AsScalar() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsScalar"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidScalarVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectVectorVariable * TUncastableVariable<IBaseInterface>::AsVector() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsVector"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidVectorVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectMatrixVariable * TUncastableVariable<IBaseInterface>::AsMatrix() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsMatrix"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidMatrixVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectStringVariable * TUncastableVariable<IBaseInterface>::AsString() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsString"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidStringVariable; +} + +template<typename IBaseClassInstance> +ID3DX11EffectClassInstanceVariable * TUncastableVariable<IBaseClassInstance>::AsClassInstance() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsClassInstance"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidClassInstanceVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectInterfaceVariable * TUncastableVariable<IBaseInterface>::AsInterface() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsInterface"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidInterfaceVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectShaderResourceVariable * TUncastableVariable<IBaseInterface>::AsShaderResource() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsShaderResource"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidShaderResourceVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectUnorderedAccessViewVariable * TUncastableVariable<IBaseInterface>::AsUnorderedAccessView() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsUnorderedAccessView"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidUnorderedAccessViewVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectRenderTargetViewVariable * TUncastableVariable<IBaseInterface>::AsRenderTargetView() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsRenderTargetView"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidRenderTargetViewVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectDepthStencilViewVariable * TUncastableVariable<IBaseInterface>::AsDepthStencilView() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencilView"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidDepthStencilViewVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectConstantBuffer * TUncastableVariable<IBaseInterface>::AsConstantBuffer() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsConstantBuffer"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidConstantBuffer; +} + +template<typename IBaseInterface> +ID3DX11EffectShaderVariable * TUncastableVariable<IBaseInterface>::AsShader() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsShader"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidShaderVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectBlendVariable * TUncastableVariable<IBaseInterface>::AsBlend() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsBlend"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidBlendVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectDepthStencilVariable * TUncastableVariable<IBaseInterface>::AsDepthStencil() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencil"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidDepthStencilVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectRasterizerVariable * TUncastableVariable<IBaseInterface>::AsRasterizer() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsRasterizer"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidRasterizerVariable; +} + +template<typename IBaseInterface> +ID3DX11EffectSamplerVariable * TUncastableVariable<IBaseInterface>::AsSampler() +{ + LPCSTR pFuncName = "ID3DX11EffectVariable::AsSampler"; + DPF(0, "%s: Invalid typecast", pFuncName); + return &g_InvalidSamplerVariable; +} + +//////////////////////////////////////////////////////////////////////////////// +// Macros to instantiate the myriad templates +//////////////////////////////////////////////////////////////////////////////// + +// generates a global variable, annotation, global variable member, and annotation member of each struct type +#define GenerateReflectionClasses(Type, BaseInterface) \ +struct S##Type##GlobalVariable : public T##Type##Variable<TGlobalVariable<BaseInterface>, FALSE> { }; \ +struct S##Type##Annotation : public T##Type##Variable<TAnnotation<BaseInterface>, TRUE> { }; \ +struct S##Type##GlobalVariableMember : public T##Type##Variable<TVariable<TMember<BaseInterface> >, FALSE> { }; \ +struct S##Type##AnnotationMember : public T##Type##Variable<TVariable<TMember<BaseInterface> >, TRUE> { }; + +#define GenerateVectorReflectionClasses(Type, BaseType, BaseInterface) \ +struct S##Type##GlobalVariable : public TVectorVariable<TGlobalVariable<BaseInterface>, FALSE, BaseType> { }; \ +struct S##Type##Annotation : public TVectorVariable<TAnnotation<BaseInterface>, TRUE, BaseType> { }; \ +struct S##Type##GlobalVariableMember : public TVectorVariable<TVariable<TMember<BaseInterface> >, FALSE, BaseType> { }; \ +struct S##Type##AnnotationMember : public TVectorVariable<TVariable<TMember<BaseInterface> >, TRUE, BaseType> { }; + +#define GenerateReflectionGlobalOnlyClasses(Type) \ +struct S##Type##GlobalVariable : public T##Type##Variable<TGlobalVariable<ID3DX11Effect##Type##Variable> > { }; \ +struct S##Type##GlobalVariableMember : public T##Type##Variable<TVariable<TMember<ID3DX11Effect##Type##Variable> > > { }; \ + +GenerateReflectionClasses(Numeric, ID3DX11EffectVariable); +GenerateReflectionClasses(FloatScalar, ID3DX11EffectScalarVariable); +GenerateReflectionClasses(IntScalar, ID3DX11EffectScalarVariable); +GenerateReflectionClasses(BoolScalar, ID3DX11EffectScalarVariable); +GenerateVectorReflectionClasses(FloatVector, ETVT_Float, ID3DX11EffectVectorVariable); +GenerateVectorReflectionClasses(BoolVector, ETVT_Bool, ID3DX11EffectVectorVariable); +GenerateVectorReflectionClasses(IntVector, ETVT_Int, ID3DX11EffectVectorVariable); +GenerateReflectionClasses(Matrix, ID3DX11EffectMatrixVariable); +GenerateReflectionClasses(String, ID3DX11EffectStringVariable); +GenerateReflectionGlobalOnlyClasses(ClassInstance); +GenerateReflectionGlobalOnlyClasses(Interface); +GenerateReflectionGlobalOnlyClasses(ShaderResource); +GenerateReflectionGlobalOnlyClasses(UnorderedAccessView); +GenerateReflectionGlobalOnlyClasses(RenderTargetView); +GenerateReflectionGlobalOnlyClasses(DepthStencilView); +GenerateReflectionGlobalOnlyClasses(Shader); +GenerateReflectionGlobalOnlyClasses(Blend); +GenerateReflectionGlobalOnlyClasses(DepthStencil); +GenerateReflectionGlobalOnlyClasses(Rasterizer); +GenerateReflectionGlobalOnlyClasses(Sampler); + +// Optimized matrix classes +struct SMatrix4x4ColumnMajorGlobalVariable : public TMatrix4x4Variable<TGlobalVariable<ID3DX11EffectMatrixVariable>, TRUE> { }; +struct SMatrix4x4RowMajorGlobalVariable : public TMatrix4x4Variable<TGlobalVariable<ID3DX11EffectMatrixVariable>, FALSE> { }; + +struct SMatrix4x4ColumnMajorGlobalVariableMember : public TMatrix4x4Variable<TVariable<TMember<ID3DX11EffectMatrixVariable> >, TRUE> { }; +struct SMatrix4x4RowMajorGlobalVariableMember : public TMatrix4x4Variable<TVariable<TMember<ID3DX11EffectMatrixVariable> >, FALSE> { }; + +// Optimized vector classes +struct SFloatVector4GlobalVariable : public TVector4Variable<TGlobalVariable<ID3DX11EffectVectorVariable> > { }; +struct SFloatVector4GlobalVariableMember : public TVector4Variable<TVariable<TMember<ID3DX11EffectVectorVariable> > > { }; + +// These 3 classes should never be used directly + +// The "base" global variable struct (all global variables should be the same size in bytes, +// but we pick this as the default). +struct SGlobalVariable : public TGlobalVariable<ID3DX11EffectVariable> +{ + +}; + +// The "base" annotation struct (all annotations should be the same size in bytes, +// but we pick this as the default). +struct SAnnotation : public TAnnotation<ID3DX11EffectVariable> +{ + +}; + +// The "base" variable member struct (all annotation/global variable members should be the +// same size in bytes, but we pick this as the default). +struct SMember : public TVariable<TMember<ID3DX11EffectVariable> > +{ + +}; + +// creates a new variable of the appropriate polymorphic type where pVar was +HRESULT PlacementNewVariable(void *pVar, SType *pType, BOOL IsAnnotation); +SMember * CreateNewMember(SType *pType, BOOL IsAnnotation); + + diff --git a/sample/d3d11/Effects11/Inc/d3dx11dbg.h b/sample/d3d11/Effects11/Inc/d3dx11dbg.h new file mode 100644 index 0000000..49ed3b3 --- /dev/null +++ b/sample/d3d11/Effects11/Inc/d3dx11dbg.h @@ -0,0 +1,66 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: d3dx11dbg.h +// Content: D3DX11 debugging functions +// +////////////////////////////////////////////////////////////////////////////// + + +#ifndef __D3DX11DBG_H__ +#define __D3DX11DBG_H__ + +#ifndef _PREFAST_ + +#pragma warning( disable: 4068 ) + +#endif + + +#include <strsafe.h> +#include <new> + +#undef NEW +#undef DELETE + +#define NEW new (std::nothrow) +#define NEW_PROTO_ARGS size_t s, const std::nothrow_t& t + + + +typedef signed char INT8; +typedef signed short INT16; +typedef unsigned char UINT8; +typedef unsigned short UINT16; + + +//---------------------------------------------------------------------------- +// DPF +//---------------------------------------------------------------------------- + +#ifdef FXDPF +void cdecl D3DXDebugPrintf(UINT lvl, LPCSTR szFormat, ...); +#define DPF D3DXDebugPrintf +#else // !FXDPF +#pragma warning(disable:4002) +#define DPF() 0 +#endif // !FXDPF + + +//---------------------------------------------------------------------------- +// D3DXASSERT +//---------------------------------------------------------------------------- + +#if _DEBUG +int WINAPI D3DXDebugAssert(LPCSTR szFile, int nLine, LPCSTR szCondition); +#define D3DXASSERT(condition) \ + do { if(!(condition)) D3DXDebugAssert(__FILE__, __LINE__, #condition); } while(0) +#else // !_DEBUG +#define D3DXASSERT(condition) 0 +#endif // !_DEBUG + + + +#endif // __D3DX11DBG_H__ + diff --git a/sample/d3d11/Effects11/Inc/d3dx11effect.h b/sample/d3d11/Effects11/Inc/d3dx11effect.h new file mode 100644 index 0000000..fc162fc --- /dev/null +++ b/sample/d3d11/Effects11/Inc/d3dx11effect.h @@ -0,0 +1,1566 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// File: D3DX11Effect.h +// Content: D3DX11 Effect Types & APIs Header +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef __D3DX11EFFECT_H__ +#define __D3DX11EFFECT_H__ + +#include "d3d11.h" +#include "d3d11shader.h" + +////////////////////////////////////////////////////////////////////////////// +// File contents: +// +// 1) Stateblock enums, structs, interfaces, flat APIs +// 2) Effect enums, structs, interfaces, flat APIs +////////////////////////////////////////////////////////////////////////////// + +#ifndef D3DX11_BYTES_FROM_BITS +#define D3DX11_BYTES_FROM_BITS(x) (((x) + 7) / 8) +#endif // D3DX11_BYTES_FROM_BITS + +typedef struct _D3DX11_STATE_BLOCK_MASK +{ + BYTE VS; + BYTE VSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + BYTE VSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + BYTE VSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + BYTE VSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + BYTE HS; + BYTE HSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + BYTE HSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + BYTE HSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + BYTE HSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + BYTE DS; + BYTE DSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + BYTE DSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + BYTE DSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + BYTE DSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + BYTE GS; + BYTE GSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + BYTE GSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + BYTE GSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + BYTE GSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + + BYTE PS; + BYTE PSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + BYTE PSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + BYTE PSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + BYTE PSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + BYTE PSUnorderedAccessViews; + + BYTE CS; + BYTE CSSamplers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT)]; + BYTE CSShaderResources[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT)]; + BYTE CSConstantBuffers[D3DX11_BYTES_FROM_BITS(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT)]; + BYTE CSInterfaces[D3DX11_BYTES_FROM_BITS(D3D11_SHADER_MAX_INTERFACES)]; + BYTE CSUnorderedAccessViews; + + BYTE IAVertexBuffers[D3DX11_BYTES_FROM_BITS(D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT)]; + BYTE IAIndexBuffer; + BYTE IAInputLayout; + BYTE IAPrimitiveTopology; + + BYTE OMRenderTargets; + BYTE OMDepthStencilState; + BYTE OMBlendState; + + BYTE RSViewports; + BYTE RSScissorRects; + BYTE RSRasterizerState; + + BYTE SOBuffers; + + BYTE Predication; +} D3DX11_STATE_BLOCK_MASK; + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT flags: +// ------------------------------------- +// +// These flags are passed in when creating an effect, and affect +// the runtime effect behavior: +// +// (Currently none) +// +// +// These flags are set by the effect runtime: +// +// D3DX11_EFFECT_OPTIMIZED +// This effect has been optimized. Reflection functions that rely on +// names/semantics/strings should fail. This is set when Optimize() is +// called, but CEffect::IsOptimized() should be used to test for this. +// +// D3DX11_EFFECT_CLONE +// This effect is a clone of another effect. Single CBs will never be +// updated when internal variable values are changed. +// This flag is not set when the D3DX11_EFFECT_CLONE_FORCE_NONSINGLE flag +// is used in cloning. +// +//---------------------------------------------------------------------------- + +#define D3DX11_EFFECT_OPTIMIZED (1 << 21) +#define D3DX11_EFFECT_CLONE (1 << 22) + +// These are the only valid parameter flags to D3DX11CreateEffect* +#define D3DX11_EFFECT_RUNTIME_VALID_FLAGS (0) + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_VARIABLE flags: +// ---------------------------- +// +// These flags describe an effect variable (global or annotation), +// and are returned in D3DX11_EFFECT_VARIABLE_DESC::Flags. +// +// D3DX11_EFFECT_VARIABLE_ANNOTATION +// Indicates that this is an annotation on a technique, pass, or global +// variable. Otherwise, this is a global variable. Annotations cannot +// be shared. +// +// D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT +// Indicates that the variable has been explicitly bound using the +// register keyword. +//---------------------------------------------------------------------------- + +#define D3DX11_EFFECT_VARIABLE_ANNOTATION (1 << 1) +#define D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT (1 << 2) + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_CLONE flags: +// ---------------------------- +// +// These flags modify the effect cloning process and are passed into Clone. +// +// D3DX11_EFFECT_CLONE_FORCE_NONSINGLE +// Ignore all "single" qualifiers on cbuffers. All cbuffers will have their +// own ID3D11Buffer's created in the cloned effect. +//---------------------------------------------------------------------------- + +#define D3DX11_EFFECT_CLONE_FORCE_NONSINGLE (1 << 0) + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_PASS flags: +// ---------------------------- +// +// These flags modify the effect cloning process and are passed into Clone. +// +// D3DX11_EFFECT_PASS_COMMIT_CHANGES +// This flag tells the effect runtime to assume that the device state was +// not modified outside of effects, so that only updated state needs to +// be set. +// +// D3DX11_EFFECT_PASS_OMIT_* +// When applying a pass, do not set the state indicated in the flag name. +//---------------------------------------------------------------------------- + +#define D3DX11_EFFECT_PASS_COMMIT_CHANGES (1 << 0) // TODO: not yet implemented +#define D3DX11_EFFECT_PASS_OMIT_SHADERS_AND_INTERFACES (1 << 1) // TODO: not yet implemented +#define D3DX11_EFFECT_PASS_OMIT_STATE_OBJECTS (1 << 2) // TODO: not yet implemented +#define D3DX11_EFFECT_PASS_OMIT_RTVS_AND_DSVS (1 << 3) // TODO: not yet implemented +#define D3DX11_EFFECT_PASS_OMIT_SAMPLERS (1 << 4) // TODO: not yet implemented +#define D3DX11_EFFECT_PASS_OMIT_CBS (1 << 5) // TODO: not yet implemented +#define D3DX11_EFFECT_PASS_OMIT_SRVS (1 << 6) // TODO: not yet implemented +#define D3DX11_EFFECT_PASS_OMIT_UAVS (1 << 7) // TODO: not yet implemented + +#define D3DX11_EFFECT_PASS_ONLY_SET_SHADERS_AND_CBS ( D3DX11_EFFECT_PASS_OMIT_STATE_OBJECTS | \ + D3DX11_EFFECT_PASS_OMIT_RTVS_AND_DSVS | \ + D3DX11_EFFECT_PASS_OMIT_SAMPLERS | \ + D3DX11_EFFECT_PASS_OMIT_SRVS | \ + D3DX11_EFFECT_PASS_OMIT_UAVS ); + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectType ////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_TYPE_DESC: +// +// Retrieved by ID3DX11EffectType::GetDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_EFFECT_TYPE_DESC +{ + LPCSTR TypeName; // Name of the type + // (e.g. "float4" or "MyStruct") + + D3D10_SHADER_VARIABLE_CLASS Class; // (e.g. scalar, vector, object, etc.) + D3D10_SHADER_VARIABLE_TYPE Type; // (e.g. float, texture, vertexshader, etc.) + + UINT Elements; // Number of elements in this type + // (0 if not an array) + UINT Members; // Number of members + // (0 if not a structure) + UINT Rows; // Number of rows in this type + // (0 if not a numeric primitive) + UINT Columns; // Number of columns in this type + // (0 if not a numeric primitive) + + UINT PackedSize; // Number of bytes required to represent + // this data type, when tightly packed + UINT UnpackedSize; // Number of bytes occupied by this data + // type, when laid out in a constant buffer + UINT Stride; // Number of bytes to seek between elements, + // when laid out in a constant buffer +} D3DX11_EFFECT_TYPE_DESC; + +typedef interface ID3DX11EffectType ID3DX11EffectType; +typedef interface ID3DX11EffectType *LPD3D11EFFECTTYPE; + +// {4250D721-D5E5-491F-B62B-587C43186285} +DEFINE_GUID(IID_ID3DX11EffectType, + 0x4250d721, 0xd5e5, 0x491f, 0xb6, 0x2b, 0x58, 0x7c, 0x43, 0x18, 0x62, 0x85); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectType + +DECLARE_INTERFACE(ID3DX11EffectType) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_TYPE_DESC *pDesc) PURE; + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(THIS_ LPCSTR Semantic) PURE; + STDMETHOD_(LPCSTR, GetMemberName)(THIS_ UINT Index) PURE; + STDMETHOD_(LPCSTR, GetMemberSemantic)(THIS_ UINT Index) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectVariable ////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_VARIABLE_DESC: +// +// Retrieved by ID3DX11EffectVariable::GetDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_EFFECT_VARIABLE_DESC +{ + LPCSTR Name; // Name of this variable, annotation, + // or structure member + LPCSTR Semantic; // Semantic string of this variable + // or structure member (NULL for + // annotations or if not present) + + UINT Flags; // D3DX11_EFFECT_VARIABLE_* flags + UINT Annotations; // Number of annotations on this variable + // (always 0 for annotations) + + UINT BufferOffset; // Offset into containing cbuffer or tbuffer + // (always 0 for annotations or variables + // not in constant buffers) + + UINT ExplicitBindPoint; // Used if the variable has been explicitly bound + // using the register keyword. Check Flags for + // D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT; +} D3DX11_EFFECT_VARIABLE_DESC; + +typedef interface ID3DX11EffectVariable ID3DX11EffectVariable; +typedef interface ID3DX11EffectVariable *LPD3D11EFFECTVARIABLE; + +// {036A777D-B56E-4B25-B313-CC3DDAB71873} +DEFINE_GUID(IID_ID3DX11EffectVariable, + 0x036a777d, 0xb56e, 0x4b25, 0xb3, 0x13, 0xcc, 0x3d, 0xda, 0xb7, 0x18, 0x73); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectVariable + +// Forward defines +typedef interface ID3DX11EffectScalarVariable ID3DX11EffectScalarVariable; +typedef interface ID3DX11EffectVectorVariable ID3DX11EffectVectorVariable; +typedef interface ID3DX11EffectMatrixVariable ID3DX11EffectMatrixVariable; +typedef interface ID3DX11EffectStringVariable ID3DX11EffectStringVariable; +typedef interface ID3DX11EffectClassInstanceVariable ID3DX11EffectClassInstanceVariable; +typedef interface ID3DX11EffectInterfaceVariable ID3DX11EffectInterfaceVariable; +typedef interface ID3DX11EffectShaderResourceVariable ID3DX11EffectShaderResourceVariable; +typedef interface ID3DX11EffectUnorderedAccessViewVariable ID3DX11EffectUnorderedAccessViewVariable; +typedef interface ID3DX11EffectRenderTargetViewVariable ID3DX11EffectRenderTargetViewVariable; +typedef interface ID3DX11EffectDepthStencilViewVariable ID3DX11EffectDepthStencilViewVariable; +typedef interface ID3DX11EffectConstantBuffer ID3DX11EffectConstantBuffer; +typedef interface ID3DX11EffectShaderVariable ID3DX11EffectShaderVariable; +typedef interface ID3DX11EffectBlendVariable ID3DX11EffectBlendVariable; +typedef interface ID3DX11EffectDepthStencilVariable ID3DX11EffectDepthStencilVariable; +typedef interface ID3DX11EffectRasterizerVariable ID3DX11EffectRasterizerVariable; +typedef interface ID3DX11EffectSamplerVariable ID3DX11EffectSamplerVariable; + +DECLARE_INTERFACE(ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectScalarVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectScalarVariable ID3DX11EffectScalarVariable; +typedef interface ID3DX11EffectScalarVariable *LPD3D11EFFECTSCALARVARIABLE; + +// {921EF2E5-A65D-4E92-9FC6-4E9CC09A4ADE} +DEFINE_GUID(IID_ID3DX11EffectScalarVariable, + 0x921ef2e5, 0xa65d, 0x4e92, 0x9f, 0xc6, 0x4e, 0x9c, 0xc0, 0x9a, 0x4a, 0xde); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectScalarVariable + +DECLARE_INTERFACE_(ID3DX11EffectScalarVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT ByteOffset, UINT ByteCount) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT ByteOffset, UINT ByteCount) PURE; + + STDMETHOD(SetFloat)(THIS_ CONST float Value) PURE; + STDMETHOD(GetFloat)(THIS_ float *pValue) PURE; + + STDMETHOD(SetFloatArray)(THIS_ CONST float *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetFloatArray)(THIS_ float *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetInt)(THIS_ CONST int Value) PURE; + STDMETHOD(GetInt)(THIS_ int *pValue) PURE; + + STDMETHOD(SetIntArray)(THIS_ CONST int *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetIntArray)(THIS_ int *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetBool)(THIS_ CONST BOOL Value) PURE; + STDMETHOD(GetBool)(THIS_ BOOL *pValue) PURE; + + STDMETHOD(SetBoolArray)(THIS_ CONST BOOL *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetBoolArray)(THIS_ BOOL *pData, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectVectorVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectVectorVariable ID3DX11EffectVectorVariable; +typedef interface ID3DX11EffectVectorVariable *LPD3D11EFFECTVECTORVARIABLE; + +// {5E785D4A-D87B-48D8-B6E6-0F8CA7E7467A} +DEFINE_GUID(IID_ID3DX11EffectVectorVariable, + 0x5e785d4a, 0xd87b, 0x48d8, 0xb6, 0xe6, 0x0f, 0x8c, 0xa7, 0xe7, 0x46, 0x7a); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectVectorVariable + +DECLARE_INTERFACE_(ID3DX11EffectVectorVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT ByteOffset, UINT ByteCount) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT ByteOffset, UINT ByteCount) PURE; + + STDMETHOD(SetBoolVector) (THIS_ CONST BOOL *pData) PURE; + STDMETHOD(SetIntVector) (THIS_ CONST int *pData) PURE; + STDMETHOD(SetFloatVector)(THIS_ CONST float *pData) PURE; + + STDMETHOD(GetBoolVector) (THIS_ BOOL *pData) PURE; + STDMETHOD(GetIntVector) (THIS_ int *pData) PURE; + STDMETHOD(GetFloatVector)(THIS_ float *pData) PURE; + + STDMETHOD(SetBoolVectorArray) (THIS_ CONST BOOL *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(SetIntVectorArray) (THIS_ CONST int *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(SetFloatVectorArray)(THIS_ CONST float *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetBoolVectorArray) (THIS_ BOOL *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetIntVectorArray) (THIS_ int *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetFloatVectorArray)(THIS_ float *pData, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectMatrixVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectMatrixVariable ID3DX11EffectMatrixVariable; +typedef interface ID3DX11EffectMatrixVariable *LPD3D11EFFECTMATRIXVARIABLE; + +// {E1096CF4-C027-419A-8D86-D29173DC803E} +DEFINE_GUID(IID_ID3DX11EffectMatrixVariable, + 0xe1096cf4, 0xc027, 0x419a, 0x8d, 0x86, 0xd2, 0x91, 0x73, 0xdc, 0x80, 0x3e); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectMatrixVariable + +DECLARE_INTERFACE_(ID3DX11EffectMatrixVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT ByteOffset, UINT ByteCount) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT ByteOffset, UINT ByteCount) PURE; + + STDMETHOD(SetMatrix)(THIS_ CONST float *pData) PURE; + STDMETHOD(GetMatrix)(THIS_ float *pData) PURE; + + STDMETHOD(SetMatrixArray)(THIS_ CONST float *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetMatrixArray)(THIS_ float *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetMatrixTranspose)(THIS_ CONST float *pData) PURE; + STDMETHOD(GetMatrixTranspose)(THIS_ float *pData) PURE; + + STDMETHOD(SetMatrixTransposeArray)(THIS_ CONST float *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetMatrixTransposeArray)(THIS_ float *pData, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectStringVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectStringVariable ID3DX11EffectStringVariable; +typedef interface ID3DX11EffectStringVariable *LPD3D11EFFECTSTRINGVARIABLE; + +// {F355C818-01BE-4653-A7CC-60FFFEDDC76D} +DEFINE_GUID(IID_ID3DX11EffectStringVariable, + 0xf355c818, 0x01be, 0x4653, 0xa7, 0xcc, 0x60, 0xff, 0xfe, 0xdd, 0xc7, 0x6d); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectStringVariable + +DECLARE_INTERFACE_(ID3DX11EffectStringVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetString)(THIS_ LPCSTR *ppString) PURE; + STDMETHOD(GetStringArray)(THIS_ LPCSTR *ppStrings, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectClassInstanceVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectClassInstanceVariable ID3DX11EffectClassInstanceVariable; +typedef interface ID3DX11EffectClassInstanceVariable *LPD3D11EFFECTCLASSINSTANCEVARIABLE; + +// {926A8053-2A39-4DB4-9BDE-CF649ADEBDC1} +DEFINE_GUID(IID_ID3DX11EffectClassInstanceVariable, + 0x926a8053, 0x2a39, 0x4db4, 0x9b, 0xde, 0xcf, 0x64, 0x9a, 0xde, 0xbd, 0xc1); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectClassInstanceVariable + +DECLARE_INTERFACE_(ID3DX11EffectClassInstanceVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetClassInstance)(ID3D11ClassInstance** ppClassInstance) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectInterfaceVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectInterfaceVariable ID3DX11EffectInterfaceVariable; +typedef interface ID3DX11EffectInterfaceVariable *LPD3D11EFFECTINTERFACEVARIABLE; + +// {516C8CD8-1C80-40A4-B19B-0688792F11A5} +DEFINE_GUID(IID_ID3DX11EffectInterfaceVariable, + 0x516c8cd8, 0x1c80, 0x40a4, 0xb1, 0x9b, 0x06, 0x88, 0x79, 0x2f, 0x11, 0xa5); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectInterfaceVariable + +DECLARE_INTERFACE_(ID3DX11EffectInterfaceVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetClassInstance)(ID3DX11EffectClassInstanceVariable *pEffectClassInstance) PURE; + STDMETHOD(GetClassInstance)(ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderResourceVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectShaderResourceVariable ID3DX11EffectShaderResourceVariable; +typedef interface ID3DX11EffectShaderResourceVariable *LPD3D11EFFECTSHADERRESOURCEVARIABLE; + +// {350DB233-BBE0-485C-9BFE-C0026B844F89} +DEFINE_GUID(IID_ID3DX11EffectShaderResourceVariable, + 0x350db233, 0xbbe0, 0x485c, 0x9b, 0xfe, 0xc0, 0x02, 0x6b, 0x84, 0x4f, 0x89); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectShaderResourceVariable + +DECLARE_INTERFACE_(ID3DX11EffectShaderResourceVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetResource)(THIS_ ID3D11ShaderResourceView *pResource) PURE; + STDMETHOD(GetResource)(THIS_ ID3D11ShaderResourceView **ppResource) PURE; + + STDMETHOD(SetResourceArray)(THIS_ ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) PURE; + STDMETHOD(GetResourceArray)(THIS_ ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectUnorderedAccessViewVariable //////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectUnorderedAccessViewVariable ID3DX11EffectUnorderedAccessViewVariable; +typedef interface ID3DX11EffectUnorderedAccessViewVariable *LPD3D11EFFECTUNORDEREDACCESSVIEWVARIABLE; + +// {79B4AC8C-870A-47D2-B05A-8BD5CC3EE6C9} +DEFINE_GUID(IID_ID3DX11EffectUnorderedAccessViewVariable, + 0x79b4ac8c, 0x870a, 0x47d2, 0xb0, 0x5a, 0x8b, 0xd5, 0xcc, 0x3e, 0xe6, 0xc9); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectUnorderedAccessViewVariable + +DECLARE_INTERFACE_(ID3DX11EffectUnorderedAccessViewVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetUnorderedAccessView)(THIS_ ID3D11UnorderedAccessView *pResource) PURE; + STDMETHOD(GetUnorderedAccessView)(THIS_ ID3D11UnorderedAccessView **ppResource) PURE; + + STDMETHOD(SetUnorderedAccessViewArray)(THIS_ ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) PURE; + STDMETHOD(GetUnorderedAccessViewArray)(THIS_ ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectRenderTargetViewVariable ////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectRenderTargetViewVariable ID3DX11EffectRenderTargetViewVariable; +typedef interface ID3DX11EffectRenderTargetViewVariable *LPD3D11EFFECTRENDERTARGETVIEWVARIABLE; + +// {D5066909-F40C-43F8-9DB5-057C2A208552} +DEFINE_GUID(IID_ID3DX11EffectRenderTargetViewVariable, + 0xd5066909, 0xf40c, 0x43f8, 0x9d, 0xb5, 0x05, 0x7c, 0x2a, 0x20, 0x85, 0x52); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectRenderTargetViewVariable + +DECLARE_INTERFACE_(ID3DX11EffectRenderTargetViewVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetRenderTarget)(THIS_ ID3D11RenderTargetView *pResource) PURE; + STDMETHOD(GetRenderTarget)(THIS_ ID3D11RenderTargetView **ppResource) PURE; + + STDMETHOD(SetRenderTargetArray)(THIS_ ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRenderTargetArray)(THIS_ ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectDepthStencilViewVariable ////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectDepthStencilViewVariable ID3DX11EffectDepthStencilViewVariable; +typedef interface ID3DX11EffectDepthStencilViewVariable *LPD3D11EFFECTDEPTHSTENCILVIEWVARIABLE; + +// {33C648AC-2E9E-4A2E-9CD6-DE31ACC5B347} +DEFINE_GUID(IID_ID3DX11EffectDepthStencilViewVariable, + 0x33c648ac, 0x2e9e, 0x4a2e, 0x9c, 0xd6, 0xde, 0x31, 0xac, 0xc5, 0xb3, 0x47); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectDepthStencilViewVariable + +DECLARE_INTERFACE_(ID3DX11EffectDepthStencilViewVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetDepthStencil)(THIS_ ID3D11DepthStencilView *pResource) PURE; + STDMETHOD(GetDepthStencil)(THIS_ ID3D11DepthStencilView **ppResource) PURE; + + STDMETHOD(SetDepthStencilArray)(THIS_ ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) PURE; + STDMETHOD(GetDepthStencilArray)(THIS_ ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectConstantBuffer //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectConstantBuffer ID3DX11EffectConstantBuffer; +typedef interface ID3DX11EffectConstantBuffer *LPD3D11EFFECTCONSTANTBUFFER; + +// {2CB6C733-82D2-4000-B3DA-6219D9A99BF2} +DEFINE_GUID(IID_ID3DX11EffectConstantBuffer, + 0x2cb6c733, 0x82d2, 0x4000, 0xb3, 0xda, 0x62, 0x19, 0xd9, 0xa9, 0x9b, 0xf2); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectConstantBuffer + +DECLARE_INTERFACE_(ID3DX11EffectConstantBuffer, ID3DX11EffectVariable) +{ + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(SetConstantBuffer)(THIS_ ID3D11Buffer *pConstantBuffer) PURE; + STDMETHOD(UndoSetConstantBuffer)(THIS) PURE; + STDMETHOD(GetConstantBuffer)(THIS_ ID3D11Buffer **ppConstantBuffer) PURE; + + STDMETHOD(SetTextureBuffer)(THIS_ ID3D11ShaderResourceView *pTextureBuffer) PURE; + STDMETHOD(UndoSetTextureBuffer)(THIS) PURE; + STDMETHOD(GetTextureBuffer)(THIS_ ID3D11ShaderResourceView **ppTextureBuffer) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectShaderVariable //////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_SHADER_DESC: +// +// Retrieved by ID3DX11EffectShaderVariable::GetShaderDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_EFFECT_SHADER_DESC +{ + CONST BYTE *pInputSignature; // Passed into CreateInputLayout, + // valid on VS and GS only + + BOOL IsInline; // Is this an anonymous shader variable + // resulting from an inline shader assignment? + + + // -- The following fields are not valid after Optimize() -- + CONST BYTE *pBytecode; // Shader bytecode + UINT BytecodeLength; + + LPCSTR SODecls[D3D11_SO_STREAM_COUNT]; // Stream out declaration string (for GS with SO) + UINT RasterizedStream; + + UINT NumInputSignatureEntries; // Number of entries in the input signature + UINT NumOutputSignatureEntries; // Number of entries in the output signature + UINT NumPatchConstantSignatureEntries; // Number of entries in the patch constant signature +} D3DX11_EFFECT_SHADER_DESC; + + +typedef interface ID3DX11EffectShaderVariable ID3DX11EffectShaderVariable; +typedef interface ID3DX11EffectShaderVariable *LPD3D11EFFECTSHADERVARIABLE; + +// {7508B344-020A-4EC7-9118-62CDD36C88D7} +DEFINE_GUID(IID_ID3DX11EffectShaderVariable, + 0x7508b344, 0x020a, 0x4ec7, 0x91, 0x18, 0x62, 0xcd, 0xd3, 0x6c, 0x88, 0xd7); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectShaderVariable + +DECLARE_INTERFACE_(ID3DX11EffectShaderVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetShaderDesc)(THIS_ UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc) PURE; + + STDMETHOD(GetVertexShader)(THIS_ UINT ShaderIndex, ID3D11VertexShader **ppVS) PURE; + STDMETHOD(GetGeometryShader)(THIS_ UINT ShaderIndex, ID3D11GeometryShader **ppGS) PURE; + STDMETHOD(GetPixelShader)(THIS_ UINT ShaderIndex, ID3D11PixelShader **ppPS) PURE; + STDMETHOD(GetHullShader)(THIS_ UINT ShaderIndex, ID3D11HullShader **ppPS) PURE; + STDMETHOD(GetDomainShader)(THIS_ UINT ShaderIndex, ID3D11DomainShader **ppPS) PURE; + STDMETHOD(GetComputeShader)(THIS_ UINT ShaderIndex, ID3D11ComputeShader **ppPS) PURE; + + STDMETHOD(GetInputSignatureElementDesc)(THIS_ UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetOutputSignatureElementDesc)(THIS_ UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetPatchConstantSignatureElementDesc)(THIS_ UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectBlendVariable ///////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectBlendVariable ID3DX11EffectBlendVariable; +typedef interface ID3DX11EffectBlendVariable *LPD3D11EFFECTBLENDVARIABLE; + +// {D664F4D7-3B81-4805-B277-C1DF58C39F53} +DEFINE_GUID(IID_ID3DX11EffectBlendVariable, + 0xd664f4d7, 0x3b81, 0x4805, 0xb2, 0x77, 0xc1, 0xdf, 0x58, 0xc3, 0x9f, 0x53); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectBlendVariable + +DECLARE_INTERFACE_(ID3DX11EffectBlendVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetBlendState)(THIS_ UINT Index, ID3D11BlendState **ppBlendState) PURE; + STDMETHOD(SetBlendState)(THIS_ UINT Index, ID3D11BlendState *pBlendState) PURE; + STDMETHOD(UndoSetBlendState)(THIS_ UINT Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ UINT Index, D3D11_BLEND_DESC *pBlendDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectDepthStencilVariable ////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectDepthStencilVariable ID3DX11EffectDepthStencilVariable; +typedef interface ID3DX11EffectDepthStencilVariable *LPD3D11EFFECTDEPTHSTENCILVARIABLE; + +// {69B5751B-61A5-48E5-BD41-D93988111563} +DEFINE_GUID(IID_ID3DX11EffectDepthStencilVariable, + 0x69b5751b, 0x61a5, 0x48e5, 0xbd, 0x41, 0xd9, 0x39, 0x88, 0x11, 0x15, 0x63); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectDepthStencilVariable + +DECLARE_INTERFACE_(ID3DX11EffectDepthStencilVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetDepthStencilState)(THIS_ UINT Index, ID3D11DepthStencilState **ppDepthStencilState) PURE; + STDMETHOD(SetDepthStencilState)(THIS_ UINT Index, ID3D11DepthStencilState *pDepthStencilState) PURE; + STDMETHOD(UndoSetDepthStencilState)(THIS_ UINT Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ UINT Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectRasterizerVariable //////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectRasterizerVariable ID3DX11EffectRasterizerVariable; +typedef interface ID3DX11EffectRasterizerVariable *LPD3D11EFFECTRASTERIZERVARIABLE; + +// {53A262F6-5F74-4151-A132-E3DD19A62C9D} +DEFINE_GUID(IID_ID3DX11EffectRasterizerVariable, + 0x53a262f6, 0x5f74, 0x4151, 0xa1, 0x32, 0xe3, 0xdd, 0x19, 0xa6, 0x2c, 0x9d); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectRasterizerVariable + +DECLARE_INTERFACE_(ID3DX11EffectRasterizerVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetRasterizerState)(THIS_ UINT Index, ID3D11RasterizerState **ppRasterizerState) PURE; + STDMETHOD(SetRasterizerState)(THIS_ UINT Index, ID3D11RasterizerState *pRasterizerState) PURE; + STDMETHOD(UndoSetRasterizerState)(THIS_ UINT Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ UINT Index, D3D11_RASTERIZER_DESC *pRasterizerDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectSamplerVariable /////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3DX11EffectSamplerVariable ID3DX11EffectSamplerVariable; +typedef interface ID3DX11EffectSamplerVariable *LPD3D11EFFECTSAMPLERVARIABLE; + +// {C6402E55-1095-4D95-8931-F92660513DD9} +DEFINE_GUID(IID_ID3DX11EffectSamplerVariable, + 0xc6402e55, 0x1095, 0x4d95, 0x89, 0x31, 0xf9, 0x26, 0x60, 0x51, 0x3d, 0xd9); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectSamplerVariable + +DECLARE_INTERFACE_(ID3DX11EffectSamplerVariable, ID3DX11EffectVariable) +{ + STDMETHOD_(ID3DX11EffectType*, GetType)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetElement)(THIS_ UINT Index) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)(THIS) PURE; + + STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(THIS) PURE; + STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(THIS) PURE; + STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(THIS) PURE; + STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(THIS) PURE; + STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(THIS) PURE; + STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(THIS) PURE; + STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(THIS) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(THIS) PURE; + STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(THIS) PURE; + STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(THIS) PURE; + STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(THIS) PURE; + STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(THIS) PURE; + + STDMETHOD(SetRawValue)(THIS_ CONST void *pData, UINT Offset, UINT Count) PURE; + STDMETHOD(GetRawValue)(THIS_ void *pData, UINT Offset, UINT Count) PURE; + + STDMETHOD(GetSampler)(THIS_ UINT Index, ID3D11SamplerState **ppSampler) PURE; + STDMETHOD(SetSampler)(THIS_ UINT Index, ID3D11SamplerState *pSampler) PURE; + STDMETHOD(UndoSetSampler)(THIS_ UINT Index) PURE; + STDMETHOD(GetBackingStore)(THIS_ UINT Index, D3D11_SAMPLER_DESC *pSamplerDesc) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectPass ////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_PASS_DESC: +// +// Retrieved by ID3DX11EffectPass::GetDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_PASS_DESC +{ + LPCSTR Name; // Name of this pass (NULL if not anonymous) + UINT Annotations; // Number of annotations on this pass + + BYTE *pIAInputSignature; // Signature from VS or GS (if there is no VS) + // or NULL if neither exists + SIZE_T IAInputSignatureSize; // Singature size in bytes + + UINT StencilRef; // Specified in SetDepthStencilState() + UINT SampleMask; // Specified in SetBlendState() + FLOAT BlendFactor[4]; // Specified in SetBlendState() +} D3DX11_PASS_DESC; + +//---------------------------------------------------------------------------- +// D3DX11_PASS_SHADER_DESC: +// +// Retrieved by ID3DX11EffectPass::Get**ShaderDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_PASS_SHADER_DESC +{ + ID3DX11EffectShaderVariable *pShaderVariable; // The variable that this shader came from. + // If this is an inline shader assignment, + // the returned interface will be an + // anonymous shader variable, which is + // not retrievable any other way. It's + // name in the variable description will + // be "$Anonymous". + // If there is no assignment of this type in + // the pass block, pShaderVariable != NULL, + // but pShaderVariable->IsValid() == FALSE. + + UINT ShaderIndex; // The element of pShaderVariable (if an array) + // or 0 if not applicable +} D3DX11_PASS_SHADER_DESC; + +typedef interface ID3DX11EffectPass ID3DX11EffectPass; +typedef interface ID3DX11EffectPass *LPD3D11EFFECTPASS; + +// {3437CEC4-4AC1-4D87-8916-F4BD5A41380C} +DEFINE_GUID(IID_ID3DX11EffectPass, + 0x3437cec4, 0x4ac1, 0x4d87, 0x89, 0x16, 0xf4, 0xbd, 0x5a, 0x41, 0x38, 0x0c); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectPass + +DECLARE_INTERFACE(ID3DX11EffectPass) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_PASS_DESC *pDesc) PURE; + + STDMETHOD(GetVertexShaderDesc)(THIS_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetGeometryShaderDesc)(THIS_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetPixelShaderDesc)(THIS_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetHullShaderDesc)(THIS_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetDomainShaderDesc)(THIS_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + STDMETHOD(GetComputeShaderDesc)(THIS_ D3DX11_PASS_SHADER_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD(Apply)(THIS_ UINT Flags, ID3D11DeviceContext* pContext) PURE; + + STDMETHOD(ComputeStateBlockMask)(THIS_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectTechnique ///////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_TECHNIQUE_DESC: +// +// Retrieved by ID3DX11EffectTechnique::GetDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_TECHNIQUE_DESC +{ + LPCSTR Name; // Name of this technique (NULL if not anonymous) + UINT Passes; // Number of passes contained within + UINT Annotations; // Number of annotations on this technique +} D3DX11_TECHNIQUE_DESC; + +typedef interface ID3DX11EffectTechnique ID3DX11EffectTechnique; +typedef interface ID3DX11EffectTechnique *LPD3D11EFFECTTECHNIQUE; + +// {51198831-1F1D-4F47-BD76-41CB0835B1DE} +DEFINE_GUID(IID_ID3DX11EffectTechnique, + 0x51198831, 0x1f1d, 0x4f47, 0xbd, 0x76, 0x41, 0xcb, 0x08, 0x35, 0xb1, 0xde); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectTechnique + +DECLARE_INTERFACE(ID3DX11EffectTechnique) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_TECHNIQUE_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectPass*, GetPassByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectPass*, GetPassByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD(ComputeStateBlockMask)(THIS_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11EffectTechnique ///////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_GROUP_DESC: +// +// Retrieved by ID3DX11EffectTechnique::GetDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_GROUP_DESC +{ + LPCSTR Name; // Name of this group (only NULL if global) + UINT Techniques; // Number of techniques contained within + UINT Annotations; // Number of annotations on this group +} D3DX11_GROUP_DESC; + +typedef interface ID3DX11EffectGroup ID3DX11EffectGroup; +typedef interface ID3DX11EffectGroup *LPD3D11EFFECTGROUP; + +// {03074acf-97de-485f-b201-cb775264afd6} +DEFINE_GUID(IID_ID3DX11EffectGroup, + 0x03074acf, 0x97de, 0x485f, 0xb2, 0x01, 0xcb, 0x77, 0x52, 0x64, 0xaf, 0xd6); + +#undef INTERFACE +#define INTERFACE ID3DX11EffectGroup + +DECLARE_INTERFACE(ID3DX11EffectGroup) +{ + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + STDMETHOD(GetDesc)(THIS_ D3DX11_GROUP_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(THIS_ LPCSTR Name) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// ID3DX11Effect ////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// D3DX11_EFFECT_DESC: +// +// Retrieved by ID3DX11Effect::GetDesc() +//---------------------------------------------------------------------------- + +typedef struct _D3DX11_EFFECT_DESC +{ + UINT ConstantBuffers; // Number of constant buffers in this effect + UINT GlobalVariables; // Number of global variables in this effect + UINT InterfaceVariables; // Number of global interfaces in this effect + UINT Techniques; // Number of techniques in this effect + UINT Groups; // Number of groups in this effect +} D3DX11_EFFECT_DESC; + +typedef interface ID3DX11Effect ID3DX11Effect; +typedef interface ID3DX11Effect *LPD3D11EFFECT; + +// {FA61CA24-E4BA-4262-9DB8-B132E8CAE319} +DEFINE_GUID(IID_ID3DX11Effect, + 0xfa61ca24, 0xe4ba, 0x4262, 0x9d, 0xb8, 0xb1, 0x32, 0xe8, 0xca, 0xe3, 0x19); + +#undef INTERFACE +#define INTERFACE ID3DX11Effect + +DECLARE_INTERFACE_(ID3DX11Effect, IUnknown) +{ + // IUnknown + STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE; + STDMETHOD_(ULONG, AddRef)(THIS) PURE; + STDMETHOD_(ULONG, Release)(THIS) PURE; + + STDMETHOD_(BOOL, IsValid)(THIS) PURE; + + // Managing D3D Device + STDMETHOD(GetDevice)(THIS_ ID3D11Device** ppDevice) PURE; + + // New Reflection APIs + STDMETHOD(GetDesc)(THIS_ D3DX11_EFFECT_DESC *pDesc) PURE; + + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectConstantBuffer*, GetConstantBufferByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectVariable*, GetVariableByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetVariableByName)(THIS_ LPCSTR Name) PURE; + STDMETHOD_(ID3DX11EffectVariable*, GetVariableBySemantic)(THIS_ LPCSTR Semantic) PURE; + + STDMETHOD_(ID3DX11EffectGroup*, GetGroupByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectGroup*, GetGroupByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(THIS_ UINT Index) PURE; + STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(THIS_ LPCSTR Name) PURE; + + STDMETHOD_(ID3D11ClassLinkage*, GetClassLinkage)(THIS) PURE; + + STDMETHOD(CloneEffect)(THIS_ UINT Flags, ID3DX11Effect** ppClonedEffect ) PURE; + STDMETHOD(Optimize)(THIS) PURE; + STDMETHOD_(BOOL, IsOptimized)(THIS) PURE; +}; + +////////////////////////////////////////////////////////////////////////////// +// APIs ////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + +//---------------------------------------------------------------------------- +// D3DX11CreateEffectFromMemory: +// -------------------------- +// Creates an effect from a binary effect or file +// +// Parameters: +// +// [in] +// +// +// pData +// Blob of compiled effect data +// DataLength +// Length of the data blob +// FXFlags +// Compilation flags pertaining to Effect compilation, honored +// by the Effect compiler +// pDevice +// Pointer to the D3D11 device on which to create Effect resources +// +// [out] +// +// ppEffect +// Address of the newly created Effect interface +// +//---------------------------------------------------------------------------- + +HRESULT WINAPI D3DX11CreateEffectFromMemory(CONST void *pData, SIZE_T DataLength, UINT FXFlags, ID3D11Device *pDevice, ID3DX11Effect **ppEffect); + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif //__D3DX11EFFECT_H__ + diff --git a/sample/d3d11/Effects11/Inc/d3dxGlobal.h b/sample/d3d11/Effects11/Inc/d3dxGlobal.h new file mode 100644 index 0000000..3b5cdf8 --- /dev/null +++ b/sample/d3d11/Effects11/Inc/d3dxGlobal.h @@ -0,0 +1,1337 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: D3DXGlobal.h +// Content: D3DX11 Effects helper defines and data structures +// +////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#pragma warning(disable : 4100 4127 4189 4201 4245 4389 4505 4701 4706) + +namespace D3DX11Debug +{ +} + +using namespace D3DX11Debug; + +#include "d3dx11dbg.h" + +#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } } +#define SAFE_ADDREF(p) { if (p) { (p)->AddRef(); } } + +#define SAFE_DELETE_ARRAY(p) { delete [](p); p = NULL; } +#define SAFE_DELETE(p) { delete (p); p = NULL; } + +#if FXDEBUG +#define __BREAK_ON_FAIL { __debugbreak(); } +#else +#define __BREAK_ON_FAIL +#endif + +#define VA(x, action) { hr = (x); if (FAILED(hr)) { action; __BREAK_ON_FAIL; return hr; } } +#define VNA(x,action) { if (!(x)) { action; __BREAK_ON_FAIL; hr = E_OUTOFMEMORY; goto lExit; } } +#define VBA(x,action) { if (!(x)) { action; __BREAK_ON_FAIL; hr = E_FAIL; goto lExit; } } +#define VHA(x,action) { hr = (x); if (FAILED(hr)) { action; __BREAK_ON_FAIL; goto lExit; } } + +#define V(x) { VA (x, 0) } +#define VN(x) { VNA(x, 0) } +#define VB(x) { VBA(x, 0) } +#define VH(x) { VHA(x, 0) } + +#define VBD(x,str) { VBA(x, DPF(1,str)) } +#define VHD(x,str) { VHA(x, DPF(1,str)) } + +#define VEASSERT(x) { hr = (x); if (FAILED(hr)) { __BREAK_ON_FAIL; D3DXASSERT(!#x); goto lExit; } } +#define VNASSERT(x) { if (!(x)) { __BREAK_ON_FAIL; D3DXASSERT(!#x); hr = E_OUTOFMEMORY; goto lExit; } } + +#define ANALYSIS_ASSUME(x) { D3DXASSERT(x); __analysis_assume(x); __assume(x); } + +#define D3DX11FLTASSIGN(a,b) { *reinterpret_cast< UINT32* >(&(a)) = *reinterpret_cast< UINT32* >(&(b)); } + +// Preferred data alignment -- must be a power of 2! +static const UINT c_DataAlignment = sizeof(UINT_PTR); + +D3DX11INLINE UINT AlignToPowerOf2(UINT Value, UINT Alignment) +{ + D3DXASSERT((Alignment & (Alignment - 1)) == 0); + // to align to 2^N, add 2^N - 1 and AND with all but lowest N bits set + ANALYSIS_ASSUME(Alignment > 0 && Value < MAXDWORD - Alignment); + return (Value + Alignment - 1) & (~(Alignment - 1)); +} + +D3DX11INLINE void * AlignToPowerOf2(void *pValue, UINT_PTR Alignment) +{ + D3DXASSERT((Alignment & (Alignment - 1)) == 0); + // to align to 2^N, add 2^N - 1 and AND with all but lowest N bits set + return (void *)(((UINT_PTR)pValue + Alignment - 1) & (~((UINT_PTR)Alignment - 1))); +} + + +// Fast memcpy +D3DX11INLINE void dwordMemcpy( __out_bcount(uByteCount) void * __restrict pDest, __in_bcount(uByteCount) CONST void * __restrict pSource, UINT uByteCount) +{ + UINT i; + D3DXASSERT(uByteCount % 4 == 0); +#ifdef _AMD64_ + const UINT qwordCount = uByteCount >> 3; + + __int64* src64 = (__int64*) pSource; + __int64* dst64 = (__int64*) pDest; + + for (i=0; i<(qwordCount & 0x3); i++) + { + *(dst64) = *(src64); + dst64++; + src64++; + } + + for (; i<qwordCount; i+= 4) + { + *(dst64 ) = *(src64 ); + *(dst64 + 1 ) = *(src64 + 1 ); + *(dst64 + 2 ) = *(src64 + 2 ); + *(dst64 + 3 ) = *(src64 + 3 ); + dst64 += 4; + src64 += 4; + } + + ANALYSIS_ASSUME( dst64 - static_cast< __int64* >(pDest) <= uByteCount - 4 ); + ANALYSIS_ASSUME( src64 - static_cast< const __int64* >(pSource) <= uByteCount - 4 ); + if( uByteCount & 0x4 ) + { + *((UINT*)dst64) = *((UINT*)src64); + } +#else + const UINT dwordCount = uByteCount >> 2; + + for (i=0; i<(dwordCount & 0x3); i++) + { +#pragma prefast(suppress: __WARNING_UNRELATED_LOOP_TERMINATION, "(dwordCount & 03) < dwordCount") + ((UINT*)pDest)[i ] = ((UINT*)pSource)[i ]; + } + for (; i<dwordCount; i+= 4) + { + ((UINT*)pDest)[i ] = ((UINT*)pSource)[i ]; + ((UINT*)pDest)[i+1] = ((UINT*)pSource)[i+1]; + ((UINT*)pDest)[i+2] = ((UINT*)pSource)[i+2]; + ((UINT*)pDest)[i+3] = ((UINT*)pSource)[i+3]; + } +#endif +} + + +namespace D3DX11Core +{ + +////////////////////////////////////////////////////////////////////////// +// CMemoryStream - A class to simplify reading binary data +////////////////////////////////////////////////////////////////////////// +class CMemoryStream +{ + BYTE *m_pData; + SIZE_T m_cbData; + SIZE_T m_readPtr; + +public: + HRESULT SetData(const void *pData, SIZE_T size); + + HRESULT Read(UINT *pUint); + HRESULT Read(void **ppData, SIZE_T size); + HRESULT Read(LPCSTR *ppString); + + HRESULT ReadAtOffset(SIZE_T offset, SIZE_T size, void **ppData); + HRESULT ReadAtOffset(SIZE_T offset, LPCSTR *ppString); + + SIZE_T GetPosition(); + HRESULT Seek(SIZE_T offset); + + CMemoryStream(); + ~CMemoryStream(); +}; + +} + +#if FXDEBUG + +namespace D3DX11Debug +{ + +// This variable indicates how many ticks to go before rolling over +// all of the timer variables in the FX system. +// It is read from the system registry in debug builds; in retail the high bit is simply tested. + +_declspec(selectany) unsigned int g_TimerRolloverCount = 0x80000000; +} + +#endif // FXDEBUG + + +////////////////////////////////////////////////////////////////////////// +// CEffectVector - A vector implementation +////////////////////////////////////////////////////////////////////////// + +template<class T> class CEffectVector +{ +protected: +#if _DEBUG + T *m_pCastData; // makes debugging easier to have a casted version of the data +#endif // _DEBUG + + BYTE *m_pData; + UINT m_MaxSize; + UINT m_CurSize; + + HRESULT Grow() + { + return Reserve(m_CurSize + 1); + } + + HRESULT Reserve(UINT DesiredSize) + { + if (DesiredSize > m_MaxSize) + { + BYTE *pNewData; + UINT newSize = max(m_MaxSize * 2, DesiredSize); + + if (newSize < 16) + newSize = 16; + + if ((newSize < m_MaxSize) || (newSize < m_CurSize) || (newSize >= UINT_MAX / sizeof(T))) + { + m_hLastError = E_OUTOFMEMORY; + return m_hLastError; + } + + pNewData = NEW BYTE[newSize * sizeof(T)]; + if (pNewData == NULL) + { + m_hLastError = E_OUTOFMEMORY; + return m_hLastError; + } + + if (m_pData) + { + memcpy(pNewData, m_pData, m_CurSize * sizeof(T)); + delete []m_pData; + } + + m_pData = pNewData; + m_MaxSize = newSize; + } +#if _DEBUG + m_pCastData = (T*) m_pData; +#endif // _DEBUG + return S_OK; + } + +public: + HRESULT m_hLastError; + + CEffectVector<T>() + { + m_hLastError = S_OK; +#if _DEBUG + m_pCastData = NULL; +#endif // _DEBUG + m_pData = NULL; + m_CurSize = m_MaxSize = 0; + } + + ~CEffectVector<T>() + { + Clear(); + } + + // cleanly swaps two vectors -- useful for when you want + // to reallocate a vector and copy data over, then swap them back + void SwapVector(CEffectVector<T> &vOther) + { + BYTE tempData[sizeof(*this)]; + + memcpy(tempData, this, sizeof(*this)); + memcpy(this, &vOther, sizeof(*this)); + memcpy(&vOther, tempData, sizeof(*this)); + } + + HRESULT CopyFrom(CEffectVector<T> &vOther) + { + HRESULT hr = S_OK; + Clear(); + VN( m_pData = NEW BYTE[vOther.m_MaxSize * sizeof(T)] ); + + m_CurSize = vOther.m_CurSize; + m_MaxSize = vOther.m_MaxSize; + m_hLastError = vOther.m_hLastError; + + UINT i; + for (i = 0; i < m_CurSize; ++ i) + { + ((T*)m_pData)[i] = ((T*)vOther.m_pData)[i]; + } + +lExit: + +#if _DEBUG + m_pCastData = (T*) m_pData; +#endif // _DEBUG + + return hr; + } + + void Clear() + { + Empty(); + SAFE_DELETE_ARRAY(m_pData); + m_MaxSize = 0; +#if _DEBUG + m_pCastData = NULL; +#endif // _DEBUG + } + + void ClearWithoutDestructor() + { + m_CurSize = 0; + m_hLastError = S_OK; + SAFE_DELETE_ARRAY(m_pData); + m_MaxSize = 0; + +#if _DEBUG + m_pCastData = NULL; +#endif // _DEBUG + } + + void Empty() + { + UINT i; + + // manually invoke destructor on all elements + for (i = 0; i < m_CurSize; ++ i) + { + ((T*)m_pData + i)->~T(); + } + m_CurSize = 0; + m_hLastError = S_OK; + } + + T* Add() + { + if (FAILED(Grow())) + return NULL; + + // placement new + return new((T*)m_pData + (m_CurSize ++)) T; + } + + T* AddRange(UINT count) + { + if (m_CurSize + count < m_CurSize) + { + m_hLastError = E_OUTOFMEMORY; + return NULL; + } + + if (FAILED(Reserve(m_CurSize + count))) + return NULL; + + T *pData = (T*)m_pData + m_CurSize; + UINT i; + for (i = 0; i < count; ++ i) + { + new(pData + i) T; + } + m_CurSize += count; + return pData; + } + + HRESULT Add(const T& var) + { + if (FAILED(Grow())) + return m_hLastError; + + memcpy((T*)m_pData + m_CurSize, &var, sizeof(T)); + m_CurSize++; + + return S_OK; + } + + HRESULT AddRange(const T *pVar, UINT count) + { + if (m_CurSize + count < m_CurSize) + { + m_hLastError = E_OUTOFMEMORY; + return m_hLastError; + } + + if (FAILED(Reserve(m_CurSize + count))) + return m_hLastError; + + memcpy((T*)m_pData + m_CurSize, pVar, count * sizeof(T)); + m_CurSize += count; + + return S_OK; + } + + HRESULT Insert(const T& var, UINT index) + { + D3DXASSERT(index < m_CurSize); + + if (FAILED(Grow())) + return m_hLastError; + + memmove((T*)m_pData + index + 1, (T*)m_pData + index, (m_CurSize - index) * sizeof(T)); + memcpy((T*)m_pData + index, &var, sizeof(T)); + m_CurSize++; + + return S_OK; + } + + HRESULT InsertRange(const T *pVar, UINT index, UINT count) + { + D3DXASSERT(index < m_CurSize); + + if (m_CurSize + count < m_CurSize) + { + m_hLastError = E_OUTOFMEMORY; + return m_hLastError; + } + + if (FAILED(Reserve(m_CurSize + count))) + return m_hLastError; + + memmove((T*)m_pData + index + count, (T*)m_pData + index, (m_CurSize - index) * sizeof(T)); + memcpy((T*)m_pData + index, pVar, count * sizeof(T)); + m_CurSize += count; + + return S_OK; + } + + inline T& operator[](UINT index) + { + D3DXASSERT(index < m_CurSize); + return ((T*)m_pData)[index]; + } + + // Deletes element at index and shifts all other values down + void Delete(UINT index) + { + D3DXASSERT(index < m_CurSize); + + -- m_CurSize; + memmove((T*)m_pData + index, (T*)m_pData + index + 1, (m_CurSize - index) * sizeof(T)); + } + + // Deletes element at index and moves the last element into its place + void QuickDelete(UINT index) + { + D3DXASSERT(index < m_CurSize); + + -- m_CurSize; + memcpy((T*)m_pData + index, (T*)m_pData + m_CurSize, sizeof(T)); + } + + inline UINT GetSize() const + { + return m_CurSize; + } + + inline T* GetData() const + { + return (T*)m_pData; + } + + UINT FindIndexOf(void *pEntry) const + { + UINT i; + + for (i = 0; i < m_CurSize; ++ i) + { + if (((T*)m_pData + i) == pEntry) + return i; + } + + return -1; + } + + void Sort(int (__cdecl *pfnCompare)(const void *pElem1, const void *pElem2)) + { + qsort(m_pData, m_CurSize, sizeof(T), pfnCompare); + } +}; + +////////////////////////////////////////////////////////////////////////// +// CEffectVectorOwner - implements a vector of ptrs to objects. The vector owns the objects. +////////////////////////////////////////////////////////////////////////// +template<class T> class CEffectVectorOwner : public CEffectVector<T*> +{ +public: + ~CEffectVectorOwner<T>() + { + Clear(); + UINT i; + + for (i=0; i<m_CurSize; i++) + SAFE_DELETE(((T**)m_pData)[i]); + + SAFE_DELETE_ARRAY(m_pData); + } + + void Clear() + { + Empty(); + SAFE_DELETE_ARRAY(m_pData); + m_MaxSize = 0; + } + + void Empty() + { + UINT i; + + // manually invoke destructor on all elements + for (i = 0; i < m_CurSize; ++ i) + { + SAFE_DELETE(((T**)m_pData)[i]); + } + m_CurSize = 0; + m_hLastError = S_OK; + } + + void Delete(UINT index) + { + D3DXASSERT(index < m_CurSize); + + SAFE_DELETE(((T**)m_pData)[index]); + + CEffectVector<T*>::Delete(index); + } +}; + + +////////////////////////////////////////////////////////////////////////// +// Checked UINT, DWORD64 +// Use CheckedNumber only with UINT and DWORD64 +////////////////////////////////////////////////////////////////////////// +template <class T, T MaxValue> class CheckedNumber +{ + T m_Value; + BOOL m_bValid; + +public: + CheckedNumber<T, MaxValue>() + { + m_Value = 0; + m_bValid = TRUE; + } + + CheckedNumber<T, MaxValue>(const T &value) + { + m_Value = value; + m_bValid = TRUE; + } + + CheckedNumber<T, MaxValue>(const CheckedNumber<T, MaxValue> &value) + { + m_bValid = value.m_bValid; + m_Value = value.m_Value; + } + + CheckedNumber<T, MaxValue> &operator+(const CheckedNumber<T, MaxValue> &other) + { + CheckedNumber<T, MaxValue> Res(*this); + return Res+=other; + } + + CheckedNumber<T, MaxValue> &operator+=(const CheckedNumber<T, MaxValue> &other) + { + if (!other.m_bValid) + { + m_bValid = FALSE; + } + else + { + m_Value += other.m_Value; + + if (m_Value < other.m_Value) + m_bValid = FALSE; + } + + return *this; + } + + CheckedNumber<T, MaxValue> &operator*(const CheckedNumber<T, MaxValue> &other) + { + CheckedNumber<T, MaxValue> Res(*this); + return Res*=other; + } + + CheckedNumber<T, MaxValue> &operator*=(const CheckedNumber<T, MaxValue> &other) + { + if (!other.m_bValid) + { + m_bValid = FALSE; + } + else + { + if (other.m_Value != 0) + { + if (m_Value > MaxValue / other.m_Value) + { + m_bValid = FALSE; + } + } + m_Value *= other.m_Value; + } + + return *this; + } + + HRESULT GetValue(T *pValue) + { + if (!m_bValid) + { + *pValue = -1; + return E_FAIL; + } + + *pValue = m_Value; + return S_OK; + } +}; + +typedef CheckedNumber<UINT, _UI32_MAX> CCheckedDword; +typedef CheckedNumber<DWORD64, _UI64_MAX> CCheckedDword64; + + +////////////////////////////////////////////////////////////////////////// +// Data Block Store - A linked list of allocations +////////////////////////////////////////////////////////////////////////// + +class CDataBlock +{ +protected: + UINT m_size; + UINT m_maxSize; + BYTE *m_pData; + CDataBlock *m_pNext; + + BOOL m_IsAligned; // Whether or not to align the data to c_DataAlignment + +public: + // AddData appends an existing use buffer to the data block + HRESULT AddData(const void *pNewData, UINT bufferSize, CDataBlock **ppBlock); + + // Allocate reserves bufferSize bytes of contiguous memory and returns a pointer to the user + void* Allocate(UINT bufferSize, CDataBlock **ppBlock); + + void EnableAlignment(); + + CDataBlock(); + ~CDataBlock(); + + friend class CDataBlockStore; +}; + + +class CDataBlockStore +{ +protected: + CDataBlock *m_pFirst; + CDataBlock *m_pLast; + UINT m_Size; + UINT m_Offset; // m_Offset gets added to offsets returned from AddData & AddString. Use this to set a global for the entire string block + BOOL m_IsAligned; // Whether or not to align the data to c_DataAlignment + +public: +#if _DEBUG + UINT m_cAllocations; +#endif + +public: + HRESULT AddString(LPCSTR pString, UINT *pOffset); // Writes a null-terminated string to buffer + HRESULT AddData(const void *pNewData, UINT bufferSize, UINT *pOffset); // Writes data block to buffer + + void* Allocate(UINT buffferSize); // Memory allocator support + UINT GetSize(); + void EnableAlignment(); + + CDataBlockStore(); + ~CDataBlockStore(); +}; + +// Custom allocator that uses CDataBlockStore +// The trick is that we never free, so we don't have to keep as much state around +// Use PRIVATENEW in CEffectLoader + +static void* __cdecl operator new(size_t s, CDataBlockStore &pAllocator) +{ + D3DXASSERT( s <= 0xffffffff ); + return pAllocator.Allocate( (UINT)s ); +} + +static void __cdecl operator delete(void* p, CDataBlockStore &pAllocator) +{ +} + + +////////////////////////////////////////////////////////////////////////// +// Hash table +////////////////////////////////////////////////////////////////////////// + +#define HASH_MIX(a,b,c) \ +{ \ + a -= b; a -= c; a ^= (c>>13); \ + b -= c; b -= a; b ^= (a<<8); \ + c -= a; c -= b; c ^= (b>>13); \ + a -= b; a -= c; a ^= (c>>12); \ + b -= c; b -= a; b ^= (a<<16); \ + c -= a; c -= b; c ^= (b>>5); \ + a -= b; a -= c; a ^= (c>>3); \ + b -= c; b -= a; b ^= (a<<10); \ + c -= a; c -= b; c ^= (b>>15); \ +} + +static UINT ComputeHash(BYTE *pb, UINT cbToHash) +{ + UINT a; + UINT b; + UINT c; + UINT cbLeft; + + cbLeft = cbToHash; + + a = b = 0x9e3779b9; // the golden ratio; an arbitrary value + c = 0; + + while (cbLeft >= 12) + { + UINT *pdw = reinterpret_cast<UINT *>(pb); + + a += pdw[0]; + b += pdw[1]; + c += pdw[2]; + + HASH_MIX(a,b,c); + pb += 12; + cbLeft -= 12; + } + + c += cbToHash; + + switch(cbLeft) // all the case statements fall through + { + case 11: c+=((UINT) pb[10] << 24); + case 10: c+=((UINT) pb[9] << 16); + case 9 : c+=((UINT) pb[8] << 8); + // the first byte of c is reserved for the length + case 8 : b+=((UINT) pb[7] << 24); + case 7 : b+=((UINT) pb[6] << 16); + case 6 : b+=((UINT) pb[5] << 8); + case 5 : b+=pb[4]; + case 4 : a+=((UINT) pb[3] << 24); + case 3 : a+=((UINT) pb[2] << 16); + case 2 : a+=((UINT) pb[1] << 8); + case 1 : a+=pb[0]; + } + + HASH_MIX(a,b,c); + + return c; +} + +static UINT ComputeHashLower(BYTE *pb, UINT cbToHash) +{ + UINT a; + UINT b; + UINT c; + UINT cbLeft; + + cbLeft = cbToHash; + + a = b = 0x9e3779b9; // the golden ratio; an arbitrary value + c = 0; + + while (cbLeft >= 12) + { + BYTE pbT[12]; + for( UINT i = 0; i < 12; i++ ) + pbT[i] = (BYTE)tolower(pb[i]); + + UINT *pdw = reinterpret_cast<UINT *>(pbT); + + a += pdw[0]; + b += pdw[1]; + c += pdw[2]; + + HASH_MIX(a,b,c); + pb += 12; + cbLeft -= 12; + } + + c += cbToHash; + + BYTE pbT[12]; + for( UINT i = 0; i < cbLeft; i++ ) + pbT[i] = (BYTE)tolower(pb[i]); + + switch(cbLeft) // all the case statements fall through + { + case 11: c+=((UINT) pbT[10] << 24); + case 10: c+=((UINT) pbT[9] << 16); + case 9 : c+=((UINT) pbT[8] << 8); + // the first byte of c is reserved for the length + case 8 : b+=((UINT) pbT[7] << 24); + case 7 : b+=((UINT) pbT[6] << 16); + case 6 : b+=((UINT) pbT[5] << 8); + case 5 : b+=pbT[4]; + case 4 : a+=((UINT) pbT[3] << 24); + case 3 : a+=((UINT) pbT[2] << 16); + case 2 : a+=((UINT) pbT[1] << 8); + case 1 : a+=pbT[0]; + } + + HASH_MIX(a,b,c); + + return c; +} + + +static UINT ComputeHash(LPCSTR pString) +{ + return ComputeHash((BYTE*) pString, (UINT)strlen(pString)); +} + + +// 1) these numbers are prime +// 2) each is slightly less than double the last +// 4) each is roughly in between two powers of 2; +// (2^n hash table sizes are VERY BAD; they effectively truncate your +// precision down to the n least significant bits of the hash) +static const UINT c_PrimeSizes[] = +{ + 11, + 23, + 53, + 97, + 193, + 389, + 769, + 1543, + 3079, + 6151, + 12289, + 24593, + 49157, + 98317, + 196613, + 393241, + 786433, + 1572869, + 3145739, + 6291469, + 12582917, + 25165843, + 50331653, + 100663319, + 201326611, + 402653189, + 805306457, + 1610612741, +}; + +static const UINT c_NumPrimes = sizeof(c_PrimeSizes) / sizeof(UINT); + +template<typename T, BOOL (*pfnIsEqual)(const T &Data1, const T &Data2)> +class CEffectHashTable +{ +protected: + + struct SHashEntry + { + UINT Hash; + T Data; + SHashEntry *pNext; + }; + + // Array of hash entries + SHashEntry **m_rgpHashEntries; + UINT m_NumHashSlots; + UINT m_NumEntries; + bool m_bOwnHashEntryArray; + +public: + class CIterator + { + friend class CEffectHashTable; + + protected: + SHashEntry **ppHashSlot; + SHashEntry *pHashEntry; + + public: + T GetData() + { + D3DXASSERT(NULL != pHashEntry); + return pHashEntry->Data; + } + + UINT GetHash() + { + D3DXASSERT(NULL != pHashEntry); + return pHashEntry->Hash; + } + }; + + CEffectHashTable() + { + m_rgpHashEntries = NULL; + m_NumHashSlots = 0; + m_NumEntries = 0; + m_bOwnHashEntryArray = false; + } + + HRESULT Initialize(CEffectHashTable *pOther) + { + HRESULT hr = S_OK; + SHashEntry **rgpNewHashEntries = NULL; + SHashEntry ***rgppListEnds = NULL; + UINT i; + UINT valuesMigrated = 0; + UINT actualSize; + + Cleanup(); + + actualSize = pOther->m_NumHashSlots; + VN( rgpNewHashEntries = NEW SHashEntry*[actualSize] ); + + ZeroMemory(rgpNewHashEntries, sizeof(SHashEntry*) * actualSize); + + // Expensive operation: rebuild the hash table + CIterator iter, nextIter; + pOther->GetFirstEntry(&iter); + while (!pOther->PastEnd(&iter)) + { + UINT index = iter.GetHash() % actualSize; + + // we need to advance to the next element + // before we seize control of this element and move + // it to the new table + nextIter = iter; + pOther->GetNextEntry(&nextIter); + + // seize this hash entry, migrate it to the new table + SHashEntry *pNewEntry; + VN( pNewEntry = NEW SHashEntry ); + + pNewEntry->pNext = rgpNewHashEntries[index]; + pNewEntry->Data = iter.pHashEntry->Data; + pNewEntry->Hash = iter.pHashEntry->Hash; + rgpNewHashEntries[index] = pNewEntry; + + iter = nextIter; + ++ valuesMigrated; + } + + D3DXASSERT(valuesMigrated == pOther->m_NumEntries); + + m_rgpHashEntries = rgpNewHashEntries; + m_NumHashSlots = actualSize; + m_NumEntries = pOther->m_NumEntries; + m_bOwnHashEntryArray = true; + rgpNewHashEntries = NULL; + +lExit: + SAFE_DELETE_ARRAY( rgpNewHashEntries ); + return hr; + } + +protected: + void CleanArray() + { + if (m_bOwnHashEntryArray) + { + SAFE_DELETE_ARRAY(m_rgpHashEntries); + m_bOwnHashEntryArray = false; + } + } + +public: + void Cleanup() + { + UINT i; + for (i = 0; i < m_NumHashSlots; ++ i) + { + SHashEntry *pCurrentEntry = m_rgpHashEntries[i]; + SHashEntry *pTempEntry; + while (NULL != pCurrentEntry) + { + pTempEntry = pCurrentEntry->pNext; + SAFE_DELETE(pCurrentEntry); + pCurrentEntry = pTempEntry; + -- m_NumEntries; + } + } + CleanArray(); + m_NumHashSlots = 0; + D3DXASSERT(m_NumEntries == 0); + } + + ~CEffectHashTable() + { + Cleanup(); + } + + static UINT GetNextHashTableSize(__in UINT DesiredSize) + { + // figure out the next logical size to use + for (UINT i = 0; i < c_NumPrimes; ++ i) + { + if (c_PrimeSizes[i] >= DesiredSize) + { + return c_PrimeSizes[i]; + } + } + + return DesiredSize; + } + + // O(n) function + // Grows to the next suitable size (based off of the prime number table) + // DesiredSize is merely a suggestion + HRESULT Grow(__in UINT DesiredSize, + __in UINT ProvidedArraySize = 0, + __in_ecount_opt(ProvidedArraySize) + void** ProvidedArray = NULL, + __in bool OwnProvidedArray = false) + { + HRESULT hr = S_OK; + SHashEntry **rgpNewHashEntries = NULL; + SHashEntry ***rgppListEnds = NULL; + UINT valuesMigrated = 0; + UINT actualSize; + + VB( DesiredSize > m_NumHashSlots ); + + actualSize = GetNextHashTableSize(DesiredSize); + + if (ProvidedArray && + ProvidedArraySize >= actualSize) + { + rgpNewHashEntries = reinterpret_cast<SHashEntry**>(ProvidedArray); + } + else + { + OwnProvidedArray = true; + + VN( rgpNewHashEntries = NEW SHashEntry*[actualSize] ); + } + + ZeroMemory(rgpNewHashEntries, sizeof(SHashEntry*) * actualSize); + + // Expensive operation: rebuild the hash table + CIterator iter, nextIter; + GetFirstEntry(&iter); + while (!PastEnd(&iter)) + { + UINT index = iter.GetHash() % actualSize; + + // we need to advance to the next element + // before we seize control of this element and move + // it to the new table + nextIter = iter; + GetNextEntry(&nextIter); + + // seize this hash entry, migrate it to the new table + iter.pHashEntry->pNext = rgpNewHashEntries[index]; + rgpNewHashEntries[index] = iter.pHashEntry; + + iter = nextIter; + ++ valuesMigrated; + } + + D3DXASSERT(valuesMigrated == m_NumEntries); + + CleanArray(); + m_rgpHashEntries = rgpNewHashEntries; + m_NumHashSlots = actualSize; + m_bOwnHashEntryArray = OwnProvidedArray; + +lExit: + return hr; + } + + HRESULT AutoGrow() + { + // arbitrary heuristic -- grow if 1:1 + if (m_NumEntries >= m_NumHashSlots) + { + // grows this hash table so that it is roughly 50% full + return Grow(m_NumEntries * 2 + 1); + } + return S_OK; + } + +#if _DEBUG + void PrintHashTableStats() + { + if (m_NumHashSlots == 0) + { + DPF(0, "Uninitialized hash table!"); + return; + } + + UINT i; + float variance = 0.0f; + float mean = (float)m_NumEntries / (float)m_NumHashSlots; + UINT unusedSlots = 0; + + DPF(0, "Hash table slots: %d, Entries in table: %d", m_NumHashSlots, m_NumEntries); + + for (i = 0; i < m_NumHashSlots; ++ i) + { + UINT entries = 0; + SHashEntry *pCurrentEntry = m_rgpHashEntries[i]; + + while (NULL != pCurrentEntry) + { + SHashEntry *pCurrentEntry2 = m_rgpHashEntries[i]; + + // check other hash entries in this slot for hash collisions or duplications + while (pCurrentEntry2 != pCurrentEntry) + { + if (pCurrentEntry->Hash == pCurrentEntry2->Hash) + { + if (pfnIsEqual(pCurrentEntry->Data, pCurrentEntry2->Data)) + { + D3DXASSERT(0); + DPF(0, "Duplicate entry (identical hash, identical data) found!"); + } + else + { + DPF(0, "Hash collision (hash: %d)", pCurrentEntry->Hash); + } + } + pCurrentEntry2 = pCurrentEntry2->pNext; + } + + pCurrentEntry = pCurrentEntry->pNext; + ++ entries; + } + + if (0 == entries) + { + ++ unusedSlots; + } + + // mean must be greater than 0 at this point + variance += (float)entries * (float)entries / mean; + } + + variance /= max(1.0f, (m_NumHashSlots - 1)); + variance -= (mean * mean); + + DPF(0, "Mean number of entries per slot: %f, Standard deviation: %f, Unused slots; %d", mean, variance, unusedSlots); + } +#endif // _DEBUG + + // S_OK if element is found, E_FAIL otherwise + HRESULT FindValueWithHash(T Data, UINT Hash, CIterator *pIterator) + { + D3DXASSERT(m_NumHashSlots > 0); + + UINT index = Hash % m_NumHashSlots; + SHashEntry *pEntry = m_rgpHashEntries[index]; + while (NULL != pEntry) + { + if (Hash == pEntry->Hash && pfnIsEqual(pEntry->Data, Data)) + { + pIterator->ppHashSlot = m_rgpHashEntries + index; + pIterator->pHashEntry = pEntry; + return S_OK; + } + pEntry = pEntry->pNext; + } + return E_FAIL; + } + + // S_OK if element is found, E_FAIL otherwise + HRESULT FindFirstMatchingValue(UINT Hash, CIterator *pIterator) + { + D3DXASSERT(m_NumHashSlots > 0); + + UINT index = Hash % m_NumHashSlots; + SHashEntry *pEntry = m_rgpHashEntries[index]; + while (NULL != pEntry) + { + if (Hash == pEntry->Hash) + { + pIterator->ppHashSlot = m_rgpHashEntries + index; + pIterator->pHashEntry = pEntry; + return S_OK; + } + pEntry = pEntry->pNext; + } + return E_FAIL; + } + + // Adds data at the specified hash slot without checking for existence + HRESULT AddValueWithHash(T Data, UINT Hash) + { + HRESULT hr = S_OK; + + D3DXASSERT(m_NumHashSlots > 0); + + SHashEntry *pHashEntry; + UINT index = Hash % m_NumHashSlots; + + VN( pHashEntry = NEW SHashEntry ); + pHashEntry->pNext = m_rgpHashEntries[index]; + pHashEntry->Data = Data; + pHashEntry->Hash = Hash; + m_rgpHashEntries[index] = pHashEntry; + + ++ m_NumEntries; + +lExit: + return hr; + } + + // Iterator code: + // + // CMyHashTable::CIterator myIt; + // for (myTable.GetFirstEntry(&myIt); !myTable.PastEnd(&myIt); myTable.GetNextEntry(&myIt) + // { myTable.GetData(&myIt); } + void GetFirstEntry(CIterator *pIterator) + { + SHashEntry **ppEnd = m_rgpHashEntries + m_NumHashSlots; + pIterator->ppHashSlot = m_rgpHashEntries; + while (pIterator->ppHashSlot < ppEnd) + { + if (NULL != *(pIterator->ppHashSlot)) + { + pIterator->pHashEntry = *(pIterator->ppHashSlot); + return; + } + ++ pIterator->ppHashSlot; + } + } + + BOOL PastEnd(CIterator *pIterator) + { + SHashEntry **ppEnd = m_rgpHashEntries + m_NumHashSlots; + D3DXASSERT(pIterator->ppHashSlot >= m_rgpHashEntries && pIterator->ppHashSlot <= ppEnd); + return (pIterator->ppHashSlot == ppEnd); + } + + void GetNextEntry(CIterator *pIterator) + { + SHashEntry **ppEnd = m_rgpHashEntries + m_NumHashSlots; + D3DXASSERT(pIterator->ppHashSlot >= m_rgpHashEntries && pIterator->ppHashSlot <= ppEnd); + D3DXASSERT(NULL != pIterator->pHashEntry); + + pIterator->pHashEntry = pIterator->pHashEntry->pNext; + if (NULL != pIterator->pHashEntry) + { + return; + } + + ++ pIterator->ppHashSlot; + while (pIterator->ppHashSlot < ppEnd) + { + pIterator->pHashEntry = *(pIterator->ppHashSlot); + if (NULL != pIterator->pHashEntry) + { + return; + } + ++ pIterator->ppHashSlot; + } + // hit the end of the list, ppHashSlot == ppEnd + } + + void RemoveEntry(CIterator *pIterator) + { + SHashEntry *pTemp; + SHashEntry **ppPrev; + SHashEntry **ppEnd = m_rgpHashEntries + m_NumHashSlots; + + D3DXASSERT(pIterator && !PastEnd(pIterator)); + ppPrev = pIterator->ppHashSlot; + pTemp = *ppPrev; + while (pTemp) + { + if (pTemp == pIterator->pHashEntry) + { + *ppPrev = pTemp->pNext; + pIterator->ppHashSlot = ppEnd; + delete pTemp; + return; + } + ppPrev = &pTemp->pNext; + pTemp = pTemp->pNext; + } + + // Should never get here + D3DXASSERT(0); + } + +}; + +// Allocates the hash slots on the regular heap (since the +// hash table can grow), but all hash entries are allocated on +// a private heap + +template<typename T, BOOL (*pfnIsEqual)(const T &Data1, const T &Data2)> +class CEffectHashTableWithPrivateHeap : public CEffectHashTable<T, pfnIsEqual> +{ +protected: + CDataBlockStore *m_pPrivateHeap; + +public: + CEffectHashTableWithPrivateHeap() + { + m_pPrivateHeap = NULL; + } + + void Cleanup() + { + CleanArray(); + m_NumHashSlots = 0; + m_NumEntries = 0; + } + + ~CEffectHashTableWithPrivateHeap() + { + Cleanup(); + } + + // Call this only once + void SetPrivateHeap(CDataBlockStore *pPrivateHeap) + { + D3DXASSERT(NULL == m_pPrivateHeap); + m_pPrivateHeap = pPrivateHeap; + } + + // Adds data at the specified hash slot without checking for existence + HRESULT AddValueWithHash(T Data, UINT Hash) + { + HRESULT hr = S_OK; + + D3DXASSERT(NULL != m_pPrivateHeap); + D3DXASSERT(m_NumHashSlots > 0); + + SHashEntry *pHashEntry; + UINT index = Hash % m_NumHashSlots; + + VN( pHashEntry = new(*m_pPrivateHeap) SHashEntry ); + pHashEntry->pNext = m_rgpHashEntries[index]; + pHashEntry->Data = Data; + pHashEntry->Hash = Hash; + m_rgpHashEntries[index] = pHashEntry; + + ++ m_NumEntries; + +lExit: + return hr; + } +}; diff --git a/sample/d3d11/Effects11/d3dx11dbg.cpp b/sample/d3d11/Effects11/d3dx11dbg.cpp new file mode 100644 index 0000000..330e8d9 --- /dev/null +++ b/sample/d3d11/Effects11/d3dx11dbg.cpp @@ -0,0 +1,62 @@ +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: d3dx11dbg.cpp +// Content: D3DX11 Effects debugging functions +// +/////////////////////////////////////////////////////////////////////////// + +#include "pchfx.h" + + +#ifdef FXDPF + +// +// DPF +// + +void cdecl D3DXDebugPrintf(UINT lvl, LPCSTR szFormat, ...) +{ + static UINT uDebugLevel = (UINT) -1; + + char strA[4096]; + char strB[4096]; + + va_list ap; + va_start(ap, szFormat); + StringCchVPrintfA(strA, sizeof(strA), szFormat, ap); + strA[4095] = '\0'; + va_end(ap); + + StringCchPrintfA(strB, sizeof(strB), "Effects11: %s\r\n", strA); + + strB[4095] = '\0'; + + OutputDebugStringA(strB); +} +#else +// This is defined so warning LNK4211 is not generated (object file has no public symbols) +void cdecl D3DXDebugPrintf(UINT lvl, LPCSTR szFormat, ...) {} +#endif + + +// +// D3DXASSERT +// + +#ifdef _DEBUG + +int WINAPI D3DXDebugAssert(LPCSTR szFile, int nLine, LPCSTR szCondition) +{ + char str[512]; + + // Print message to debug console + StringCchPrintfA(str, sizeof(str), "Assertion failure! (%s %d): %s\r\n", szFile, nLine, szCondition); + str[511] = 0; + OutputDebugStringA(str); + + return 0; +} +#endif + diff --git a/sample/d3d11/Effects11/d3dxGlobal.cpp b/sample/d3d11/Effects11/d3dxGlobal.cpp new file mode 100644 index 0000000..72f4efb --- /dev/null +++ b/sample/d3d11/Effects11/d3dxGlobal.cpp @@ -0,0 +1,351 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: d3dxGlobal.cpp +// Content: D3DX11 Effects implementation for helper data structures +// +////////////////////////////////////////////////////////////////////////////// + +#include "pchfx.h" +#include <intsafe.h> + +namespace D3DX11Core +{ + +////////////////////////////////////////////////////////////////////////// +// CMemoryStream - A class to simplify reading binary data +////////////////////////////////////////////////////////////////////////// + +CMemoryStream::CMemoryStream() +{ + m_pData = NULL; + m_cbData = 0; + m_readPtr = 0; +} + +CMemoryStream::~CMemoryStream() +{ +} + +HRESULT CMemoryStream::SetData(const void *pData, SIZE_T size) +{ + m_pData = (BYTE*) pData; + m_cbData = size; + m_readPtr = 0; + + return S_OK; +} + +HRESULT CMemoryStream::ReadAtOffset(SIZE_T offset, SIZE_T size, void **ppData) +{ + if (offset >= m_cbData) + return E_FAIL; + + m_readPtr = offset; + return Read(ppData, size); +} + +HRESULT CMemoryStream::ReadAtOffset(SIZE_T offset, LPCSTR *ppString) +{ + if (offset >= m_cbData) + return E_FAIL; + + m_readPtr = offset; + return Read(ppString); +} + +HRESULT CMemoryStream::Read(void **ppData, SIZE_T size) +{ + SIZE_T temp = m_readPtr + size; + + if (temp < m_readPtr || temp > m_cbData) + return E_FAIL; + + *ppData = m_pData + m_readPtr; + m_readPtr = temp; + return S_OK; +} + +HRESULT CMemoryStream::Read(UINT *pDword) +{ + UINT *pTempDword; + HRESULT hr; + + hr = Read((void**) &pTempDword, sizeof(UINT)); + if (FAILED(hr)) + return E_FAIL; + + *pDword = *pTempDword; + return S_OK; +} + +HRESULT CMemoryStream::Read(LPCSTR *ppString) +{ + SIZE_T iChar; + + for(iChar=m_readPtr; m_pData[iChar]; iChar++) + { + if (iChar > m_cbData) + return E_FAIL; + } + + *ppString = (LPCSTR) (m_pData + m_readPtr); + m_readPtr = iChar; + + return S_OK; +} + +SIZE_T CMemoryStream::GetPosition() +{ + return m_readPtr; +} + +HRESULT CMemoryStream::Seek(SIZE_T offset) +{ + if (offset > m_cbData) + return E_FAIL; + + m_readPtr = offset; + return S_OK; +} + +} + +////////////////////////////////////////////////////////////////////////// +// CDataBlock - used to dynamically build up the effect file in memory +////////////////////////////////////////////////////////////////////////// + +CDataBlock::CDataBlock() +{ + m_size = 0; + m_maxSize = 0; + m_pData = NULL; + m_pNext = NULL; + m_IsAligned = FALSE; +} + +CDataBlock::~CDataBlock() +{ + SAFE_DELETE_ARRAY(m_pData); + SAFE_DELETE(m_pNext); +} + +void CDataBlock::EnableAlignment() +{ + m_IsAligned = TRUE; +} + +HRESULT CDataBlock::AddData(const void *pvNewData, UINT bufferSize, CDataBlock **ppBlock) +{ + HRESULT hr = S_OK; + UINT bytesToCopy; + const BYTE *pNewData = (const BYTE*) pvNewData; + + if (m_maxSize == 0) + { + // This is a brand new DataBlock, fill it up + m_maxSize = max(8192, bufferSize); + + VN( m_pData = NEW BYTE[m_maxSize] ); + } + + D3DXASSERT(m_pData == AlignToPowerOf2(m_pData, c_DataAlignment)); + + bytesToCopy = min(m_maxSize - m_size, bufferSize); + memcpy(m_pData + m_size, pNewData, bytesToCopy); + pNewData += bytesToCopy; + + if (m_IsAligned) + { + D3DXASSERT(m_size == AlignToPowerOf2(m_size, c_DataAlignment)); + m_size += AlignToPowerOf2(bytesToCopy, c_DataAlignment); + } + else + { + m_size += bytesToCopy; + } + + bufferSize -= bytesToCopy; + *ppBlock = this; + + if (bufferSize != 0) + { + D3DXASSERT(NULL == m_pNext); // make sure we're not overwriting anything + + // Couldn't fit all data into this block, spill over into next + VN( m_pNext = NEW CDataBlock() ); + if (m_IsAligned) + { + m_pNext->EnableAlignment(); + } + VH( m_pNext->AddData(pNewData, bufferSize, ppBlock) ); + } + +lExit: + return hr; +} + +void* CDataBlock::Allocate(UINT bufferSize, CDataBlock **ppBlock) +{ + void *pRetValue; + UINT temp = m_size + bufferSize; + + if (temp < m_size) + return NULL; + + *ppBlock = this; + + if (m_maxSize == 0) + { + // This is a brand new DataBlock, fill it up + m_maxSize = max(8192, bufferSize); + + m_pData = NEW BYTE[m_maxSize]; + if (!m_pData) + return NULL; + memset(m_pData, 0xDD, m_maxSize); + } + else if (temp > m_maxSize) + { + D3DXASSERT(NULL == m_pNext); // make sure we're not overwriting anything + + // Couldn't fit data into this block, spill over into next + m_pNext = NEW CDataBlock(); + if (!m_pNext) + return NULL; + if (m_IsAligned) + { + m_pNext->EnableAlignment(); + } + + return m_pNext->Allocate(bufferSize, ppBlock); + } + + D3DXASSERT(m_pData == AlignToPowerOf2(m_pData, c_DataAlignment)); + + pRetValue = m_pData + m_size; + if (m_IsAligned) + { + D3DXASSERT(m_size == AlignToPowerOf2(m_size, c_DataAlignment)); + m_size = AlignToPowerOf2(temp, c_DataAlignment); + } + else + { + m_size = temp; + } + + return pRetValue; +} + + +////////////////////////////////////////////////////////////////////////// + +CDataBlockStore::CDataBlockStore() +{ + m_pFirst = NULL; + m_pLast = NULL; + m_Size = 0; + m_Offset = 0; + m_IsAligned = FALSE; + +#if _DEBUG + m_cAllocations = 0; +#endif +} + +CDataBlockStore::~CDataBlockStore() +{ + // Can't just do SAFE_DELETE(m_pFirst) since it blows the stack when deleting long chains of data + CDataBlock* pData = m_pFirst; + while(pData) + { + CDataBlock* pCurrent = pData; + pData = pData->m_pNext; + pCurrent->m_pNext = NULL; + delete pCurrent; + } + + // m_pLast will be deleted automatically +} + +void CDataBlockStore::EnableAlignment() +{ + m_IsAligned = TRUE; +} + +HRESULT CDataBlockStore::AddString(LPCSTR pString, UINT *pOffset) +{ + size_t strSize = strlen(pString) + 1; + D3DXASSERT( strSize <= 0xffffffff ); + return AddData(pString, (UINT)strSize, pOffset); +} + +HRESULT CDataBlockStore::AddData(const void *pNewData, UINT bufferSize, UINT *pCurOffset) +{ + HRESULT hr = S_OK; + + if (bufferSize == 0) + { + if (pCurOffset) + { + *pCurOffset = 0; + } + goto lExit; + } + + if (!m_pFirst) + { + VN( m_pFirst = NEW CDataBlock() ); + if (m_IsAligned) + { + m_pFirst->EnableAlignment(); + } + m_pLast = m_pFirst; + } + + if (pCurOffset) + *pCurOffset = m_Size + m_Offset; + + VH( m_pLast->AddData(pNewData, bufferSize, &m_pLast) ); + m_Size += bufferSize; + +lExit: + return hr; +} + +void* CDataBlockStore::Allocate(UINT bufferSize) +{ + void *pRetValue = NULL; + +#if _DEBUG + m_cAllocations++; +#endif + + if (!m_pFirst) + { + m_pFirst = NEW CDataBlock(); + if (!m_pFirst) + return NULL; + + if (m_IsAligned) + { + m_pFirst->EnableAlignment(); + } + m_pLast = m_pFirst; + } + + if (FAILED(UIntAdd(m_Size, bufferSize, &m_Size))) + return NULL; + + pRetValue = m_pLast->Allocate(bufferSize, &m_pLast); + if (!pRetValue) + return NULL; + + return pRetValue; +} + +UINT CDataBlockStore::GetSize() +{ + return m_Size; +} diff --git a/sample/d3d11/Effects11/pchfx.h b/sample/d3d11/Effects11/pchfx.h new file mode 100644 index 0000000..a374084 --- /dev/null +++ b/sample/d3d11/Effects11/pchfx.h @@ -0,0 +1,44 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: pchfx.h +// Content: D3D shader effects precompiled header +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef __D3DX11_PCHFX_H__ +#define __D3DX11_PCHFX_H__ + +#define WIN32_LEAN_AND_MEAN + +#include "d3d11.h" +#include "d3dx11.h" +#undef DEFINE_GUID +#include "INITGUID.h" +#include "d3dx11effect.h" + +#define UNUSED -1 + +////////////////////////////////////////////////////////////////////////// + +#define offsetof_fx( a, b ) (UINT)offsetof( a, b ) + +#include "d3dxGlobal.h" + +#include <stddef.h> +#include <strsafe.h> + +#include "Effect.h" +#include "EffectStateBase11.h" +#include "EffectLoad.h" + +#include "D3DCompiler.h" + +////////////////////////////////////////////////////////////////////////// + +namespace D3DX11Effects +{ +} // end namespace D3DX11Effects + +#endif // __D3DX11_PCHFX_H__ |