diff options
| author | Egor Yusov <egor.yusov@gmail.com> | 2019-11-24 08:03:16 +0000 |
|---|---|---|
| committer | Egor Yusov <egor.yusov@gmail.com> | 2019-11-24 08:03:16 +0000 |
| commit | 0cc615c573a132489f7ea101daaea22e14b45037 (patch) | |
| tree | 9c7985d2b381261a9b15b5a29f30075bca172179 /Common/interface | |
| parent | Fixed few formatting issues; updated format validation script to make validat... (diff) | |
| download | DiligentCore-0cc615c573a132489f7ea101daaea22e14b45037.tar.gz DiligentCore-0cc615c573a132489f7ea101daaea22e14b45037.zip | |
clang-formatted Common project
Diffstat (limited to 'Common/interface')
| -rw-r--r-- | Common/interface/AdvancedMath.h | 312 | ||||
| -rw-r--r-- | Common/interface/Align.h | 8 | ||||
| -rw-r--r-- | Common/interface/BasicFileStream.h | 16 | ||||
| -rw-r--r-- | Common/interface/BasicMath.h | 1572 | ||||
| -rw-r--r-- | Common/interface/DataBlobImpl.h | 12 | ||||
| -rw-r--r-- | Common/interface/DefaultRawMemoryAllocator.h | 16 | ||||
| -rw-r--r-- | Common/interface/FileWrapper.h | 34 | ||||
| -rw-r--r-- | Common/interface/FixedBlockMemoryAllocator.h | 168 | ||||
| -rw-r--r-- | Common/interface/HashUtils.h | 262 | ||||
| -rw-r--r-- | Common/interface/LockHelper.h | 79 | ||||
| -rw-r--r-- | Common/interface/MemoryFileStream.h | 14 | ||||
| -rw-r--r-- | Common/interface/ObjectBase.h | 46 | ||||
| -rw-r--r-- | Common/interface/RefCntAutoPtr.h | 220 | ||||
| -rw-r--r-- | Common/interface/RefCountedObjectImpl.h | 327 | ||||
| -rw-r--r-- | Common/interface/STDAllocator.h | 114 | ||||
| -rw-r--r-- | Common/interface/StringDataBlobImpl.h | 21 | ||||
| -rw-r--r-- | Common/interface/StringPool.h | 66 | ||||
| -rw-r--r-- | Common/interface/StringTools.h | 73 | ||||
| -rw-r--r-- | Common/interface/ThreadSignal.h | 43 | ||||
| -rw-r--r-- | Common/interface/Timer.h | 24 | ||||
| -rw-r--r-- | Common/interface/UniqueIdentifier.h | 68 | ||||
| -rw-r--r-- | Common/interface/ValidatedCast.h | 6 |
22 files changed, 1813 insertions, 1688 deletions
diff --git a/Common/interface/AdvancedMath.h b/Common/interface/AdvancedMath.h index 8a085760..5be38da1 100644 --- a/Common/interface/AdvancedMath.h +++ b/Common/interface/AdvancedMath.h @@ -35,7 +35,7 @@ namespace Diligent struct Plane3D { float3 Normal; - float Distance = 0; //Distance from the coordinate system origin to the plane along the normal direction + float Distance = 0; //Distance from the coordinate system origin to the plane along the normal direction }; struct ViewFrustum @@ -50,44 +50,44 @@ struct ViewFrustumExt : public ViewFrustum // For OpenGL, matrix is still considered row-major. The only difference is that // near clip plane is at -1, not 0. -inline void ExtractViewFrustumPlanesFromMatrix(const float4x4 &Matrix, ViewFrustum &Frustum, bool bIsOpenGL) +inline void ExtractViewFrustumPlanesFromMatrix(const float4x4& Matrix, ViewFrustum& Frustum, bool bIsOpenGL) { - // For more details, see Gribb G., Hartmann K., "Fast Extraction of Viewing Frustum Planes from the - // World-View-Projection Matrix" (the paper is available at + // For more details, see Gribb G., Hartmann K., "Fast Extraction of Viewing Frustum Planes from the + // World-View-Projection Matrix" (the paper is available at // http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf) - // Left clipping plane - Frustum.LeftPlane.Normal.x = Matrix._14 + Matrix._11; - Frustum.LeftPlane.Normal.y = Matrix._24 + Matrix._21; - Frustum.LeftPlane.Normal.z = Matrix._34 + Matrix._31; - Frustum.LeftPlane.Distance = Matrix._44 + Matrix._41; - - // Right clipping plane - Frustum.RightPlane.Normal.x = Matrix._14 - Matrix._11; - Frustum.RightPlane.Normal.y = Matrix._24 - Matrix._21; - Frustum.RightPlane.Normal.z = Matrix._34 - Matrix._31; - Frustum.RightPlane.Distance = Matrix._44 - Matrix._41; - - // Top clipping plane - Frustum.TopPlane.Normal.x = Matrix._14 - Matrix._12; - Frustum.TopPlane.Normal.y = Matrix._24 - Matrix._22; - Frustum.TopPlane.Normal.z = Matrix._34 - Matrix._32; - Frustum.TopPlane.Distance = Matrix._44 - Matrix._42; - - // Bottom clipping plane - Frustum.BottomPlane.Normal.x = Matrix._14 + Matrix._12; - Frustum.BottomPlane.Normal.y = Matrix._24 + Matrix._22; - Frustum.BottomPlane.Normal.z = Matrix._34 + Matrix._32; - Frustum.BottomPlane.Distance = Matrix._44 + Matrix._42; - - // Near clipping plane - if( bIsOpenGL ) + // Left clipping plane + Frustum.LeftPlane.Normal.x = Matrix._14 + Matrix._11; + Frustum.LeftPlane.Normal.y = Matrix._24 + Matrix._21; + Frustum.LeftPlane.Normal.z = Matrix._34 + Matrix._31; + Frustum.LeftPlane.Distance = Matrix._44 + Matrix._41; + + // Right clipping plane + Frustum.RightPlane.Normal.x = Matrix._14 - Matrix._11; + Frustum.RightPlane.Normal.y = Matrix._24 - Matrix._21; + Frustum.RightPlane.Normal.z = Matrix._34 - Matrix._31; + Frustum.RightPlane.Distance = Matrix._44 - Matrix._41; + + // Top clipping plane + Frustum.TopPlane.Normal.x = Matrix._14 - Matrix._12; + Frustum.TopPlane.Normal.y = Matrix._24 - Matrix._22; + Frustum.TopPlane.Normal.z = Matrix._34 - Matrix._32; + Frustum.TopPlane.Distance = Matrix._44 - Matrix._42; + + // Bottom clipping plane + Frustum.BottomPlane.Normal.x = Matrix._14 + Matrix._12; + Frustum.BottomPlane.Normal.y = Matrix._24 + Matrix._22; + Frustum.BottomPlane.Normal.z = Matrix._34 + Matrix._32; + Frustum.BottomPlane.Distance = Matrix._44 + Matrix._42; + + // Near clipping plane + if (bIsOpenGL) { // -w <= z <= w - Frustum.NearPlane.Normal.x = Matrix._14 + Matrix._13; - Frustum.NearPlane.Normal.y = Matrix._24 + Matrix._23; - Frustum.NearPlane.Normal.z = Matrix._34 + Matrix._33; - Frustum.NearPlane.Distance = Matrix._44 + Matrix._43; + Frustum.NearPlane.Normal.x = Matrix._14 + Matrix._13; + Frustum.NearPlane.Normal.y = Matrix._24 + Matrix._23; + Frustum.NearPlane.Normal.z = Matrix._34 + Matrix._33; + Frustum.NearPlane.Distance = Matrix._44 + Matrix._43; } else { @@ -98,36 +98,39 @@ inline void ExtractViewFrustumPlanesFromMatrix(const float4x4 &Matrix, ViewFrust Frustum.NearPlane.Distance = Matrix._43; } - // Far clipping plane - Frustum.FarPlane.Normal.x = Matrix._14 - Matrix._13; - Frustum.FarPlane.Normal.y = Matrix._24 - Matrix._23; - Frustum.FarPlane.Normal.z = Matrix._34 - Matrix._33; - Frustum.FarPlane.Distance = Matrix._44 - Matrix._43; + // Far clipping plane + Frustum.FarPlane.Normal.x = Matrix._14 - Matrix._13; + Frustum.FarPlane.Normal.y = Matrix._24 - Matrix._23; + Frustum.FarPlane.Normal.z = Matrix._34 - Matrix._33; + Frustum.FarPlane.Distance = Matrix._44 - Matrix._43; } -inline void ExtractViewFrustumPlanesFromMatrix(const float4x4 &Matrix, ViewFrustumExt &FrustumExt, bool bIsOpenGL) +inline void ExtractViewFrustumPlanesFromMatrix(const float4x4& Matrix, ViewFrustumExt& FrustumExt, bool bIsOpenGL) { ExtractViewFrustumPlanesFromMatrix(Matrix, static_cast<ViewFrustum&>(FrustumExt), bIsOpenGL); // Compute frustum corners float4x4 InvMatrix = Matrix.Inverse(); - + float nearClipZ = bIsOpenGL ? -1.f : 0.f; - static const float3 ProjSpaceCorners[] = - { - float3(-1,-1, nearClipZ), - float3( 1,-1, nearClipZ), - float3(-1, 1, nearClipZ), - float3( 1, 1, nearClipZ), - - float3(-1,-1, 1), - float3( 1,-1, 1), - float3(-1, 1, 1), - float3( 1, 1, 1), - }; - - for(int i = 0; i < 8; ++i) - FrustumExt.FrustumCorners[i] = ProjSpaceCorners[i] * InvMatrix; + + static const float3 ProjSpaceCorners[] = + { + // clang-format off + float3(-1, -1, nearClipZ), + float3( 1, -1, nearClipZ), + float3(-1, 1, nearClipZ), + float3( 1, 1, nearClipZ), + + float3(-1, -1, 1), + float3( 1, -1, 1), + float3(-1, 1, 1), + float3( 1, 1, 1), + // clang-format on + }; + + for (int i = 0; i < 8; ++i) + FrustumExt.FrustumCorners[i] = ProjSpaceCorners[i] * InvMatrix; } struct BoundBox @@ -160,7 +163,7 @@ enum class BoxVisibility // |____| ' . // Intersecting, - + // Bounding box is fully inside the view frustum // . // . ' | @@ -176,45 +179,45 @@ enum class BoxVisibility /// Returns the nearest bounding box corner along the given direction inline float3 GetBoxNearestCorner(const float3& Direction, const BoundBox& Box) { - return float3 - { - (Direction.x > 0) ? Box.Min.x : Box.Max.x, - (Direction.y > 0) ? Box.Min.y : Box.Max.y, - (Direction.z > 0) ? Box.Min.z : Box.Max.z - }; + return float3 // + { + (Direction.x > 0) ? Box.Min.x : Box.Max.x, + (Direction.y > 0) ? Box.Min.y : Box.Max.y, + (Direction.z > 0) ? Box.Min.z : Box.Max.z // + }; } /// Returns the farthest bounding box corner along the given direction inline float3 GetBoxFarthestCorner(const float3& Direction, const BoundBox& Box) { - return float3 - { - (Direction.x > 0) ? Box.Max.x : Box.Min.x, - (Direction.y > 0) ? Box.Max.y : Box.Min.y, - (Direction.z > 0) ? Box.Max.z : Box.Min.z - }; + return float3 // + { + (Direction.x > 0) ? Box.Max.x : Box.Min.x, + (Direction.y > 0) ? Box.Max.y : Box.Min.y, + (Direction.z > 0) ? Box.Max.z : Box.Min.z // + }; } inline BoxVisibility GetBoxVisibilityAgainstPlane(const Plane3D& Plane, const BoundBox& Box) { const float3& Normal = Plane.Normal; - - float3 MaxPoint - { - (Normal.x > 0) ? Box.Max.x : Box.Min.x, - (Normal.y > 0) ? Box.Max.y : Box.Min.y, - (Normal.z > 0) ? Box.Max.z : Box.Min.z - }; + + float3 MaxPoint // + { + (Normal.x > 0) ? Box.Max.x : Box.Min.x, + (Normal.y > 0) ? Box.Max.y : Box.Min.y, + (Normal.z > 0) ? Box.Max.z : Box.Min.z // + }; float DMax = dot(MaxPoint, Normal) + Plane.Distance; - if( DMax < 0 ) + if (DMax < 0) return BoxVisibility::Invisible; - float3 MinPoint - { - (Normal.x > 0) ? Box.Min.x : Box.Max.x, - (Normal.y > 0) ? Box.Min.y : Box.Max.y, - (Normal.z > 0) ? Box.Min.z : Box.Max.z - }; + float3 MinPoint // + { + (Normal.x > 0) ? Box.Min.x : Box.Max.x, + (Normal.y > 0) ? Box.Min.y : Box.Max.y, + (Normal.z > 0) ? Box.Min.z : Box.Max.z // + }; float DMin = dot(MinPoint, Normal) + Plane.Distance; if (DMin > 0) return BoxVisibility::FullyVisible; @@ -234,18 +237,18 @@ enum FRUSTUM_PLANE_FLAGS : Uint32 FRUSTUM_PLANE_FLAG_NEAR_PLANE = 0x10, FRUSTUM_PLANE_FLAG_FAR_PLANE = 0x20, - FRUSTUM_PLANE_FLAG_FULL_FRUSTUM = FRUSTUM_PLANE_FLAG_LEFT_PLANE | - FRUSTUM_PLANE_FLAG_RIGHT_PLANE | - FRUSTUM_PLANE_FLAG_BOTTOM_PLANE | - FRUSTUM_PLANE_FLAG_TOP_PLANE | - FRUSTUM_PLANE_FLAG_NEAR_PLANE | - FRUSTUM_PLANE_FLAG_FAR_PLANE, - - FRUSTUM_PLANE_FLAG_OPEN_NEAR = FRUSTUM_PLANE_FLAG_LEFT_PLANE | - FRUSTUM_PLANE_FLAG_RIGHT_PLANE | - FRUSTUM_PLANE_FLAG_BOTTOM_PLANE | - FRUSTUM_PLANE_FLAG_TOP_PLANE | - FRUSTUM_PLANE_FLAG_FAR_PLANE + FRUSTUM_PLANE_FLAG_FULL_FRUSTUM = FRUSTUM_PLANE_FLAG_LEFT_PLANE | + FRUSTUM_PLANE_FLAG_RIGHT_PLANE | + FRUSTUM_PLANE_FLAG_BOTTOM_PLANE | + FRUSTUM_PLANE_FLAG_TOP_PLANE | + FRUSTUM_PLANE_FLAG_NEAR_PLANE | + FRUSTUM_PLANE_FLAG_FAR_PLANE, + + FRUSTUM_PLANE_FLAG_OPEN_NEAR = FRUSTUM_PLANE_FLAG_LEFT_PLANE | + FRUSTUM_PLANE_FLAG_RIGHT_PLANE | + FRUSTUM_PLANE_FLAG_BOTTOM_PLANE | + FRUSTUM_PLANE_FLAG_TOP_PLANE | + FRUSTUM_PLANE_FLAG_FAR_PLANE }; DEFINE_FLAG_ENUM_OPERATORS(FRUSTUM_PLANE_FLAGS); @@ -255,15 +258,16 @@ inline BoxVisibility GetBoxVisibility(const ViewFrustum& ViewFrustum, FRUSTUM_PLANE_FLAGS PlaneFlags = FRUSTUM_PLANE_FLAG_FULL_FRUSTUM) { const Plane3D* pPlanes = reinterpret_cast<const Plane3D*>(&ViewFrustum); - + int NumPlanesInside = 0; - int TotalPlanes = 0; + int TotalPlanes = 0; for (int iViewFrustumPlane = 0; iViewFrustumPlane < 6; iViewFrustumPlane++) { - if ( (PlaneFlags & (1 << iViewFrustumPlane)) == 0 ) + if ((PlaneFlags & (1 << iViewFrustumPlane)) == 0) continue; const Plane3D& CurrPlane = pPlanes[iViewFrustumPlane]; + auto VisibilityAgainstPlane = GetBoxVisibilityAgainstPlane(CurrPlane, Box); // If bounding box is "behind" one of the planes, it is definitely invisible @@ -290,12 +294,12 @@ inline BoxVisibility GetBoxVisibility(const ViewFrustumExt& ViewFrustumExt, if ((PlaneFlags & FRUSTUM_PLANE_FLAG_FULL_FRUSTUM) == FRUSTUM_PLANE_FLAG_FULL_FRUSTUM) { - // Additionally test if the whole frustum is outside one of + // Additionally test if the whole frustum is outside one of // the the bounding box planes. This helps in the following situation: - // + // // // . - // / ' . . + // / ' . . // / AABB / . ' | // / /. ' | // ' . / | | @@ -317,15 +321,15 @@ inline BoxVisibility GetBoxVisibility(const ViewFrustumExt& ViewFrustumExt, int iCoordOrder = iBoundBoxPlane % 3; // 0, 1, 2, 0, 1, 2 // Since plane normal is directed along one of the axis, we only need to select // if it is pointing in the positive (max planes) or negative (min planes) direction - float fSign = (iBoundBoxPlane >= 3) ? +1.f : -1.f; - bool bAllCornersOutside = true; - for (int iCorner=0; iCorner < 8; iCorner++) + float fSign = (iBoundBoxPlane >= 3) ? +1.f : -1.f; + bool bAllCornersOutside = true; + for (int iCorner = 0; iCorner < 8; iCorner++) { // Pick the frustum corner coordinate float CurrCornerCoord = ViewFrustumExt.FrustumCorners[iCorner][iCoordOrder]; // Dot product is simply the coordinate difference multiplied by the sign if (fSign * (CurrPlaneCoord - CurrCornerCoord) > 0) - { + { bAllCornersOutside = false; break; } @@ -338,39 +342,41 @@ inline BoxVisibility GetBoxVisibility(const ViewFrustumExt& ViewFrustumExt, return BoxVisibility::Intersecting; } -inline float GetPointToBoxDistance(const BoundBox &BndBox, const float3 &Pos) +inline float GetPointToBoxDistance(const BoundBox& BndBox, const float3& Pos) { - VERIFY_EXPR(BndBox.Max.x >= BndBox.Min.x && - BndBox.Max.y >= BndBox.Min.y && + VERIFY_EXPR(BndBox.Max.x >= BndBox.Min.x && + BndBox.Max.y >= BndBox.Min.y && BndBox.Max.z >= BndBox.Min.z); - float fdX = (Pos.x > BndBox.Max.x) ? (Pos.x - BndBox.Max.x) : ( (Pos.x < BndBox.Min.x) ? (BndBox.Min.x - Pos.x) : 0.f ); - float fdY = (Pos.y > BndBox.Max.y) ? (Pos.y - BndBox.Max.y) : ( (Pos.y < BndBox.Min.y) ? (BndBox.Min.y - Pos.y) : 0.f ); - float fdZ = (Pos.z > BndBox.Max.z) ? (Pos.z - BndBox.Max.z) : ( (Pos.z < BndBox.Min.z) ? (BndBox.Min.z - Pos.z) : 0.f ); + float fdX = (Pos.x > BndBox.Max.x) ? (Pos.x - BndBox.Max.x) : ((Pos.x < BndBox.Min.x) ? (BndBox.Min.x - Pos.x) : 0.f); + float fdY = (Pos.y > BndBox.Max.y) ? (Pos.y - BndBox.Max.y) : ((Pos.y < BndBox.Min.y) ? (BndBox.Min.y - Pos.y) : 0.f); + float fdZ = (Pos.z > BndBox.Max.z) ? (Pos.z - BndBox.Max.z) : ((Pos.z < BndBox.Min.z) ? (BndBox.Min.z - Pos.z) : 0.f); VERIFY_EXPR(fdX >= 0 && fdY >= 0 && fdZ >= 0); float3 RangeVec(fdX, fdY, fdZ); - return length( RangeVec ); + return length(RangeVec); } -inline bool operator == (const Plane3D &p1, const Plane3D &p2) +inline bool operator==(const Plane3D& p1, const Plane3D& p2) { - return p1.Normal == p2.Normal && - p1.Distance == p2.Distance; + return p1.Normal == p2.Normal && + p1.Distance == p2.Distance; } -inline bool operator == (const ViewFrustum &f1, const ViewFrustum &f2) +inline bool operator==(const ViewFrustum& f1, const ViewFrustum& f2) { - return f1.LeftPlane == f2.LeftPlane && - f1.RightPlane == f2.RightPlane && + // clang-format off + return f1.LeftPlane == f2.LeftPlane && + f1.RightPlane == f2.RightPlane && f1.BottomPlane == f2.BottomPlane && f1.TopPlane == f2.TopPlane && f1.NearPlane == f2.NearPlane && f1.FarPlane == f2.FarPlane; + // clang-format on } -inline bool operator == (const ViewFrustumExt &f1, const ViewFrustumExt &f2) +inline bool operator==(const ViewFrustumExt& f1, const ViewFrustumExt& f2) { - if (! (static_cast<const ViewFrustum &>(f1) == static_cast<const ViewFrustum &>(f2)) ) + if (!(static_cast<const ViewFrustum&>(f1) == static_cast<const ViewFrustum&>(f2))) return false; for (int c = 0; c < _countof(f1.FrustumCorners); ++c) @@ -380,7 +386,7 @@ inline bool operator == (const ViewFrustumExt &f1, const ViewFrustumExt &f2) return true; } -template<typename T, typename Y> +template <typename T, typename Y> T HermiteSpline(T f0, // F(0) T f1, // F(1) T t0, // F'(0) @@ -388,19 +394,19 @@ T HermiteSpline(T f0, // F(0) Y x) { // https://en.wikipedia.org/wiki/Cubic_Hermite_spline - auto x2 = x*x; - auto x3 = x2*x; - return (2*x3 - 3*x2 + 1) * f0 + (x3 - 2*x2 + x) * t0 + (-2*x3 + 3*x2) * f1 + (x3 - x2) * t1; + auto x2 = x * x; + auto x3 = x2 * x; + return (2 * x3 - 3 * x2 + 1) * f0 + (x3 - 2 * x2 + x) * t0 + (-2 * x3 + 3 * x2) * f1 + (x3 - x2) * t1; } // Retuns the minimum bounding sphere of a view frustum inline void GetFrustumMinimumBoundingSphere(float Proj_00, // cot(HorzFOV / 2) - float Proj_11, // cot(VertFOV / 2) == proj_00 / AspectRatio + float Proj_11, // cot(VertFOV / 2) == proj_00 / AspectRatio float NearPlane, // Near clip plane float FarPlane, // Far clip plane float3& Center, // Sphere center == (0, 0, c) float& Radius // Sphere radius - ) +) { // https://lxjk.github.io/2017/04/15/Calculate-Minimal-Bounding-Sphere-of-Frustum.html VERIFY_EXPR(FarPlane >= NearPlane); @@ -413,9 +419,7 @@ inline void GetFrustumMinimumBoundingSphere(float Proj_00, // cot(HorzFOV / else { Center = float3(0, 0, 0.5f * (FarPlane + NearPlane) * (1 + k2)); - Radius = 0.5f * std::sqrt( (FarPlane-NearPlane) * (FarPlane-NearPlane) - + 2 * (FarPlane*FarPlane + NearPlane*NearPlane) * k2 - + (FarPlane+NearPlane) * (FarPlane+NearPlane) * k2 * k2 ); + Radius = 0.5f * std::sqrt((FarPlane - NearPlane) * (FarPlane - NearPlane) + 2 * (FarPlane * FarPlane + NearPlane * NearPlane) * k2 + (FarPlane + NearPlane) * (FarPlane + NearPlane) * k2 * k2); } } @@ -423,33 +427,35 @@ inline void GetFrustumMinimumBoundingSphere(float Proj_00, // cot(HorzFOV / namespace std { - template<> - struct hash<Diligent::Plane3D> + +template <> +struct hash<Diligent::Plane3D> +{ + size_t operator()(const Diligent::Plane3D& Plane) const { - size_t operator()( const Diligent::Plane3D &Plane ) const - { - return Diligent::ComputeHash(Plane.Normal, Plane.Distance); - } - }; + return Diligent::ComputeHash(Plane.Normal, Plane.Distance); + } +}; - template<> - struct hash<Diligent::ViewFrustum> +template <> +struct hash<Diligent::ViewFrustum> +{ + size_t operator()(const Diligent::ViewFrustum& Frustum) const { - size_t operator()( const Diligent::ViewFrustum &Frustum ) const - { - return Diligent::ComputeHash(Frustum.LeftPlane, Frustum.RightPlane, Frustum.BottomPlane, Frustum.TopPlane, Frustum.NearPlane, Frustum.FarPlane); - } - }; + return Diligent::ComputeHash(Frustum.LeftPlane, Frustum.RightPlane, Frustum.BottomPlane, Frustum.TopPlane, Frustum.NearPlane, Frustum.FarPlane); + } +}; - template<> - struct hash<Diligent::ViewFrustumExt> +template <> +struct hash<Diligent::ViewFrustumExt> +{ + size_t operator()(const Diligent::ViewFrustumExt& Frustum) const { - size_t operator()( const Diligent::ViewFrustumExt &Frustum ) const - { - auto Seed = Diligent::ComputeHash(static_cast<const Diligent::ViewFrustum&>(Frustum)); - for (int Corner = 0; Corner < _countof(Frustum.FrustumCorners); ++Corner) - Diligent::HashCombine(Seed, Frustum.FrustumCorners[Corner]); - return Seed; - } - }; + auto Seed = Diligent::ComputeHash(static_cast<const Diligent::ViewFrustum&>(Frustum)); + for (int Corner = 0; Corner < _countof(Frustum.FrustumCorners); ++Corner) + Diligent::HashCombine(Seed, Frustum.FrustumCorners[Corner]); + return Seed; + } +}; + } // namespace std diff --git a/Common/interface/Align.h b/Common/interface/Align.h index b3a434be..03877819 100644 --- a/Common/interface/Align.h +++ b/Common/interface/Align.h @@ -34,14 +34,14 @@ namespace Diligent template <typename T> bool IsPowerOfTwo(T val) { - return val > 0 && (val & (val-1)) == 0; + return val > 0 && (val & (val - 1)) == 0; } template <typename T> inline T Align(T val, T alignment) { - VERIFY( IsPowerOfTwo(alignment), "Alignment (", alignment, ") must be power of 2" ); - return (val + (alignment-1)) & ~(alignment-1); + VERIFY(IsPowerOfTwo(alignment), "Alignment (", alignment, ") must be power of 2"); + return (val + (alignment - 1)) & ~(alignment - 1); } -} +} // namespace Diligent diff --git a/Common/interface/BasicFileStream.h b/Common/interface/BasicFileStream.h index 39b9be08..c6f9997d 100644 --- a/Common/interface/BasicFileStream.h +++ b/Common/interface/BasicFileStream.h @@ -42,26 +42,26 @@ public: typedef ObjectBase<IFileStream> TBase; BasicFileStream(IReferenceCounters* pRefCounters, - const Char* Path, + const Char* Path, EFileAccessMode Access = EFileAccessMode::Read); - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override; /// Reads data from the stream - virtual void Read( IDataBlob* pData )override; + virtual void Read(IDataBlob* pData) override; /// Reads data from the stream - virtual bool Read( void* Data, size_t Size )override; + virtual bool Read(void* Data, size_t Size) override; /// Writes data to the stream - virtual bool Write( const void* Data, size_t Size )override; + virtual bool Write(const void* Data, size_t Size) override; - virtual size_t GetSize()override; + virtual size_t GetSize() override; - virtual bool IsValid()override; + virtual bool IsValid() override; private: FileWrapper m_FileWrpr; }; -} +} // namespace Diligent diff --git a/Common/interface/BasicMath.h b/Common/interface/BasicMath.h index 1baedfb9..41c49ece 100644 --- a/Common/interface/BasicMath.h +++ b/Common/interface/BasicMath.h @@ -31,14 +31,14 @@ /// - ClipPos = WorldPos * WorldViewProj /// - Matrices are stored using row-major layout: m = {row0, row1, row2, row3} /// - Note that GL-style math libraries use column-vectors and column-major matrix layout. -/// As a result, matrices that perform similar transforms use exactly the same element +/// As a result, matrices that perform similar transforms use exactly the same element /// order. However, matrix multiplication order is reversed: M1_D3D * M2_D3D = M2_GL * M1_GL -/// +/// /// Diligent Engine shaders always use column-major matrices for the purposes of data storage. This means /// that if you use D3D-style math in shaders (ClipPos = mul(WorldPos, WorldViewProj)), you need to /// transpose the host-side matrix before writing it to GPU memory. /// -/// If you use GL-style math in shaders (ClipPos = mul(WorldViewProj, WorldPos)), you do not need to +/// If you use GL-style math in shaders (ClipPos = mul(WorldViewProj, WorldPos)), you do not need to /// transpose the host-side matrix and should write it to GPU memory as is. Since the matrix rows will /// be written to the GPU matrix columns, this will have the effect of transposing the matrix. /// Since mul(WorldViewProj, WorldPos) == mul(WorldPos, transpose(WorldViewProj)), the results will @@ -52,8 +52,8 @@ #include "HashUtils.h" #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4201) // nonstandard extension used: nameless struct/union +# pragma warning(push) +# pragma warning(disable : 4201) // nonstandard extension used: nameless struct/union #endif namespace Diligent @@ -90,60 +90,60 @@ template <class T> struct Vector2 }; - Vector2 operator-(const Vector2<T> &right)const + Vector2 operator-(const Vector2<T>& right) const { return Vector2(x - right.x, y - right.y); } - Vector2& operator-=(const Vector2<T> &right) + Vector2& operator-=(const Vector2<T>& right) { x -= right.x; y -= right.y; return *this; } - Vector2 operator-()const + Vector2 operator-() const { return Vector2(-x, -y); } - Vector2 operator+(const Vector2<T> &right)const + Vector2 operator+(const Vector2<T>& right) const { return Vector2(x + right.x, y + right.y); } - Vector2& operator+=(const Vector2<T> &right) + Vector2& operator+=(const Vector2<T>& right) { x += right.x; y += right.y; return *this; } - Vector2 operator*(T s)const + Vector2 operator*(T s) const { return Vector2(x * s, y * s); } - Vector2 operator*(const Vector2 &right)const + Vector2 operator*(const Vector2& right) const { return Vector2(x * right.x, y * right.y); } - Vector2& operator*=( const Vector2 &right) + Vector2& operator*=(const Vector2& right) { x *= right.x; y *= right.y; return *this; } - Vector2& operator*=( T s) + Vector2& operator*=(T s) { x *= s; y *= s; return *this; } - Vector2 operator*(const Matrix2x2<T>& m)const + Vector2 operator*(const Matrix2x2<T>& m) const { Vector2 out; out[0] = x * m[0][0] + y * m[1][0]; @@ -151,100 +151,96 @@ template <class T> struct Vector2 return out; } - Vector2 operator/(const Vector2 &right)const + Vector2 operator/(const Vector2& right) const { return Vector2(x / right.x, y / right.y); } - Vector2& operator/=( const Vector2 &right) + Vector2& operator/=(const Vector2& right) { x /= right.x; y /= right.y; return *this; } - Vector2 operator/(T s)const + Vector2 operator/(T s) const { return Vector2(x / s, y / s); } - Vector2& operator/=( T s) + Vector2& operator/=(T s) { x /= s; y /= s; return *this; } - bool operator == (const Vector2 &right)const + bool operator==(const Vector2& right) const { return x == right.x && y == right.y; } - bool operator != (const Vector2 &right)const + bool operator!=(const Vector2& right) const { return !(*this == right); } - Vector2 operator < ( const Vector2 &right )const - { - return Vector2(x < right.x ? static_cast<T>(1) : static_cast<T>(0), - y < right.y ? static_cast<T>(1) : static_cast<T>(0)); - } + Vector2 operator<(const Vector2& right) const + { + return Vector2(x < right.x ? static_cast<T>(1) : static_cast<T>(0), + y < right.y ? static_cast<T>(1) : static_cast<T>(0)); + } - Vector2 operator > ( const Vector2 &right )const - { - return Vector2(x > right.x ? static_cast<T>(1) : static_cast<T>(0), - y > right.y ? static_cast<T>(1) : static_cast<T>(0)); - } + Vector2 operator>(const Vector2& right) const + { + return Vector2(x > right.x ? static_cast<T>(1) : static_cast<T>(0), + y > right.y ? static_cast<T>(1) : static_cast<T>(0)); + } - Vector2 operator <= ( const Vector2 &right )const - { - return Vector2(x <= right.x ? static_cast<T>(1) : static_cast<T>(0), - y <= right.y ? static_cast<T>(1) : static_cast<T>(0)); - } + Vector2 operator<=(const Vector2& right) const + { + return Vector2(x <= right.x ? static_cast<T>(1) : static_cast<T>(0), + y <= right.y ? static_cast<T>(1) : static_cast<T>(0)); + } - Vector2 operator >= ( const Vector2 &right )const - { - return Vector2(x >= right.x ? static_cast<T>(1) : static_cast<T>(0), - y >= right.y ? static_cast<T>(1) : static_cast<T>(0)); - } + Vector2 operator>=(const Vector2& right) const + { + return Vector2(x >= right.x ? static_cast<T>(1) : static_cast<T>(0), + y >= right.y ? static_cast<T>(1) : static_cast<T>(0)); + } T& operator[](size_t index) { return reinterpret_cast<T*>(this)[index]; } - const T& operator[](size_t index)const + const T& operator[](size_t index) const { return reinterpret_cast<const T*>(this)[index]; } - Vector2() : x(0), y(0) { } - Vector2(T _x, T _y) : x(_x), y(_y) { } + Vector2() : + x(0), y(0) {} + Vector2(T _x, T _y) : + x(_x), y(_y) {} - template<typename Y> + template <typename Y> static Vector2 MakeVector(Y it) { - return Vector2 - { - static_cast<T>(*it++), - static_cast<T>(*it++) - }; + return Vector2{static_cast<T>(*it++), + static_cast<T>(*it++)}; } - template<typename Y> - Vector2<Y> Recast()const + template <typename Y> + Vector2<Y> Recast() const { - return Vector2<Y> - { - static_cast<Y>(x), - static_cast<Y>(y) - }; + return Vector2<Y>{static_cast<Y>(x), + static_cast<Y>(y)}; } }; template <class T> -Vector2<T> operator*(T s, const Vector2<T> &a) +Vector2<T> operator*(T s, const Vector2<T>& a) { return a * s; } @@ -275,17 +271,17 @@ template <class T> struct Vector3 }; - Vector3 operator-( const Vector3 &right )const + Vector3 operator-(const Vector3& right) const { return Vector3(x - right.x, y - right.y, z - right.z); } - Vector3 operator-()const + Vector3 operator-() const { return Vector3(-x, -y, -z); } - Vector3& operator-=(const Vector3<T> &right) + Vector3& operator-=(const Vector3<T>& right) { x -= right.x; y -= right.y; @@ -293,12 +289,12 @@ template <class T> struct Vector3 return *this; } - Vector3 operator+( const Vector3 &right )const + Vector3 operator+(const Vector3& right) const { return Vector3(x + right.x, y + right.y, z + right.z); } - Vector3& operator+=(const Vector3<T> &right) + Vector3& operator+=(const Vector3<T>& right) { x += right.x; y += right.y; @@ -306,12 +302,12 @@ template <class T> struct Vector3 return *this; } - Vector3 operator*( T s )const + Vector3 operator*(T s) const { return Vector3(x * s, y * s, z * s); } - Vector3& operator*=( T s) + Vector3& operator*=(T s) { x *= s; y *= s; @@ -319,18 +315,18 @@ template <class T> struct Vector3 return *this; } - Vector3 operator*( const Vector3 &right )const + Vector3 operator*(const Vector3& right) const { return Vector3(x * right.x, y * right.y, z * right.z); } - Vector3 operator* (const Matrix4x4<T>& m)const + Vector3 operator*(const Matrix4x4<T>& m) const { Vector4<T> out4 = Vector4<T>(x, y, z, 1) * m; - return Vector3(out4.x / out4.w, out4.y / out4.w, out4.z / out4.w) ; + return Vector3(out4.x / out4.w, out4.y / out4.w, out4.z / out4.w); } - Vector3& operator*=( const Vector3 &right) + Vector3& operator*=(const Vector3& right) { x *= right.x; y *= right.y; @@ -338,7 +334,7 @@ template <class T> struct Vector3 return *this; } - Vector3 operator*(const Matrix3x3<T>& m)const + Vector3 operator*(const Matrix3x3<T>& m) const { Vector3 out; out[0] = x * m[0][0] + y * m[1][0] + z * m[2][0]; @@ -347,12 +343,12 @@ template <class T> struct Vector3 return out; } - Vector3 operator/ ( T s)const + Vector3 operator/(T s) const { return Vector3(x / s, y / s, z / s); } - Vector3& operator/=( T s) + Vector3& operator/=(T s) { x /= s; y /= s; @@ -360,12 +356,12 @@ template <class T> struct Vector3 return *this; } - Vector3 operator/( const Vector3 &right )const + Vector3 operator/(const Vector3& right) const { return Vector3(x / right.x, y / right.y, z / right.z); } - Vector3& operator/=( const Vector3 &right) + Vector3& operator/=(const Vector3& right) { x /= right.x; y /= right.y; @@ -373,84 +369,80 @@ template <class T> struct Vector3 return *this; } - bool operator == (const Vector3 &right)const + bool operator==(const Vector3& right) const { return x == right.x && y == right.y && z == right.z; } - bool operator != (const Vector3 &right)const + bool operator!=(const Vector3& right) const { return !(*this == right); } - Vector3 operator < ( const Vector3 &right )const - { - return Vector3(x < right.x ? static_cast<T>(1) : static_cast<T>(0), - y < right.y ? static_cast<T>(1) : static_cast<T>(0), - z < right.z ? static_cast<T>(1) : static_cast<T>(0)); - } - - Vector3 operator > ( const Vector3 &right )const - { - return Vector3(x > right.x ? static_cast<T>(1) : static_cast<T>(0), - y > right.y ? static_cast<T>(1) : static_cast<T>(0), - z > right.z ? static_cast<T>(1) : static_cast<T>(0)); - } - - Vector3 operator <= ( const Vector3 &right )const - { - return Vector3(x <= right.x ? static_cast<T>(1) : static_cast<T>(0), - y <= right.y ? static_cast<T>(1) : static_cast<T>(0), - z <= right.z ? static_cast<T>(1) : static_cast<T>(0)); - } - - Vector3 operator >= ( const Vector3 &right )const - { - return Vector3(x >= right.x ? static_cast<T>(1) : static_cast<T>(0), - y >= right.y ? static_cast<T>(1) : static_cast<T>(0), - z >= right.z ? static_cast<T>(1) : static_cast<T>(0)); - } + Vector3 operator<(const Vector3& right) const + { + return Vector3(x < right.x ? static_cast<T>(1) : static_cast<T>(0), + y < right.y ? static_cast<T>(1) : static_cast<T>(0), + z < right.z ? static_cast<T>(1) : static_cast<T>(0)); + } + + Vector3 operator>(const Vector3& right) const + { + return Vector3(x > right.x ? static_cast<T>(1) : static_cast<T>(0), + y > right.y ? static_cast<T>(1) : static_cast<T>(0), + z > right.z ? static_cast<T>(1) : static_cast<T>(0)); + } + + Vector3 operator<=(const Vector3& right) const + { + return Vector3(x <= right.x ? static_cast<T>(1) : static_cast<T>(0), + y <= right.y ? static_cast<T>(1) : static_cast<T>(0), + z <= right.z ? static_cast<T>(1) : static_cast<T>(0)); + } + + Vector3 operator>=(const Vector3& right) const + { + return Vector3(x >= right.x ? static_cast<T>(1) : static_cast<T>(0), + y >= right.y ? static_cast<T>(1) : static_cast<T>(0), + z >= right.z ? static_cast<T>(1) : static_cast<T>(0)); + } T& operator[](size_t index) { return reinterpret_cast<T*>(this)[index]; } - const T& operator[](size_t index)const + const T& operator[](size_t index) const { return reinterpret_cast<const T*>(this)[index]; } - Vector3() : x(0), y(0), z(0) {} - Vector3(T _x, T _y, T _z) : x(_x), y(_y), z(_z) { } + Vector3() : + x(0), y(0), z(0) {} + Vector3(T _x, T _y, T _z) : + x(_x), y(_y), z(_z) {} - template<typename Y> + template <typename Y> static Vector3 MakeVector(Y it) { - return Vector3 - { - static_cast<T>(*it++), - static_cast<T>(*it++), - static_cast<T>(*it++) - }; + return Vector3{static_cast<T>(*it++), + static_cast<T>(*it++), + static_cast<T>(*it++)}; } - template<typename Y> - Vector3<Y> Recast()const + template <typename Y> + Vector3<Y> Recast() const { - return Vector3<Y> - { - static_cast<Y>(x), - static_cast<Y>(y), - static_cast<Y>(z) - }; + return Vector3<Y>{static_cast<Y>(x), + static_cast<Y>(y), + static_cast<Y>(z)}; } - operator Vector2<T>()const{return Vector2<T>(x,y);} + operator Vector2<T>() const { return Vector2<T>(x, y); } }; template <class T> -Vector3<T> operator*(T s, const Vector3<T> &a) +Vector3<T> operator*(T s, const Vector3<T>& a) { return a * s; } @@ -476,17 +468,17 @@ template <class T> struct Vector4 }; }; - Vector4 operator-( const Vector4 &right)const + Vector4 operator-(const Vector4& right) const { return Vector4(x - right.x, y - right.y, z - right.z, w - right.w); } - Vector4 operator-()const + Vector4 operator-() const { return Vector4(-x, -y, -z, -w); } - Vector4& operator-=(const Vector4<T> &right) + Vector4& operator-=(const Vector4<T>& right) { x -= right.x; y -= right.y; @@ -495,12 +487,12 @@ template <class T> struct Vector4 return *this; } - Vector4 operator+( const Vector4 &right)const + Vector4 operator+(const Vector4& right) const { return Vector4(x + right.x, y + right.y, z + right.z, w + right.w); } - Vector4& operator+=(const Vector4<T> &right) + Vector4& operator+=(const Vector4<T>& right) { x += right.x; y += right.y; @@ -509,12 +501,12 @@ template <class T> struct Vector4 return *this; } - Vector4 operator*( T s)const + Vector4 operator*(T s) const { return Vector4(x * s, y * s, z * s, w * s); } - Vector4& operator*=( T s) + Vector4& operator*=(T s) { x *= s; y *= s; @@ -523,12 +515,12 @@ template <class T> struct Vector4 return *this; } - Vector4 operator*( const Vector4 &right)const + Vector4 operator*(const Vector4& right) const { return Vector4(x * right.x, y * right.y, z * right.z, w * right.w); } - Vector4& operator*=( const Vector4 &right) + Vector4& operator*=(const Vector4& right) { x *= right.x; y *= right.y; @@ -537,12 +529,12 @@ template <class T> struct Vector4 return *this; } - Vector4 operator/( T s)const + Vector4 operator/(T s) const { return Vector4(x / s, y / s, z / s, w / s); } - Vector4& operator/=( T s) + Vector4& operator/=(T s) { x /= s; y /= s; @@ -551,12 +543,12 @@ template <class T> struct Vector4 return *this; } - Vector4 operator/( const Vector4 &right)const + Vector4 operator/(const Vector4& right) const { return Vector4(x / right.x, y / right.y, z / right.z, w / right.w); } - Vector4& operator/=( const Vector4 &right) + Vector4& operator/=(const Vector4& right) { x /= right.x; y /= right.y; @@ -565,17 +557,17 @@ template <class T> struct Vector4 return *this; } - bool operator == (const Vector4 &right)const + bool operator==(const Vector4& right) const { return x == right.x && y == right.y && z == right.z && w == right.w; } - bool operator != (const Vector4 &right)const + bool operator!=(const Vector4& right) const { return !(*this == right); } - Vector4 operator*(const Matrix4x4<T>& m)const + Vector4 operator*(const Matrix4x4<T>& m) const { Vector4 out; out[0] = x * m[0][0] + y * m[1][0] + z * m[2][0] + w * m[3][0]; @@ -585,7 +577,7 @@ template <class T> struct Vector4 return out; } - Vector4& operator = (const Vector3<T> &v3) + Vector4& operator=(const Vector3<T>& v3) { x = v3.x; y = v3.y; @@ -593,76 +585,73 @@ template <class T> struct Vector4 w = 1; return *this; } - Vector4& operator = (const Vector4 &) = default; - - Vector4 operator < ( const Vector4 &right )const - { - return Vector4(x < right.x ? static_cast<T>(1) : static_cast<T>(0), - y < right.y ? static_cast<T>(1) : static_cast<T>(0), - z < right.z ? static_cast<T>(1) : static_cast<T>(0), - w < right.w ? static_cast<T>(1) : static_cast<T>(0)); - } - - Vector4 operator > ( const Vector4 &right )const - { - return Vector4(x > right.x ? static_cast<T>(1) : static_cast<T>(0), - y > right.y ? static_cast<T>(1) : static_cast<T>(0), - z > right.z ? static_cast<T>(1) : static_cast<T>(0), - w > right.w ? static_cast<T>(1) : static_cast<T>(0)); - } - - Vector4 operator <= ( const Vector4 &right )const - { - return Vector4(x <= right.x ? static_cast<T>(1) : static_cast<T>(0), - y <= right.y ? static_cast<T>(1) : static_cast<T>(0), - z <= right.z ? static_cast<T>(1) : static_cast<T>(0), - w <= right.w ? static_cast<T>(1) : static_cast<T>(0)); - } - - Vector4 operator >= ( const Vector4 &right )const - { - return Vector4(x >= right.x ? static_cast<T>(1) : static_cast<T>(0), - y >= right.y ? static_cast<T>(1) : static_cast<T>(0), - z >= right.z ? static_cast<T>(1) : static_cast<T>(0), - w >= right.w ? static_cast<T>(1) : static_cast<T>(0)); - } + Vector4& operator=(const Vector4&) = default; + + Vector4 operator<(const Vector4& right) const + { + return Vector4(x < right.x ? static_cast<T>(1) : static_cast<T>(0), + y < right.y ? static_cast<T>(1) : static_cast<T>(0), + z < right.z ? static_cast<T>(1) : static_cast<T>(0), + w < right.w ? static_cast<T>(1) : static_cast<T>(0)); + } + + Vector4 operator>(const Vector4& right) const + { + return Vector4(x > right.x ? static_cast<T>(1) : static_cast<T>(0), + y > right.y ? static_cast<T>(1) : static_cast<T>(0), + z > right.z ? static_cast<T>(1) : static_cast<T>(0), + w > right.w ? static_cast<T>(1) : static_cast<T>(0)); + } + + Vector4 operator<=(const Vector4& right) const + { + return Vector4(x <= right.x ? static_cast<T>(1) : static_cast<T>(0), + y <= right.y ? static_cast<T>(1) : static_cast<T>(0), + z <= right.z ? static_cast<T>(1) : static_cast<T>(0), + w <= right.w ? static_cast<T>(1) : static_cast<T>(0)); + } + + Vector4 operator>=(const Vector4& right) const + { + return Vector4(x >= right.x ? static_cast<T>(1) : static_cast<T>(0), + y >= right.y ? static_cast<T>(1) : static_cast<T>(0), + z >= right.z ? static_cast<T>(1) : static_cast<T>(0), + w >= right.w ? static_cast<T>(1) : static_cast<T>(0)); + } T& operator[](size_t index) { return reinterpret_cast<T*>(this)[index]; } - const T& operator[](size_t index)const + const T& operator[](size_t index) const { return reinterpret_cast<const T*>(this)[index]; } - Vector4() : x(0), y(0), z(0), w(0) { } - Vector4(T _x, T _y, T _z, T _w) : x(_x), y(_y), z(_z), w(_w) { } - Vector4(const Vector3<T>& v3, T _w) : x(v3.x), y(v3.y), z(v3.z), w(_w) { } + Vector4() : + x(0), y(0), z(0), w(0) {} + Vector4(T _x, T _y, T _z, T _w) : + x(_x), y(_y), z(_z), w(_w) {} + Vector4(const Vector3<T>& v3, T _w) : + x(v3.x), y(v3.y), z(v3.z), w(_w) {} - template<typename Y> + template <typename Y> static Vector4 MakeVector(Y it) { - return Vector4 - { - static_cast<T>(*it++), - static_cast<T>(*it++), - static_cast<T>(*it++), - static_cast<T>(*it++) - }; + return Vector4{static_cast<T>(*it++), + static_cast<T>(*it++), + static_cast<T>(*it++), + static_cast<T>(*it++)}; } - template<typename Y> - Vector4<Y> Recast()const + template <typename Y> + Vector4<Y> Recast() const { - return Vector4<Y> - { - static_cast<Y>(x), - static_cast<Y>(y), - static_cast<Y>(z), - static_cast<Y>(w) - }; + return Vector4<Y>{static_cast<Y>(x), + static_cast<Y>(y), + static_cast<Y>(z), + static_cast<Y>(w)}; } operator Vector3<T>() const @@ -673,7 +662,7 @@ template <class T> struct Vector4 template <class T> -Vector4<T> operator*(T s, const Vector4<T> &a) +Vector4<T> operator*(T s, const Vector4<T>& a) { return a * s; } @@ -685,45 +674,50 @@ template <class T> struct Matrix2x2 { struct { - T _11; T _12; - T _21; T _22; + T _11; + T _12; + T _21; + T _22; }; struct { - T m00; T m01; - T m10; T m11; + T m00; + T m01; + T m10; + T m11; }; T m[2][2]; }; - explicit - Matrix2x2(T value) + explicit Matrix2x2(T value) { _11 = _12 = value; _21 = _22 = value; } - Matrix2x2() : Matrix2x2(0) {} + Matrix2x2() : + Matrix2x2(0) {} Matrix2x2( - T i11, T i12, - T i21, T i22) + T i11, + T i12, + T i21, + T i22) { - _11 = i11; _12 = i12; - _21 = i21; _22 = i22; + _11 = i11; + _12 = i12; + _21 = i21; + _22 = i22; } - template<typename Y> + template <typename Y> static Matrix2x2 MakeMatrix(Y it) { - return Matrix2x2 - { - static_cast<T>(*it++), static_cast<T>(*it++), - static_cast<T>(*it++), static_cast<T>(*it++) - }; + return Matrix2x2{static_cast<T>(*it++), static_cast<T>(*it++), + static_cast<T>(*it++), static_cast<T>(*it++)}; } - bool operator == (const Matrix2x2 &r)const + bool operator==(const Matrix2x2& r) const { for (int i = 0; i < 2; ++i) for (int j = 0; i < 2; ++i) @@ -733,7 +727,7 @@ template <class T> struct Matrix2x2 return true; } - bool operator != (const Matrix2x2 &r)const + bool operator!=(const Matrix2x2& r) const { return !(*this == r); } @@ -743,12 +737,12 @@ template <class T> struct Matrix2x2 return m[row]; } - const T* operator[](size_t row)const + const T* operator[](size_t row) const { return m[row]; } - Matrix2x2& operator *=(T s) + Matrix2x2& operator*=(T s) { for (int i = 0; i < 4; ++i) (reinterpret_cast<T*>(this))[i] *= s; @@ -756,28 +750,24 @@ template <class T> struct Matrix2x2 return *this; } - Matrix2x2& operator *= (const Matrix2x2& right) + Matrix2x2& operator*=(const Matrix2x2& right) { *this = Mul(*this, right); return *this; } - Matrix2x2 Transpose()const + Matrix2x2 Transpose() const { - return Matrix2x2 - { + return Matrix2x2{ _11, _21, - _12, _22 - }; + _12, _22}; } static Matrix2x2 Identity() { - return Matrix2x2 - { + return Matrix2x2{ 1, 0, - 0, 1 - }; + 0, 1}; } static Matrix2x2 Mul(const Matrix2x2& m1, const Matrix2x2& m2) @@ -801,16 +791,16 @@ template <class T> struct Matrix2x2 auto s = std::sin(angleInRadians); auto c = std::cos(angleInRadians); - return Matrix2x2 - { - c, s, - -s, c - }; + return Matrix2x2 // + { + c, s, + -s, c // + }; } - T Determinant()const + T Determinant() const { - return _11*_22 - _12*_21; + return _11 * _22 - _12 * _21; } }; @@ -821,61 +811,85 @@ template <class T> struct Matrix3x3 { struct { - T _11; T _12; T _13; - T _21; T _22; T _23; - T _31; T _32; T _33; + T _11; + T _12; + T _13; + T _21; + T _22; + T _23; + T _31; + T _32; + T _33; }; struct { - T m00; T m01; T m02; - T m10; T m11; T m12; - T m20; T m21; T m22; + T m00; + T m01; + T m02; + T m10; + T m11; + T m12; + T m20; + T m21; + T m22; }; T m[3][3]; }; - explicit - Matrix3x3(T value) + explicit Matrix3x3(T value) { - _11 = _12 = _13 =value; - _21 = _22 = _23 =value; - _31 = _32 = _33 =value; + _11 = _12 = _13 = value; + _21 = _22 = _23 = value; + _31 = _32 = _33 = value; } - Matrix3x3() : Matrix3x3(0) {} + Matrix3x3() : + Matrix3x3(0) {} Matrix3x3( - T i11, T i12, T i13, - T i21, T i22, T i23, - T i31, T i32, T i33 ) - { - _11 = i11; _12 = i12; _13 = i13; - _21 = i21; _22 = i22; _23 = i23; - _31 = i31; _32 = i32; _33 = i33; - } - - template<typename Y> + T i11, + T i12, + T i13, + T i21, + T i22, + T i23, + T i31, + T i32, + T i33) + { + _11 = i11; + _12 = i12; + _13 = i13; + _21 = i21; + _22 = i22; + _23 = i23; + _31 = i31; + _32 = i32; + _33 = i33; + } + + template <typename Y> static Matrix3x3 MakeMatrix(Y it) { - return Matrix3x3 - { - static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), - static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), - static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++) - }; + return Matrix3x3 // + { + static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), + static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), + static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++) // + }; } - bool operator == (const Matrix3x3 &r)const + bool operator==(const Matrix3x3& r) const { - for( int i = 0; i < 3; ++i ) - for( int j = 0; i < 3; ++i ) - if( (*this)[i][j] != r[i][j] ) + for (int i = 0; i < 3; ++i) + for (int j = 0; i < 3; ++i) + if ((*this)[i][j] != r[i][j]) return false; return true; } - bool operator != (const Matrix3x3 &r)const + bool operator!=(const Matrix3x3& r) const { return !(*this == r); } @@ -885,43 +899,43 @@ template <class T> struct Matrix3x3 return m[row]; } - const T* operator[](size_t row)const + const T* operator[](size_t row) const { return m[row]; } - Matrix3x3& operator *=(T s) + Matrix3x3& operator*=(T s) { - for( int i = 0; i < 9; ++i ) + for (int i = 0; i < 9; ++i) (reinterpret_cast<T*>(this))[i] *= s; return *this; } - Matrix3x3& operator *= (const Matrix3x3& right) + Matrix3x3& operator*=(const Matrix3x3& right) { *this = Mul(*this, right); return *this; } - Matrix3x3 Transpose()const + Matrix3x3 Transpose() const { - return Matrix3x3 - { - _11, _21, _31, - _12, _22, _32, - _13, _23, _33 - }; + return Matrix3x3 // + { + _11, _21, _31, + _12, _22, _32, + _13, _23, _33 // + }; } static Matrix3x3 Identity() { - return Matrix3x3 - { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - }; + return Matrix3x3 // + { + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 // + }; } static Matrix3x3 Mul(const Matrix3x3& m1, const Matrix3x3& m2) @@ -941,12 +955,12 @@ template <class T> struct Matrix3x3 return mOut; } - T Determinant()const + T Determinant() const { T det = 0; - det += _11 * (_22*_33 - _32*_23); - det -= _12 * (_21*_33 - _31*_23); - det += _13 * (_21*_32 - _31*_22); + det += _11 * (_22 * _33 - _32 * _23); + det -= _12 * (_21 * _33 - _31 * _23); + det += _13 * (_21 * _32 - _31 * _22); return det; } }; @@ -957,23 +971,46 @@ template <class T> struct Matrix4x4 { struct { - T _11; T _12; T _13; T _14; - T _21; T _22; T _23; T _24; - T _31; T _32; T _33; T _34; - T _41; T _42; T _43; T _44; + T _11; + T _12; + T _13; + T _14; + T _21; + T _22; + T _23; + T _24; + T _31; + T _32; + T _33; + T _34; + T _41; + T _42; + T _43; + T _44; }; struct { - T m00; T m01; T m02; T m03; - T m10; T m11; T m12; T m13; - T m20; T m21; T m22; T m23; - T m30; T m31; T m32; T m33; + T m00; + T m01; + T m02; + T m03; + T m10; + T m11; + T m12; + T m13; + T m20; + T m21; + T m22; + T m23; + T m30; + T m31; + T m32; + T m33; }; T m[4][4]; }; - explicit - Matrix4x4(T value) + explicit Matrix4x4(T value) { _11 = _12 = _13 = _14 = value; _21 = _22 = _23 = _24 = value; @@ -981,44 +1018,68 @@ template <class T> struct Matrix4x4 _41 = _42 = _43 = _44 = value; } - Matrix4x4() : Matrix4x4(0) {} + Matrix4x4() : + Matrix4x4(0) {} Matrix4x4( - T i11, T i12, T i13, T i14, - T i21, T i22, T i23, T i24, - T i31, T i32, T i33, T i34, - T i41, T i42, T i43, T i44 - ) - { - _11 = i11; _12 = i12; _13 = i13; _14 = i14; - _21 = i21; _22 = i22; _23 = i23; _24 = i24; - _31 = i31; _32 = i32; _33 = i33; _34 = i34; - _41 = i41; _42 = i42; _43 = i43; _44 = i44; - } - - template<typename Y> + T i11, + T i12, + T i13, + T i14, + T i21, + T i22, + T i23, + T i24, + T i31, + T i32, + T i33, + T i34, + T i41, + T i42, + T i43, + T i44) + { + _11 = i11; + _12 = i12; + _13 = i13; + _14 = i14; + _21 = i21; + _22 = i22; + _23 = i23; + _24 = i24; + _31 = i31; + _32 = i32; + _33 = i33; + _34 = i34; + _41 = i41; + _42 = i42; + _43 = i43; + _44 = i44; + } + + template <typename Y> static Matrix4x4 MakeMatrix(Y it) { - return Matrix4x4 - { - static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), - static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), - static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), - static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++) - }; + return Matrix4x4 // + { + static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), + static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), + static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), + static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++), static_cast<T>(*it++) // + }; } - bool operator == (const Matrix4x4 &r)const + bool operator==(const Matrix4x4& r) const { - for( int i = 0; i < 4; ++i ) - for( int j = 0; i < 4; ++i ) - if( (*this)[i][j] != r[i][j] ) + for (int i = 0; i < 4; ++i) + for (int j = 0; i < 4; ++i) + if ((*this)[i][j] != r[i][j]) return false; return true; } - bool operator != (const Matrix4x4 &r)const + bool operator!=(const Matrix4x4& r) const { return !(*this == r); } @@ -1028,56 +1089,56 @@ template <class T> struct Matrix4x4 return m[row]; } - const T* operator[](size_t row)const + const T* operator[](size_t row) const { return m[row]; } - Matrix4x4& operator *=(T s) + Matrix4x4& operator*=(T s) { - for( int i = 0; i < 16; ++i ) + for (int i = 0; i < 16; ++i) (reinterpret_cast<T*>(this))[i] *= s; return *this; } - Matrix4x4& operator *= (const Matrix4x4& right) + Matrix4x4& operator*=(const Matrix4x4& right) { *this = Mul(*this, right); return *this; } - Matrix4x4 Transpose()const + Matrix4x4 Transpose() const { - return Matrix4x4 - { - _11, _21, _31, _41, - _12, _22, _32, _42, - _13, _23, _33, _43, - _14, _24, _34, _44 - }; + return Matrix4x4 // + { + _11, _21, _31, _41, + _12, _22, _32, _42, + _13, _23, _33, _43, + _14, _24, _34, _44 // + }; } static Matrix4x4 Identity() { - return Matrix4x4 - { - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - }; + return Matrix4x4 // + { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 // + }; } static Matrix4x4 Translation(T x, T y, T z) { - return Matrix4x4 - { - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - x, y, z, 1 - }; + return Matrix4x4 // + { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + x, y, z, 1 // + }; } static Matrix4x4 Translation(const Vector3<T>& v) @@ -1087,13 +1148,13 @@ template <class T> struct Matrix4x4 static Matrix4x4 Scale(T x, T y, T z) { - return Matrix4x4 - { - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 - }; + return Matrix4x4 // + { + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 // + }; } static Matrix4x4 Scale(const Vector3<T>& v) @@ -1103,7 +1164,7 @@ template <class T> struct Matrix4x4 static Matrix4x4 Scale(T s) { - return Scale(s,s,s); + return Scale(s, s, s); } @@ -1115,13 +1176,13 @@ template <class T> struct Matrix4x4 auto s = std::sin(angleInRadians); auto c = std::cos(angleInRadians); - return Matrix4x4 - { - 1, 0, 0, 0, - 0, c, s, 0, - 0, -s, c, 0, - 0, 0, 0, 1 - }; + return Matrix4x4 // clang-format off + { + 1, 0, 0, 0, + 0, c, s, 0, + 0, -s, c, 0, + 0, 0, 0, 1 // clang-format on + }; } // D3D-style left-handed matrix that rotates a point around the y axis. Angle (in radians) @@ -1132,13 +1193,13 @@ template <class T> struct Matrix4x4 auto s = std::sin(angleInRadians); auto c = std::cos(angleInRadians); - return Matrix4x4 - { - c, 0, -s, 0, - 0, 1, 0, 0, - s, 0, c, 0, - 0, 0, 0, 1 - }; + return Matrix4x4 // clang-format off + { + c, 0, -s, 0, + 0, 1, 0, 0, + s, 0, c, 0, + 0, 0, 0, 1 // clang-format on + }; } // D3D-style left-handed matrix that rotates a point around the z axis. Angle (in radians) @@ -1149,13 +1210,13 @@ template <class T> struct Matrix4x4 auto s = std::sin(angleInRadians); auto c = std::cos(angleInRadians); - return Matrix4x4 - { - c, s, 0, 0, - -s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - }; + return Matrix4x4 // clang-format off + { + c, s, 0, 0, + -s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 // clang-format on + }; } // 3D Rotation matrix for an arbitrary axis specified by x, y and z @@ -1163,26 +1224,26 @@ template <class T> struct Matrix4x4 { axis = normalize(axis); - auto sinAngle = std::sin(angleInRadians); - auto cosAngle = std::cos(angleInRadians); + auto sinAngle = std::sin(angleInRadians); + auto cosAngle = std::cos(angleInRadians); auto oneMinusCosAngle = 1 - cosAngle; Matrix4x4 mOut; - mOut._11 = 1 + oneMinusCosAngle * (axis.x * axis.x - 1); - mOut._12 = axis.z * sinAngle + oneMinusCosAngle * axis.x * axis.y; + mOut._11 = 1 + oneMinusCosAngle * (axis.x * axis.x - 1); + mOut._12 = axis.z * sinAngle + oneMinusCosAngle * axis.x * axis.y; mOut._13 = -axis.y * sinAngle + oneMinusCosAngle * axis.x * axis.z; - mOut._41 = 0; + mOut._41 = 0; mOut._21 = -axis.z * sinAngle + oneMinusCosAngle * axis.y * axis.x; - mOut._22 = 1 + oneMinusCosAngle * (axis.y * axis.y - 1); - mOut._23 = axis.x * sinAngle + oneMinusCosAngle * axis.y * axis.z; - mOut._24 = 0; + mOut._22 = 1 + oneMinusCosAngle * (axis.y * axis.y - 1); + mOut._23 = axis.x * sinAngle + oneMinusCosAngle * axis.y * axis.z; + mOut._24 = 0; - mOut._31 = axis.y * sinAngle + oneMinusCosAngle * axis.z * axis.x; + mOut._31 = axis.y * sinAngle + oneMinusCosAngle * axis.z * axis.x; mOut._32 = -axis.x * sinAngle + oneMinusCosAngle * axis.z * axis.y; - mOut._33 = 1 + oneMinusCosAngle * (axis.z * axis.z - 1); - mOut._34 = 0; + mOut._33 = 1 + oneMinusCosAngle * (axis.z * axis.z - 1); + mOut._34 = 0; mOut._41 = 0; mOut._42 = 0; @@ -1192,21 +1253,21 @@ template <class T> struct Matrix4x4 return mOut; } - static Matrix4x4 ViewFromBasis( const Vector3<T>& f3X, const Vector3<T>& f3Y, const Vector3<T>& f3Z ) + static Matrix4x4 ViewFromBasis(const Vector3<T>& f3X, const Vector3<T>& f3Y, const Vector3<T>& f3Z) { - return Matrix4x4 - { - f3X.x, f3Y.x, f3Z.x, 0, - f3X.y, f3Y.y, f3Z.y, 0, - f3X.z, f3Y.z, f3Z.z, 0, - 0, 0, 0, 1 - }; + return Matrix4x4 // clang-format off + { + f3X.x, f3Y.x, f3Z.x, 0, + f3X.y, f3Y.y, f3Z.y, 0, + f3X.z, f3Y.z, f3Z.z, 0, + 0, 0, 0, 1 // clang-format on + }; } - void SetNearFarClipPlanes(T zNear, T zFar, T bIsGL ) + void SetNearFarClipPlanes(T zNear, T zFar, T bIsGL) { - if( bIsGL ) + if (bIsGL) { // https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml // http://www.terathon.com/gdc07_lengyel.pdf @@ -1219,13 +1280,13 @@ template <class T> struct Matrix4x4 // references inverts z axis. // We do not need to do this, because we use DX coordinate - // system for the camera space. Thus we need to invert the - // sign of the values in the third column in the matrix + // system for the camera space. Thus we need to invert the + // sign of the values in the third column in the matrix // from the references: - _33 = -(-(zFar + zNear) / (zFar - zNear)); - _43 = -2 * zNear * zFar / (zFar - zNear); - _34 = -(-1); + _33 = -(-(zFar + zNear) / (zFar - zNear)); + _43 = -2 * zNear * zFar / (zFar - zNear); + _34 = -(-1); } else { @@ -1235,9 +1296,9 @@ template <class T> struct Matrix4x4 } } - void GetNearFarClipPlanes(T& zNear, T& zFar, bool bIsGL)const + void GetNearFarClipPlanes(T& zNear, T& zFar, bool bIsGL) const { - if( bIsGL ) + if (bIsGL) { zNear = _43 / (-1 - _33); zFar = _43 / (+1 - _33); @@ -1245,41 +1306,43 @@ template <class T> struct Matrix4x4 else { zNear = -_43 / _33; - zFar = _33 / (_33 - 1) * zNear; + zFar = _33 / (_33 - 1) * zNear; } } - static Matrix4x4 Projection(T fov, T aspectRatio, T zNear, T zFar, bool bIsGL ) // Left-handed projection + static Matrix4x4 Projection(T fov, T aspectRatio, T zNear, T zFar, bool bIsGL) // Left-handed projection { Matrix4x4 mOut; - auto yScale = static_cast<T>(1) / std::tan(fov / static_cast<T>(2)); - auto xScale = yScale / aspectRatio; - mOut._11 = xScale; - mOut._22 = yScale; + auto yScale = static_cast<T>(1) / std::tan(fov / static_cast<T>(2)); + auto xScale = yScale / aspectRatio; + mOut._11 = xScale; + mOut._22 = yScale; mOut.SetNearFarClipPlanes(zNear, zFar, bIsGL); - + return mOut; } - static Matrix4x4 OrthoOffCenter(T left, T right, T bottom, T top, T zNear, T zFar, bool bIsGL ) // Left-handed ortho projection + static Matrix4x4 OrthoOffCenter(T left, T right, T bottom, T top, T zNear, T zFar, bool bIsGL) // Left-handed ortho projection { - auto _22 = (bIsGL ? 2 : 1 ) / (zFar - zNear); - auto _32 = (bIsGL ? zNear + zFar : zNear ) / (zNear - zFar); + auto _22 = (bIsGL ? 2 : 1) / (zFar - zNear); + auto _32 = (bIsGL ? zNear + zFar : zNear) / (zNear - zFar); + // clang-format off return Matrix4x4 - { - 2 / (right - left), 0, 0, 0, - 0, 2 / (top - bottom), 0, 0, - 0, 0, _22, 0, - (left + right)/(left - right), (top + bottom) / (bottom - top), _32, 1 - }; + { + 2 / (right - left), 0, 0, 0, + 0, 2 / (top - bottom), 0, 0, + 0, 0, _22, 0, + (left + right)/(left - right), (top + bottom) / (bottom - top), _32, 1 + }; + // clang-format on } - static Matrix4x4 Ortho(T width, T height, T zNear, T zFar, bool bIsGL ) // Left-handed ortho projection + static Matrix4x4 Ortho(T width, T height, T zNear, T zFar, bool bIsGL) // Left-handed ortho projection { return OrthoOffCenter( - -width * static_cast<T>(0.5), - +width * static_cast<T>(0.5), + -width * static_cast<T>(0.5), + +width * static_cast<T>(0.5), -height * static_cast<T>(0.5), +height * static_cast<T>(0.5), zNear, zFar, bIsGL); @@ -1302,34 +1365,38 @@ template <class T> struct Matrix4x4 } - T Determinant()const + T Determinant() const { T det = 0.f; - det += _11 * - Matrix3x3<T>(_22,_23,_24, - _32,_33,_34, - _42,_43,_44).Determinant(); + det += _11 * + Matrix3x3<T>(_22, _23, _24, + _32, _33, _34, + _42, _43, _44) + .Determinant(); det -= _12 * - Matrix3x3<T>(_21,_23,_24, - _31,_33,_34, - _41,_43,_44).Determinant(); + Matrix3x3<T>(_21, _23, _24, + _31, _33, _34, + _41, _43, _44) + .Determinant(); - det += _13 * - Matrix3x3<T>(_21,_22,_24, - _31,_32,_34, - _41,_42,_44).Determinant(); + det += _13 * + Matrix3x3<T>(_21, _22, _24, + _31, _32, _34, + _41, _42, _44) + .Determinant(); det -= _14 * - Matrix3x3<T>(_21,_22,_23, - _31,_32,_33, - _41,_42,_43).Determinant(); + Matrix3x3<T>(_21, _22, _23, + _31, _32, _33, + _41, _42, _43) + .Determinant(); return det; } - Matrix4x4 Inverse()const + Matrix4x4 Inverse() const { Matrix4x4 inv; @@ -1337,105 +1404,121 @@ template <class T> struct Matrix4x4 inv._11 = Matrix3x3<T>(_22, _23, _24, _32, _33, _34, - _42, _43, _44).Determinant(); + _42, _43, _44) + .Determinant(); inv._12 = - -Matrix3x3<T>(_21, _23, _24, - _31, _33, _34, - _41, _43, _44).Determinant(); + -Matrix3x3<T>(_21, _23, _24, + _31, _33, _34, + _41, _43, _44) + .Determinant(); - inv._13 = + inv._13 = Matrix3x3<T>(_21, _22, _24, _31, _32, _34, - _41, _42, _44).Determinant(); + _41, _42, _44) + .Determinant(); inv._14 = - -Matrix3x3<T>(_21, _22, _23, - _31, _32, _33, - _41, _42, _43).Determinant(); + -Matrix3x3<T>(_21, _22, _23, + _31, _32, _33, + _41, _42, _43) + .Determinant(); // row 2 inv._21 = - -Matrix3x3<T>(_12, _13, _14, - _32, _33, _34, - _42, _43, _44).Determinant(); + -Matrix3x3<T>(_12, _13, _14, + _32, _33, _34, + _42, _43, _44) + .Determinant(); inv._22 = Matrix3x3<T>(_11, _13, _14, _31, _33, _34, - _41, _43, _44).Determinant(); + _41, _43, _44) + .Determinant(); inv._23 = - -Matrix3x3<T>(_11, _12, _14, - _31, _32, _34, - _41, _42, _44).Determinant(); + -Matrix3x3<T>(_11, _12, _14, + _31, _32, _34, + _41, _42, _44) + .Determinant(); inv._24 = Matrix3x3<T>(_11, _12, _13, _31, _32, _33, - _41, _42, _43).Determinant(); + _41, _42, _43) + .Determinant(); // row 3 inv._31 = - Matrix3x3<T>(_12,_13,_14, - _22,_23,_24, - _42,_43,_44).Determinant(); + Matrix3x3<T>(_12, _13, _14, + _22, _23, _24, + _42, _43, _44) + .Determinant(); inv._32 = - -Matrix3x3<T>(_11,_13,_14, - _21,_23,_24, - _41,_43,_44).Determinant(); + -Matrix3x3<T>(_11, _13, _14, + _21, _23, _24, + _41, _43, _44) + .Determinant(); inv._33 = - Matrix3x3<T>(_11,_12,_14, - _21,_22,_24, - _41,_42,_44).Determinant(); + Matrix3x3<T>(_11, _12, _14, + _21, _22, _24, + _41, _42, _44) + .Determinant(); inv._34 = - -Matrix3x3<T>(_11,_12,_13, - _21,_22,_23, - _41,_42,_43).Determinant(); + -Matrix3x3<T>(_11, _12, _13, + _21, _22, _23, + _41, _42, _43) + .Determinant(); // row 4 inv._41 = - -Matrix3x3<T>(_12, _13, _14, - _22, _23, _24, - _32, _33, _34).Determinant(); + -Matrix3x3<T>(_12, _13, _14, + _22, _23, _24, + _32, _33, _34) + .Determinant(); inv._42 = Matrix3x3<T>(_11, _13, _14, _21, _23, _24, - _31, _33, _34).Determinant(); + _31, _33, _34) + .Determinant(); inv._43 = - -Matrix3x3<T>(_11, _12, _14, - _21, _22, _24, - _31, _32, _34).Determinant(); + -Matrix3x3<T>(_11, _12, _14, + _21, _22, _24, + _31, _32, _34) + .Determinant(); inv._44 = Matrix3x3<T>(_11, _12, _13, _21, _22, _23, - _31, _32, _33).Determinant(); + _31, _32, _33) + .Determinant(); auto det = _11 * inv._11 + _12 * inv._12 + _13 * inv._13 + _14 * inv._14; - inv = inv.Transpose(); + inv = inv.Transpose(); inv *= static_cast<T>(1) / det; return inv; } - Matrix4x4 RemoveTranslation()const + Matrix4x4 RemoveTranslation() const { - return Matrix4x4 - { - _11, _12, _13, _14, - _21, _22, _23, _24, - _31, _32, _33, _34, - 0, 0, 0, _44 - }; + return Matrix4x4 // clang-format off + { + _11, _12, _13, _14, + _21, _22, _23, _24, + _31, _32, _33, _34, + 0, 0, 0, _44 // clang-format on + }; } }; @@ -1443,124 +1526,124 @@ template <class T> struct Matrix4x4 template <class T> -T dot(const Vector2<T> &a, const Vector2<T> &b) +T dot(const Vector2<T>& a, const Vector2<T>& b) { return a.x * b.x + a.y * b.y; } template <class T> -T dot(const Vector3<T> &a, const Vector3<T> &b) +T dot(const Vector3<T>& a, const Vector3<T>& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } template <class T> -T dot(const Vector4<T> &a, const Vector4<T> &b) +T dot(const Vector4<T>& a, const Vector4<T>& b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } template <class VectorType> -auto length(const VectorType &a)->decltype(dot(a,a)) +auto length(const VectorType& a) -> decltype(dot(a, a)) { - return sqrt( dot(a,a) ); + return sqrt(dot(a, a)); } template <class T> -Vector3<T> min(const Vector3<T> &a, const Vector3<T> &b) +Vector3<T> min(const Vector3<T>& a, const Vector3<T>& b) { - return Vector3<T>( std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z) ); + return Vector3<T>(std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z)); } template <class T> -Vector4<T> min(const Vector4<T> &a, const Vector4<T> &b) +Vector4<T> min(const Vector4<T>& a, const Vector4<T>& b) { - return Vector4<T>( std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z), std::min(a.w, b.w) ); + return Vector4<T>(std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z), std::min(a.w, b.w)); } template <class T> -Vector3<T> max(const Vector3<T> &a, const Vector3<T> &b) +Vector3<T> max(const Vector3<T>& a, const Vector3<T>& b) { - return Vector3<T>( std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z) ); + return Vector3<T>(std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z)); } template <class T> -Vector4<T> max(const Vector4<T> &a, const Vector4<T> &b) +Vector4<T> max(const Vector4<T>& a, const Vector4<T>& b) { - return Vector4<T>( std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z), std::max(a.w, b.w) ); + return Vector4<T>(std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z), std::max(a.w, b.w)); } template <class T> -Vector2<T> abs(const Vector2<T> &a) +Vector2<T> abs(const Vector2<T>& a) { - // WARNING: abs() on gcc is for integers only! - return Vector2<T>( a.x < 0 ? -a.x : a.x, - a.y < 0 ? -a.y : a.y); + // WARNING: abs() on gcc is for integers only! + return Vector2<T>(a.x < 0 ? -a.x : a.x, + a.y < 0 ? -a.y : a.y); } template <class T> -Vector3<T> abs(const Vector3<T> &a) +Vector3<T> abs(const Vector3<T>& a) { - // WARNING: abs() on gcc is for integers only! - return Vector3<T>( a.x < 0 ? -a.x : a.x, - a.y < 0 ? -a.y : a.y, - a.z < 0 ? -a.z : a.z); + // WARNING: abs() on gcc is for integers only! + return Vector3<T>(a.x < 0 ? -a.x : a.x, + a.y < 0 ? -a.y : a.y, + a.z < 0 ? -a.z : a.z); } template <class T> -Vector4<T> abs(const Vector4<T> &a) +Vector4<T> abs(const Vector4<T>& a) { - // WARNING: abs() on gcc is for integers only! - return Vector4<T>( a.x < 0 ? -a.x : a.x, - a.y < 0 ? -a.y : a.y, - a.z < 0 ? -a.z : a.z, - a.w < 0 ? -a.w : a.w); + // WARNING: abs() on gcc is for integers only! + return Vector4<T>(a.x < 0 ? -a.x : a.x, + a.y < 0 ? -a.y : a.y, + a.z < 0 ? -a.z : a.z, + a.w < 0 ? -a.w : a.w); } -template<typename T> +template <typename T> T clamp(T val, T _min, T _max) { return val < _min ? _min : (val > _max ? _max : val); } template <class T> -Vector2<T> clamp(const Vector2<T> &a, const Vector2<T> &_min, const Vector2<T> &_max) +Vector2<T> clamp(const Vector2<T>& a, const Vector2<T>& _min, const Vector2<T>& _max) { - return Vector2<T>( clamp(a.x, _min.x, _max.x), - clamp(a.y, _min.y, _max.y)); + return Vector2<T>(clamp(a.x, _min.x, _max.x), + clamp(a.y, _min.y, _max.y)); } template <class T> -Vector3<T> clamp(const Vector3<T> &a, const Vector3<T> &_min, const Vector3<T> &_max) +Vector3<T> clamp(const Vector3<T>& a, const Vector3<T>& _min, const Vector3<T>& _max) { - return Vector3<T>( clamp(a.x, _min.x, _max.x), - clamp(a.y, _min.y, _max.y), - clamp(a.z, _min.z, _max.z)); + return Vector3<T>(clamp(a.x, _min.x, _max.x), + clamp(a.y, _min.y, _max.y), + clamp(a.z, _min.z, _max.z)); } template <class T> -Vector4<T> clamp(const Vector4<T> &a, const Vector4<T> &_min, const Vector4<T> &_max) +Vector4<T> clamp(const Vector4<T>& a, const Vector4<T>& _min, const Vector4<T>& _max) { - return Vector4<T>( clamp(a.x, _min.x, _max.x), - clamp(a.y, _min.y, _max.y), - clamp(a.z, _min.z, _max.z), - clamp(a.w, _min.w, _max.w)); + return Vector4<T>(clamp(a.x, _min.x, _max.x), + clamp(a.y, _min.y, _max.y), + clamp(a.z, _min.z, _max.z), + clamp(a.w, _min.w, _max.w)); } template <class T> -Vector3<T> cross(const Vector3<T> &a, const Vector3<T> &b) +Vector3<T> cross(const Vector3<T>& a, const Vector3<T>& b) { // | i j k | // | a.x a.y a.z | // | b.x b.y b.z | - return Vector3<T>((a.y*b.z)-(a.z*b.y), (a.z*b.x)-(a.x*b.z), (a.x*b.y)-(a.y*b.x)); + return Vector3<T>((a.y * b.z) - (a.z * b.y), (a.z * b.x) - (a.x * b.z), (a.x * b.y) - (a.y * b.x)); } template <class VectorType> -VectorType normalize(const VectorType &a) +VectorType normalize(const VectorType& a) { auto len = length(a); return a / len; @@ -1570,19 +1653,19 @@ VectorType normalize(const VectorType &a) // Template Matrix Operations template <class T> -Matrix4x4<T> operator* (const Matrix4x4<T> &m1, const Matrix4x4<T> &m2) +Matrix4x4<T> operator*(const Matrix4x4<T>& m1, const Matrix4x4<T>& m2) { - return Matrix4x4<T>::Mul( m1, m2 ); + return Matrix4x4<T>::Mul(m1, m2); } template <class T> -Matrix3x3<T> operator* (const Matrix3x3<T> &m1, const Matrix3x3<T> &m2) +Matrix3x3<T> operator*(const Matrix3x3<T>& m1, const Matrix3x3<T>& m2) { - return Matrix3x3<T>::Mul( m1, m2 ); + return Matrix3x3<T>::Mul(m1, m2); } template <class T> -Matrix2x2<T> operator* (const Matrix2x2<T> &m1, const Matrix2x2<T> &m2) +Matrix2x2<T> operator*(const Matrix2x2<T>& m1, const Matrix2x2<T>& m2) { return Matrix2x2<T>::Mul(m1, m2); } @@ -1618,21 +1701,21 @@ struct Quaternion { float4 q; - Quaternion(const float4& _q) noexcept : - q(_q) + Quaternion(const float4& _q) noexcept : + q{_q} {} - Quaternion(float x, float y, float z, float w) noexcept : + Quaternion(float x, float y, float z, float w) noexcept : q{x, y, z, w} { } Quaternion() noexcept {} - bool operator == (const Quaternion& right)const + bool operator==(const Quaternion& right) const { return q == right.q; } - template<typename Y> + template <typename Y> static Quaternion MakeQuaternion(Y it) { return Quaternion{float4::MakeVector(it)}; @@ -1641,87 +1724,87 @@ struct Quaternion static Quaternion RotationFromAxisAngle(const float3& axis, float angle) { Quaternion out{0, 0, 0, 1}; - float norm = length(axis); + float norm = length(axis); if (norm != 0) { float sina2 = sin(0.5f * angle); - out.q[0] = sina2 * axis[0] / norm; - out.q[1] = sina2 * axis[1] / norm; - out.q[2] = sina2 * axis[2] / norm; - out.q[3] = cos(0.5f * angle); + out.q[0] = sina2 * axis[0] / norm; + out.q[1] = sina2 * axis[1] / norm; + out.q[2] = sina2 * axis[2] / norm; + out.q[3] = cos(0.5f * angle); } return out; } void GetAxisAngle(float3& outAxis, float& outAngle) const { - float sina2 = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]); - outAngle = 2.0f * atan2(sina2, q[3]); - float r = (sina2 > 0) ? (1.0f / sina2) : 0; - outAxis[0] = r * q[0]; - outAxis[1] = r * q[1]; - outAxis[2] = r * q[2]; + float sina2 = sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2]); + outAngle = 2.0f * atan2(sina2, q[3]); + float r = (sina2 > 0) ? (1.0f / sina2) : 0; + outAxis[0] = r * q[0]; + outAxis[1] = r * q[1]; + outAxis[2] = r * q[2]; } float4x4 ToMatrix() const { float4x4 out; - float yy2 = 2.0f * q[1] * q[1]; - float xy2 = 2.0f * q[0] * q[1]; - float xz2 = 2.0f * q[0] * q[2]; - float yz2 = 2.0f * q[1] * q[2]; - float zz2 = 2.0f * q[2] * q[2]; - float wz2 = 2.0f * q[3] * q[2]; - float wy2 = 2.0f * q[3] * q[1]; - float wx2 = 2.0f * q[3] * q[0]; - float xx2 = 2.0f * q[0] * q[0]; - out[0][0] = - yy2 - zz2 + 1.0f; - out[0][1] = xy2 + wz2; - out[0][2] = xz2 - wy2; - out[0][3] = 0; - out[1][0] = xy2 - wz2; - out[1][1] = - xx2 - zz2 + 1.0f; - out[1][2] = yz2 + wx2; - out[1][3] = 0; - out[2][0] = xz2 + wy2; - out[2][1] = yz2 - wx2; - out[2][2] = - xx2 - yy2 + 1.0f; - out[2][3] = 0; + float yy2 = 2.0f * q[1] * q[1]; + float xy2 = 2.0f * q[0] * q[1]; + float xz2 = 2.0f * q[0] * q[2]; + float yz2 = 2.0f * q[1] * q[2]; + float zz2 = 2.0f * q[2] * q[2]; + float wz2 = 2.0f * q[3] * q[2]; + float wy2 = 2.0f * q[3] * q[1]; + float wx2 = 2.0f * q[3] * q[0]; + float xx2 = 2.0f * q[0] * q[0]; + out[0][0] = -yy2 - zz2 + 1.0f; + out[0][1] = xy2 + wz2; + out[0][2] = xz2 - wy2; + out[0][3] = 0; + out[1][0] = xy2 - wz2; + out[1][1] = -xx2 - zz2 + 1.0f; + out[1][2] = yz2 + wx2; + out[1][3] = 0; + out[2][0] = xz2 + wy2; + out[2][1] = yz2 - wx2; + out[2][2] = -xx2 - yy2 + 1.0f; + out[2][3] = 0; out[3][0] = out[3][1] = out[3][2] = 0; - out[3][3] = 1; + out[3][3] = 1; return out; } static Quaternion Mul(const Quaternion& q1, const Quaternion& q2) { Quaternion q1_q2; - q1_q2.q.x = q1.q.x * q2.q.w + q1.q.y * q2.q.z - q1.q.z * q2.q.y + q1.q.w * q2.q.x; + q1_q2.q.x = +q1.q.x * q2.q.w + q1.q.y * q2.q.z - q1.q.z * q2.q.y + q1.q.w * q2.q.x; q1_q2.q.y = -q1.q.x * q2.q.z + q1.q.y * q2.q.w + q1.q.z * q2.q.x + q1.q.w * q2.q.y; - q1_q2.q.z = q1.q.x * q2.q.y - q1.q.y * q2.q.x + q1.q.z * q2.q.w + q1.q.w * q2.q.z; + q1_q2.q.z = +q1.q.x * q2.q.y - q1.q.y * q2.q.x + q1.q.z * q2.q.w + q1.q.w * q2.q.z; q1_q2.q.w = -q1.q.x * q2.q.x - q1.q.y * q2.q.y - q1.q.z * q2.q.z + q1.q.w * q2.q.w; return q1_q2; } - Quaternion& operator = (const Quaternion& rhs) + Quaternion& operator=(const Quaternion& rhs) { q = rhs.q; return *this; } - Quaternion& operator*= (const Quaternion& rhs) + Quaternion& operator*=(const Quaternion& rhs) { *this = Mul(*this, rhs); return *this; } - float3 RotateVector(const float3& v)const + float3 RotateVector(const float3& v) const { const float3 axis(q.x, q.y, q.z); return v + 2.f * cross(axis, cross(axis, v) + q.w * v); } }; -inline Quaternion operator* (const Quaternion& q1, const Quaternion& q2) +inline Quaternion operator*(const Quaternion& q1, const Quaternion& q2) { return Quaternion::Mul(q1, q2); } @@ -1747,13 +1830,13 @@ inline Quaternion slerp(Quaternion v0, Quaternion v1, float t, bool DoNotNormali // If the dot product is negative, slerp won't take // the shorter path. Note that v1 and -v1 are equivalent when - // the negation is applied to all four components. Fix by + // the negation is applied to all four components. Fix by // reversing one quaternion. if (dp < 0) { v1.q = -v1.q; - dp = -dp; - } + dp = -dp; + } const double DOT_THRESHOLD = 0.9995; if (dp > DOT_THRESHOLD) @@ -1761,18 +1844,18 @@ inline Quaternion slerp(Quaternion v0, Quaternion v1, float t, bool DoNotNormali // If the inputs are too close for comfort, linearly interpolate // and normalize the result. - Quaternion result = Quaternion{v0.q + t*(v1.q - v0.q)}; - result.q = normalize(result.q); + Quaternion result = Quaternion{v0.q + t * (v1.q - v0.q)}; + result.q = normalize(result.q); return result; } // Since dot is in range [0, DOT_THRESHOLD], acos is safe auto theta_0 = std::acos(dp); // theta_0 = angle between input vectors - auto theta = theta_0*t; // theta = angle between v0 and result + auto theta = theta_0 * t; // theta = angle between v0 and result auto sin_theta = std::sin(theta); // compute this value only once auto sin_theta_0 = std::sin(theta_0); // compute this value only once - auto s0 = cos(theta) - dp * sin_theta / sin_theta_0; // == sin(theta_0 - theta) / sin(theta_0) + auto s0 = cos(theta) - dp * sin_theta / sin_theta_0; // == sin(theta_0 - theta) / sin(theta_0) auto s1 = sin_theta / sin_theta_0; auto v = Quaternion{v0.q * s0 + v1.q * s1}; @@ -1784,13 +1867,13 @@ inline Quaternion slerp(Quaternion v0, Quaternion v1, float t, bool DoNotNormali } -template<typename T> +template <typename T> T lerp(const T& Left, const T& Right, float w) { return Left * (1.f - w) + Right * w; } -template<typename T> +template <typename T> T SmoothStep(T Left, T Right, T w) { auto t = clamp((w - Left) / (Right - Left), static_cast<T>(0), static_cast<T>(1)); @@ -1801,197 +1884,182 @@ T SmoothStep(T Left, T Right, T w) namespace std { - template<typename T> - Diligent::Vector2<T> max( const Diligent::Vector2<T> &Left, const Diligent::Vector2<T> &Right ) - { - return Diligent::Vector2<T>( - std::max( Left.x, Right.x ), - std::max( Left.y, Right.y ) - ); - } +template <typename T> +Diligent::Vector2<T> max(const Diligent::Vector2<T>& Left, const Diligent::Vector2<T>& Right) +{ + return Diligent::Vector2<T>( + std::max(Left.x, Right.x), + std::max(Left.y, Right.y)); +} - template<typename T> - Diligent::Vector3<T> max( const Diligent::Vector3<T> &Left, const Diligent::Vector3<T> &Right ) - { - return Diligent::Vector3<T>( - std::max( Left.x, Right.x ), - std::max( Left.y, Right.y ), - std::max( Left.z, Right.z ) - ); - } +template <typename T> +Diligent::Vector3<T> max(const Diligent::Vector3<T>& Left, const Diligent::Vector3<T>& Right) +{ + return Diligent::Vector3<T>( + std::max(Left.x, Right.x), + std::max(Left.y, Right.y), + std::max(Left.z, Right.z)); +} - template<typename T> - Diligent::Vector4<T> max( const Diligent::Vector4<T> &Left, const Diligent::Vector4<T> &Right ) - { - return Diligent::Vector4<T>( - std::max( Left.x, Right.x ), - std::max( Left.y, Right.y ), - std::max( Left.z, Right.z ), - std::max( Left.w, Right.w ) - ); - } +template <typename T> +Diligent::Vector4<T> max(const Diligent::Vector4<T>& Left, const Diligent::Vector4<T>& Right) +{ + return Diligent::Vector4<T>( + std::max(Left.x, Right.x), + std::max(Left.y, Right.y), + std::max(Left.z, Right.z), + std::max(Left.w, Right.w)); +} - template<typename T> - Diligent::Vector2<T> min( const Diligent::Vector2<T> &Left, const Diligent::Vector2<T> &Right ) - { - return Diligent::Vector2<T>( - std::min( Left.x, Right.x ), - std::min( Left.y, Right.y ) - ); - } +template <typename T> +Diligent::Vector2<T> min(const Diligent::Vector2<T>& Left, const Diligent::Vector2<T>& Right) +{ + return Diligent::Vector2<T>( + std::min(Left.x, Right.x), + std::min(Left.y, Right.y)); +} - template<typename T> - Diligent::Vector3<T> min( const Diligent::Vector3<T> &Left, const Diligent::Vector3<T> &Right ) - { - return Diligent::Vector3<T>( - std::min( Left.x, Right.x ), - std::min( Left.y, Right.y ), - std::min( Left.z, Right.z ) - ); - } +template <typename T> +Diligent::Vector3<T> min(const Diligent::Vector3<T>& Left, const Diligent::Vector3<T>& Right) +{ + return Diligent::Vector3<T>( + std::min(Left.x, Right.x), + std::min(Left.y, Right.y), + std::min(Left.z, Right.z)); +} - template<typename T> - Diligent::Vector4<T> min( const Diligent::Vector4<T> &Left, const Diligent::Vector4<T> &Right ) - { - return Diligent::Vector4<T>( - std::min( Left.x, Right.x ), - std::min( Left.y, Right.y ), - std::min( Left.z, Right.z ), - std::min( Left.w, Right.w ) - ); - } +template <typename T> +Diligent::Vector4<T> min(const Diligent::Vector4<T>& Left, const Diligent::Vector4<T>& Right) +{ + return Diligent::Vector4<T>( + std::min(Left.x, Right.x), + std::min(Left.y, Right.y), + std::min(Left.z, Right.z), + std::min(Left.w, Right.w)); +} - template<typename T> - Diligent::Vector2<T> floor( const Diligent::Vector2<T>& vec ) - { - return Diligent::Vector2<T>( - std::floor( vec.x ), - std::floor( vec.y ) - ); - } +template <typename T> +Diligent::Vector2<T> floor(const Diligent::Vector2<T>& vec) +{ + return Diligent::Vector2<T>( + std::floor(vec.x), + std::floor(vec.y)); +} - template<typename T> - Diligent::Vector3<T> floor( const Diligent::Vector3<T>& vec ) - { - return Diligent::Vector3<T>( - std::floor( vec.x ), - std::floor( vec.y ), - std::floor( vec.z ) - ); - } +template <typename T> +Diligent::Vector3<T> floor(const Diligent::Vector3<T>& vec) +{ + return Diligent::Vector3<T>( + std::floor(vec.x), + std::floor(vec.y), + std::floor(vec.z)); +} - template<typename T> - Diligent::Vector4<T> floor( const Diligent::Vector4<T>& vec ) - { - return Diligent::Vector4<T>( - std::floor( vec.x ), - std::floor( vec.y ), - std::floor( vec.z ), - std::floor( vec.w ) - ); - } +template <typename T> +Diligent::Vector4<T> floor(const Diligent::Vector4<T>& vec) +{ + return Diligent::Vector4<T>( + std::floor(vec.x), + std::floor(vec.y), + std::floor(vec.z), + std::floor(vec.w)); +} - template<typename T> - Diligent::Vector2<T> ceil( const Diligent::Vector2<T>& vec ) - { - return Diligent::Vector2<T>( - std::ceil( vec.x ), - std::ceil( vec.y ) - ); - } +template <typename T> +Diligent::Vector2<T> ceil(const Diligent::Vector2<T>& vec) +{ + return Diligent::Vector2<T>( + std::ceil(vec.x), + std::ceil(vec.y)); +} - template<typename T> - Diligent::Vector3<T> ceil( const Diligent::Vector3<T>& vec ) - { - return Diligent::Vector3<T>( - std::ceil( vec.x ), - std::ceil( vec.y ), - std::ceil( vec.z ) - ); - } +template <typename T> +Diligent::Vector3<T> ceil(const Diligent::Vector3<T>& vec) +{ + return Diligent::Vector3<T>( + std::ceil(vec.x), + std::ceil(vec.y), + std::ceil(vec.z)); +} - template<typename T> - Diligent::Vector4<T> ceil( const Diligent::Vector4<T>& vec ) - { - return Diligent::Vector4<T>( - std::ceil( vec.x ), - std::ceil( vec.y ), - std::ceil( vec.z ), - std::ceil( vec.w ) - ); - } +template <typename T> +Diligent::Vector4<T> ceil(const Diligent::Vector4<T>& vec) +{ + return Diligent::Vector4<T>( + std::ceil(vec.x), + std::ceil(vec.y), + std::ceil(vec.z), + std::ceil(vec.w)); +} - template<typename T> - struct hash<Diligent::Vector2<T>> +template <typename T> +struct hash<Diligent::Vector2<T>> +{ + size_t operator()(const Diligent::Vector2<T>& v2) const { - size_t operator()( const Diligent::Vector2<T> &v2 ) const - { - return Diligent::ComputeHash(v2.x, v2.y); - } - }; + return Diligent::ComputeHash(v2.x, v2.y); + } +}; - template<typename T> - struct hash<Diligent::Vector3<T>> +template <typename T> +struct hash<Diligent::Vector3<T>> +{ + size_t operator()(const Diligent::Vector3<T>& v3) const { - size_t operator()( const Diligent::Vector3<T> &v3 ) const - { - return Diligent::ComputeHash(v3.x, v3.y, v3.z); - } - }; + return Diligent::ComputeHash(v3.x, v3.y, v3.z); + } +}; - template<typename T> - struct hash<Diligent::Vector4<T>> +template <typename T> +struct hash<Diligent::Vector4<T>> +{ + size_t operator()(const Diligent::Vector4<T>& v4) const { - size_t operator()( const Diligent::Vector4<T> &v4 ) const - { - return Diligent::ComputeHash(v4.x, v4.y, v4.z, v4.w); - } - }; + return Diligent::ComputeHash(v4.x, v4.y, v4.z, v4.w); + } +}; - template<typename T> - struct hash<Diligent::Matrix2x2<T>> +template <typename T> +struct hash<Diligent::Matrix2x2<T>> +{ + size_t operator()(const Diligent::Matrix2x2<T>& m) const { - size_t operator()(const Diligent::Matrix2x2<T> &m) const - { - return Diligent::ComputeHash( - m.m00, m.m01, - m.m10, m.m11 - ); - } - }; + return Diligent::ComputeHash( + m.m00, m.m01, + m.m10, m.m11); + } +}; - template<typename T> - struct hash<Diligent::Matrix3x3<T>> +template <typename T> +struct hash<Diligent::Matrix3x3<T>> +{ + size_t operator()(const Diligent::Matrix3x3<T>& m) const { - size_t operator()( const Diligent::Matrix3x3<T> &m ) const - { - return Diligent::ComputeHash( - m.m00, m.m01, m.m02, - m.m10, m.m11, m.m12, - m.m20, m.m21, m.m22 - ); - } - }; + return Diligent::ComputeHash( + m.m00, m.m01, m.m02, + m.m10, m.m11, m.m12, + m.m20, m.m21, m.m22); + } +}; - template<typename T> - struct hash<Diligent::Matrix4x4<T>> +template <typename T> +struct hash<Diligent::Matrix4x4<T>> +{ + size_t operator()(const Diligent::Matrix4x4<T>& m) const { - size_t operator()( const Diligent::Matrix4x4<T> &m ) const - { - return Diligent::ComputeHash( - m.m00, m.m01, m.m02, m.m03, - m.m10, m.m11, m.m12, m.m13, - m.m20, m.m21, m.m22, m.m23, - m.m30, m.m31, m.m32, m.m33 - ); - } - }; + return Diligent::ComputeHash( + m.m00, m.m01, m.m02, m.m03, + m.m10, m.m11, m.m12, m.m13, + m.m20, m.m21, m.m22, m.m23, + m.m30, m.m31, m.m32, m.m33); + } +}; } // namespace std #ifdef _MSC_VER -# pragma warning(pop) +# pragma warning(pop) #endif diff --git a/Common/interface/DataBlobImpl.h b/Common/interface/DataBlobImpl.h index 244dd074..aa1053af 100644 --- a/Common/interface/DataBlobImpl.h +++ b/Common/interface/DataBlobImpl.h @@ -33,7 +33,7 @@ namespace Diligent { - + /// Base interface for a data blob class DataBlobImpl : public Diligent::ObjectBase<IDataBlob> { @@ -42,19 +42,19 @@ public: DataBlobImpl(IReferenceCounters* pRefCounters, size_t InitialSize = 0); - virtual void QueryInterface(const INTERFACE_ID &IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override; /// Sets the size of the internal data buffer - virtual void Resize( size_t NewSize )override; + virtual void Resize(size_t NewSize) override; /// Returns the size of the internal data buffer - virtual size_t GetSize()override; + virtual size_t GetSize() override; /// Returns the pointer to the internal data buffer - virtual void* GetDataPtr()override; + virtual void* GetDataPtr() override; private: std::vector<Uint8> m_DataBuff; }; -} +} // namespace Diligent diff --git a/Common/interface/DefaultRawMemoryAllocator.h b/Common/interface/DefaultRawMemoryAllocator.h index 07c94405..414801ef 100644 --- a/Common/interface/DefaultRawMemoryAllocator.h +++ b/Common/interface/DefaultRawMemoryAllocator.h @@ -35,20 +35,20 @@ class DefaultRawMemoryAllocator : public IMemoryAllocator { public: DefaultRawMemoryAllocator(); - + /// Allocates block of memory - virtual void* Allocate( size_t Size, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber)override; + virtual void* Allocate(size_t Size, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber) override; /// Releases memory - virtual void Free(void *Ptr)override; + virtual void Free(void* Ptr) override; static DefaultRawMemoryAllocator& GetAllocator(); private: DefaultRawMemoryAllocator(const DefaultRawMemoryAllocator&) = delete; - DefaultRawMemoryAllocator(DefaultRawMemoryAllocator&&) = delete; - DefaultRawMemoryAllocator& operator = (const DefaultRawMemoryAllocator&) = delete; - DefaultRawMemoryAllocator& operator = (DefaultRawMemoryAllocator&&) = delete; + DefaultRawMemoryAllocator(DefaultRawMemoryAllocator&&) = delete; + DefaultRawMemoryAllocator& operator=(const DefaultRawMemoryAllocator&) = delete; + DefaultRawMemoryAllocator& operator=(DefaultRawMemoryAllocator&&) = delete; }; - -} + +} // namespace Diligent diff --git a/Common/interface/FileWrapper.h b/Common/interface/FileWrapper.h index 2786305e..1967849e 100644 --- a/Common/interface/FileWrapper.h +++ b/Common/interface/FileWrapper.h @@ -33,13 +33,13 @@ namespace Diligent class FileWrapper { public: - FileWrapper( ) : - m_pFile(nullptr) + FileWrapper() : + m_pFile{nullptr} {} - FileWrapper( const Diligent::Char *Path, - EFileAccessMode Access = EFileAccessMode::Read) : - m_pFile( nullptr ) + FileWrapper(const Char* Path, + EFileAccessMode Access = EFileAccessMode::Read) : + m_pFile{nullptr} { FileOpenAttribs OpenAttribs(Path, Access); Open(OpenAttribs); @@ -52,19 +52,19 @@ public: void Open(const FileOpenAttribs& OpenAttribs) { - VERIFY( !m_pFile, "Another file already attached" ); + VERIFY(!m_pFile, "Another file already attached"); Close(); - m_pFile = FileSystem::OpenFile( OpenAttribs ); + m_pFile = FileSystem::OpenFile(OpenAttribs); } - - CFile *Detach() + + CFile* Detach() { - CFile *pFile = m_pFile; - m_pFile = NULL; + CFile* pFile = m_pFile; + m_pFile = NULL; return pFile; } - void Attach(CFile *pFile) + void Attach(CFile* pFile) { VERIFY(!m_pFile, "Another file already attached"); Close(); @@ -73,19 +73,19 @@ public: void Close() { - if( m_pFile ) + if (m_pFile) FileSystem::ReleaseFile(m_pFile); m_pFile = nullptr; } - operator CFile*(){return m_pFile;} - CFile* operator->(){return m_pFile;} + operator CFile*() { return m_pFile; } + CFile* operator->() { return m_pFile; } private: FileWrapper(const FileWrapper&); const FileWrapper& operator=(const FileWrapper&); - CFile *m_pFile; + CFile* m_pFile; }; -} +} // namespace Diligent diff --git a/Common/interface/FixedBlockMemoryAllocator.h b/Common/interface/FixedBlockMemoryAllocator.h index 9f1186a7..4ee6dd9f 100644 --- a/Common/interface/FixedBlockMemoryAllocator.h +++ b/Common/interface/FixedBlockMemoryAllocator.h @@ -40,12 +40,12 @@ namespace Diligent { #ifdef _DEBUG - inline void FillWithDebugPattern(void *ptr, Uint8 Pattern, size_t NumBytes) - { - memset(ptr, Pattern, NumBytes); - } +inline void FillWithDebugPattern(void* ptr, Uint8 Pattern, size_t NumBytes) +{ + memset(ptr, Pattern, NumBytes); +} #else - #define FillWithDebugPattern(...) +# define FillWithDebugPattern(...) #endif /// Memory allocator that allocates memory in a fixed-size chunks @@ -56,48 +56,53 @@ public: ~FixedBlockMemoryAllocator(); /// Allocates block of memory - virtual void* Allocate( size_t Size, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber)override final; + virtual void* Allocate(size_t Size, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber) override final; /// Releases memory - virtual void Free(void *Ptr)override final; - + virtual void Free(void* Ptr) override final; + private: + // clang-format off FixedBlockMemoryAllocator (const FixedBlockMemoryAllocator&) = delete; FixedBlockMemoryAllocator (FixedBlockMemoryAllocator&&) = delete; FixedBlockMemoryAllocator& operator = (const FixedBlockMemoryAllocator&) = delete; FixedBlockMemoryAllocator& operator = (FixedBlockMemoryAllocator&&) = delete; + // clang-format on void CreateNewPage(); // Memory page class is based on the fixed-size memory pool described in "Fast Efficient Fixed-Size Memory Pool" // by Ben Kenwright class MemoryPage - { + { public: static constexpr Uint8 NewPageMemPattern = 0xAA; static constexpr Uint8 AllocatedBlockMemPattern = 0xAB; static constexpr Uint8 DeallocatedBlockMemPattern = 0xDE; static constexpr Uint8 InitializedBlockMemPattern = 0xCF; - MemoryPage(FixedBlockMemoryAllocator& OwnerAllocator): - m_NumFreeBlocks (OwnerAllocator.m_NumBlocksInPage), - m_NumInitializedBlocks(0), - m_pOwnerAllocator (&OwnerAllocator) + MemoryPage(FixedBlockMemoryAllocator& OwnerAllocator) : + // clang-format off + m_NumFreeBlocks {OwnerAllocator.m_NumBlocksInPage}, + m_NumInitializedBlocks{0}, + m_pOwnerAllocator {&OwnerAllocator} + // clang-format on { auto PageSize = OwnerAllocator.m_BlockSize * OwnerAllocator.m_NumBlocksInPage; - m_pPageStart = reinterpret_cast<Uint8*>( - OwnerAllocator.m_RawMemoryAllocator.Allocate(PageSize, "FixedBlockMemoryAllocator page", __FILE__, __LINE__) - ); + m_pPageStart = reinterpret_cast<Uint8*>( + OwnerAllocator.m_RawMemoryAllocator.Allocate(PageSize, "FixedBlockMemoryAllocator page", __FILE__, __LINE__)); m_pNextFreeBlock = m_pPageStart; FillWithDebugPattern(m_pPageStart, NewPageMemPattern, PageSize); } - MemoryPage(MemoryPage&& Page) noexcept : - m_NumFreeBlocks (Page.m_NumFreeBlocks), - m_NumInitializedBlocks(Page.m_NumInitializedBlocks), - m_pPageStart (Page.m_pPageStart), - m_pNextFreeBlock (Page.m_pNextFreeBlock), - m_pOwnerAllocator (Page.m_pOwnerAllocator) + MemoryPage(MemoryPage&& Page) noexcept : + // clang-format off + m_NumFreeBlocks {Page.m_NumFreeBlocks }, + m_NumInitializedBlocks{Page.m_NumInitializedBlocks}, + m_pPageStart {Page.m_pPageStart }, + m_pNextFreeBlock {Page.m_pNextFreeBlock }, + m_pOwnerAllocator {Page.m_pOwnerAllocator } + // clang-format on { Page.m_NumFreeBlocks = 0; Page.m_NumInitializedBlocks = 0; @@ -106,31 +111,31 @@ private: Page.m_pOwnerAllocator = nullptr; } - ~MemoryPage() - { - if(m_pOwnerAllocator) + ~MemoryPage() + { + if (m_pOwnerAllocator) m_pOwnerAllocator->m_RawMemoryAllocator.Free(m_pPageStart); } void* GetBlockStartAddress(Uint32 BlockIndex) const { VERIFY_EXPR(m_pOwnerAllocator != nullptr); - VERIFY(BlockIndex >= 0 && BlockIndex < m_pOwnerAllocator->m_NumBlocksInPage, "Invalid block index" ); + VERIFY(BlockIndex >= 0 && BlockIndex < m_pOwnerAllocator->m_NumBlocksInPage, "Invalid block index"); return reinterpret_cast<Uint8*>(m_pPageStart) + BlockIndex * m_pOwnerAllocator->m_BlockSize; } #ifdef _DEBUG - void dbgVerifyAddress(const void* pBlockAddr)const + void dbgVerifyAddress(const void* pBlockAddr) const { size_t Delta = reinterpret_cast<const Uint8*>(pBlockAddr) - reinterpret_cast<Uint8*>(m_pPageStart); VERIFY(Delta % m_pOwnerAllocator->m_BlockSize == 0, "Invalid address"); Uint32 BlockIndex = static_cast<Uint32>(Delta / m_pOwnerAllocator->m_BlockSize); - VERIFY(BlockIndex >= 0 && BlockIndex < m_pOwnerAllocator->m_NumBlocksInPage, "Invalid block index" ); + VERIFY(BlockIndex >= 0 && BlockIndex < m_pOwnerAllocator->m_NumBlocksInPage, "Invalid block index"); } #else - #define dbgVerifyAddress(...) +# define dbgVerifyAddress(...) #endif - + void* Allocate() { VERIFY_EXPR(m_pOwnerAllocator != nullptr); @@ -149,33 +154,33 @@ private: // // ___________ ___________ // | | | | - // | 0xcdcdcd | -->| 0xcdcdcd | m_NumInitializedBlocks + // | 0xcdcdcd | -->| 0xcdcdcd | m_NumInitializedBlocks // |-----------| | |-----------| // | | | | | - // m_NumInitializedBlocks | 0xcdcdcd | ==> ---| | + // m_NumInitializedBlocks | 0xcdcdcd | ==> ---| | // |-----------| |-----------| - // + // // ~ ~ ~ ~ // | | | | - // 0 | | | | + // 0 | | | | // ----------- ----------- - // - auto *pUninitializedBlock = GetBlockStartAddress(m_NumInitializedBlocks); + // + auto* pUninitializedBlock = GetBlockStartAddress(m_NumInitializedBlocks); FillWithDebugPattern(pUninitializedBlock, InitializedBlockMemPattern, m_pOwnerAllocator->m_BlockSize); - void** ppNextBlock = reinterpret_cast<void**>( pUninitializedBlock ); + void** ppNextBlock = reinterpret_cast<void**>(pUninitializedBlock); ++m_NumInitializedBlocks; - if( m_NumInitializedBlocks < m_pOwnerAllocator->m_NumBlocksInPage ) + if (m_NumInitializedBlocks < m_pOwnerAllocator->m_NumBlocksInPage) *ppNextBlock = GetBlockStartAddress(m_NumInitializedBlocks); else *ppNextBlock = nullptr; } - + void* res = m_pNextFreeBlock; dbgVerifyAddress(res); // Move pointer to the next free block m_pNextFreeBlock = *reinterpret_cast<void**>(m_pNextFreeBlock); --m_NumFreeBlocks; - if(m_NumFreeBlocks != 0) + if (m_NumFreeBlocks != 0) dbgVerifyAddress(m_pNextFreeBlock); else VERIFY_EXPR(m_pNextFreeBlock == nullptr); @@ -192,47 +197,48 @@ private: FillWithDebugPattern(p, DeallocatedBlockMemPattern, m_pOwnerAllocator->m_BlockSize); // Add block to the beginning of the linked list *reinterpret_cast<void**>(p) = m_pNextFreeBlock; - m_pNextFreeBlock = p; + m_pNextFreeBlock = p; ++m_NumFreeBlocks; } - bool HasSpace()const{return m_NumFreeBlocks>0;} - bool HasAllocations()const{return m_NumFreeBlocks<m_NumInitializedBlocks;} - private: - - MemoryPage(const MemoryPage&)=delete; - MemoryPage& operator = (const MemoryPage)=delete; - MemoryPage& operator = (MemoryPage&&)=delete; + bool HasSpace() const { return m_NumFreeBlocks > 0; } + bool HasAllocations() const { return m_NumFreeBlocks < m_NumInitializedBlocks; } - Uint32 m_NumFreeBlocks = 0; // Num of remaining blocks - Uint32 m_NumInitializedBlocks = 0; // Num of initialized blocks - void* m_pPageStart = nullptr; // Beginning of memory pool - void* m_pNextFreeBlock = nullptr; // Num of next free block - FixedBlockMemoryAllocator *m_pOwnerAllocator = nullptr; + private: + MemoryPage(const MemoryPage&) = delete; + MemoryPage& operator=(const MemoryPage) = delete; + MemoryPage& operator=(MemoryPage&&) = delete; + + Uint32 m_NumFreeBlocks = 0; // Num of remaining blocks + Uint32 m_NumInitializedBlocks = 0; // Num of initialized blocks + void* m_pPageStart = nullptr; // Beginning of memory pool + void* m_pNextFreeBlock = nullptr; // Num of next free block + FixedBlockMemoryAllocator* m_pOwnerAllocator = nullptr; }; - std::vector<MemoryPage, STDAllocatorRawMem<MemoryPage> > m_PagePool; - std::unordered_set<size_t, std::hash<size_t>, std::equal_to<size_t>, STDAllocatorRawMem<size_t> > m_AvailablePages; - typedef std::pair<void* const, size_t> AddrToPageIdMapElem; - std::unordered_map<void*, size_t, std::hash<void*>, std::equal_to<void*>, STDAllocatorRawMem<AddrToPageIdMapElem> > m_AddrToPageId; + std::vector<MemoryPage, STDAllocatorRawMem<MemoryPage>> m_PagePool; + std::unordered_set<size_t, std::hash<size_t>, std::equal_to<size_t>, STDAllocatorRawMem<size_t>> m_AvailablePages; + + using AddrToPageIdMapElem = std::pair<void* const, size_t>; + std::unordered_map<void*, size_t, std::hash<void*>, std::equal_to<void*>, STDAllocatorRawMem<AddrToPageIdMapElem>> m_AddrToPageId; std::mutex m_Mutex; - IMemoryAllocator &m_RawMemoryAllocator; - size_t m_BlockSize; - Uint32 m_NumBlocksInPage; + IMemoryAllocator& m_RawMemoryAllocator; + size_t m_BlockSize; + Uint32 m_NumBlocksInPage; }; IMemoryAllocator& GetRawAllocator(); -template<typename ObjectType> +template <typename ObjectType> class ObjectPool { public: - static void SetRawAllocator(IMemoryAllocator &Allocator) + static void SetRawAllocator(IMemoryAllocator& Allocator) { #ifdef _DEBUG - if(m_bPoolInitialized && m_pRawAllocator != &Allocator) + if (m_bPoolInitialized && m_pRawAllocator != &Allocator) { LOG_WARNING_MESSAGE("Setting pool raw allocator after the pool has been initialized has no effect"); } @@ -242,7 +248,7 @@ public: static void SetPageSize(Uint32 NumAllocationsInPage) { #ifdef _DEBUG - if(m_bPoolInitialized && m_NumAllocationsInPage != NumAllocationsInPage) + if (m_bPoolInitialized && m_NumAllocationsInPage != NumAllocationsInPage) { LOG_WARNING_MESSAGE("Setting pool page size after the pool has been initialized has no effect"); } @@ -258,13 +264,13 @@ public: return ThePool; } - template<typename ... CtorArgTypes> - ObjectType* NewObject(const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber, CtorArgTypes&& ... CtorArgs) + template <typename... CtorArgTypes> + ObjectType* NewObject(const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber, CtorArgTypes&&... CtorArgs) { - void *pRawMem = m_FixedBlockAlloctor.Allocate(sizeof(ObjectType), dbgDescription, dbgFileName, dbgLineNumber); + void* pRawMem = m_FixedBlockAlloctor.Allocate(sizeof(ObjectType), dbgDescription, dbgFileName, dbgLineNumber); try { - return new(pRawMem) ObjectType(std::forward<CtorArgTypes>(CtorArgs)...); + return new (pRawMem) ObjectType(std::forward<CtorArgTypes>(CtorArgs)...); } catch (...) { @@ -275,7 +281,7 @@ public: void Destroy(ObjectType* pObj) { - if(pObj != nullptr) + if (pObj != nullptr) { pObj->~ObjectType(); m_FixedBlockAlloctor.Free(pObj); @@ -283,31 +289,31 @@ public: } private: - static Uint32 m_NumAllocationsInPage; - static IMemoryAllocator *m_pRawAllocator; + static Uint32 m_NumAllocationsInPage; + static IMemoryAllocator* m_pRawAllocator; - ObjectPool() : - m_FixedBlockAlloctor(m_pRawAllocator ? *m_pRawAllocator : GetRawAllocator(), sizeof(ObjectType), m_NumAllocationsInPage) + ObjectPool() : + m_FixedBlockAlloctor(m_pRawAllocator ? *m_pRawAllocator : GetRawAllocator(), sizeof(ObjectType), m_NumAllocationsInPage) {} #ifdef _DEBUG static bool m_bPoolInitialized; #endif FixedBlockMemoryAllocator m_FixedBlockAlloctor; }; -template<typename ObjectType> +template <typename ObjectType> Uint32 ObjectPool<ObjectType>::m_NumAllocationsInPage = 64; -template<typename ObjectType> +template <typename ObjectType> IMemoryAllocator* ObjectPool<ObjectType>::m_pRawAllocator = nullptr; #ifdef _DEBUG -template<typename ObjectType> +template <typename ObjectType> bool ObjectPool<ObjectType>::m_bPoolInitialized = false; #endif -#define SET_POOL_RAW_ALLOCATOR(ObjectType, Allocator)ObjectPool<ObjectType>::SetRawAllocator(Allocator) -#define SET_POOL_PAGE_SIZE(ObjectType, NumAllocationsInPage)ObjectPool<ObjectType>::SetPageSize(NumAllocationsInPage) -#define NEW_POOL_OBJECT(ObjectType, Desc, ...)ObjectPool<ObjectType>::GetPool().NewObject(Desc, __FILE__, __LINE__, ##__VA_ARGS__) -#define DESTROY_POOL_OBJECT(pObject)ObjectPool< std::remove_reference<decltype(*pObject)>::type >::GetPool().Destroy(pObject) +#define SET_POOL_RAW_ALLOCATOR(ObjectType, Allocator) ObjectPool<ObjectType>::SetRawAllocator(Allocator) +#define SET_POOL_PAGE_SIZE(ObjectType, NumAllocationsInPage) ObjectPool<ObjectType>::SetPageSize(NumAllocationsInPage) +#define NEW_POOL_OBJECT(ObjectType, Desc, ...) ObjectPool<ObjectType>::GetPool().NewObject(Desc, __FILE__, __LINE__, ##__VA_ARGS__) +#define DESTROY_POOL_OBJECT(pObject) ObjectPool<std::remove_reference<decltype(*pObject)>::type>::GetPool().Destroy(pObject) -} +} // namespace Diligent diff --git a/Common/interface/HashUtils.h b/Common/interface/HashUtils.h index 2af623e7..ad674a45 100644 --- a/Common/interface/HashUtils.h +++ b/Common/interface/HashUtils.h @@ -34,162 +34,168 @@ namespace Diligent { - // http://www.boost.org/doc/libs/1_35_0/doc/html/hash/combine.html - template<typename T> - void HashCombine(std::size_t &Seed, const T& Val) - { - Seed ^= std::hash<T>()(Val) + 0x9e3779b9 + (Seed << 6) + (Seed >> 2); - } - template<typename FirstArgType, typename... RestArgsType> - void HashCombine( std::size_t &Seed, const FirstArgType& FirstArg, const RestArgsType&... RestArgs ) - { - HashCombine( Seed, FirstArg ); - HashCombine( Seed, RestArgs... ); // recursive call using pack expansion syntax - } +// http://www.boost.org/doc/libs/1_35_0/doc/html/hash/combine.html +template <typename T> +void HashCombine(std::size_t& Seed, const T& Val) +{ + Seed ^= std::hash<T>()(Val) + 0x9e3779b9 + (Seed << 6) + (Seed >> 2); +} - template<typename... ArgsType> - std::size_t ComputeHash( const ArgsType&... Args ) +template <typename FirstArgType, typename... RestArgsType> +void HashCombine(std::size_t& Seed, const FirstArgType& FirstArg, const RestArgsType&... RestArgs) +{ + HashCombine(Seed, FirstArg); + HashCombine(Seed, RestArgs...); // recursive call using pack expansion syntax +} + +template <typename... ArgsType> +std::size_t ComputeHash(const ArgsType&... Args) +{ + std::size_t Seed = 0; + HashCombine(Seed, Args...); + return Seed; +} + +template <typename CharType> +struct CStringHash +{ + size_t operator()(const CharType* str) const { + // http://www.cse.yorku.ca/~oz/hash.html std::size_t Seed = 0; - HashCombine( Seed, Args... ); + while (size_t Ch = *(str++)) + Seed = Seed * 65599 + Ch; return Seed; } +}; - template<typename CharType> - struct CStringHash +template <typename CharType> +struct CStringCompare +{ + bool operator()(const CharType* str1, const CharType* str2) const { - size_t operator()( const CharType *str ) const - { - // http://www.cse.yorku.ca/~oz/hash.html - std::size_t Seed = 0; - while( size_t Ch = *(str++) ) - Seed = Seed * 65599 + Ch; - return Seed; - } - }; + UNSUPPORTED("Template specialization is not implemented"); + return false; + } +}; - template<typename CharType> - struct CStringCompare +template <> +struct CStringCompare<Char> +{ + bool operator()(const Char* str1, const Char* str2) const { - bool operator()( const CharType *str1, const CharType *str2 )const - { - UNSUPPORTED( "Template specialization is not implemented" ); - return false; - } - }; + return strcmp(str1, str2) == 0; + } +}; - template<> - struct CStringCompare<Char> +/// This helper structure is intended to facilitate using strings as a +/// hash table key. It provides constructors that can make a copy of the +/// source string or just keep pointer to it, which enables searching in +/// the hash using raw const Char* pointers. +struct HashMapStringKey +{ +public: + // This constructor can perform implicit const Char* -> HashMapStringKey + // conversion without copying the string + HashMapStringKey(const Char* Str, bool bMakeCopy = false) : + StrPtr{nullptr}, + Hash{0} { - bool operator()( const Char *str1, const Char *str2 )const + VERIFY(Str, "String pointer cannot be null"); + if (bMakeCopy) { - return strcmp( str1, str2 ) == 0; + MakeCopy(Str); } - }; - - /// This helper structure is intended to facilitate using strings as a - /// hash table key. It provides constructors that can make a copy of the - /// source string or just keep pointer to it, which enables searching in - /// the hash using raw const Char* pointers. - struct HashMapStringKey - { - public: - // This constructor can perform implicit const Char* -> HashMapStringKey - // conversion without copying the string - HashMapStringKey(const Char* Str, bool bMakeCopy = false) : - StrPtr(nullptr), - Hash(0) + else { - VERIFY( Str, "String pointer cannot be null" ); - if( bMakeCopy ) - { - MakeCopy( Str ); - } - else - { - StrPtr = Str; - } + StrPtr = Str; } - - explicit // Make this constructor explicit to avoid unintentional string copies + } + + explicit // Make this constructor explicit to avoid unintentional string copies HashMapStringKey(const String& Str) : - StrPtr( nullptr ), - Hash(0) - { - MakeCopy( Str.c_str() ); - } + StrPtr{nullptr}, + Hash{0} + { + MakeCopy(Str.c_str()); + } - HashMapStringKey(HashMapStringKey&& Key)noexcept : - StringBuff(std::move(Key.StringBuff)), - StrPtr (std::move(Key.StrPtr)), - Hash (0) - { - Key.StrPtr = nullptr; - Key.Hash = 0; - } + HashMapStringKey(HashMapStringKey&& Key) noexcept : + // clang-format off + StringBuff{std::move(Key.StringBuff)}, + StrPtr {std::move(Key.StrPtr)}, + Hash {0} + // clang-format on + { + Key.StrPtr = nullptr; + Key.Hash = 0; + } - // Disable copy constuctor and assignments. The struct is designed - // to be initialized at creation time only - HashMapStringKey( const HashMapStringKey& ) = delete; - HashMapStringKey& operator = ( const HashMapStringKey& ) = delete; - HashMapStringKey& operator = ( HashMapStringKey&& ) = delete; + // Disable copy constuctor and assignments. The struct is designed + // to be initialized at creation time only + // clang-format off + HashMapStringKey (const HashMapStringKey&) = delete; + HashMapStringKey& operator=(const HashMapStringKey&) = delete; + HashMapStringKey& operator=(HashMapStringKey&&) = delete; + // clang-format on - // Comparison operator - bool operator == (const HashMapStringKey& RHS)const - { - if( StrPtr == RHS.StrPtr ) - return true; - - // Hash member might not have been initialized - if( (Hash != 0 && RHS.Hash !=0 && Hash != RHS.Hash) || StrPtr == nullptr || RHS.StrPtr == nullptr ) - return false; + // Comparison operator + bool operator==(const HashMapStringKey& RHS) const + { + if (StrPtr == RHS.StrPtr) + return true; - bool IsEqual = strcmp( StrPtr, RHS.StrPtr ) == 0; + // Hash member might not have been initialized + if ((Hash != 0 && RHS.Hash != 0 && Hash != RHS.Hash) || StrPtr == nullptr || RHS.StrPtr == nullptr) + return false; -#if LOG_HASH_CONFLICTS - if( Hash != 0 && RHS.Hash !=0 && Hash == RHS.Hash && !IsEqual ) - { - LOG_WARNING_MESSAGE("Unequal strings \"", StrPtr, "\" and \"", RHS.StrPtr, "\" hashed to the same bucket. " - "You may want to use better hash function. You may disable this warning by defining LOG_HASH_CONFLICTS to 0"); - } -#endif - return IsEqual; - } + bool IsEqual = strcmp(StrPtr, RHS.StrPtr) == 0; - size_t GetHash()const +#if LOG_HASH_CONFLICTS + if (Hash != 0 && RHS.Hash != 0 && Hash == RHS.Hash && !IsEqual) { - if( Hash == 0 ) - Hash = CStringHash<Char>()(StrPtr); - - return Hash; + LOG_WARNING_MESSAGE("Unequal strings \"", StrPtr, "\" and \"", RHS.StrPtr, "\" hashed to the same bucket. " + "You may want to use better hash function. You may disable this warning by defining LOG_HASH_CONFLICTS to 0"); } +#endif + return IsEqual; + } - struct Hasher - { - size_t operator()( const HashMapStringKey &Key ) const - { - return Key.GetHash(); - } - }; + size_t GetHash() const + { + if (Hash == 0) + Hash = CStringHash<Char>()(StrPtr); - const Char* GetStr()const{ return StrPtr; } + return Hash; + } - private: - void MakeCopy( const Char* Str ) + struct Hasher + { + size_t operator()(const HashMapStringKey& Key) const { - auto LenWithZeroTerm = strlen( Str ) + 1; - StringBuff.reset( new char[ LenWithZeroTerm ] ); - memcpy( StringBuff.get(), Str, LenWithZeroTerm ); - StrPtr = StringBuff.get(); + return Key.GetHash(); } - - // !!! WARNING !!! - // We can't use String to store the buffer, because String default - // constructor always allocates memory even when the string is empty, - // nor can we use vector for the same reason - std::unique_ptr< Char[] > StringBuff; // Must be declared first - const Char* StrPtr;// Must be declared after StringBuff - mutable size_t Hash; }; -} + + const Char* GetStr() const { return StrPtr; } + +private: + void MakeCopy(const Char* Str) + { + auto LenWithZeroTerm = strlen(Str) + 1; + StringBuff.reset(new char[LenWithZeroTerm]); + memcpy(StringBuff.get(), Str, LenWithZeroTerm); + StrPtr = StringBuff.get(); + } + + // !!! WARNING !!! + // We can't use String to store the buffer, because String default + // constructor always allocates memory even when the string is empty, + // nor can we use vector for the same reason + std::unique_ptr<Char[]> StringBuff; // Must be declared first + const Char* StrPtr; // Must be declared after StringBuff + mutable size_t Hash; +}; + +} // namespace Diligent diff --git a/Common/interface/LockHelper.h b/Common/interface/LockHelper.h index 395ab61d..37f09941 100644 --- a/Common/interface/LockHelper.h +++ b/Common/interface/LockHelper.h @@ -32,45 +32,45 @@ namespace ThreadingTools class LockFlag { public: - enum {LOCK_FLAG_UNLOCKED = 0, LOCK_FLAG_LOCKED = 1}; - LockFlag(Atomics::Long InitFlag = LOCK_FLAG_UNLOCKED)noexcept + enum + { + LOCK_FLAG_UNLOCKED = 0, + LOCK_FLAG_LOCKED = 1 + }; + LockFlag(Atomics::Long InitFlag = LOCK_FLAG_UNLOCKED) noexcept { //m_Flag.store(InitFlag); m_Flag = InitFlag; } - operator Atomics::Long()const{return m_Flag;} + operator Atomics::Long() const { return m_Flag; } private: friend class LockHelper; Atomics::AtomicLong m_Flag; }; - + // Spinlock implementation. This kind of lock should be used in scenarios // where simultaneous access is uncommon but possible. class LockHelper { public: - - LockHelper()noexcept : - m_pLockFlag(nullptr) - { - } - LockHelper(LockFlag& LockFlag)noexcept : - m_pLockFlag(nullptr) + LockHelper() noexcept {} + + LockHelper(LockFlag& LockFlag) noexcept { Lock(LockFlag); } - LockHelper( LockHelper&& LockHelper )noexcept : - m_pLockFlag( std::move(LockHelper.m_pLockFlag) ) + LockHelper(LockHelper&& LockHelper) noexcept : + m_pLockFlag{std::move(LockHelper.m_pLockFlag)} { LockHelper.m_pLockFlag = nullptr; } - const LockHelper& operator = (LockHelper&& LockHelper)noexcept + const LockHelper& operator=(LockHelper&& LockHelper) noexcept { - m_pLockFlag = std::move( LockHelper.m_pLockFlag ); + m_pLockFlag = std::move(LockHelper.m_pLockFlag); LockHelper.m_pLockFlag = nullptr; return *this; } @@ -80,33 +80,33 @@ public: Unlock(); } - static bool UnsafeTryLock(LockFlag& LockFlag)noexcept + static bool UnsafeTryLock(LockFlag& LockFlag) noexcept { - return Atomics::AtomicCompareExchange( LockFlag.m_Flag, - static_cast<Atomics::Long>( LockFlag::LOCK_FLAG_LOCKED ), - static_cast<Atomics::Long>( LockFlag::LOCK_FLAG_UNLOCKED) ) == LockFlag::LOCK_FLAG_UNLOCKED; + return Atomics::AtomicCompareExchange(LockFlag.m_Flag, + static_cast<Atomics::Long>(LockFlag::LOCK_FLAG_LOCKED), + static_cast<Atomics::Long>(LockFlag::LOCK_FLAG_UNLOCKED)) == LockFlag::LOCK_FLAG_UNLOCKED; } - bool TryLock(LockFlag& LockFlag)noexcept + bool TryLock(LockFlag& LockFlag) noexcept { - if( UnsafeTryLock( LockFlag) ) + if (UnsafeTryLock(LockFlag)) { m_pLockFlag = &LockFlag; return true; } - else + else return false; } - + static constexpr const int DefaultSpinCountToYield = 256; - static void UnsafeLock(LockFlag& LockFlag, int SpinCountToYield = DefaultSpinCountToYield)noexcept + static void UnsafeLock(LockFlag& LockFlag, int SpinCountToYield = DefaultSpinCountToYield) noexcept { int SpinCount = 0; - while( !UnsafeTryLock( LockFlag ) ) + while (!UnsafeTryLock(LockFlag)) { ++SpinCount; - if(SpinCount == SpinCountToYield) + if (SpinCount == SpinCountToYield) { SpinCount = 0; YieldThread(); @@ -114,15 +114,15 @@ public: } } - void Lock(LockFlag& LockFlag, int SpinCountToYield = DefaultSpinCountToYield)noexcept + void Lock(LockFlag& LockFlag, int SpinCountToYield = DefaultSpinCountToYield) noexcept { - VERIFY( m_pLockFlag == NULL, "Object already locked" ); + VERIFY(m_pLockFlag == NULL, "Object already locked"); // Wait for the flag to become unlocked and lock it int SpinCount = 0; - while( !TryLock( LockFlag ) ) + while (!TryLock(LockFlag)) { ++SpinCount; - if(SpinCount == SpinCountToYield) + if (SpinCount == SpinCountToYield) { SpinCount = 0; YieldThread(); @@ -130,24 +130,27 @@ public: } } - static void UnsafeUnlock(LockFlag& LockFlag)noexcept + static void UnsafeUnlock(LockFlag& LockFlag) noexcept { LockFlag.m_Flag = LockFlag::LOCK_FLAG_UNLOCKED; } - void Unlock()noexcept + void Unlock() noexcept { - if( m_pLockFlag ) + if (m_pLockFlag) UnsafeUnlock(*m_pLockFlag); m_pLockFlag = NULL; } private: - static void YieldThread()noexcept; + static void YieldThread() noexcept; + + LockFlag* m_pLockFlag = nullptr; - LockFlag* m_pLockFlag; - LockHelper( const LockHelper& LockHelper ); - const LockHelper& operator = ( const LockHelper& LockHelper ); + // clang-format off + LockHelper (const LockHelper& LockHelper) = delete; + LockHelper& operator=(const LockHelper& LockHelper) = delete; + // clang-format on }; -} +} // namespace ThreadingTools diff --git a/Common/interface/MemoryFileStream.h b/Common/interface/MemoryFileStream.h index a694815d..39752a0b 100644 --- a/Common/interface/MemoryFileStream.h +++ b/Common/interface/MemoryFileStream.h @@ -44,24 +44,24 @@ public: MemoryFileStream(IReferenceCounters* pRefCounters, IDataBlob* pData); - virtual void QueryInterface( const INTERFACE_ID& IID, IObject** ppInterface )override; + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override; /// Reads data from the stream - virtual void Read( IDataBlob* pData )override; + virtual void Read(IDataBlob* pData) override; /// Reads data from the stream - virtual bool Read( void* Data, size_t Size )override; + virtual bool Read(void* Data, size_t Size) override; /// Writes data to the stream - virtual bool Write( const void* Data, size_t Size )override; + virtual bool Write(const void* Data, size_t Size) override; - virtual size_t GetSize()override; + virtual size_t GetSize() override; - virtual bool IsValid()override; + virtual bool IsValid() override; private: RefCntAutoPtr<IDataBlob> m_DataBlob; size_t m_CurrentOffset = 0; }; -} +} // namespace Diligent diff --git a/Common/interface/ObjectBase.h b/Common/interface/ObjectBase.h index fe9f720b..0646b52d 100644 --- a/Common/interface/ObjectBase.h +++ b/Common/interface/ObjectBase.h @@ -34,36 +34,36 @@ namespace Diligent #define IMPLEMENT_QUERY_INTERFACE_BODY(InterfaceID, ParentClassName) \ -{ \ - if( ppInterface == nullptr ) \ - return; \ - if( IID == InterfaceID ) \ - { \ - *ppInterface = this; \ - (*ppInterface)->AddRef(); \ - } \ - else \ - { \ - ParentClassName::QueryInterface( IID, ppInterface ); \ - } \ -} + { \ + if (ppInterface == nullptr) \ + return; \ + if (IID == InterfaceID) \ + { \ + *ppInterface = this; \ + (*ppInterface)->AddRef(); \ + } \ + else \ + { \ + ParentClassName::QueryInterface(IID, ppInterface); \ + } \ + } -#define IMPLEMENT_QUERY_INTERFACE(ClassName, InterfaceID, ParentClassName) \ - void ClassName :: QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) \ - IMPLEMENT_QUERY_INTERFACE_BODY(InterfaceID, ParentClassName) +#define IMPLEMENT_QUERY_INTERFACE(ClassName, InterfaceID, ParentClassName) \ + void ClassName ::QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) \ + IMPLEMENT_QUERY_INTERFACE_BODY(InterfaceID, ParentClassName) -#define IMPLEMENT_QUERY_INTERFACE_IN_PLACE(InterfaceID, ParentClassName) \ - virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface)override \ - IMPLEMENT_QUERY_INTERFACE_BODY(InterfaceID, ParentClassName) +#define IMPLEMENT_QUERY_INTERFACE_IN_PLACE(InterfaceID, ParentClassName) \ + virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) override \ + IMPLEMENT_QUERY_INTERFACE_BODY(InterfaceID, ParentClassName) /// Template class implementing base functionality for an object -template<typename BaseInterface> +template <typename BaseInterface> class ObjectBase : public RefCountedObject<BaseInterface> { public: - ObjectBase(IReferenceCounters* pRefCounters) : - RefCountedObject<BaseInterface>(pRefCounters) + ObjectBase(IReferenceCounters* pRefCounters) : + RefCountedObject<BaseInterface>{pRefCounters} {} virtual void QueryInterface(const INTERFACE_ID& IID, IObject** ppInterface) @@ -80,4 +80,4 @@ public: } }; -} +} // namespace Diligent diff --git a/Common/interface/RefCntAutoPtr.h b/Common/interface/RefCntAutoPtr.h index 7e59c0fc..86051a63 100644 --- a/Common/interface/RefCntAutoPtr.h +++ b/Common/interface/RefCntAutoPtr.h @@ -37,7 +37,7 @@ namespace Diligent template <typename T> class RefCntWeakPtr; -// The main advantage of RefCntAutoPtr over the std::shared_ptr is that you can +// The main advantage of RefCntAutoPtr over the std::shared_ptr is that you can // attach the same raw pointer to different smart pointers. // // For instance, the following code will crash since p will be released twice: @@ -71,45 +71,45 @@ template <typename T> class RefCntAutoPtr { public: - explicit RefCntAutoPtr(T* pObj = nullptr) noexcept : - m_pObject(pObj) + explicit RefCntAutoPtr(T* pObj = nullptr) noexcept : + m_pObject{pObj} { - if( m_pObject ) + if (m_pObject) m_pObject->AddRef(); } RefCntAutoPtr(IObject* pObj, const INTERFACE_ID& IID) noexcept : - m_pObject(nullptr) + m_pObject{nullptr} { - if(pObj) - pObj->QueryInterface( IID, reinterpret_cast<IObject**>(&m_pObject) ); + if (pObj) + pObj->QueryInterface(IID, reinterpret_cast<IObject**>(&m_pObject)); } // Copy constructor must not be template! - RefCntAutoPtr(const RefCntAutoPtr& AutoPtr) noexcept : - m_pObject(AutoPtr.m_pObject) + RefCntAutoPtr(const RefCntAutoPtr& AutoPtr) noexcept : + m_pObject{AutoPtr.m_pObject} { - if(m_pObject) + if (m_pObject) m_pObject->AddRef(); } - template<typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> - RefCntAutoPtr(const RefCntAutoPtr<DerivedType>& AutoPtr) noexcept : - RefCntAutoPtr<T>(AutoPtr.m_pObject) + template <typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> + RefCntAutoPtr(const RefCntAutoPtr<DerivedType>& AutoPtr) noexcept : + RefCntAutoPtr<T>{AutoPtr.m_pObject} { } // Non-template move constructor - RefCntAutoPtr(RefCntAutoPtr&& AutoPtr) noexcept : - m_pObject(std::move(AutoPtr.m_pObject)) + RefCntAutoPtr(RefCntAutoPtr&& AutoPtr) noexcept : + m_pObject{std::move(AutoPtr.m_pObject)} { //Make sure original pointer has no references to the object AutoPtr.m_pObject = nullptr; } - template<typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> - RefCntAutoPtr(RefCntAutoPtr<DerivedType>&& AutoPtr) noexcept : - m_pObject(std::move(AutoPtr.m_pObject)) + template <typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> + RefCntAutoPtr(RefCntAutoPtr<DerivedType>&& AutoPtr) noexcept : + m_pObject{std::move(AutoPtr.m_pObject)} { //Make sure original pointer has no references to the object AutoPtr.m_pObject = nullptr; @@ -133,21 +133,21 @@ public: T* Detach() noexcept { - T* pObj = m_pObject; + T* pObj = m_pObject; m_pObject = nullptr; return pObj; } void Release() noexcept { - if( m_pObject ) + if (m_pObject) { m_pObject->Release(); m_pObject = nullptr; } } - RefCntAutoPtr& operator = (T* pObj) noexcept + RefCntAutoPtr& operator=(T* pObj) noexcept { if (m_pObject != pObj) { @@ -160,59 +160,59 @@ public: return *this; } - RefCntAutoPtr& operator = (const RefCntAutoPtr& AutoPtr) noexcept + RefCntAutoPtr& operator=(const RefCntAutoPtr& AutoPtr) noexcept { return *this = AutoPtr.m_pObject; } - template<typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> - RefCntAutoPtr& operator = (const RefCntAutoPtr<DerivedType>& AutoPtr) noexcept + template <typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> + RefCntAutoPtr& operator=(const RefCntAutoPtr<DerivedType>& AutoPtr) noexcept { return *this = static_cast<T*>(AutoPtr.m_pObject); } - RefCntAutoPtr& operator = (RefCntAutoPtr&& AutoPtr) noexcept + RefCntAutoPtr& operator=(RefCntAutoPtr&& AutoPtr) noexcept { if (m_pObject != AutoPtr.m_pObject) Attach(AutoPtr.Detach()); return *this; - } + } - template<typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> - RefCntAutoPtr& operator = (RefCntAutoPtr<DerivedType>&& AutoPtr) noexcept + template <typename DerivedType, typename = typename std::enable_if<std::is_base_of<T, DerivedType>::value>::type> + RefCntAutoPtr& operator=(RefCntAutoPtr<DerivedType>&& AutoPtr) noexcept { if (m_pObject != AutoPtr.m_pObject) Attach(AutoPtr.Detach()); return *this; - } + } // All the access functions do not require locking reference counters pointer because if it is valid, - // the smart pointer holds strong reference to the object and it thus cannot be released by + // the smart pointer holds strong reference to the object and it thus cannot be released by // ohter thread - bool operator ! () const noexcept {return m_pObject == nullptr;} - operator bool () const noexcept {return m_pObject != nullptr;} - bool operator == (const RefCntAutoPtr& Ptr) const noexcept {return m_pObject == Ptr.m_pObject;} - bool operator != (const RefCntAutoPtr& Ptr) const noexcept {return m_pObject != Ptr.m_pObject;} - bool operator < (const RefCntAutoPtr& Ptr) const noexcept {return static_cast<const T*>(*this) < static_cast<const T*>(Ptr);} + bool operator!() const noexcept { return m_pObject == nullptr; } + operator bool() const noexcept { return m_pObject != nullptr; } + bool operator==(const RefCntAutoPtr& Ptr) const noexcept { return m_pObject == Ptr.m_pObject; } + bool operator!=(const RefCntAutoPtr& Ptr) const noexcept { return m_pObject != Ptr.m_pObject; } + bool operator<(const RefCntAutoPtr& Ptr) const noexcept { return static_cast<const T*>(*this) < static_cast<const T*>(Ptr); } - T& operator * () noexcept { return *m_pObject; } - const T& operator * () const noexcept { return *m_pObject; } + T& operator*() noexcept { return *m_pObject; } + const T& operator*() const noexcept { return *m_pObject; } - T* RawPtr() noexcept { return m_pObject; } + T* RawPtr() noexcept { return m_pObject; } const T* RawPtr() const noexcept { return m_pObject; } - - template<typename DstType> - DstType* RawPtr() noexcept { return ValidatedCast<DstType>(m_pObject); } - template<typename DstType> + + template <typename DstType> + DstType* RawPtr() noexcept { return ValidatedCast<DstType>(m_pObject); } + template <typename DstType> DstType* RawPtr() const noexcept { return ValidatedCast<DstType>(m_pObject); } - operator T* () noexcept { return RawPtr(); } - operator const T* () const noexcept { return RawPtr(); } + operator T*() noexcept { return RawPtr(); } + operator const T*() const noexcept { return RawPtr(); } - T* operator -> () noexcept { return m_pObject; } - const T* operator -> () const noexcept { return m_pObject; } + T* operator->() noexcept { return m_pObject; } + const T* operator->() const noexcept { return m_pObject; } private: // Note that the DoublePtrHelper is a private class, and can be created only by RefCntWeakPtr @@ -221,57 +221,61 @@ private: class DoublePtrHelper { public: - DoublePtrHelper(RefCntAutoPtr& AutoPtr) noexcept: - NewRawPtr( static_cast<T*>(AutoPtr) ), - m_pAutoPtr( std::addressof(AutoPtr) ) + DoublePtrHelper(RefCntAutoPtr& AutoPtr) noexcept : + NewRawPtr{static_cast<T*>(AutoPtr)}, + m_pAutoPtr{std::addressof(AutoPtr)} { } - DoublePtrHelper(DoublePtrHelper&& Helper) noexcept: - NewRawPtr(Helper.NewRawPtr), - m_pAutoPtr(Helper.m_pAutoPtr) + DoublePtrHelper(DoublePtrHelper&& Helper) noexcept : + NewRawPtr{Helper.NewRawPtr}, + m_pAutoPtr{Helper.m_pAutoPtr} { Helper.m_pAutoPtr = nullptr; - Helper.NewRawPtr = nullptr; + Helper.NewRawPtr = nullptr; } ~DoublePtrHelper() { - if( m_pAutoPtr && static_cast<T*>(*m_pAutoPtr) != NewRawPtr ) + if (m_pAutoPtr && static_cast<T*>(*m_pAutoPtr) != NewRawPtr) { m_pAutoPtr->Attach(NewRawPtr); } } - T*& operator*() noexcept {return NewRawPtr;} - const T* operator*()const noexcept {return NewRawPtr;} + T*& operator*() noexcept { return NewRawPtr; } + const T* operator*() const noexcept { return NewRawPtr; } + + operator T**() noexcept { return &NewRawPtr; } + operator const T**() const noexcept { return &NewRawPtr; } - operator T**() noexcept {return &NewRawPtr;} - operator const T**() const noexcept {return &NewRawPtr;} private: - T* NewRawPtr; + T* NewRawPtr; RefCntAutoPtr* m_pAutoPtr; - DoublePtrHelper(const DoublePtrHelper&); - DoublePtrHelper& operator = (const DoublePtrHelper&); - DoublePtrHelper& operator = (DoublePtrHelper&&); + + // clang-format off + DoublePtrHelper (const DoublePtrHelper&) = delete; + DoublePtrHelper& operator = (const DoublePtrHelper&) = delete; + DoublePtrHelper& operator = (DoublePtrHelper&&) = delete; + // clang-format on }; public: - DoublePtrHelper operator& () + DoublePtrHelper operator&() { return DoublePtrHelper(*this); } - const DoublePtrHelper operator& ()const + const DoublePtrHelper operator&() const { return DoublePtrHelper(*this); } - T** GetRawDblPtr() {return &m_pObject;} - const T** GetRawDblPtr() const {return &m_pObject;} + T** GetRawDblPtr() { return &m_pObject; } + const T** GetRawDblPtr() const { return &m_pObject; } private: - template<typename OtherType> + template <typename OtherType> friend class RefCntAutoPtr; T* m_pObject; @@ -282,13 +286,13 @@ template <typename T> class RefCntWeakPtr { public: - explicit RefCntWeakPtr(T* pObj = nullptr) noexcept: - m_pRefCounters(nullptr), - m_pObject(pObj) + explicit RefCntWeakPtr(T* pObj = nullptr) noexcept : + m_pRefCounters{nullptr}, + m_pObject{pObj} { - if( m_pObject ) + if (m_pObject) { - m_pRefCounters = ValidatedCast<RefCountersImpl>( m_pObject->GetReferenceCounters() ); + m_pRefCounters = ValidatedCast<RefCountersImpl>(m_pObject->GetReferenceCounters()); m_pRefCounters->AddWeakRef(); } } @@ -298,77 +302,77 @@ public: Release(); } - RefCntWeakPtr(const RefCntWeakPtr& WeakPtr) noexcept: - m_pRefCounters(WeakPtr.m_pRefCounters), - m_pObject(WeakPtr.m_pObject) + RefCntWeakPtr(const RefCntWeakPtr& WeakPtr) noexcept : + m_pRefCounters{WeakPtr.m_pRefCounters}, + m_pObject{WeakPtr.m_pObject} { - if( m_pRefCounters ) + if (m_pRefCounters) m_pRefCounters->AddWeakRef(); } - RefCntWeakPtr(RefCntWeakPtr&& WeakPtr) noexcept: - m_pRefCounters(std::move(WeakPtr.m_pRefCounters)), - m_pObject(std::move(WeakPtr.m_pObject)) + RefCntWeakPtr(RefCntWeakPtr&& WeakPtr) noexcept : + m_pRefCounters{std::move(WeakPtr.m_pRefCounters)}, + m_pObject{std::move(WeakPtr.m_pObject)} { WeakPtr.m_pRefCounters = nullptr; - WeakPtr.m_pObject = nullptr; + WeakPtr.m_pObject = nullptr; } - explicit RefCntWeakPtr(RefCntAutoPtr<T>& AutoPtr) noexcept: - m_pRefCounters(AutoPtr ? ValidatedCast<RefCountersImpl>( AutoPtr->GetReferenceCounters() ) : nullptr), - m_pObject( static_cast<T*>(AutoPtr) ) + explicit RefCntWeakPtr(RefCntAutoPtr<T>& AutoPtr) noexcept : + m_pRefCounters{AutoPtr ? ValidatedCast<RefCountersImpl>(AutoPtr->GetReferenceCounters()) : nullptr}, + m_pObject{static_cast<T*>(AutoPtr)} { - if( m_pRefCounters ) + if (m_pRefCounters) m_pRefCounters->AddWeakRef(); } - RefCntWeakPtr& operator = (const RefCntWeakPtr& WeakPtr) noexcept + RefCntWeakPtr& operator=(const RefCntWeakPtr& WeakPtr) noexcept { - if( *this == WeakPtr ) + if (*this == WeakPtr) return *this; Release(); - m_pObject = WeakPtr.m_pObject; + m_pObject = WeakPtr.m_pObject; m_pRefCounters = WeakPtr.m_pRefCounters; - if( m_pRefCounters ) + if (m_pRefCounters) m_pRefCounters->AddWeakRef(); return *this; } - RefCntWeakPtr& operator = (T* pObj) noexcept + RefCntWeakPtr& operator=(T* pObj) noexcept { - return operator= (RefCntWeakPtr(pObj)); + return operator=(RefCntWeakPtr(pObj)); } - RefCntWeakPtr& operator = (RefCntWeakPtr&& WeakPtr) noexcept + RefCntWeakPtr& operator=(RefCntWeakPtr&& WeakPtr) noexcept { - if( *this == WeakPtr ) + if (*this == WeakPtr) return *this; Release(); - m_pObject = std::move(WeakPtr.m_pObject); - m_pRefCounters = std::move(WeakPtr.m_pRefCounters); + m_pObject = std::move(WeakPtr.m_pObject); + m_pRefCounters = std::move(WeakPtr.m_pRefCounters); WeakPtr.m_pRefCounters = nullptr; - WeakPtr.m_pObject = nullptr; + WeakPtr.m_pObject = nullptr; return *this; } - RefCntWeakPtr& operator = (RefCntAutoPtr<T>& AutoPtr) noexcept + RefCntWeakPtr& operator=(RefCntAutoPtr<T>& AutoPtr) noexcept { Release(); - m_pObject = static_cast<T*>( AutoPtr ); - m_pRefCounters = m_pObject ? ValidatedCast<RefCountersImpl>( m_pObject->GetReferenceCounters() ) : nullptr; - if( m_pRefCounters ) + m_pObject = static_cast<T*>(AutoPtr); + m_pRefCounters = m_pObject ? ValidatedCast<RefCountersImpl>(m_pObject->GetReferenceCounters()) : nullptr; + if (m_pRefCounters) m_pRefCounters->AddWeakRef(); return *this; } void Release() noexcept { - if( m_pRefCounters ) + if (m_pRefCounters) m_pRefCounters->ReleaseWeakRef(); m_pRefCounters = nullptr; - m_pObject = nullptr; + m_pObject = nullptr; } /// \note This method may not be reliable in a multithreaded environment. @@ -383,15 +387,15 @@ public: RefCntAutoPtr<T> Lock() { RefCntAutoPtr<T> spObj; - if( m_pRefCounters ) + if (m_pRefCounters) { // Try to obtain pointer to the owner object. // spOwner is only used to keep the object // alive while obtaining strong reference from // the raw pointer m_pObject - RefCntAutoPtr<Diligent::IObject> spOwner; - m_pRefCounters->GetObject( &spOwner ); - if( spOwner ) + RefCntAutoPtr<IObject> spOwner; + m_pRefCounters->GetObject(&spOwner); + if (spOwner) { // If owner is alive, we can use our RAW pointer to // create strong reference @@ -407,8 +411,8 @@ public: return spObj; } - bool operator == (const RefCntWeakPtr& Ptr) const noexcept {return m_pRefCounters == Ptr.m_pRefCounters;} - bool operator != (const RefCntWeakPtr& Ptr) const noexcept {return m_pRefCounters != Ptr.m_pRefCounters;} + bool operator==(const RefCntWeakPtr& Ptr) const noexcept { return m_pRefCounters == Ptr.m_pRefCounters; } + bool operator!=(const RefCntWeakPtr& Ptr) const noexcept { return m_pRefCounters != Ptr.m_pRefCounters; } protected: RefCountersImpl* m_pRefCounters; @@ -419,4 +423,4 @@ protected: T* m_pObject; }; -} +} // namespace Diligent diff --git a/Common/interface/RefCountedObjectImpl.h b/Common/interface/RefCountedObjectImpl.h index f5df1020..4e0f3fd1 100644 --- a/Common/interface/RefCountedObjectImpl.h +++ b/Common/interface/RefCountedObjectImpl.h @@ -40,23 +40,23 @@ namespace Diligent class RefCountersImpl final : public IReferenceCounters { public: - inline virtual CounterValueType AddStrongRef()override final + inline virtual CounterValueType AddStrongRef() override final { - VERIFY( m_ObjectState == ObjectState::Alive, "Attempting to increment strong reference counter for a destroyed or not itialized object!" ); - VERIFY( m_ObjectWrapperBuffer[0] != 0 && m_ObjectWrapperBuffer[1] != 0, "Object wrapper is not initialized"); + VERIFY(m_ObjectState == ObjectState::Alive, "Attempting to increment strong reference counter for a destroyed or not itialized object!"); + VERIFY(m_ObjectWrapperBuffer[0] != 0 && m_ObjectWrapperBuffer[1] != 0, "Object wrapper is not initialized"); return Atomics::AtomicIncrement(m_lNumStrongReferences); } - template<class TPreObjectDestroy> + template <class TPreObjectDestroy> inline CounterValueType ReleaseStrongRef(TPreObjectDestroy PreObjectDestroy) { - VERIFY( m_ObjectState == ObjectState::Alive, "Attempting to decrement strong reference counter for an object that is not alive" ); - VERIFY( m_ObjectWrapperBuffer[0] != 0 && m_ObjectWrapperBuffer[1] != 0, "Object wrapper is not initialized"); + VERIFY(m_ObjectState == ObjectState::Alive, "Attempting to decrement strong reference counter for an object that is not alive"); + VERIFY(m_ObjectWrapperBuffer[0] != 0 && m_ObjectWrapperBuffer[1] != 0, "Object wrapper is not initialized"); - // Decrement strong reference counter without acquiring the lock. + // Decrement strong reference counter without acquiring the lock. auto RefCount = Atomics::AtomicDecrement(m_lNumStrongReferences); - VERIFY( RefCount >= 0, "Inconsistent call to ReleaseStrongRef()" ); - if( RefCount == 0 ) + VERIFY(RefCount >= 0, "Inconsistent call to ReleaseStrongRef()"); + if (RefCount == 0) { PreObjectDestroy(); TryDestroyObject(); @@ -65,26 +65,26 @@ public: return RefCount; } - inline virtual CounterValueType ReleaseStrongRef()override final + inline virtual CounterValueType ReleaseStrongRef() override final { - return ReleaseStrongRef([](){}); + return ReleaseStrongRef([]() {}); } - inline virtual CounterValueType AddWeakRef()override final + inline virtual CounterValueType AddWeakRef() override final { return Atomics::AtomicIncrement(m_lNumWeakReferences); } - inline virtual CounterValueType ReleaseWeakRef()override final + inline virtual CounterValueType ReleaseWeakRef() override final { // The method must be serialized! ThreadingTools::LockHelper Lock(m_LockFlag); // It is essentially important to check the number of weak references // while holding the lock. Otherwise reference counters object - // may be destroyed twice if ReleaseStrongRef() is executed by other + // may be destroyed twice if ReleaseStrongRef() is executed by other // thread. auto NumWeakReferences = Atomics::AtomicDecrement(m_lNumWeakReferences); - VERIFY( NumWeakReferences >= 0, "Inconsistent call to ReleaseWeakRef()" ); + VERIFY(NumWeakReferences >= 0, "Inconsistent call to ReleaseWeakRef()"); // There are two special case when we must not destroy the ref counters object even // when NumWeakReferences == 0 && m_lNumStrongReferences == 0 : @@ -92,7 +92,7 @@ public: // This thread | Another thread - ReleaseStrongRef() // | // 1. Lock the object | - // | + // | // 2. Decrement m_lNumWeakReferences, | 1. Decrement m_lNumStrongReferences, // m_lNumWeakReferences==0 | RefCount == 0 // | @@ -100,9 +100,9 @@ public: // | the object, m_ObjectState != ObjectState::Destroyed // 3. Do not destroy reference | // counters, unlock | - // | 3. Acquire the lock, - // | destroy the object, - // | read m_lNumWeakReferences==0 + // | 3. Acquire the lock, + // | destroy the object, + // | read m_lNumWeakReferences==0 // | destroy the reference counters // @@ -125,21 +125,21 @@ public: // { // Destory ref counters second time // } - // - if( NumWeakReferences == 0 && /*m_lNumStrongReferences == 0 &&*/ m_ObjectState == ObjectState::Destroyed ) + // + if (NumWeakReferences == 0 && /*m_lNumStrongReferences == 0 &&*/ m_ObjectState == ObjectState::Destroyed) { VERIFY_EXPR(m_lNumStrongReferences == 0); - VERIFY( m_ObjectWrapperBuffer[0] == 0 && m_ObjectWrapperBuffer[1] == 0, "Object wrapper must be null"); - // m_ObjectState is set to ObjectState::Destroyed under the lock. If the state is not Destroyed, - // ReleaseStrongRef() will take care of it. - // Access to Object wrapper and decrementing m_lNumWeakReferences is atomic. Since we acquired the lock, - // no other thread can access either of them. + VERIFY(m_ObjectWrapperBuffer[0] == 0 && m_ObjectWrapperBuffer[1] == 0, "Object wrapper must be null"); + // m_ObjectState is set to ObjectState::Destroyed under the lock. If the state is not Destroyed, + // ReleaseStrongRef() will take care of it. + // Access to Object wrapper and decrementing m_lNumWeakReferences is atomic. Since we acquired the lock, + // no other thread can access either of them. // Access to m_lNumStrongReferences is NOT PROTECTED by lock. // There are no more references to the ref counters object and the object itself // is already destroyed. // We can safely unlock it and destroy. - // If we do not unlock it, this->m_LockFlag will expire, + // If we do not unlock it, this->m_LockFlag will expire, // which will cause Lock.~LockHelper() to crash. Lock.Unlock(); SelfDestroy(); @@ -147,12 +147,12 @@ public: return NumWeakReferences; } - inline virtual void GetObject( class IObject **ppObject )override final + inline virtual void GetObject(class IObject** ppObject) override final { - if( m_ObjectState != ObjectState::Alive) + if (m_ObjectState != ObjectState::Alive) return; // Early exit - // It is essential to INCREMENT REF COUNTER while HOLDING THE LOCK to make sure that + // It is essential to INCREMENT REF COUNTER while HOLDING THE LOCK to make sure that // StrongRefCnt > 1 guarantees that the object is alive. // If other thread started deleting the object in ReleaseStrongRef(), then m_lNumStrongReferences==0 @@ -160,62 +160,62 @@ public: // there is at least one real strong reference left. Otherwise the following scenario may occur: // // m_lNumStrongReferences == 1 - // + // // Thread 1 - ReleaseStrongRef() | Thread 2 - GetObject() | Thread 3 - GetObject() // | | // - Decrement m_lNumStrongReferences | -Increment m_lNumStrongReferences | -Increment m_lNumStrongReferences - // - Read RefCount == 0 | -Read StrongRefCnt==1 | -Read StrongRefCnt==2 + // - Read RefCount == 0 | -Read StrongRefCnt==1 | -Read StrongRefCnt==2 // Destroy the object | | -Return reference to the soon // | | to expire object - // + // ThreadingTools::LockHelper Lock(m_LockFlag); auto StrongRefCnt = Atomics::AtomicIncrement(m_lNumStrongReferences); - + // Checking if m_ObjectState == ObjectState::Alive only is not reliable: // // This thread | Another thread - // | - // 1. Acquire the lock | - // | 1. Decrement m_lNumStrongReferences - // 2. Increment m_lNumStrongReferences | 2. Test RefCount==0 - // 3. Read StrongRefCnt == 1 | 3. Start destroying the object + // | + // 1. Acquire the lock | + // | 1. Decrement m_lNumStrongReferences + // 2. Increment m_lNumStrongReferences | 2. Test RefCount==0 + // 3. Read StrongRefCnt == 1 | 3. Start destroying the object // m_ObjectState == ObjectState::Alive | // 4. DO NOT return the reference to | 4. Wait for the lock, m_ObjectState == ObjectState::Alive // the object | // 5. Decrement m_lNumStrongReferences | // | 5. Destroy the object - if( m_ObjectState == ObjectState::Alive && StrongRefCnt > 1 ) + if (m_ObjectState == ObjectState::Alive && StrongRefCnt > 1) { - VERIFY( m_ObjectWrapperBuffer[0] != 0 && m_ObjectWrapperBuffer[1] != 0, "Object wrapper is not initialized"); + VERIFY(m_ObjectWrapperBuffer[0] != 0 && m_ObjectWrapperBuffer[1] != 0, "Object wrapper is not initialized"); // QueryInterface() must not lock the object, or a deadlock happens. // The only other two methods that lock the object are ReleaseStrongRef() // and ReleaseWeakRef(), which are never called by QueryInterface() - auto *pWrapper = reinterpret_cast<ObjectWrapperBase*>(m_ObjectWrapperBuffer); + auto* pWrapper = reinterpret_cast<ObjectWrapperBase*>(m_ObjectWrapperBuffer); pWrapper->QueryInterface(IID_Unknown, ppObject); } Atomics::AtomicDecrement(m_lNumStrongReferences); } - inline virtual CounterValueType GetNumStrongRefs()const override final + inline virtual CounterValueType GetNumStrongRefs() const override final { return m_lNumStrongReferences; } - inline virtual CounterValueType GetNumWeakRefs()const override final + inline virtual CounterValueType GetNumWeakRefs() const override final { return m_lNumWeakReferences; } private: - template<typename AllocatorType, typename ObjectType> + template <typename AllocatorType, typename ObjectType> friend class MakeNewRCObj; - RefCountersImpl()noexcept + RefCountersImpl() noexcept { m_lNumStrongReferences = 0; - m_lNumWeakReferences = 0; + m_lNumWeakReferences = 0; #ifdef _DEBUG memset(m_ObjectWrapperBuffer, 0, sizeof(m_ObjectWrapperBuffer)); #endif @@ -224,19 +224,19 @@ private: class ObjectWrapperBase { public: - virtual void DestroyObject() = 0; - virtual void QueryInterface(const INTERFACE_ID& iid, IObject** ppInterface)=0; + virtual void DestroyObject() = 0; + virtual void QueryInterface(const INTERFACE_ID& iid, IObject** ppInterface) = 0; }; - template<typename ObjectType, typename AllocatorType> + template <typename ObjectType, typename AllocatorType> class ObjectWrapper : public ObjectWrapperBase { public: - ObjectWrapper(ObjectType *pObject, AllocatorType *pAllocator)noexcept : - m_pObject(pObject), - m_pAllocator(pAllocator) + ObjectWrapper(ObjectType* pObject, AllocatorType* pAllocator) noexcept : + m_pObject{pObject}, + m_pAllocator{pAllocator} {} - virtual void DestroyObject()override final + virtual void DestroyObject() override final { if (m_pAllocator) { @@ -248,51 +248,52 @@ private: delete m_pObject; } } - virtual void QueryInterface(const INTERFACE_ID& iid, IObject** ppInterface)override final + virtual void QueryInterface(const INTERFACE_ID& iid, IObject** ppInterface) override final { return m_pObject->QueryInterface(iid, ppInterface); } + private: // It is crucially important that the type of the pointer // is ObjectType and not IObject, since the latter // does not have virtual dtor. - ObjectType* const m_pObject; - AllocatorType * const m_pAllocator; + ObjectType* const m_pObject; + AllocatorType* const m_pAllocator; }; - template<typename ObjectType, typename AllocatorType> - void Attach(ObjectType *pObject, AllocatorType *pAllocator) + template <typename ObjectType, typename AllocatorType> + void Attach(ObjectType* pObject, AllocatorType* pAllocator) { VERIFY(m_ObjectState == ObjectState::NotInitialized, "Object has already been attached"); static_assert(sizeof(ObjectWrapper<ObjectType, AllocatorType>) == sizeof(m_ObjectWrapperBuffer), "Unexpected object wrapper size"); - new(m_ObjectWrapperBuffer) ObjectWrapper<ObjectType, AllocatorType>(pObject, pAllocator); + new (m_ObjectWrapperBuffer) ObjectWrapper<ObjectType, AllocatorType>(pObject, pAllocator); m_ObjectState = ObjectState::Alive; } void TryDestroyObject() { - // Since RefCount==0, there are no more strong references and the only place + // Since RefCount==0, there are no more strong references and the only place // where strong ref counter can be incremented is from GetObject(). - // If several threads were allowed to get to this point, there would - // be serious risk that <this> had already been destroyed and m_LockFlag expired. + // If several threads were allowed to get to this point, there would + // be serious risk that <this> had already been destroyed and m_LockFlag expired. // Consider the following scenario: // | // This thread | Another thread // | // m_lNumStrongReferences == 1 // m_lNumWeakReferences == 1 - // | - // 1. Decrement m_lNumStrongReferences | - // Read RefCount==0, no lock acquired| + // | + // 1. Decrement m_lNumStrongReferences | + // Read RefCount==0, no lock acquired| // | 1. Run GetObject() // | - acquire the lock // | - increment m_lNumStrongReferences // | - release the lock - // | + // | // | 2. Run ReleaseWeakRef() // | - decrement m_lNumWeakReferences - // | + // | // | 3. Run ReleaseStrongRef() // | - decrement m_lNumStrongReferences // | - read RefCount==0 @@ -321,12 +322,12 @@ private: // | to the object | // | 5. Decrement m_lNumStrongReferences | // _ _ _ _ _ _ _ _ _ _ _ _ _| 6. Release the lock _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ - // | | 2. Acquire the lock + // | | 2. Acquire the lock // | | 3. Increment m_lNumStrongReferences // | | 4. Read StrongRefCnt == 1 - // | | 5. DO NOT return the reference + // | | 5. DO NOT return the reference // | | to the object - // | | 6. Decrement m_lNumStrongReferences + // | | 6. Decrement m_lNumStrongReferences // _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ 7. Release the lock _ _ _ _ _ _ // 5. Acquire the lock | | // - m_lNumStrongReferences==0 | | @@ -342,10 +343,10 @@ private: // | // m_lNumStrongReferences == 1 // | - // | 1. Acquire the lock + // | 1. Acquire the lock // | 2. Increment m_lNumStrongReferences // 1. Decrement m_lNumStrongReferences | - // 2. Read RefCount>0 | + // 2. Read RefCount>0 | // 3. DO NOT destroy the object | 3. Read StrongRefCnt > 1 (while m_lNumStrongReferences == 1) // | 4. Return the reference to the object // | - Increment m_lNumStrongReferences @@ -353,27 +354,27 @@ private: #ifdef _DEBUG Atomics::Long NumStrongRefs = m_lNumStrongReferences; - VERIFY( NumStrongRefs == 0 || NumStrongRefs == 1, "Num strong references (", NumStrongRefs, ") is expected to be 0 or 1" ); + VERIFY(NumStrongRefs == 0 || NumStrongRefs == 1, "Num strong references (", NumStrongRefs, ") is expected to be 0 or 1"); #endif // Acquire the lock. ThreadingTools::LockHelper Lock(m_LockFlag); - // GetObject() first acquires the lock, and only then increments and + // GetObject() first acquires the lock, and only then increments and // decrements the ref counter. If it reads 1 after incremeting the counter, // it does not return the reference to the object and decrements the counter. // If we acquired the lock, GetObject() will not start until we are done - VERIFY_EXPR( m_lNumStrongReferences == 0 && m_ObjectState == ObjectState::Alive ); - + VERIFY_EXPR(m_lNumStrongReferences == 0 && m_ObjectState == ObjectState::Alive); + // Extra caution - if(m_lNumStrongReferences == 0 && m_ObjectState == ObjectState::Alive) + if (m_lNumStrongReferences == 0 && m_ObjectState == ObjectState::Alive) { VERIFY(m_ObjectWrapperBuffer[0] != 0 && m_ObjectWrapperBuffer[1] != 0, "Object wrapper is not initialized"); - // We cannot destroy the object while reference counters are locked as this will + // We cannot destroy the object while reference counters are locked as this will // cause a deadlock in cases like this: // // A ==sp==> B ---wp---> A - // + // // RefCounters_A.Lock(); // delete A{ // A.~dtor(){ @@ -385,17 +386,17 @@ private: // So we copy the object wrapper and destroy the object after unlocking the // reference counters size_t ObjectWrapperBufferCopy[ObjectWrapperBufferSize]; - for(size_t i=0; i < ObjectWrapperBufferSize; ++i) + for (size_t i = 0; i < ObjectWrapperBufferSize; ++i) ObjectWrapperBufferCopy[i] = m_ObjectWrapperBuffer[i]; #ifdef _DEBUG memset(m_ObjectWrapperBuffer, 0, sizeof(m_ObjectWrapperBuffer)); #endif - auto *pWrapper = reinterpret_cast<ObjectWrapperBase*>(ObjectWrapperBufferCopy); + auto* pWrapper = reinterpret_cast<ObjectWrapperBase*>(ObjectWrapperBufferCopy); - // In a multithreaded environment, reference counters object may + // In a multithreaded environment, reference counters object may // be destroyed at any time while m_pObject->~dtor() is running. // NOTE: m_pObject may not be the only object referencing m_pRefCounters. - // All objects that are owned by m_pObject will point to the same + // All objects that are owned by m_pObject will point to the same // reference counters object. // Note that this is the only place where m_ObjectState is @@ -410,15 +411,15 @@ private: // may be destroyed twice if ReleaseWeakRef() is executed by other thread: // // This thread | Another thread - ReleaseWeakRef() - // | - // 1. Decrement m_lNumStrongReferences,| - // m_lNumStrongReferences==0, | + // | + // 1. Decrement m_lNumStrongReferences,| + // m_lNumStrongReferences==0, | // acquire the lock, destroy | // the obj, release the lock | - // m_lNumWeakReferences == 1 | - // | 1. Aacquire the lock, + // m_lNumWeakReferences == 1 | + // | 1. Aacquire the lock, // | decrement m_lNumWeakReferences, - // | m_lNumWeakReferences == 0, + // | m_lNumWeakReferences == 0, // | m_ObjectState == ObjectState::Destroyed // | // 2. Read m_lNumWeakReferences == 0 | @@ -426,21 +427,21 @@ private: // bool bDestroyThis = m_lNumWeakReferences == 0; // ReleaseWeakRef() decrements m_lNumWeakReferences, and checks it for - // zero only after acquiring the lock. So if m_lNumWeakReferences==0, no + // zero only after acquiring the lock. So if m_lNumWeakReferences==0, no // weak reference-related code may be running - // We must explicitly unlock the object now to avoid deadlocks. Also, - // if this is deleted, this->m_LockFlag will expire, which will cause + // We must explicitly unlock the object now to avoid deadlocks. Also, + // if this is deleted, this->m_LockFlag will expire, which will cause // Lock.~LockHelper() to crash Lock.Unlock(); // Destroy referenced object pWrapper->DestroyObject(); - // Note that <this> may be destroyed here already, + // Note that <this> may be destroyed here already, // see comments in ~ControlledObjectType() - if( bDestroyThis ) + if (bDestroyThis) SelfDestroy(); } } @@ -452,20 +453,22 @@ private: ~RefCountersImpl() { - VERIFY( m_lNumStrongReferences == 0 && m_lNumWeakReferences == 0, - "There exist outstanding references to the object being destroyed" ); + VERIFY(m_lNumStrongReferences == 0 && m_lNumWeakReferences == 0, + "There exist outstanding references to the object being destroyed"); } // No copies/moves - RefCountersImpl(const RefCountersImpl&) = delete; - RefCountersImpl(RefCountersImpl&&) = delete; + // clang-format off + RefCountersImpl (const RefCountersImpl&) = delete; + RefCountersImpl (RefCountersImpl&&) = delete; RefCountersImpl& operator = (const RefCountersImpl&) = delete; - RefCountersImpl& operator = (RefCountersImpl&&) = delete; + RefCountersImpl& operator = (RefCountersImpl&&) = delete; + // clang-format on - static constexpr size_t ObjectWrapperBufferSize = sizeof(ObjectWrapper<IObject, IMemoryAllocator>) / sizeof(size_t); - size_t m_ObjectWrapperBuffer[ObjectWrapperBufferSize]; - Atomics::AtomicLong m_lNumStrongReferences; - Atomics::AtomicLong m_lNumWeakReferences; + static constexpr size_t ObjectWrapperBufferSize = sizeof(ObjectWrapper<IObject, IMemoryAllocator>) / sizeof(size_t); + size_t m_ObjectWrapperBuffer[ObjectWrapperBufferSize]; + Atomics::AtomicLong m_lNumStrongReferences; + Atomics::AtomicLong m_lNumWeakReferences; ThreadingTools::LockFlag m_LockFlag; enum class ObjectState : Int32 { @@ -478,29 +481,31 @@ private: /// Base class for all reference counting objects -template<typename Base> +template <typename Base> class RefCountedObject : public Base { public: using CounterValueType = IReferenceCounters::CounterValueType; - template<typename ... BaseCtorArgTypes> - RefCountedObject(IReferenceCounters* pRefCounters, BaseCtorArgTypes&& ... BaseCtorArgs)noexcept : - Base ( std::forward<BaseCtorArgTypes>(BaseCtorArgs)... ), - m_pRefCounters( ValidatedCast<RefCountersImpl>(pRefCounters) ) + template <typename... BaseCtorArgTypes> + RefCountedObject(IReferenceCounters* pRefCounters, BaseCtorArgTypes&&... BaseCtorArgs) noexcept : + // clang-format off + Base {std::forward<BaseCtorArgTypes>(BaseCtorArgs)...}, + m_pRefCounters{ValidatedCast<RefCountersImpl>(pRefCounters) } + // clang-format on { // If object is allocated on stack, ref counters will be null //VERIFY(pRefCounters != nullptr, "Reference counters must not be null") } - // Virtual destructor makes sure all derived classes can be destroyed + // Virtual destructor makes sure all derived classes can be destroyed // through the pointer to the base class virtual ~RefCountedObject() { // WARNING! m_pRefCounters may be expired in scenarios like this: // // A ==sp==> B ---wp---> A - // + // // RefCounters_A.ReleaseStrongRef(){ // NumStrongRef == 0, NumWeakRef == 1 // bDestroyThis = (m_lNumWeakReferences == 0) == false; // delete A{ @@ -509,7 +514,7 @@ public: // wpA.ReleaseWeakRef(){ // NumStrongRef == 0, NumWeakRef == 0, m_pObject==nullptr // delete RefCounters_A; // ... - // VERIFY( m_pRefCounters->GetNumStrongRefs() == 0 // Access violation! + // VERIFY( m_pRefCounters->GetNumStrongRefs() == 0 // Access violation! // This also may happen if one thread is executing ReleaseStrongRef(), while // another one is simultaneously running ReleaseWeakRef(). @@ -518,13 +523,13 @@ public: // "There remain strong references to the object being destroyed" ); } - inline virtual IReferenceCounters* GetReferenceCounters()const override final + inline virtual IReferenceCounters* GetReferenceCounters() const override final { VERIFY_EXPR(m_pRefCounters != nullptr); return m_pRefCounters; } - inline virtual CounterValueType AddRef()override final + inline virtual CounterValueType AddRef() override final { VERIFY_EXPR(m_pRefCounters != nullptr); // Since type of m_pRefCounters is RefCountersImpl, @@ -532,15 +537,15 @@ public: return m_pRefCounters->AddStrongRef(); } - inline virtual CounterValueType Release()override + inline virtual CounterValueType Release() override { VERIFY_EXPR(m_pRefCounters != nullptr); // Since type of m_pRefCounters is RefCountersImpl, // this call will not be virtual and should be inlined return m_pRefCounters->ReleaseStrongRef(); } - - template<class TPreObjectDestroy> + + template <class TPreObjectDestroy> inline CounterValueType Release(TPreObjectDestroy PreObjectDestroy) { VERIFY_EXPR(m_pRefCounters != nullptr); @@ -548,7 +553,7 @@ public: } protected: - template<typename AllocatorType, typename ObjectType> + template <typename AllocatorType, typename ObjectType> friend class MakeNewRCObj; friend class RefCountersImpl; @@ -558,13 +563,13 @@ protected: // or from RefCountersImpl when object is destroyed // It needs to be protected (not private!) to allow generation of destructors in derived classes - void operator delete(void *ptr) + void operator delete(void* ptr) { delete[] reinterpret_cast<Uint8*>(ptr); } - - template<typename ObjectAllocatorType> - void operator delete(void *ptr, ObjectAllocatorType &Allocator, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber) + + template <typename ObjectAllocatorType> + void operator delete(void* ptr, ObjectAllocatorType& Allocator, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber) { return Allocator.Free(ptr); } @@ -577,8 +582,8 @@ private: return new Uint8[Size]; } - template<typename ObjectAllocatorType> - void* operator new(size_t Size, ObjectAllocatorType &Allocator, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber) + template <typename ObjectAllocatorType> + void* operator new(size_t Size, ObjectAllocatorType& Allocator, const Char* dbgDescription, const char* dbgFileName, const Int32 dbgLineNumber) { return Allocator.Allocate(Size, dbgDescription, dbgFileName, dbgLineNumber); } @@ -587,55 +592,61 @@ private: // Note that the type of the reference counters is RefCountersImpl, // not IReferenceCounters. This avoids virtual calls from // AddRef() and Release() methods - RefCountersImpl *const m_pRefCounters; + RefCountersImpl* const m_pRefCounters; }; -template<typename ObjectType, typename AllocatorType = IMemoryAllocator> +template <typename ObjectType, typename AllocatorType = IMemoryAllocator> class MakeNewRCObj { public: - MakeNewRCObj(AllocatorType &Allocator, const Char* Description, const char* FileName, const Int32 LineNumber, IObject* pOwner = nullptr)noexcept : - m_pAllocator(&Allocator), - m_pOwner(pOwner) + MakeNewRCObj(AllocatorType& Allocator, const Char* Description, const char* FileName, const Int32 LineNumber, IObject* pOwner = nullptr) noexcept : + // clang-format off + m_pAllocator{&Allocator}, + m_pOwner{pOwner} #ifdef DEVELOPMENT - , m_dvpDescription(Description) - , m_dvpFileName (FileName) - , m_dvpLineNumber (LineNumber) + , m_dvpDescription{Description} + , m_dvpFileName {FileName } + , m_dvpLineNumber {LineNumber } + // clang-format on #endif { } - MakeNewRCObj(IObject* pOwner = nullptr)noexcept : - m_pAllocator (nullptr), - m_pOwner (pOwner) + MakeNewRCObj(IObject* pOwner = nullptr) noexcept : + // clang-format off + m_pAllocator {nullptr}, + m_pOwner {pOwner } #ifdef DEVELOPMENT - , m_dvpDescription(nullptr) - , m_dvpFileName (nullptr) - , m_dvpLineNumber (0) + , m_dvpDescription{nullptr} + , m_dvpFileName {nullptr} + , m_dvpLineNumber {0 } #endif + // clang-format on {} - - MakeNewRCObj(const MakeNewRCObj&) = delete; - MakeNewRCObj(MakeNewRCObj&&) = delete; + + // clang-format off + MakeNewRCObj (const MakeNewRCObj&) = delete; + MakeNewRCObj (MakeNewRCObj&&) = delete; MakeNewRCObj& operator=(const MakeNewRCObj&) = delete; - MakeNewRCObj& operator=(MakeNewRCObj&&) = delete; + MakeNewRCObj& operator=(MakeNewRCObj&&) = delete; + // clang-format on - template<typename ... CtorArgTypes> - ObjectType* operator() (CtorArgTypes&& ... CtorArgs) + template <typename... CtorArgTypes> + ObjectType* operator()(CtorArgTypes&&... CtorArgs) { - RefCountersImpl *pNewRefCounters = nullptr; - IReferenceCounters *pRefCounters = nullptr; - if(m_pOwner != nullptr) + RefCountersImpl* pNewRefCounters = nullptr; + IReferenceCounters* pRefCounters = nullptr; + if (m_pOwner != nullptr) pRefCounters = m_pOwner->GetReferenceCounters(); else { // Constructor of RefCountersImpl class is private and only accessible // by methods of MakeNewRCObj pNewRefCounters = new RefCountersImpl(); - pRefCounters = pNewRefCounters; + pRefCounters = pNewRefCounters; } - ObjectType *pObj = nullptr; + ObjectType* pObj = nullptr; try { #ifndef DEVELOPMENT @@ -645,33 +656,33 @@ public: #endif // Operators new and delete of RefCountedObject are private and only accessible // by methods of MakeNewRCObj - if(m_pAllocator) - pObj = new(*m_pAllocator, m_dvpDescription, m_dvpFileName, m_dvpLineNumber) ObjectType(pRefCounters, std::forward<CtorArgTypes>(CtorArgs)... ); + if (m_pAllocator) + pObj = new (*m_pAllocator, m_dvpDescription, m_dvpFileName, m_dvpLineNumber) ObjectType(pRefCounters, std::forward<CtorArgTypes>(CtorArgs)...); else - pObj = new ObjectType( pRefCounters, std::forward<CtorArgTypes>(CtorArgs)... ); - if(pNewRefCounters != nullptr) + pObj = new ObjectType(pRefCounters, std::forward<CtorArgTypes>(CtorArgs)...); + if (pNewRefCounters != nullptr) pNewRefCounters->Attach<ObjectType, AllocatorType>(pObj, m_pAllocator); } catch (...) { - if(pNewRefCounters != nullptr) + if (pNewRefCounters != nullptr) pNewRefCounters->SelfDestroy(); throw; } return pObj; } - + private: AllocatorType* const m_pAllocator; - IObject* const m_pOwner; + IObject* const m_pOwner; #ifdef DEVELOPMENT const Char* const m_dvpDescription; const char* const m_dvpFileName; - Int32 const m_dvpLineNumber; + Int32 const m_dvpLineNumber; #endif }; #define NEW_RC_OBJ(Allocator, Desc, Type, ...) MakeNewRCObj<Type, typename std::remove_reference<decltype(Allocator)>::type>(Allocator, Desc, __FILE__, __LINE__, ##__VA_ARGS__) -} +} // namespace Diligent diff --git a/Common/interface/STDAllocator.h b/Common/interface/STDAllocator.h index f2ddd9f0..a9a2a868 100644 --- a/Common/interface/STDAllocator.h +++ b/Common/interface/STDAllocator.h @@ -35,13 +35,13 @@ namespace Diligent { template <typename T> -typename std::enable_if<std::is_destructible<T>::value, void>::type Destruct(T *ptr) +typename std::enable_if<std::is_destructible<T>::value, void>::type Destruct(T* ptr) { ptr->~T(); } template <typename T> -typename std::enable_if<!std::is_destructible<T>::value, void>::type Destruct(T *ptr) +typename std::enable_if<!std::is_destructible<T>::value, void>::type Destruct(T* ptr) { } @@ -56,40 +56,46 @@ struct STDAllocator using size_type = std::size_t; using difference_type = std::ptrdiff_t; - STDAllocator(AllocatorType& Allocator, const Char* Description, const Char* FileName, const Int32 LineNumber)noexcept : - m_Allocator (Allocator) + STDAllocator(AllocatorType& Allocator, const Char* Description, const Char* FileName, const Int32 LineNumber) noexcept : + // clang-format off + m_Allocator {Allocator} #ifdef DEVELOPMENT - , m_dvpDescription(Description) - , m_dvpFileName (FileName) - , m_dvpLineNumber (LineNumber) + , m_dvpDescription{Description} + , m_dvpFileName {FileName } + , m_dvpLineNumber {LineNumber } #endif + // clang-format on { } - template <class U> - STDAllocator(const STDAllocator<U, AllocatorType>& other)noexcept : - m_Allocator (other.m_Allocator) + template <class U> + STDAllocator(const STDAllocator<U, AllocatorType>& other) noexcept : + // clang-format off + m_Allocator {other.m_Allocator} #ifdef DEVELOPMENT - , m_dvpDescription(other.m_dvpDescription) - , m_dvpFileName (other.m_dvpFileName) - , m_dvpLineNumber (other.m_dvpLineNumber) + , m_dvpDescription{other.m_dvpDescription} + , m_dvpFileName {other.m_dvpFileName } + , m_dvpLineNumber {other.m_dvpLineNumber } #endif + // clang-format on { } - template <class U> - STDAllocator(STDAllocator<U, AllocatorType>&& other)noexcept : - m_Allocator (other.m_Allocator) + template <class U> + STDAllocator(STDAllocator<U, AllocatorType>&& other) noexcept : + // clang-format off + m_Allocator {other.m_Allocator} #ifdef DEVELOPMENT - , m_dvpDescription(other.m_dvpDescription) - , m_dvpFileName (other.m_dvpFileName) - , m_dvpLineNumber (other.m_dvpLineNumber) + , m_dvpDescription{other.m_dvpDescription} + , m_dvpFileName {other.m_dvpFileName } + , m_dvpLineNumber {other.m_dvpLineNumber } #endif + // clang-format on { } - template <class U> - STDAllocator& operator = (STDAllocator<U, AllocatorType>&& other)noexcept + template <class U> + STDAllocator& operator=(STDAllocator<U, AllocatorType>&& other) noexcept { // Android build requires this operator to be defined - I have no idea why. // There is no default constructor to create null allocator, so all fields must be @@ -97,14 +103,14 @@ struct STDAllocator DEV_CHECK_ERR(&m_Allocator == &other.m_Allocator, "Inconsistent allocators"); #ifdef DEVELOPMENT DEV_CHECK_ERR(m_dvpDescription == other.m_dvpDescription, "Incosistent allocator descriptions"); - DEV_CHECK_ERR(m_dvpFileName == other.m_dvpFileName, "Incosistent allocator file names"); - DEV_CHECK_ERR(m_dvpLineNumber == other.m_dvpLineNumber, "Incosistent allocator line numbers"); + DEV_CHECK_ERR(m_dvpFileName == other.m_dvpFileName, "Incosistent allocator file names"); + DEV_CHECK_ERR(m_dvpLineNumber == other.m_dvpLineNumber, "Incosistent allocator line numbers"); #endif return *this; } - template< class U > struct rebind - { + template <class U> struct rebind + { typedef STDAllocator<U, AllocatorType> other; }; @@ -115,10 +121,10 @@ struct STDAllocator static constexpr const char* m_dvpFileName = "<Unavailable in release build>"; static constexpr Int32 m_dvpLineNumber = -1; #endif - return reinterpret_cast<T*>( m_Allocator.Allocate(count * sizeof(T), m_dvpDescription, m_dvpFileName, m_dvpLineNumber ) ); + return reinterpret_cast<T*>(m_Allocator.Allocate(count * sizeof(T), m_dvpDescription, m_dvpFileName, m_dvpLineNumber)); } - pointer address(reference r) { return &r; } + pointer address(reference r) { return &r; } const_pointer address(const_reference r) { return &r; } void deallocate(T* p, std::size_t count) @@ -126,74 +132,74 @@ struct STDAllocator m_Allocator.Free(p); } - inline size_type max_size() const - { - return std::numeric_limits<size_type>::max() / sizeof(T); + inline size_type max_size() const + { + return std::numeric_limits<size_type>::max() / sizeof(T); } // construction/destruction - template< class U, class... Args > - void construct( U* p, Args&&... args ) - { - ::new(p) U(std::forward<Args>(args)...); + template <class U, class... Args> + void construct(U* p, Args&&... args) + { + ::new (p) U(std::forward<Args>(args)...); } inline void destroy(pointer p) - { - p->~T(); + { + p->~T(); } - AllocatorType &m_Allocator; + AllocatorType& m_Allocator; #ifdef DEVELOPMENT const Char* const m_dvpDescription; const Char* const m_dvpFileName; - Int32 const m_dvpLineNumber; + Int32 const m_dvpLineNumber; #endif }; #define STD_ALLOCATOR(Type, AllocatorType, Allocator, Description) STDAllocator<Type, AllocatorType>(Allocator, Description, __FILE__, __LINE__) template <class T, class U, class A> -bool operator==(const STDAllocator<T, A>&left, const STDAllocator<U, A>&right) +bool operator==(const STDAllocator<T, A>& left, const STDAllocator<U, A>& right) { return &left.m_Allocator == &right.m_Allocator; } template <class T, class U, class A> -bool operator!=(const STDAllocator<T, A> &left, const STDAllocator<U, A> &right) +bool operator!=(const STDAllocator<T, A>& left, const STDAllocator<U, A>& right) { return !(left == right); } -template<class T> using STDAllocatorRawMem = STDAllocator<T, IMemoryAllocator>; +template <class T> using STDAllocatorRawMem = STDAllocator<T, IMemoryAllocator>; #define STD_ALLOCATOR_RAW_MEM(Type, Allocator, Description) STDAllocatorRawMem<Type>(Allocator, Description, __FILE__, __LINE__) -template< class T, typename AllocatorType > +template <class T, typename AllocatorType> struct STDDeleter { STDDeleter() noexcept {} - STDDeleter(AllocatorType& Allocator) noexcept : - m_Allocator(&Allocator) + STDDeleter(AllocatorType& Allocator) noexcept : + m_Allocator{&Allocator} {} - - STDDeleter (const STDDeleter&) = default; - STDDeleter& operator = (const STDDeleter&) = default; - STDDeleter(STDDeleter&& rhs) noexcept : - m_Allocator(rhs.m_Allocator) + STDDeleter(const STDDeleter&) = default; + STDDeleter& operator=(const STDDeleter&) = default; + + STDDeleter(STDDeleter&& rhs) noexcept : + m_Allocator{rhs.m_Allocator} { rhs.m_Allocator = nullptr; } - STDDeleter& operator = (STDDeleter&& rhs) noexcept + STDDeleter& operator=(STDDeleter&& rhs) noexcept { - m_Allocator = rhs.m_Allocator; + m_Allocator = rhs.m_Allocator; rhs.m_Allocator = nullptr; return *this; } - void operator()(T *ptr) noexcept + void operator()(T* ptr) noexcept { VERIFY(m_Allocator != nullptr, "The deleter has been moved away or never initialized, and can't be used"); Destruct(ptr); @@ -203,6 +209,6 @@ struct STDDeleter private: AllocatorType* m_Allocator = nullptr; }; -template<class T> using STDDeleterRawMem = STDDeleter<T, IMemoryAllocator>; +template <class T> using STDDeleterRawMem = STDDeleter<T, IMemoryAllocator>; -} +} // namespace Diligent diff --git a/Common/interface/StringDataBlobImpl.h b/Common/interface/StringDataBlobImpl.h index c3541317..dd664911 100644 --- a/Common/interface/StringDataBlobImpl.h +++ b/Common/interface/StringDataBlobImpl.h @@ -33,33 +33,36 @@ namespace Diligent { - + /// Base interface for a file stream class StringDataBlobImpl : public Diligent::ObjectBase<IDataBlob> { public: typedef Diligent::ObjectBase<IDataBlob> TBase; - StringDataBlobImpl( IReferenceCounters* pRefCounters, const char* str ) : TBase(pRefCounters), m_String(str) {} - StringDataBlobImpl( IReferenceCounters* pRefCounters, const String& str ) : TBase(pRefCounters), m_String(str) {} - StringDataBlobImpl( IReferenceCounters* pRefCounters, String&& str ) : TBase(pRefCounters), m_String( std::move(str) ) {} + StringDataBlobImpl(IReferenceCounters* pRefCounters, const char* str) : + TBase(pRefCounters), m_String(str) {} + StringDataBlobImpl(IReferenceCounters* pRefCounters, const String& str) : + TBase(pRefCounters), m_String(str) {} + StringDataBlobImpl(IReferenceCounters* pRefCounters, String&& str) : + TBase(pRefCounters), m_String(std::move(str)) {} - IMPLEMENT_QUERY_INTERFACE_IN_PLACE( IID_DataBlob, TBase ) + IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_DataBlob, TBase) /// Sets the size of the internal data buffer - virtual void Resize(size_t NewSize)override + virtual void Resize(size_t NewSize) override { m_String.resize(NewSize); } /// Returns the size of the internal data buffer - virtual size_t GetSize()override + virtual size_t GetSize() override { return m_String.length(); } /// Returns the pointer to the internal data buffer - virtual void* GetDataPtr()override + virtual void* GetDataPtr() override { return &m_String[0]; } @@ -68,4 +71,4 @@ private: String m_String; }; -} +} // namespace Diligent diff --git a/Common/interface/StringPool.h b/Common/interface/StringPool.h index 2ea0a242..b391710c 100644 --- a/Common/interface/StringPool.h +++ b/Common/interface/StringPool.h @@ -38,26 +38,30 @@ namespace Diligent class StringPool { public: - StringPool(){} - - StringPool (const StringPool&) = delete; - StringPool& operator = (const StringPool&) = delete; - - StringPool (StringPool&& Pool) : - m_pBuffer (Pool.m_pBuffer ), - m_pCurrPtr (Pool.m_pCurrPtr ), - m_ReservedSize(Pool.m_ReservedSize), - m_pAllocator (Pool.m_pAllocator ) + StringPool() {} + + // clang-format off + StringPool (const StringPool&) = delete; + StringPool& operator=(const StringPool&) = delete; + // clang-format on + + StringPool(StringPool&& Pool) : + // clang-format off + m_pBuffer {Pool.m_pBuffer }, + m_pCurrPtr {Pool.m_pCurrPtr }, + m_ReservedSize{Pool.m_ReservedSize}, + m_pAllocator {Pool.m_pAllocator } + // clang-format on { - Pool.m_pBuffer = nullptr; - Pool.m_pCurrPtr = nullptr; - Pool.m_ReservedSize = 0; - Pool.m_pAllocator = nullptr; + Pool.m_pBuffer = nullptr; + Pool.m_pCurrPtr = nullptr; + Pool.m_ReservedSize = 0; + Pool.m_pAllocator = nullptr; } ~StringPool() { - if(m_pBuffer != nullptr && m_pAllocator != nullptr) + if (m_pBuffer != nullptr && m_pAllocator != nullptr) { m_pAllocator->Free(m_pBuffer); } @@ -66,7 +70,7 @@ public: void Reserve(size_t Size, IMemoryAllocator& Allocator) { VERIFY(m_ReservedSize == 0, "Pool is already initialized"); - m_pAllocator = &Allocator; + m_pAllocator = &Allocator; m_ReservedSize = Size; if (m_ReservedSize != 0) { @@ -79,23 +83,23 @@ public: { VERIFY(m_ReservedSize == 0, "Pool is already initialized"); m_ReservedSize = Size; - m_pBuffer = pBuffer; - m_pCurrPtr = m_pBuffer; + m_pBuffer = pBuffer; + m_pCurrPtr = m_pBuffer; } Char* Allocate(size_t Length) { VERIFY(m_pCurrPtr + Length <= m_pBuffer + m_ReservedSize, "Not enough space in the buffer"); - auto *Ptr = m_pCurrPtr; + auto* Ptr = m_pCurrPtr; m_pCurrPtr += Length; return Ptr; } Char* CopyString(const String& Str) { - auto len = Str.length(); - auto *str = Allocate(len + 1); - if(len != 0) + auto len = Str.length(); + auto* str = Allocate(len + 1); + if (len != 0) { memcpy(str, Str.data(), len * sizeof(str[0])); } @@ -106,11 +110,11 @@ public: Char* CopyString(const char* Str) { auto* Ptr = m_pCurrPtr; - while(*Str != 0 && m_pCurrPtr < m_pBuffer + m_ReservedSize) + while (*Str != 0 && m_pCurrPtr < m_pBuffer + m_ReservedSize) { *(m_pCurrPtr++) = *(Str++); } - if(m_pCurrPtr < m_pBuffer + m_ReservedSize) + if (m_pCurrPtr < m_pBuffer + m_ReservedSize) *(m_pCurrPtr++) = 0; else UNEXPECTED("Not enough space reserved in the string pool"); @@ -118,22 +122,22 @@ public: } - size_t GetRemainingSize()const + size_t GetRemainingSize() const { VERIFY(m_pCurrPtr <= m_pBuffer + m_ReservedSize, "Buffer overflow"); return m_ReservedSize - (m_pCurrPtr - m_pBuffer); } - size_t GetUsedSize()const + size_t GetUsedSize() const { VERIFY(m_pCurrPtr <= m_pBuffer + m_ReservedSize, "Buffer overflow"); return m_pCurrPtr - m_pBuffer; } private: - Char* m_pBuffer = nullptr; - Char* m_pCurrPtr = nullptr; - size_t m_ReservedSize = 0; - IMemoryAllocator* m_pAllocator = nullptr; + Char* m_pBuffer = nullptr; + Char* m_pCurrPtr = nullptr; + size_t m_ReservedSize = 0; + IMemoryAllocator* m_pAllocator = nullptr; }; -} +} // namespace Diligent diff --git a/Common/interface/StringTools.h b/Common/interface/StringTools.h index 4782b670..ee499473 100644 --- a/Common/interface/StringTools.h +++ b/Common/interface/StringTools.h @@ -38,71 +38,75 @@ namespace Diligent inline std::string NarrowString(const std::wstring& WideStr) { std::string NarrowStr; - const std::ctype<wchar_t>& ctfacet = std::use_facet< std::ctype<wchar_t> >( std::wstringstream().getloc() ) ; - for( std::wstring::const_iterator CurrWChar = WideStr.begin(); + + const std::ctype<wchar_t>& ctfacet = std::use_facet<std::ctype<wchar_t>>(std::wstringstream().getloc()); + for (std::wstring::const_iterator CurrWChar = WideStr.begin(); CurrWChar != WideStr.end(); - CurrWChar++ ) - NarrowStr.push_back( ctfacet.narrow( *CurrWChar, 0 ) ); - - return NarrowStr; + CurrWChar++) + NarrowStr.push_back(ctfacet.narrow(*CurrWChar, 0)); + + return NarrowStr; } inline std::string NarrowString(const wchar_t* WideStr) { std::string NarrowStr; - const std::ctype<wchar_t>& ctfacet = std::use_facet< std::ctype<wchar_t> >( std::wstringstream().getloc() ) ; - for( auto CurrWChar = WideStr; *CurrWChar != 0; ++CurrWChar ) - NarrowStr.push_back( ctfacet.narrow( *CurrWChar, 0 ) ); - - return NarrowStr; + + const std::ctype<wchar_t>& ctfacet = std::use_facet<std::ctype<wchar_t>>(std::wstringstream().getloc()); + for (auto CurrWChar = WideStr; *CurrWChar != 0; ++CurrWChar) + NarrowStr.push_back(ctfacet.narrow(*CurrWChar, 0)); + + return NarrowStr; } inline std::wstring WidenString(const char* Str) { - std::wstring WideStr; - const std::ctype<wchar_t>& ctfacet = std::use_facet< std::ctype<wchar_t> >( std::wstringstream().getloc() ) ; - for( auto CurrChar = Str; *CurrChar != 0; ++CurrChar ) - WideStr.push_back( ctfacet.widen( *CurrChar ) ); - - return WideStr; + std::wstring WideStr; + + const std::ctype<wchar_t>& ctfacet = std::use_facet<std::ctype<wchar_t>>(std::wstringstream().getloc()); + for (auto CurrChar = Str; *CurrChar != 0; ++CurrChar) + WideStr.push_back(ctfacet.widen(*CurrChar)); + + return WideStr; } inline std::wstring WidenString(const std::string& Str) { - std::wstring WideStr; - const std::ctype<wchar_t>& ctfacet = std::use_facet< std::ctype<wchar_t> >( std::wstringstream().getloc() ) ; - for( std::string::const_iterator CurrChar = Str.begin(); + std::wstring WideStr; + + const std::ctype<wchar_t>& ctfacet = std::use_facet<std::ctype<wchar_t>>(std::wstringstream().getloc()); + for (std::string::const_iterator CurrChar = Str.begin(); CurrChar != Str.end(); - CurrChar++ ) - WideStr.push_back( ctfacet.widen( *CurrChar ) ); - - return WideStr; + CurrChar++) + WideStr.push_back(ctfacet.widen(*CurrChar)); + + return WideStr; } inline int StrCmpNoCase(const char* Str1, const char* Str2, size_t NumChars) { #if PLATFORM_ANDROID || PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS -# define _strnicmp strncasecmp +# define _strnicmp strncasecmp #endif - return _strnicmp( Str1, Str2, NumChars ); + return _strnicmp(Str1, Str2, NumChars); } inline int StrCmpNoCase(const char* Str1, const char* Str2) { #if PLATFORM_ANDROID || PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS -# define _stricmp strcasecmp +# define _stricmp strcasecmp #endif - return _stricmp( Str1, Str2 ); + return _stricmp(Str1, Str2); } // Returns true if RefStr == Str + Suff // If Suff == nullptr or NoSuffixAllowed == true, also returns true if RefStr == Str inline bool StreqSuff(const char* RefStr, const char* Str, const char* Suff, bool NoSuffixAllowed = false) { - VERIFY_EXPR(RefStr != nullptr && Str!= nullptr); - if (RefStr==nullptr) + VERIFY_EXPR(RefStr != nullptr && Str != nullptr); + if (RefStr == nullptr) return false; const auto* r = RefStr; @@ -160,12 +164,11 @@ inline bool StreqSuff(const char* RefStr, const char* Str, const char* Suff, boo } } -inline void StrToLowerInPlace(std::string &str) +inline void StrToLowerInPlace(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), - // http://en.cppreference.com/w/cpp/string/byte/tolower - [](unsigned char c) { return static_cast<char>(std::tolower(c)); } - ); + // http://en.cppreference.com/w/cpp/string/byte/tolower + [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); } inline std::string StrToLower(std::string str) @@ -174,4 +177,4 @@ inline std::string StrToLower(std::string str) return str; } -} +} // namespace Diligent diff --git a/Common/interface/ThreadSignal.h b/Common/interface/ThreadSignal.h index 39c0d87a..9060759e 100644 --- a/Common/interface/ThreadSignal.h +++ b/Common/interface/ThreadSignal.h @@ -35,7 +35,7 @@ namespace ThreadingTools class Signal { public: - Signal() + Signal() { m_SignaledValue = 0; m_NumThreadsAwaken = 0; @@ -47,7 +47,7 @@ public: // The thread that intends to modify the variable has to // * acquire a std::mutex (typically via std::lock_guard) // * perform the modification while the lock is held - // * execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification) + // * execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification) { // std::condition_variable works only with std::unique_lock<std::mutex> std::lock_guard<std::mutex> Lock{m_Mutex}; @@ -55,9 +55,9 @@ public: VERIFY(m_SignaledValue == 0 && m_NumThreadsAwaken == 0, "Not all threads have been awaken since the signal was triggered last time, or the signal has not been reset"); m_SignaledValue = SignalValue; } - // Unlocking is done before notifying, to avoid waking up the waiting + // Unlocking is done before notifying, to avoid waking up the waiting // thread only to block again (see notify_one for details) - if(NotifyAll) + if (NotifyAll) m_CondVar.notify_all(); else m_CondVar.notify_one(); @@ -65,25 +65,25 @@ public: // WARNING! // If multiple threads are waiting for a signal in an infinite loop, - // autoresetting the signal does not guarantee that one thread cannot - // go through the loop twice. In this case, every thread must wait for its + // autoresetting the signal does not guarantee that one thread cannot + // go through the loop twice. In this case, every thread must wait for its // own auto-reset signal or the threads must be blocked by another signal int Wait(bool AutoReset = false, int NumThreadsWaiting = 0) { // Any thread that intends to wait on std::condition_variable has to // * acquire a std::unique_lock<std::mutex>, on the SAME MUTEX as used to protect the shared variable - // * execute wait, wait_for, or wait_until. The wait operations atomically release the mutex + // * execute wait, wait_for, or wait_until. The wait operations atomically release the mutex // and suspend the execution of the thread. - // * When the condition variable is notified, a timeout expires, or a spurious wakeup occurs, - // the thread is awakened, and the mutex is atomically reacquired: + // * When the condition variable is notified, a timeout expires, or a spurious wakeup occurs, + // the thread is awakened, and the mutex is atomically reacquired: // - The thread should then check the condition and resume waiting if the wake up was spurious. std::unique_lock<std::mutex> Lock(m_Mutex); // It is safe to check m_SignaledValue since we are holding // the mutex - if(m_SignaledValue == 0) + if (m_SignaledValue == 0) { - m_CondVar.wait(Lock, [&] {return m_SignaledValue != 0;} ); + m_CondVar.wait(Lock, [&] { return m_SignaledValue != 0; }); } int SignaledValue = m_SignaledValue; // Count the number of threads awaken while holding the mutex @@ -93,9 +93,9 @@ public: VERIFY(NumThreadsWaiting > 0, "Number of waiting threads must not be 0 when auto resetting the signal"); // Reset the signal while holding the mutex. If Trigger() is executed by another // thread, it will wait until we release the mutex - if(m_NumThreadsAwaken == NumThreadsWaiting) + if (m_NumThreadsAwaken == NumThreadsWaiting) { - m_SignaledValue = 0; + m_SignaledValue = 0; m_NumThreadsAwaken = 0; } } @@ -105,21 +105,20 @@ public: void Reset() { std::lock_guard<std::mutex> Lock{m_Mutex}; - m_SignaledValue = 0; + m_SignaledValue = 0; m_NumThreadsAwaken = 0; } - bool IsTriggered()const { return m_SignaledValue != 0; } + bool IsTriggered() const { return m_SignaledValue != 0; } private: - - std::mutex m_Mutex; + std::mutex m_Mutex; std::condition_variable m_CondVar; - std::atomic_int m_SignaledValue; - std::atomic_int m_NumThreadsAwaken; - + std::atomic_int m_SignaledValue; + std::atomic_int m_NumThreadsAwaken; + Signal(const Signal&) = delete; - Signal& operator = (const Signal&) = delete; + Signal& operator=(const Signal&) = delete; }; -} +} // namespace ThreadingTools diff --git a/Common/interface/Timer.h b/Common/interface/Timer.h index eda1a60f..e5ec6c9a 100644 --- a/Common/interface/Timer.h +++ b/Common/interface/Timer.h @@ -27,15 +27,17 @@ namespace Diligent { - class Timer - { - public: - Timer(); - void Restart(); - double GetElapsedTime()const; - float GetElapsedTimef()const; - private: - std::chrono::high_resolution_clock::time_point m_StartTime; - }; -} +class Timer +{ +public: + Timer(); + void Restart(); + double GetElapsedTime() const; + float GetElapsedTimef() const; + +private: + std::chrono::high_resolution_clock::time_point m_StartTime; +}; + +} // namespace Diligent diff --git a/Common/interface/UniqueIdentifier.h b/Common/interface/UniqueIdentifier.h index 891aafd1..fde2574d 100644 --- a/Common/interface/UniqueIdentifier.h +++ b/Common/interface/UniqueIdentifier.h @@ -28,43 +28,47 @@ namespace Diligent { - using UniqueIdentifier = Int32; - // Template switch is used to have distinct counters - // for unrelated groups of objects - template<typename ObjectsClass> - class UniqueIdHelper - { - public: - UniqueIdHelper()noexcept {} +using UniqueIdentifier = Int32; - UniqueIdHelper (const UniqueIdHelper&) = delete; - UniqueIdHelper& operator = (const UniqueIdHelper&) = delete; +// Template switch is used to have distinct counters +// for unrelated groups of objects +template <typename ObjectsClass> +class UniqueIdHelper +{ +public: + UniqueIdHelper() noexcept {} - UniqueIdHelper(UniqueIdHelper&& RHS)noexcept : - m_ID {RHS.m_ID} - { - RHS.m_ID = 0; - } + // clang-format off + UniqueIdHelper (const UniqueIdHelper&) = delete; + UniqueIdHelper& operator = (const UniqueIdHelper&) = delete; + // clang-format on + + UniqueIdHelper(UniqueIdHelper&& RHS) noexcept : + m_ID{RHS.m_ID} + { + RHS.m_ID = 0; + } + + UniqueIdHelper& operator=(UniqueIdHelper&& RHS) noexcept + { + m_ID = RHS.m_ID; + RHS.m_ID = 0; + return *this; + } - UniqueIdHelper& operator = (UniqueIdHelper&& RHS)noexcept + UniqueIdentifier GetID() const noexcept + { + if (m_ID == 0) { - m_ID = RHS.m_ID; - RHS.m_ID = 0; - return *this; + static Atomics::AtomicLong GlobalCounter; // = 0 causes gcc error + m_ID = static_cast<UniqueIdentifier>(Atomics::AtomicIncrement(GlobalCounter)); } + return m_ID; + } - UniqueIdentifier GetID()const noexcept - { - if (m_ID == 0) - { - static Atomics::AtomicLong GlobalCounter; // = 0 causes gcc error - m_ID = static_cast<UniqueIdentifier>(Atomics::AtomicIncrement(GlobalCounter)); - } - return m_ID; - } +private: + mutable UniqueIdentifier m_ID = 0; +}; - private: - mutable UniqueIdentifier m_ID = 0; - }; -} +} // namespace Diligent diff --git a/Common/interface/ValidatedCast.h b/Common/interface/ValidatedCast.h index febc36e8..6dcd00a1 100644 --- a/Common/interface/ValidatedCast.h +++ b/Common/interface/ValidatedCast.h @@ -25,13 +25,13 @@ #include "../../Platforms/Basic/interface/DebugUtilities.h" -template<typename DstType, typename SrcType> +template <typename DstType, typename SrcType> DstType* ValidatedCast(SrcType* Ptr) { #ifdef _DEBUG - if(Ptr != nullptr) + if (Ptr != nullptr) { - CHECK_DYNAMIC_TYPE( DstType, Ptr ); + CHECK_DYNAMIC_TYPE(DstType, Ptr); } #endif return static_cast<DstType*>(Ptr); |
