Merge branch 'main' into ly-as-sdk/LYN-2948

This commit is contained in:
phistere
2021-05-13 11:25:03 -05:00
1224 changed files with 18773 additions and 126359 deletions
-173
View File
@@ -1,173 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef __animtime_h__
#define __animtime_h__
#include <IXml.h>
#include <AzCore/Casting/numeric_cast.h>
#include <Serialization/IArchive.h>
struct SAnimTime
{
static const uint numTicksPerSecond = 6000;
// List of possible frame rates (dividers of 6000). Most commonly used ones first.
enum EFrameRate
{
// Common
eFrameRate_30fps, eFrameRate_60fps, eFrameRate_120fps,
// Possible
eFrameRate_10fps, eFrameRate_12fps, eFrameRate_15fps, eFrameRate_24fps,
eFrameRate_25fps, eFrameRate_40fps, eFrameRate_48fps, eFrameRate_50fps,
eFrameRate_75fps, eFrameRate_80fps, eFrameRate_100fps, eFrameRate_125fps,
eFrameRate_150fps, eFrameRate_200fps, eFrameRate_240fps, eFrameRate_250fps,
eFrameRate_300fps, eFrameRate_375fps, eFrameRate_400fps, eFrameRate_500fps,
eFrameRate_600fps, eFrameRate_750fps, eFrameRate_1000fps, eFrameRate_1200fps,
eFrameRate_1500fps, eFrameRate_2000fps, eFrameRate_3000fps, eFrameRate_6000fps,
eFrameRate_Num
};
SAnimTime()
: m_ticks(0) {}
explicit SAnimTime(int32 ticks)
: m_ticks(ticks) {}
explicit SAnimTime(float time)
: m_ticks(aznumeric_caster(std::lround(static_cast<double>(time) * numTicksPerSecond))) {}
static uint GetFrameRateValue(EFrameRate frameRate)
{
const uint frameRateValues[eFrameRate_Num] =
{
// Common
30, 60, 120,
// Possible
10, 12, 15, 24, 25, 40, 48, 50, 75, 80, 100, 125,
150, 200, 240, 250, 300, 375, 400, 500, 600, 750,
1000, 1200, 1500, 2000, 3000, 6000
};
return frameRateValues[frameRate];
}
static const char* GetFrameRateName(EFrameRate frameRate)
{
const char* frameRateNames[eFrameRate_Num] =
{
// Common
"30 fps", "60 fps", "120 fps",
// Possible
"10 fps", "12 fps", "15 fps", "24 fps",
"25 fps", "40 fps", "48 fps", "50 fps",
"75 fps", "80 fps", "100 fps", "125 fps",
"150 fps", "200 fps", "240 fps", "250 fps",
"300 fps", "375 fps", "400 fps", "500 fps",
"600 fps", "750 fps", "1000 fps", "1200 fps",
"1500 fps", "2000 fps", "3000 fps", "6000 fps"
};
return frameRateNames[frameRate];
}
float ToFloat() const { return static_cast<float>(m_ticks) / numTicksPerSecond; }
void Serialize(Serialization::IArchive& ar)
{
ar(m_ticks, "ticks", "Ticks");
}
// Helper to serialize from ticks or old float time
void Serialize(XmlNodeRef keyNode, bool bLoading, const char* pName, const char* pLegacyName)
{
if (bLoading)
{
int32 ticks;
if (!keyNode->getAttr(pName, ticks))
{
// Backwards compatibility
float time = 0.0f;
keyNode->getAttr(pLegacyName, time);
*this = SAnimTime(time);
}
else
{
m_ticks = ticks;
}
}
else if (m_ticks > 0)
{
keyNode->setAttr(pName, m_ticks);
}
}
int32 GetTicks() const { return m_ticks; }
static SAnimTime Min() { SAnimTime minTime; minTime.m_ticks = std::numeric_limits<int32>::lowest(); return minTime; }
static SAnimTime Max() { SAnimTime maxTime; maxTime.m_ticks = (std::numeric_limits<int32>::max)(); return maxTime; }
SAnimTime operator-() const { return SAnimTime(-m_ticks); }
SAnimTime operator-(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks -= r.m_ticks; return temp; }
SAnimTime operator+(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks += r.m_ticks; return temp; }
SAnimTime operator*(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks *= r.m_ticks; return temp; }
SAnimTime operator/(SAnimTime r) const { SAnimTime temp; temp.m_ticks = static_cast<int32>((static_cast<int64>(m_ticks) * numTicksPerSecond) / r.m_ticks); return temp; }
SAnimTime operator%(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks %= r.m_ticks; return temp; }
SAnimTime operator*(float r) const { SAnimTime temp; temp.m_ticks = aznumeric_caster(std::lround(static_cast<double>(m_ticks) * r)); return temp; }
SAnimTime operator/(float r) const { SAnimTime temp; temp.m_ticks = aznumeric_caster(std::lround(static_cast<double>(m_ticks) / r)); return temp; }
SAnimTime& operator+=(SAnimTime r) { *this = *this + r; return *this; }
SAnimTime& operator-=(SAnimTime r) { *this = *this - r; return *this; }
SAnimTime& operator*=(SAnimTime r) { *this = *this * r; return *this; }
SAnimTime& operator/=(SAnimTime r) { *this = *this / r; return *this; }
SAnimTime& operator%=(SAnimTime r) { *this = *this % r; return *this; }
SAnimTime& operator*=(float r) { *this = *this * r; return *this; }
SAnimTime& operator/=(float r) { *this = *this / r; return *this; }
bool operator<(SAnimTime r) const { return m_ticks < r.m_ticks; }
bool operator<=(SAnimTime r) const { return m_ticks <= r.m_ticks; }
bool operator>(SAnimTime r) const { return m_ticks > r.m_ticks; }
bool operator>=(SAnimTime r) const { return m_ticks >= r.m_ticks; }
bool operator==(SAnimTime r) const { return m_ticks == r.m_ticks; }
bool operator!=(SAnimTime r) const { return m_ticks != r.m_ticks; }
// Snap to nearest multiple of given frame rate
SAnimTime SnapToNearest(const EFrameRate frameRate)
{
const int sign = sgn(m_ticks);
const int32 absTicks = abs(m_ticks);
const int framesMod = numTicksPerSecond / GetFrameRateValue(frameRate);
const int32 remainder = absTicks % framesMod;
const bool bNextMultiple = remainder >= (framesMod / 2);
return SAnimTime(sign * ((absTicks - remainder) + (bNextMultiple ? framesMod : 0)));
}
private:
int32 m_ticks;
friend bool Serialize(Serialization::IArchive& ar, SAnimTime& animTime, const char* name, const char* label);
};
inline bool Serialize(Serialization::IArchive& ar, SAnimTime& animTime, const char* name, const char* label)
{
return ar(animTime.m_ticks, name, label);
}
inline SAnimTime abs(SAnimTime time)
{
return (time >= SAnimTime(0)) ? time : -time;
}
#endif
-321
View File
@@ -1,321 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef __BEZIER_H__
#define __BEZIER_H__
#include <AnimTime.h>
#include <Serialization/IArchive.h>
#include <Serialization/Math.h>
struct SBezierControlPoint
{
SBezierControlPoint()
: m_value(0.0f)
, m_inTangent(ZERO)
, m_outTangent(ZERO)
, m_inTangentType(eTangentType_Auto)
, m_outTangentType(eTangentType_Auto)
, m_bBreakTangents(false)
{
}
enum ETangentType
{
eTangentType_Custom,
eTangentType_Auto,
eTangentType_Zero,
eTangentType_Step,
eTangentType_Linear,
};
void Serialize(Serialization::IArchive& ar)
{
ar(m_value, "value", "Value");
if (ar.IsOutput())
{
bool breakTangents = m_bBreakTangents;
ar(breakTangents, "breakTangents", "Break Tangents");
}
else
{
bool breakTangents = false;
ar(breakTangents, "breakTangents", "Break Tangents");
m_bBreakTangents = breakTangents;
}
if (ar.IsOutput())
{
ETangentType inTangentType = m_inTangentType;
ar(inTangentType, "inTangentType", "Incoming tangent type");
}
else
{
ETangentType inTangentType = eTangentType_Auto;
ar(inTangentType, "inTangentType", "Incoming tangent type");
m_inTangentType = inTangentType;
}
ar(m_inTangent, "inTangent", (m_inTangentType == eTangentType_Custom) ? "Incoming Tangent" : NULL);
if (ar.IsOutput())
{
ETangentType outTangentType = m_outTangentType;
ar(outTangentType, "outTangentType", "Outgoing tangent type");
}
else
{
ETangentType outTangentType = eTangentType_Auto;
ar(outTangentType, "outTangentType", "Outgoing tangent type");
m_outTangentType = outTangentType;
}
ar(m_outTangent, "outTangent", (m_outTangentType == eTangentType_Custom) ? "Outgoing Tangent" : NULL);
}
float m_value;
// For 1D Bezier only the Y component is used
Vec2 m_inTangent;
Vec2 m_outTangent;
ETangentType m_inTangentType : 4;
ETangentType m_outTangentType : 4;
bool m_bBreakTangents : 1;
};
struct SBezierKey
{
SBezierKey()
: m_time(0) {}
void Serialize(Serialization::IArchive& ar)
{
ar(m_time, "time", "Time");
ar(m_controlPoint, "controlPoint", "Control Point");
}
SAnimTime m_time;
SBezierControlPoint m_controlPoint;
};
namespace Bezier
{
inline float Evaluate(float t, float p0, float p1, float p2, float p3)
{
const float a = 1 - t;
const float aSq = a * a;
const float tSq = t * t;
return (aSq * a * p0) + (3.0f * aSq * t * p1) + (3.0f * a * tSq * p2) + (tSq * t * p3);
}
inline float EvaluateDeriv(float t, float p0, float p1, float p2, float p3)
{
const float a = 1 - t;
const float ta = t * a;
const float aSq = a * a;
const float tSq = t * t;
return 3.0f * ((-p2 * tSq) + (p3 * tSq) - (p0 * aSq) + (p1 * aSq) + 2.0f * ((-p1 * ta) + (p2 * ta)));
}
inline float EvaluateX(const float t, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end)
{
const float p0 = 0.0f;
const float p1 = p0 + start.m_outTangent.x;
const float p3 = duration;
const float p2 = p3 + end.m_inTangent.x;
return Evaluate(t, p0, p1, p2, p3);
}
inline float EvaluateY(const float t, const SBezierControlPoint& start, const SBezierControlPoint& end)
{
const float p0 = start.m_value;
const float p1 = p0 + start.m_outTangent.y;
const float p3 = end.m_value;
const float p2 = p3 + end.m_inTangent.y;
return Evaluate(t, p0, p1, p2, p3);
}
// Duration = (time at end key) - (time at start key)
inline float EvaluateDerivX(const float t, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end)
{
const float p0 = 0.0f;
const float p1 = p0 + start.m_outTangent.x;
const float p3 = duration;
const float p2 = p3 + end.m_inTangent.x;
return EvaluateDeriv(t, p0, p1, p2, p3);
}
inline float EvaluateDerivY(const float t, const SBezierControlPoint& start, const SBezierControlPoint& end)
{
const float p0 = start.m_value;
const float p1 = p0 + start.m_outTangent.y;
const float p3 = end.m_value;
const float p2 = p3 + end.m_inTangent.y;
return EvaluateDeriv(t, p0, p1, p2, p3);
}
// Find interpolation factor where 2D bezier curve has the given x value. Works only for curves where x is monotonically increasing.
// The passed x must be in range [0, duration]. Uses the Newton-Raphson root finding method. Usually takes 2 or 3 iterations.
//
// Note: This is for "1D" 2D bezier curves as used in TrackView. The curves are restricted by the curve editor to be monotonically increasing.
//
inline float InterpolationFactorFromX(const float x, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end)
{
float t = (x / duration);
const float epsilon = 0.00001f;
const uint maxSteps = 10;
for (uint i = 0; i < maxSteps; ++i)
{
const float currentX = EvaluateX(t, duration, start, end) - x;
if (fabs(currentX) <= epsilon)
{
break;
}
const float currentXDeriv = EvaluateDerivX(t, duration, start, end);
t -= currentX / currentXDeriv;
}
return t;
}
inline SBezierControlPoint CalculateInTangent(
float time, const SBezierControlPoint& point,
float leftTime, const SBezierControlPoint* pLeftPoint,
float rightTime, const SBezierControlPoint* pRightPoint)
{
SBezierControlPoint newPoint = point;
// In tangent X can never be positive
newPoint.m_inTangent.x = std::min(point.m_inTangent.x, 0.0f);
if (pLeftPoint)
{
switch (point.m_inTangentType)
{
case SBezierControlPoint::eTangentType_Custom:
{
// Need to clamp tangent if it is reaching over last point
const float deltaTime = time - leftTime;
if (deltaTime < -newPoint.m_inTangent.x)
{
if (newPoint.m_inTangent.x == 0)
{
newPoint.m_inTangent = Vec2(ZERO);
}
else
{
float scaleFactor = deltaTime / -newPoint.m_inTangent.x;
newPoint.m_inTangent.x = -deltaTime;
newPoint.m_inTangent.y *= scaleFactor;
}
}
}
break;
case SBezierControlPoint::eTangentType_Zero:
// Fall through. Zero for y is same as Auto, x is set to 0.0f
case SBezierControlPoint::eTangentType_Auto:
{
const SBezierControlPoint& rightPoint = pRightPoint ? *pRightPoint : point;
const float deltaTime = (pRightPoint ? rightTime : time) - leftTime;
if (deltaTime > 0.0f)
{
const float ratio = (time - leftTime) / deltaTime;
const float deltaValue = rightPoint.m_value - pLeftPoint->m_value;
const bool bIsZeroTangent = (point.m_inTangentType == SBezierControlPoint::eTangentType_Zero);
newPoint.m_inTangent = Vec2(-(deltaTime * ratio) / 3.0f, bIsZeroTangent ? 0.0f : -(deltaValue * ratio) / 3.0f);
}
else
{
newPoint.m_inTangent = Vec2(ZERO);
}
}
break;
case SBezierControlPoint::eTangentType_Linear:
newPoint.m_inTangent = Vec2((leftTime - time) / 3.0f,
(pLeftPoint->m_value - point.m_value) / 3.0f);
break;
}
}
return newPoint;
}
inline SBezierControlPoint CalculateOutTangent(
float time, const SBezierControlPoint& point,
float leftTime, const SBezierControlPoint* pLeftPoint,
float rightTime, const SBezierControlPoint* pRightPoint)
{
SBezierControlPoint newPoint = point;
// Out tangent X can never be negative
newPoint.m_outTangent.x = std::max(point.m_outTangent.x, 0.0f);
if (pRightPoint)
{
switch (point.m_outTangentType)
{
case SBezierControlPoint::eTangentType_Custom:
{
// Need to clamp tangent if it is reaching over next point
const float deltaTime = rightTime - time;
if (deltaTime < newPoint.m_outTangent.x)
{
if (newPoint.m_outTangent.x == 0)
{
newPoint.m_outTangent = Vec2(ZERO);
}
else
{
float scaleFactor = deltaTime / newPoint.m_outTangent.x;
newPoint.m_outTangent.x = deltaTime;
newPoint.m_outTangent.y *= scaleFactor;
}
}
}
break;
case SBezierControlPoint::eTangentType_Zero:
// Fall through. Zero for y is same as Auto, x is set to 0.0f
case SBezierControlPoint::eTangentType_Auto:
{
const SBezierControlPoint& leftPoint = pLeftPoint ? *pLeftPoint : point;
const float deltaTime = rightTime - (pLeftPoint ? leftTime : time);
if (deltaTime > 0.0f)
{
const float ratio = (rightTime - time) / deltaTime;
const float deltaValue = pRightPoint->m_value - leftPoint.m_value;
const bool bIsZeroTangent = (point.m_outTangentType == SBezierControlPoint::eTangentType_Zero);
newPoint.m_outTangent = Vec2((deltaTime * ratio) / 3.0f, bIsZeroTangent ? 0.0f : (deltaValue * ratio) / 3.0f);
}
else
{
newPoint.m_outTangent = Vec2(ZERO);
}
}
break;
case SBezierControlPoint::eTangentType_Linear:
newPoint.m_outTangent = Vec2((rightTime - time) / 3.0f,
(pRightPoint->m_value - point.m_value) / 3.0f);
break;
}
}
return newPoint;
}
}
#endif
-43
View File
@@ -9,58 +9,15 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME})
ly_get_pal_tool_dirs(pal_tool_dirs ${CMAKE_CURRENT_LIST_DIR}/Platform)
ly_add_target(
NAME CryCommon STATIC
NAMESPACE Legacy
FILES_CMAKE
crycommon_files.cmake
${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake
PLATFORM_INCLUDE_FILES
${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}.cmake
INCLUDE_DIRECTORIES
PUBLIC
. # Lots of code without CryCommon/
.. # Dangerous since exports CryEngine's path (client code can do CrySystem/ without depending on that target)
${pal_dir}
${pal_tool_dirs}
BUILD_DEPENDENCIES
PUBLIC
AZ::AzCore
AZ::AzFramework
)
ly_add_target(
NAME CryCommon.EngineSettings.Static STATIC
NAMESPACE Legacy
FILES_CMAKE
crycommon_enginesettings_files.cmake
${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake
INCLUDE_DIRECTORIES
PUBLIC
.
${pal_dir}
BUILD_DEPENDENCIES
PUBLIC
AZ::AzCore
AZ::AzFramework
)
ly_add_target(
NAME CryCommon.EngineSettings.RC.Static STATIC
NAMESPACE Legacy
FILES_CMAKE
crycommon_enginesettings_files.cmake
${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake
INCLUDE_DIRECTORIES
PUBLIC
.
${pal_dir}
COMPILE_DEFINITIONS
PRIVATE
RESOURCE_COMPILER
BUILD_DEPENDENCIES
PUBLIC
AZ::AzCore
+1 -1
View File
@@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...)
return;
}
if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting)
if (!gEnv->bIgnoreAllAsserts)
{
if (szFormat == NULL)
{
+1 -1
View File
@@ -34,7 +34,7 @@ void CryAssertTrace(const char* szFormat, ...)
return;
}
if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting)
if (!gEnv->bIgnoreAllAsserts)
{
if (szFormat == NULL)
{
+1 -1
View File
@@ -30,7 +30,7 @@ void CryAssertTrace(const char* szFormat, ...)
return;
}
if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting)
if (!gEnv->bIgnoreAllAsserts)
{
if (szFormat == NULL)
{
+1 -1
View File
@@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...)
return;
}
if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting)
if (!gEnv->bIgnoreAllAsserts)
{
if (szFormat == NULL)
{
+1 -1
View File
@@ -305,7 +305,7 @@ void CryAssertTrace(const char* _pszFormat, ...)
{
return;
}
if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting)
if (!gEnv->bIgnoreAllAsserts)
{
if (NULL == _pszFormat)
{
@@ -1,96 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H
#define CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H
#pragma once
#include "ICryUnknown.h"
#include "ICryFactory.h"
#include "ICryFactoryRegistry.h"
#include <ISystem.h> // <> required for Interfuscator
template <class T>
bool CryCreateClassInstance(const CryClassID& cid, AZStd::shared_ptr<T>& p)
{
p = AZStd::shared_ptr<T>();
ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry();
if (pFactoryReg)
{
ICryFactory* pFactory = pFactoryReg->GetFactory(cid);
if (pFactory && pFactory->ClassSupports(cryiidof<T>()))
{
ICryUnknownPtr pUnk = pFactory->CreateClassInstance();
AZStd::shared_ptr<T> pT = cryinterface_cast<T>(pUnk);
if (pT)
{
p = pT;
}
}
}
return p.get() != NULL;
}
template <class T>
bool CryCreateClassInstance(const char* cname, AZStd::shared_ptr<T>& p)
{
p = AZStd::shared_ptr<T>();
ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry();
if (pFactoryReg)
{
ICryFactory* pFactory = pFactoryReg->GetFactory(cname);
if (pFactory != NULL && pFactory->ClassSupports(cryiidof<T>()))
{
ICryUnknownPtr pUnk = pFactory->CreateClassInstance();
AZStd::shared_ptr<T> pT = cryinterface_cast<T>(pUnk);
if (pT)
{
p = pT;
}
}
}
return p.get() != NULL;
}
template <class T>
bool CryCreateClassInstanceForInterface(const CryInterfaceID& iid, AZStd::shared_ptr<T>& p)
{
p = AZStd::shared_ptr<T>();
ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry();
if (pFactoryReg)
{
size_t numFactories = 1;
ICryFactory* pFactory = 0;
pFactoryReg->IterateFactories(iid, &pFactory, numFactories);
if (numFactories == 1 && pFactory)
{
ICryUnknownPtr pUnk = pFactory->CreateClassInstance();
AZStd::shared_ptr<T> pT = cryinterface_cast<T>(pUnk);
if (pT)
{
p = pT;
}
}
}
return p.get() != NULL;
}
#endif // CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H
@@ -1,123 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_CRYGUID_H
#define CRYINCLUDE_CRYEXTENSION_CRYGUID_H
#pragma once
#include "Serialization/IArchive.h"
#include "Random.h"
#include <functional>
struct CryGUID
{
uint64 hipart;
uint64 lopart;
// !!! Do NOT turn CryGUID into a non-aggregate !!!
// It will prevent inlining and type list unrolling opportunities within
// cryinterface_cast<T>() and cryiidof<T>(). As such prevent constructors,
// non-public members, base classes and virtual functions!
//CryGUID() : hipart(0), lopart(0) {}
//CryGUID(uint64 h, uint64 l) : hipart(h), lopart(l) {}
static CryGUID Construct(const uint64& hipart, const uint64& lopart)
{
CryGUID guid = {hipart, lopart};
return guid;
}
static CryGUID Create()
{
uint64 lopart = 0;
uint64 hipart = 0;
while (lopart == 0 || hipart == 0)
{
const uint32 a = cry_random_uint32();
const uint32 b = cry_random_uint32();
const uint32 c = cry_random_uint32();
const uint32 d = cry_random_uint32();
lopart = (uint64)a | ((uint64)b << 32);
hipart = (uint64)c | ((uint64)d << 32);
}
return Construct(lopart, hipart);
}
static CryGUID Null()
{
return Construct(0, 0);
}
bool operator ==(const CryGUID& rhs) const {return hipart == rhs.hipart && lopart == rhs.lopart; }
bool operator !=(const CryGUID& rhs) const {return hipart != rhs.hipart || lopart != rhs.lopart; }
bool operator <(const CryGUID& rhs) const {return hipart == rhs.hipart ? lopart < rhs.lopart : hipart < rhs.hipart; }
void Serialize(Serialization::IArchive& ar)
{
if (ar.IsInput())
{
uint32 dwords[4];
ar(dwords, "guid");
lopart = (((uint64)dwords[1]) << 32) | (uint64)dwords[0];
hipart = (((uint64)dwords[3]) << 32) | (uint64)dwords[2];
}
else
{
uint32 guid[4] = {
(uint32)(lopart & 0xFFFFFFFF), (uint32)((lopart >> 32) & 0xFFFFFFFF),
(uint32)(hipart & 0xFFFFFFFF), (uint32)((hipart >> 32) & 0xFFFFFFFF)
};
ar(guid, "guid");
}
}
};
// This is only used by the editor where we use C++ 11.
namespace std
{
template<>
struct hash<CryGUID>
{
public:
size_t operator()(const CryGUID& guid) const
{
std::hash<uint64> hasher;
return hasher(guid.lopart) ^ hasher(guid.hipart);
}
};
}
namespace AZStd
{
template<>
struct hash<CryGUID>
{
public:
size_t operator()(const CryGUID& guid) const
{
std::hash<CryGUID> hasher;
return hasher(guid);
}
};
}
#define MAKE_CRYGUID(high, low) CryGUID::Construct((uint64) high##LL, (uint64) low##LL)
#endif // CRYINCLUDE_CRYEXTENSION_CRYGUID_H
@@ -1,29 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H
#define CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H
#pragma once
#include "CryGUID.h"
typedef CryGUID CryInterfaceID;
typedef CryGUID CryClassID;
#endif // CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H
@@ -1,41 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H
#define CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H
#pragma once
#include "CryTypeID.h"
#include <SmartPointersHelpers.h>
struct ICryUnknown;
DECLARE_SMART_POINTERS(ICryUnknown);
struct ICryFactory
{
virtual const char* GetName() const = 0;
virtual const CryClassID& GetClassID() const = 0;
virtual bool ClassSupports(const CryInterfaceID& iid) const = 0;
virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const = 0;
virtual ICryUnknownPtr CreateClassInstance() const = 0;
protected:
// prevent explicit destruction from client side (delete, shared_ptr, etc)
virtual ~ICryFactory() {}
};
#endif // CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H
@@ -1,56 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H
#define CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H
#pragma once
#include "CryTypeID.h"
struct ICryFactory;
struct ICryFactoryRegistry
{
virtual ICryFactory* GetFactory(const char* cname) const = 0;
virtual ICryFactory* GetFactory(const CryClassID& cid) const = 0;
/**
* Iterates all factories implementing the interface specified by \p iid.
* \param[in] iid ID of the interface to iterate. Often procured using cryiidof<...>().
* \param[out] pFactories A pointer of the array of factories to fill in. May be nullptr (see below).
* \param[in] Size (in elements) of the pFactories array [out] Number of elements actually written to pFactories or, when pFactories is null, the number of elements that would be written if sufficient storage was available.
*
* Example:
* \code{.cpp}
* size_t factoryCount = 0;
* // Assigns the number of found factories to factoryCount
* factoryRegistry->IterateFactories(cryiidof<TPointer>(), 0, factoryCount);
* // Allocate an array of the proper length on the stack
* ICryFactory** factories = static_cast<ICryFactory**>(alloca(sizeof(ICryFactory*) * factoryCount);
* // Fill in factories with factoryCount results.
* factoryRegistry->IterateFactories(cryiidof<TPointer>(), factories, factoryCount);
* \endcode
*/
virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const = 0;
protected:
// prevent explicit destruction from client side (delete, shared_ptr, etc)
virtual ~ICryFactoryRegistry() {}
};
#endif // CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H
@@ -1,224 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H
#define CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H
#pragma once
#include "CryTypeID.h"
#include <SmartPointersHelpers.h>
struct ICryFactory;
struct ICryUnknown;
namespace InterfaceCastSemantics
{
template <class T>
const CryInterfaceID& cryiidof()
{
return T::IID();
}
#define _BEFRIEND_CRYIIDOF() \
template <class T> \
friend const CryInterfaceID&InterfaceCastSemantics::cryiidof();
template <class Dst, class Src>
Dst* cryinterface_cast(Src* p)
{
return static_cast<Dst*>(p ? p->QueryInterface(cryiidof<Dst>()) : 0);
}
template <class Dst, class Src>
Dst* cryinterface_cast(const Src* p)
{
return static_cast<const Dst*>(p ? p->QueryInterface(cryiidof<Dst>()) : 0);
}
namespace Internal
{
template <class Dst, class Src>
struct cryinterface_cast_shared_ptr_helper;
template <class Dst, class Src>
struct cryinterface_cast_shared_ptr_helper
{
static AZStd::shared_ptr<Dst> Op(const AZStd::shared_ptr<Src>& p)
{
Dst* dp = cryinterface_cast<Dst>(p.get());
return dp ? AZStd::shared_ptr<Dst>(p, dp) : AZStd::shared_ptr<Dst>();
}
};
template <class Src>
struct cryinterface_cast_shared_ptr_helper<ICryUnknown, Src>
{
static AZStd::shared_ptr<ICryUnknown> Op(const AZStd::shared_ptr<Src>& p)
{
ICryUnknown* dp = cryinterface_cast<ICryUnknown>(p.get());
return dp ? AZStd::shared_ptr<ICryUnknown>(*((const AZStd::shared_ptr<ICryUnknown>*) & p), dp) : AZStd::shared_ptr<ICryUnknown>();
}
};
template <class Src>
struct cryinterface_cast_shared_ptr_helper<const ICryUnknown, Src>
{
static AZStd::shared_ptr<const ICryUnknown> Op(const AZStd::shared_ptr<Src>& p)
{
const ICryUnknown* dp = cryinterface_cast<const ICryUnknown>(p.get());
return dp ? AZStd::shared_ptr<const ICryUnknown>(*((const AZStd::shared_ptr<const ICryUnknown>*) & p), dp) : AZStd::shared_ptr<const ICryUnknown>();
}
};
} // namespace Internal
template <class Dst, class Src>
AZStd::shared_ptr<Dst> cryinterface_cast(const AZStd::shared_ptr<Src>& p)
{
return Internal::cryinterface_cast_shared_ptr_helper<Dst, Src>::Op(p);
}
#define _BEFRIEND_CRYINTERFACE_CAST() \
template <class Dst, class Src> \
friend Dst * InterfaceCastSemantics::cryinterface_cast(Src*); \
template <class Dst, class Src> \
friend Dst * InterfaceCastSemantics::cryinterface_cast(const Src*); \
template <class Dst, class Src> \
friend AZStd::shared_ptr<Dst> InterfaceCastSemantics::cryinterface_cast(const AZStd::shared_ptr<Src>&);
} // namespace InterfaceCastSemantics
using InterfaceCastSemantics::cryiidof;
using InterfaceCastSemantics::cryinterface_cast;
template <class S, class T>
bool CryIsSameClassInstance(S* p0, T* p1)
{
return static_cast<const void*>(p0) == static_cast<const void*>(p1) || cryinterface_cast<const ICryUnknown>(p0) == cryinterface_cast<const ICryUnknown>(p1);
}
template <class S, class T>
bool CryIsSameClassInstance(const AZStd::shared_ptr<S>& p0, T* p1)
{
return CryIsSameClassInstance(p0.get(), p1);
}
template <class S, class T>
bool CryIsSameClassInstance(S* p0, const AZStd::shared_ptr<T>& p1)
{
return CryIsSameClassInstance(p0, p1.get());
}
template <class S, class T>
bool CryIsSameClassInstance(const AZStd::shared_ptr<S>& p0, const AZStd::shared_ptr<T>& p1)
{
return CryIsSameClassInstance(p0.get(), p1.get());
}
namespace CompositeQuerySemantics
{
template <class Src>
AZStd::shared_ptr<ICryUnknown> crycomposite_query(Src* p, const char* name, bool* pExposed = 0)
{
void* pComposite = p ? p->QueryComposite(name) : 0;
pExposed ? *pExposed = pComposite != 0 : 0;
return pComposite ? *static_cast<AZStd::shared_ptr<ICryUnknown>*>(pComposite) : AZStd::shared_ptr<ICryUnknown>();
}
template <class Src>
AZStd::shared_ptr<const ICryUnknown> crycomposite_query(const Src* p, const char* name, bool* pExposed = 0)
{
void* pComposite = p ? p->QueryComposite(name) : 0;
pExposed ? *pExposed = pComposite != 0 : 0;
return pComposite ? *static_cast<AZStd::shared_ptr<const ICryUnknown>*>(pComposite) : AZStd::shared_ptr<const ICryUnknown>();
}
template <class Src>
AZStd::shared_ptr<ICryUnknown> crycomposite_query(const AZStd::shared_ptr<Src>& p, const char* name, bool* pExposed = 0)
{
return crycomposite_query(p.get(), name, pExposed);
}
template <class Src>
AZStd::shared_ptr<const ICryUnknown> crycomposite_query(const AZStd::shared_ptr<const Src>& p, const char* name, bool* pExposed = 0)
{
return crycomposite_query(p.get(), name, pExposed);
}
#define _BEFRIEND_CRYCOMPOSITE_QUERY() \
template <class Src> \
friend AZStd::shared_ptr<ICryUnknown> CompositeQuerySemantics::crycomposite_query(Src*, const char*, bool*); \
template <class Src> \
friend AZStd::shared_ptr<const ICryUnknown> CompositeQuerySemantics::crycomposite_query(const Src*, const char*, bool*); \
template <class Src> \
friend AZStd::shared_ptr<ICryUnknown> CompositeQuerySemantics::crycomposite_query(const AZStd::shared_ptr<Src>&, const char*, bool*); \
template <class Src> \
friend AZStd::shared_ptr<const ICryUnknown> CompositeQuerySemantics::crycomposite_query(const AZStd::shared_ptr<const Src>&, const char*, bool*);
} // namespace CompositeQuerySemantics
using CompositeQuerySemantics::crycomposite_query;
#define _BEFRIEND_MAKE_SHARED() \
template <class T> \
friend class AZStd::Internal::sp_ms_deleter; \
template <class T> \
friend AZStd::shared_ptr<T> AZStd::make_shared(); \
template <class T, class A> \
friend AZStd::shared_ptr<T> AZStd::allocate_shared(A const& a);
// prevent explicit destruction from client side
#define _PROTECTED_DTOR(iname) \
protected: \
virtual ~iname() {}
// Befriending cryinterface_cast<T>() and crycomposite_query() via CRYINTERFACE_DECLARE is actually only needed for ICryUnknown
// since QueryInterface() and QueryComposite() are usually not redeclared in derived interfaces but it doesn't hurt either
#define CRYINTERFACE_DECLARE(iname, iidHigh, iidLow) \
_BEFRIEND_CRYIIDOF() \
_BEFRIEND_CRYINTERFACE_CAST() \
_BEFRIEND_CRYCOMPOSITE_QUERY() \
_BEFRIEND_MAKE_SHARED() \
_PROTECTED_DTOR(iname) \
\
private: \
static const CryInterfaceID& IID() \
{ \
static const CryInterfaceID iid = {(uint64) iidHigh##LL, (uint64) iidLow##LL}; \
return iid; \
} \
public:
struct ICryUnknown
{
CRYINTERFACE_DECLARE(ICryUnknown, 0x1000000010001000, 0x1000100000000000)
virtual ICryFactory * GetFactory() const = 0;
protected:
virtual void* QueryInterface(const CryInterfaceID& iid) const = 0;
virtual void* QueryComposite(const char* name) const = 0;
};
DECLARE_SMART_POINTERS(ICryUnknown);
#endif // CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H
@@ -1,461 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H
#define CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H
#pragma once
#include "TypeList.h"
#include "Conversion.h"
#include "RegFactoryNode.h"
#include "../ICryUnknown.h"
#include "../ICryFactory.h"
#include <AzCore/Memory/Memory.h>
namespace CW
{
namespace Internal
{
template <class Dst>
struct InterfaceCast;
template <class Dst>
struct InterfaceCast
{
template <class T>
static void* Op(T* p)
{
return (Dst*) p;
}
};
template <>
struct InterfaceCast<ICryUnknown>
{
template <class T>
static void* Op(T* p)
{
return const_cast<ICryUnknown*>(static_cast<const ICryUnknown*>(static_cast<const void*>(p)));
}
};
}
template <class TList>
struct InterfaceCast;
template <>
struct InterfaceCast<TL::NullType>
{
template <class T>
static void* Op(T*, const CryInterfaceID&)
{
return 0;
}
};
template <class Head, class Tail>
struct InterfaceCast<TL::Typelist<Head, Tail> >
{
template <class T>
static void* Op(T* p, const CryInterfaceID& iid)
{
if (cryiidof<Head>() == iid)
{
return Internal::InterfaceCast<Head>::Op(p);
}
return InterfaceCast<Tail>::Op(p, iid);
}
};
template <class TList>
struct FillIIDs;
template <>
struct FillIIDs<TL::NullType>
{
static void Op(CryInterfaceID*)
{
}
};
template <class Head, class Tail>
struct FillIIDs<TL::Typelist<Head, Tail> >
{
static void Op(CryInterfaceID* p)
{
*p++ = cryiidof<Head>();
FillIIDs<Tail>::Op(p);
}
};
namespace Internal
{
template <bool, typename S>
struct PickList;
template <bool, typename S>
struct PickList
{
typedef TL::BuildTypelist<>::Result Result;
};
template <typename S>
struct PickList<true, S>
{
typedef typename S::FullCompositeList Result;
};
}
template <typename T>
struct ProbeFullCompositeList
{
private:
typedef char y[1];
typedef char n[2];
template <typename S>
static y& test(typename S::FullCompositeList*);
template <typename>
static n& test(...);
public:
enum
{
listFound = sizeof(test<T>(0)) == sizeof(y)
};
typedef typename Internal::PickList<listFound, T>::Result ListType;
};
namespace Internal
{
template <class TList>
struct CompositeQuery;
template <>
struct CompositeQuery<TL::NullType>
{
template<typename T>
static void* Op(const T&, const char*)
{
return 0;
}
};
template <class Head, class Tail>
struct CompositeQuery<TL::Typelist<Head, Tail> >
{
template<typename T>
static void* Op(const T& ref, const char* name)
{
void* p = ref.Head::CompositeQueryImpl(name);
return p ? p : CompositeQuery<Tail>::Op(ref, name);
}
};
}
struct CompositeQuery
{
template <typename T>
static void* Op(const T& ref, const char* name)
{
return Internal::CompositeQuery<typename ProbeFullCompositeList<T>::ListType>::Op(ref, name);
}
};
inline bool NameMatch(const char* name, const char* compositeName)
{
if (!name || !compositeName)
{
return false;
}
size_t i = 0;
for (; name[i] && name[i] == compositeName[i]; ++i)
{
}
return name[i] == compositeName[i];
}
template <typename T>
void* CheckCompositeMatch(const char* name, const AZStd::shared_ptr<T>& composite, const char* compositeName)
{
typedef TC::SuperSubClass<ICryUnknown, T> Rel;
COMPILE_TIME_ASSERT(Rel::exists);
return NameMatch(name, compositeName) ? const_cast<void*>(static_cast<const void*>(&composite)) : 0;
}
} // namespace CW
#define CRYINTERFACE_BEGIN() \
private: \
typedef TL::BuildTypelist < ICryUnknown
#define CRYINTERFACE_ADD(iname) , iname
#define CRYINTERFACE_END() > ::Result _UserDefinedPartialInterfaceList; \
protected: \
typedef TL::NoDuplicates<_UserDefinedPartialInterfaceList>::Result FullInterfaceList;
#define _CRY_TPL_APPEND0(base) TL::Append<base::FullInterfaceList, _UserDefinedPartialInterfaceList>::Result
#define _CRY_TPL_APPEND(base, intermediate) TL::Append<base::FullInterfaceList, intermediate>::Result
#define CRYINTERFACE_ENDWITHBASE(base) > ::Result _UserDefinedPartialInterfaceList; \
protected: \
typedef TL::NoDuplicates<_CRY_TPL_APPEND0(base)>::Result FullInterfaceList;
#define CRYINTERFACE_ENDWITHBASE2(base0, base1) > ::Result _UserDefinedPartialInterfaceList; \
protected: \
typedef TL::NoDuplicates<_CRY_TPL_APPEND(base0, _CRY_TPL_APPEND0(base1))>::Result FullInterfaceList;
#define CRYINTERFACE_ENDWITHBASE3(base0, base1, base2) > ::Result _UserDefinedPartialInterfaceList; \
protected: \
typedef TL::NoDuplicates<_CRY_TPL_APPEND(base0, _CRY_TPL_APPEND(base1, _CRY_TPL_APPEND0(base2)))>::Result FullInterfaceList;
#define CRYINTERFACE_SIMPLE(iname) \
CRYINTERFACE_BEGIN() \
CRYINTERFACE_ADD(iname) \
CRYINTERFACE_END()
#define CRYCOMPOSITE_BEGIN() \
private: \
void* CompositeQueryImpl(const char* name) const \
{ \
(void)(name); \
void* res = 0; (void)(res); \
#define CRYCOMPOSITE_ADD(member, membername) \
COMPILE_TIME_ASSERT((sizeof(membername) / sizeof(membername[0])) > 1); \
if ((res = CW::CheckCompositeMatch(name, member, membername)) != 0) { \
return res; }
#define _CRYCOMPOSITE_END(implclassname) \
return 0; \
}; \
protected: \
typedef TL::BuildTypelist<implclassname>::Result _PartialCompositeList; \
\
template <bool, typename S> \
friend struct CW::Internal::PickList;
#define CRYCOMPOSITE_END(implclassname) \
_CRYCOMPOSITE_END(implclassname) \
protected: \
typedef _PartialCompositeList FullCompositeList;
#define _CRYCOMPOSITE_APPEND0(base) TL::Append<_PartialCompositeList, CW::ProbeFullCompositeList<base>::ListType>::Result
#define _CRYCOMPOSITE_APPEND(base, intermediate) TL::Append<intermediate, CW::ProbeFullCompositeList<base>::ListType>::Result
#define CRYCOMPOSITE_ENDWITHBASE(implclassname, base) \
_CRYCOMPOSITE_END(implclassname) \
protected: \
typedef _CRYCOMPOSITE_APPEND0 (base) FullCompositeList;
#define CRYCOMPOSITE_ENDWITHBASE2(implclassname, base0, base1) \
_CRYCOMPOSITE_END(implclassname) \
protected: \
typedef TL::NoDuplicates<_CRYCOMPOSITE_APPEND(base1, _CRYCOMPOSITE_APPEND0(base0))>::Result FullCompositeList;
#define CRYCOMPOSITE_ENDWITHBASE3(implclassname, base0, base1, base2) \
_CRYCOMPOSITE_END(implclassname) \
protected: \
typedef TL::NoDuplicates<_CRYCOMPOSITE_APPEND(base2, _CRYCOMPOSITE_APPEND(base1, _CRYCOMPOSITE_APPEND0(base0)))>::Result FullCompositeList;
template<typename T>
class CFactory
: public ICryFactory
{
public:
virtual const char* GetName() const
{
return T::GetCName();
}
virtual const CryClassID& GetClassID() const
{
return T::GetCID();
}
virtual bool ClassSupports(const CryInterfaceID& iid) const
{
for (size_t i = 0; i < m_numIIDs; ++i)
{
if (iid == m_pIIDs[i])
{
return true;
}
}
return false;
}
virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const
{
pIIDs = m_pIIDs;
numIIDs = m_numIIDs;
}
public:
virtual ICryUnknownPtr CreateClassInstance() const
{
AZStd::shared_ptr<T> p = AZStd::make_shared<T>();
return cryinterface_cast<ICryUnknown> (p);
}
CFactory<T>()
: m_numIIDs(0)
, m_pIIDs(0)
, m_regFactory()
{
static CryInterfaceID supportedIIDs[TL::Length < typename T::FullInterfaceList > ::value];
CW::FillIIDs<typename T::FullInterfaceList>::Op(supportedIIDs);
m_pIIDs = &supportedIIDs[0];
m_numIIDs = TL::Length<typename T::FullInterfaceList>::value;
new(&m_regFactory)SRegFactoryNode(this);
}
protected:
CFactory(const CFactory&);
CFactory& operator =(const CFactory&);
size_t m_numIIDs;
CryInterfaceID* m_pIIDs;
SRegFactoryNode m_regFactory;
};
template<typename T>
class CSingletonFactory
: public CFactory<T>
{
public:
CSingletonFactory()
: CFactory<T>()
, m_csCreateClassInstance()
{
}
virtual ICryUnknownPtr CreateClassInstance() const
{
CryAutoLock<CryCriticalSection> lock(m_csCreateClassInstance);
// override the allocator. These function static instances are being destroyed after the AZ alloctor has been deleted.
// On win, TerminateProcess() prevents these destructors from being called, but that is not the case on OSX.
static typename AZStd::aligned_storage<sizeof(AZStd::Internal::sp_counted_impl_pda<T*, AZStd::Internal::sp_ms_deleter<T>,SingletonAllocator>), AZStd::alignment_of<T>::value>::type m_storage;
static ICryUnknownPtr p = AZStd::allocate_shared<T>(SingletonAllocator(AZStd::addressof(m_storage)));
return p;
}
mutable CryCriticalSection m_csCreateClassInstance;
struct SingletonAllocator
{
SingletonAllocator(void* ptr) :
m_data(ptr)
{}
void* allocate(size_t /*byteSize*/, size_t /*alignment*/, int /*flags*/ = 0)
{
return m_data;
}
void deallocate(void* /*ptr*/, size_t /*byteSize*/, size_t /*alignment*/)
{
// nothing to see here
}
void* m_data;
};
};
#define _CRYFACTORY_DECLARE(implclassname) \
private: \
friend class CFactory<implclassname>; \
static CFactory<implclassname> s_factory;
#define _CRYFACTORY_DECLARE_SINGLETON(implclassname) \
private: \
friend class CFactory<implclassname>; \
friend void* Get##implclassname##Factory(); \
static CSingletonFactory<implclassname> s_factory;
#define _IMPLEMENT_ICRYUNKNOWN() \
public: \
virtual ICryFactory* GetFactory() const \
{ \
return &s_factory; \
} \
\
protected: \
virtual void* QueryInterface(const CryInterfaceID&iid) const \
{ \
return CW::InterfaceCast<FullInterfaceList>::Op(this, iid); \
} \
\
template <class TList> \
friend struct CW::Internal::CompositeQuery; \
\
virtual void* QueryComposite(const char* name) const \
{ \
return CW::CompositeQuery::Op(*this, name); \
}
#define _ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow) \
public: \
static const char* GetCName() \
{ \
return cname; \
} \
static const CryClassID& GetCID() \
{ \
static const CryClassID cid = {(uint64) cidHigh##LL, (uint64) cidLow##LL}; \
return cid; \
} \
static AZStd::shared_ptr<implclassname> CreateClassInstance() \
{ \
ICryUnknownPtr p = s_factory.CreateClassInstance(); \
return AZStd::shared_ptr<implclassname>(*static_cast<AZStd::shared_ptr<implclassname>*>(static_cast<void*>(&p))); \
} \
\
protected: \
implclassname(); \
virtual ~implclassname();
#define _BEFRIEND_OPS() \
_BEFRIEND_CRYINTERFACE_CAST() \
_BEFRIEND_CRYCOMPOSITE_QUERY() \
_BEFRIEND_MAKE_SHARED()
#define CRYGENERATE_CLASS(implclassname, cname, cidHigh, cidLow) \
_CRYFACTORY_DECLARE(implclassname) \
_BEFRIEND_OPS() \
_IMPLEMENT_ICRYUNKNOWN() \
_ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow)
#define CRYGENERATE_SINGLETONCLASS(implclassname, cname, cidHigh, cidLow) \
_CRYFACTORY_DECLARE_SINGLETON(implclassname) \
_BEFRIEND_OPS() \
_IMPLEMENT_ICRYUNKNOWN() \
_ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow)
#define CRYREGISTER_CLASS(implclassname) \
CFactory<implclassname> implclassname::s_factory;
#define DECLARE_CRYREGISTER_SINGLETON_CLASS(implclassname) \
void* Get##implclassname##Factory();
#define CRYREGISTER_SINGLETON_CLASS(implclassname) \
CSingletonFactory<implclassname> implclassname::s_factory; \
void* Get##implclassname##Factory() { \
return &implclassname::s_factory; \
}
#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H
@@ -1,109 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H
#define CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H
#pragma once
namespace TC
{
//template <class T, class U>
//struct Conversion
//{
//private:
// typedef char y[1];
// typedef char n[2];
// static y& Test(U);
// static n& Test(...);
// static T MakeT();
//public:
// enum
// {
// exists = sizeof(Test(MakeT())) == sizeof(y),
// sameType = false
// };
//};
//template <class T>
//struct Conversion<T, T>
//{
//public:
// enum
// {
// exists = true,
// sameType = true
// };
//};
//template<typename Base, typename Derived>
//struct CheckInheritance
//{
// enum
// {
// exists = Conversion<const Derived*, const Base*>::exists && !Conversion<const Base*, const void*>::sameType
// };
//};
//template<typename Base, typename Derived>
//struct CheckStrictInheritance
//{
// enum
// {
// exists = CheckInheritance<Base, Derived>::exists && !Conversion<const Base*, const Derived*>::sameType
// };
//};
template <typename Base, typename Derived>
struct SuperSubClass
{
private:
typedef char y[1];
typedef char n[2];
template<typename T>
static y& check(const volatile Derived&, T);
static n& check(const volatile Base&, int);
struct C
{
operator const volatile Base&() const;
operator const volatile Derived&();
};
static C getC();
public:
enum
{
exists = sizeof(check(getC(), 0)) == sizeof(y),
sameType = false
};
};
template <typename T>
struct SuperSubClass<T, T>
{
enum
{
exists = true
};
};
} // namespace TC
#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H
@@ -1,67 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H
#define CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H
#pragma once
#include "../CryGUID.h"
#include "../../CryString.h"
namespace CryGUIDHelper
{
string Print(const CryGUID& val)
{
char buf[39]; // sizeof("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}")
static const char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char* p = buf;
*p++ = '{';
for (int i = 15; i >= 8; --i)
{
*p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)];
}
*p++ = '-';
for (int i = 7; i >= 4; --i)
{
*p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)];
}
*p++ = '-';
for (int i = 3; i >= 0; --i)
{
*p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)];
}
*p++ = '-';
for (int i = 15; i >= 12; --i)
{
*p++ = hex[(unsigned char) ((val.lopart >> (i << 2)) & 0xF)];
}
*p++ = '-';
for (int i = 11; i >= 0; --i)
{
*p++ = hex[(unsigned char) ((val.lopart >> (i << 2)) & 0xF)];
}
*p++ = '}';
*p++ = '\0';
return string(buf);
}
}
#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H
@@ -1,58 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H
#define CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H
#pragma once
#include "../ICryFactoryRegistry.h"
struct SRegFactoryNode;
struct ICryFactoryRegistryCallback
{
virtual void OnNotifyFactoryRegistered(ICryFactory* pFactory) = 0;
virtual void OnNotifyFactoryUnregistered(ICryFactory* pFactory) = 0;
protected:
virtual ~ICryFactoryRegistryCallback() {}
};
struct ICryFactoryRegistryImpl
: public ICryFactoryRegistry
{
virtual ICryFactory* GetFactory(const char* cname) const = 0;
virtual ICryFactory* GetFactory(const CryClassID& cid) const = 0;
virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const = 0;
virtual void RegisterCallback(ICryFactoryRegistryCallback* pCallback) = 0;
virtual void UnregisterCallback(ICryFactoryRegistryCallback* pCallback) = 0;
virtual void RegisterFactories(const SRegFactoryNode* pFactories) = 0;
virtual void UnregisterFactories(const SRegFactoryNode* pFactories) = 0;
virtual void UnregisterFactory(ICryFactory* const pFactory) = 0;
protected:
// prevent explicit destruction from client side (delete, shared_ptr, etc)
virtual ~ICryFactoryRegistryImpl() {}
};
#endif // CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H
@@ -1,52 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H
#define CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H
#pragma once
struct ICryFactory;
struct SRegFactoryNode;
extern SRegFactoryNode* g_pHeadToRegFactories;
struct SRegFactoryNode
{
SRegFactoryNode()
{
}
SRegFactoryNode(ICryFactory* pFactory)
: m_pFactory(pFactory)
, m_pNext(g_pHeadToRegFactories)
{
g_pHeadToRegFactories = this;
}
static void* operator new(size_t, void* p)
{
return p;
}
static void operator delete(void*, void*)
{
}
ICryFactory* m_pFactory;
SRegFactoryNode* m_pNext;
};
#endif // CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H
@@ -1,236 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Part of CryEngine's extension framework.
#ifndef CRYINCLUDE_CRYEXTENSION_TYPELIST_H
#define CRYINCLUDE_CRYEXTENSION_TYPELIST_H
#pragma once
namespace TL
{
// typelist terminator
class NullType
{
};
// structure for typelist generation
template <class T, class U = NullType>
struct Typelist
{
typedef T Head;
typedef U Tail;
};
// helper structure to automatically build typelists containing n types
template
<
typename T0 = NullType, typename T1 = NullType, typename T2 = NullType, typename T3 = NullType, typename T4 = NullType,
typename T5 = NullType, typename T6 = NullType, typename T7 = NullType, typename T8 = NullType, typename T9 = NullType,
typename T10 = NullType, typename T11 = NullType, typename T12 = NullType, typename T13 = NullType, typename T14 = NullType,
typename T15 = NullType, typename T16 = NullType, typename T17 = NullType, typename T18 = NullType, typename T19 = NullType
>
struct BuildTypelist
{
private:
typedef typename BuildTypelist<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>::Result TailResult;
public:
typedef Typelist<T0, TailResult> Result;
};
template <>
struct BuildTypelist<>
{
typedef NullType Result;
};
// typelist operation : Length
template <class TList>
struct Length;
template <>
struct Length<NullType>
{
enum
{
value = 0
};
};
template <class T, class U>
struct Length<Typelist<T, U> >
{
enum
{
value = 1 + Length<U>::value
};
};
// typelist operation : TypeAt
template <class TList, unsigned int index>
struct TypeAt;
template <class Head, class Tail>
struct TypeAt<Typelist<Head, Tail>, 0>
{
typedef Head Result;
};
template <class Head, class Tail, unsigned int index>
struct TypeAt<Typelist<Head, Tail>, index>
{
typedef typename TypeAt<Tail, index - 1>::Result Result;
};
// typelist operation : IndexOf
template <class TList, class T>
struct IndexOf;
template <class T>
struct IndexOf<NullType, T>
{
enum
{
value = -1
};
};
template <class T, class Tail>
struct IndexOf<Typelist<T, Tail>, T>
{
enum
{
value = 0
};
};
template <class Head, class Tail, class T>
struct IndexOf<Typelist<Head, Tail>, T>
{
private:
enum
{
temp = IndexOf<Tail, T>::value
};
public:
enum
{
value = temp == -1 ? -1 : 1 + temp
};
};
// typelist operation : Append
template <class TList, class T>
struct Append;
template <>
struct Append<NullType, NullType>
{
typedef NullType Result;
};
template <class T>
struct Append<NullType, T>
{
typedef Typelist<T, NullType> Result;
};
template <class Head, class Tail>
struct Append<NullType, Typelist<Head, Tail> >
{
typedef Typelist<Head, Tail> Result;
};
template <class Head, class Tail, class T>
struct Append<Typelist<Head, Tail>, T>
{
typedef Typelist<Head, typename Append<Tail, T>::Result> Result;
};
// typelist operation : Erase
template <class TList, class T>
struct Erase;
template <class T>
struct Erase<NullType, T>
{
typedef NullType Result;
};
template <class T, class Tail>
struct Erase<Typelist<T, Tail>, T>
{
typedef Tail Result;
};
template <class Head, class Tail, class T>
struct Erase<Typelist<Head, Tail>, T>
{
typedef Typelist<Head, typename Erase<Tail, T>::Result> Result;
};
// typelist operation : Erase All
template <class TList, class T>
struct EraseAll;
template <class T>
struct EraseAll<NullType, T>
{
typedef NullType Result;
};
template <class T, class Tail>
struct EraseAll<Typelist<T, Tail>, T>
{
typedef typename EraseAll<Tail, T>::Result Result;
};
template <class Head, class Tail, class T>
struct EraseAll<Typelist<Head, Tail>, T>
{
typedef Typelist<Head, typename EraseAll<Tail, T>::Result> Result;
};
// typelist operation : NoDuplicates
template <class TList>
struct NoDuplicates;
template <>
struct NoDuplicates<NullType>
{
typedef NullType Result;
};
template <class Head, class Tail>
struct NoDuplicates<Typelist<Head, Tail> >
{
private:
typedef typename NoDuplicates<Tail>::Result L1;
typedef typename Erase<L1, Head>::Result L2;
public:
typedef Typelist<Head, L2> Result;
};
} // namespace TL
#endif // CRYINCLUDE_CRYEXTENSION_TYPELIST_H
@@ -1,207 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_ALLOCATOR_H
#define CRYINCLUDE_CRYPOOL_ALLOCATOR_H
#pragma once
namespace NCryPoolAlloc
{
template<class TPool, class TItem>
class CFirstFit
: public TPool
{
public:
ILINE CFirstFit()
{
}
template<class T>
ILINE T Allocate(size_t Size, size_t Align = 1)
{
//fastpath?
if (TPool::m_pEmpty && TPool::m_pEmpty->Available(Size, Align))
{
TItem* pItem = TPool::Split(TPool::m_pEmpty, Size, Align);
if (!pItem)
{
return 0;
}
pItem->InUse(Align);
TPool::AllocatedMemory(pItem->MemSize());
//not fully occupied empty space?
TPool::m_pEmpty = pItem != TPool::m_pEmpty ? TPool::m_pEmpty : 0;
return TPool::Handle(pItem);
}
TItem* pBestItem;
for (pBestItem = TPool::m_Items.First(); pBestItem; pBestItem = pBestItem->Next())
{
if (pBestItem->Available(Size, Align)) // && (!pBestItem || pItem->MemSize()<pBestItem->MemSize()))
{
break;
}
}
if (!pBestItem)
{
return 0; //out of mem
}
TItem* pItem = TPool::Split(pBestItem, Size, Align);
if (!pItem) //no free node
{
return 0;
}
pItem->InUse(Align);
TPool::AllocatedMemory(pItem->MemSize());
//not fully occupied empty space?
TPool::m_pEmpty = pItem != pBestItem ? pBestItem : 0;
return TPool::Handle(pItem);
}
template<class T>
ILINE bool Free(T Handle, bool ForceBoundsCheck = false)
{
return Handle ? TPool::Free(Handle, ForceBoundsCheck) : false;
}
};
template<class TPool, class TItem>
class CWorstFit
: public TPool
{
public:
ILINE CWorstFit()
{
}
template<class T>
ILINE T Allocate(size_t Size, size_t Align = 1)
{
TItem* pBestItem = 0;
for (TItem* pItem = TPool::m_Items.First(); pItem; pItem = pItem->Next())
{
if (pItem->IsFree() && (!pBestItem || pItem->MemSize() > pBestItem->MemSize()))
{
pBestItem = pItem;
}
}
if (!pBestItem || !pBestItem->Available(Size, Align))
{
return 0; //out of mem
}
TItem* pItem = Split(pBestItem, Size, Align);
if (!pItem) //no free node
{
return 0;
}
pItem->InUse(Align);
AllocatedMemory(pItem->MemSize());
return Handle(pItem);
}
};
template<class TPool, class TItem>
class CBestFit
: public TPool
{
public:
ILINE CBestFit()
{
}
template<class T>
ILINE T Allocate(size_t Size, size_t Align = 1)
{
TItem* pBestItem = 0;
for (TItem* pItem = TPool::m_Items.First(); pItem; pItem = pItem->Next())
{
if ((!pBestItem || pItem->MemSize() < pBestItem->MemSize()) && pItem->Available(Size, Align))
{
if (pItem->MemSize() == Size)
{
pItem->InUse(Align);
AllocatedMemory(pItem->MemSize());
return (T)Handle(pItem);
}
pBestItem = pItem;
}
}
if (!pBestItem)
{
return 0; //out of mem
}
TItem* pItem = Split(pBestItem, Size, Align);
if (!pItem) //no free node
{
return 0;
}
pItem->InUse(Align);
AllocatedMemory(pItem->MemSize());
return (T)Handle(pItem);
}
};
template<class TAllocator>
class CReallocator
: public TAllocator
{
public:
template<class T>
ILINE bool Reallocate(T* pData, size_t Size, size_t Alignment)
{
//special cases
if (!Size) //just free?
{
TAllocator::Free(*pData);
*pData = 0;
return true;
}
if (!*pData) //just alloc?
{
*pData = TAllocator::template Allocate<T>(Size, Alignment);
return *pData != 0;
}
//same size, nothing to do at all?
if (TAllocator::Item(*pData)->MemSize() == Size)
{
return true;
}
if (TAllocator::ReSize(pData, Size))
{
return true;
}
T pNewData = TAllocator::template Allocate<T>(Size, Alignment);
if (!pNewData)
{
return false;
}
memcpy(TAllocator::template Resolve<uint8*>(pNewData),
TAllocator::template Resolve<uint8*>(*pData), min(TAllocator::Item(*pData)->MemSize(), Size));
TAllocator::template Free(*pData);
*pData = pNewData;
return true;
}
};
}
#endif // CRYINCLUDE_CRYPOOL_ALLOCATOR_H
@@ -1,655 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_CONTAINER_H
#define CRYINCLUDE_CRYPOOL_CONTAINER_H
#pragma once
namespace NCryPoolAlloc
{
template<size_t TElementCount, class TElement>
class CPool
: public CMemoryStatic<TElementCount* sizeof(TElement)>
{
class CPoolNode;
class CPoolNode
: public CListItem<CPoolNode>
{
};
CList<CPoolNode> m_List;
public:
ILINE CPool()
{
CPoolNode* pPrev = 0;
CPoolNode* pNode = 0;
for (size_t a = 1; a < TElementCount; a++) //skip first element as it would be counted as zero ptr
{
uint8* pData = &CMemoryStatic<TElementCount* sizeof(TElement)>::Data()[a * sizeof(TElement)];
pNode = reinterpret_cast<CPoolNode*>(pData);
pNode->Prev(pPrev);
if (pPrev)
{
pPrev->Next(pNode);
}
else
{
m_List.First(pNode);
}
pPrev = pNode;
// m_List.AddLast(pNode);
}
if (pPrev)
{
pPrev->Next(0);
m_List.Last(pPrev);
}
}
ILINE uint8* Allocate([[maybe_unused]] size_t Size, [[maybe_unused]] size_t Align = 1)
{
CPoolNode* pNode = m_List.PopFirst();
return reinterpret_cast<uint8*>(pNode);
}
template<class T>
ILINE void Free(T* pData)
{
if (pData)
{
CPoolNode* pNode = reinterpret_cast<CPoolNode*>(pData);
m_List.AddLast(pNode);
}
}
ILINE TElement& operator[](uint32 Idx)
{
uint8* pData = &CMemoryStatic<TElementCount* sizeof(TElement)>::Data()[Idx * sizeof(TElement)];
return *reinterpret_cast<TElement*>(pData);
}
ILINE const TElement& operator[](uint32 Idx) const
{
const uint8* pData = &CMemoryStatic<TElementCount* sizeof(TElement)>::Data()[Idx * sizeof(TElement)];
return *reinterpret_cast<const TElement*>(pData);
}
};
template<class TMemory, bool BoundsCheck = false>
class CInPlace
: public TMemory
{
protected:
CList<CListItemInPlace> m_Items;
size_t m_Allocated;
CListItemInPlace* m_pEmpty;
ILINE void AllocatedMemory(size_t S)
{
m_Allocated += S + sizeof(CListItemInPlace);
}
ILINE void FreedMemory(size_t S)
{
m_Allocated -= S + sizeof(CListItemInPlace);
}
ILINE void Stack(CListItemInPlace* pItem)
{
}
public:
ILINE CInPlace()
: m_Allocated(0)
{
}
ILINE void InitMem(const size_t S = 0, uint8* pData = 0)
{
TMemory::InitMem(S, pData);
if (!TMemory::MemSize())
{
return;
}
pData = TMemory::Data();
CListItemInPlace* pFirst = reinterpret_cast<CListItemInPlace*>(pData);
CListItemInPlace* pFree = pFirst + 1;
CListItemInPlace* pLast = reinterpret_cast<CListItemInPlace*>(pData + TMemory::MemSize()) - 1;
m_Items.~CList<CListItemInPlace>();
new (&m_Items)CList<CListItemInPlace>();
m_Items.AddLast(pFirst);
m_Items.AddLast(pFree);
m_Items.AddLast(pLast);
pFirst->InUse(0); //static first item
pFree->Free();
pLast->InUse(0); //static last item
m_pEmpty = pFree;
m_Allocated = 0;
}
ILINE size_t FragmentCount() const
{
return m_Items.Count();
}
ILINE CListItemInPlace* Split(CListItemInPlace* pItem, size_t Size, size_t Align)
{
size_t Offset = reinterpret_cast<size_t>(pItem->Data());
Offset += pItem->MemSize(); //ptr to end
Offset -= Size; //minus size
Size += Offset & (Align - 1); //adjust size to fit required alignment
Offset -= Offset & (Align - 1);
size_t TSize = sizeof(CListItemInPlace);
Offset -= TSize; //header
if (Offset <= reinterpret_cast<size_t>(pItem + 1)) //not enough space for splitting?
{
return pItem;
}
CListItemInPlace* pItemNext = reinterpret_cast<CListItemInPlace*>(Offset);
const size_t Offset2 = reinterpret_cast<size_t>(pItemNext->Data());
CPA_ASSERT(!(Offset2 & (Align - 1)));
m_Items.AddBehind(pItemNext, pItem);
//pItemNext->Prev(pItem);
//pItemNext->Next(pItem->Next());
// if(pItem->Next())
// pItem->Next()->Prev(pItemNext);
// pItem->Next(pItemNext);
pItemNext->Free();
return pItemNext;
}
ILINE void Merge(CListItemInPlace* pItem)
{
//merge with next if possible
CListItemInPlace* pItemNext = pItem->Next();
if (pItemNext->IsFree())
{
if (m_pEmpty == pItemNext)
{
m_pEmpty = pItem;
}
m_Items.Remove(pItemNext);
//pItem->Next(pItemNext->Next());
//pItem->Next()->Prev(pItem);
}
//merge with prev if possible
CListItemInPlace* pItemPrev = pItem->Prev();
if (pItemPrev->IsFree())
{
if (m_pEmpty == pItem)
{
m_pEmpty = pItemPrev;
}
m_Items.Remove(pItem);
//pItemPrev->Next(pItem->Next());
//pItem->Next()->Prev(pItemPrev);
pItem = pItemPrev;
}
}
template<class T>
ILINE T Resolve(void* rItem) const
{
return reinterpret_cast<T>(rItem);
}
template<class T>
ILINE size_t Size(const T* pData) const
{
const CListItemInPlace* pItem = Item(pData);
return pItem->MemSize();
}
bool InBounds(const void* pData, const bool Check) const
{
return !Check || (
reinterpret_cast<size_t>(pData) >= reinterpret_cast<size_t>(TMemory::Data()) &&
reinterpret_cast<size_t>(pData) < reinterpret_cast<size_t>(TMemory::Data()) + TMemory::MemSize());
}
template<class T>
ILINE bool Free(T* pData, bool ForceBoundsCheck = false)
{
if (pData && InBounds(pData, BoundsCheck | ForceBoundsCheck))
{
CListItemInPlace* pItem = Item(pData);
FreedMemory(pItem->MemSize());
pItem->Free();
Merge(pItem);
return true;
}
return false;
}
ILINE bool Beat(){return false; }//dummy beat in case no defragmentator is wraping
ILINE size_t MemFree() const{return TMemory::MemSize() - m_Allocated; }
ILINE size_t MemSize() const{return TMemory::MemSize(); }
ILINE uint8* Handle(CListItemInPlace* pItem) const
{
return pItem->Data();
}
template<class T>
ILINE CListItemInPlace* Item(T* pData)
{
return reinterpret_cast<CListItemInPlace*>(pData) - 1;
}
template<class T>
ILINE const CListItemInPlace* Item(const T* pData) const
{
return reinterpret_cast<const CListItemInPlace*>(pData) - 1;
}
ILINE static bool Defragmentable(){return false; }
template<class T>
ILINE bool ReSize(T* pData, size_t SizeNew)
{
//special cases
CListItemInPlace* pItem = Item(*pData);
const size_t SizeOld = pItem->MemSize();
//reduction
if (SizeOld > SizeNew)
{
if (pItem->Next()->IsFree())
{
CListItemInPlace* pNextNext = pItem->Next()->Next();
size_t Offset = reinterpret_cast<size_t>(pItem->Data());
Offset += SizeNew; //Offset to next
CListItemInPlace* pItemNext = reinterpret_cast<CListItemInPlace*>(Offset);
pItem->Next(pItemNext);
pNextNext->Prev(pItemNext);
pItemNext->Prev(pItem);
pItemNext->Next(pNextNext);
pItemNext->Free();
return true;
}
if (SizeOld - SizeNew <= sizeof(CListItemInPlace))
{
return true; //header is bigger than the amount of freed memory
}
//split
size_t Offset = reinterpret_cast<size_t>(pItem->Data());
Offset += SizeNew; //Offset to next
CListItemInPlace* pItemNext = reinterpret_cast<CListItemInPlace*>(Offset);
m_Items.AddBehind(pItemNext, pItem);
pItemNext->Free();
return true;
}
//SizeOld<SizeNew grow
CListItemInPlace* pNext = pItem->Next();
CListItemInPlace* pNextNext = pNext->Next();
const size_t SizeNext = pNext->IsFree() ? pNext->MemSize() + sizeof(CListItemInPlace) : 0;
if (SizeNew <= SizeNext + SizeOld)
{
if (SizeNew + sizeof(CListItemInPlace) + 1 < SizeNext + SizeOld)
{
size_t Offset = reinterpret_cast<size_t>(pItem->Data());
Offset += SizeNew; //Offset to next
CListItemInPlace* pItemNext = reinterpret_cast<CListItemInPlace*>(Offset);
pItem->Next(pItemNext);
pNextNext->Prev(pItemNext);
pItemNext->Prev(pItem);
pItemNext->Next(pNextNext);
pItemNext->Free();
}
else
{
pItem->Next(pNextNext);
pNextNext->Prev(pItem);
}
return true;
}
return false; //no further in-place realloc possible
}
};
template<class TMemory, size_t TNodeCount, bool BoundsCheck = false>
class CReferenced
: public TMemory
{
typedef CPool<TNodeCount, CListItemReference> tdNodePool;
protected:
tdNodePool m_NodePool;
CList<CListItemReference> m_Items;
size_t m_Allocated;
CListItemReference* m_pEmpty;
ILINE void AllocatedMemory(size_t S)
{
m_Allocated += S;
}
ILINE void FreedMemory(size_t S)
{
m_Allocated -= S;
}
ILINE void Stack(CListItemReference* pItem)
{
m_Items.Validate(pItem);
CListItemReference* pItem2 = 0;
CListItemReference* pNext = pItem->Next();
uint8* pData = pItem->Data(pNext->Align());
if (pData != pItem->Data()) //needs splitting 'cause of alignment?
{
pItem2 = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
if (!pItem2) //no free node found for splitting?
{
return; //failed to stack -> return
}
}
memmove(pData, pNext->Data(), pNext->MemSize());
if (pItem2) //was not aligned?
{
//then keep the current ITem
const size_t SizeItem = pItem->MemSize();
const size_t SizeNext = pNext->MemSize();
m_Items.AddBehind(pItem2, pNext);
pItem2->Data(pData + SizeNext);
pNext->Data(pData);
pItem2->MemSize(pItem2->Next()->Data() - pItem2->Data());
pNext->MemSize(SizeNext);
pItem->MemSize(pNext->Data() - pItem->Data());
m_Items.Validate(pItem);
m_Items.Validate(pItem2);
m_Items.Validate(pNext);
}
else
{
const size_t SizeItem = pItem->MemSize();
const size_t SizeNext = pNext->MemSize();
m_Items.Remove(pItem);
m_Items.AddBehind(pItem, pNext);
pItem->Data(pNext->Data());
pNext->Data(pData);
pNext->MemSize(SizeItem);
pItem->MemSize(SizeNext);
m_Items.Validate(pItem);
m_Items.Validate(pNext);
}
}
public:
ILINE CReferenced()
: m_Allocated(0)
{
}
ILINE void InitMem(const size_t S = 0, uint8* pData = 0)
{
TMemory::InitMem(S, pData);
if (!TMemory::MemSize())
{
return;
}
pData = TMemory::Data();
CListItemReference* pItem = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
CListItemReference* pLast = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
m_Items.AddFirst(pItem);
m_Items.AddLast(pLast);
pLast->Init(pData + TMemory::MemSize(), 0, pItem, 0);
pLast->InUse(0);
pItem->Init(pData, TMemory::MemSize(), 0, pLast);
pItem->Free();
m_pEmpty = pItem;
m_Allocated = 0;
}
ILINE size_t FragmentCount() const
{
return m_Items.Count();
}
ILINE CListItemReference* Split(CListItemReference* pItem, size_t Size, size_t Align)
{
size_t Offset = reinterpret_cast<size_t>(pItem->Data());
if (!(Offset & (Align - 1))) //perfectly aligned?
{
if (pItem->MemSize() != Size) //not perfectly fitting?
{ //then split
CListItemReference* pItemPrev = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
if (!pItemPrev)
{
return 0;
}
const size_t OrgSize = pItem->MemSize();
m_Items.AddBefore(pItemPrev, pItem);
pItemPrev->Data(pItem->Data());
pItem->Data(pItem->Data() + Size);
pItem->MemSize(OrgSize - Size);
pItemPrev->MemSize(Size);
pItem = pItemPrev;
}
return pItem;
}
//not aligned to block start
//then lets try to align to block end
Offset += pItem->MemSize(); //ptr to end
Offset -= Size; //minus size
if (!(Offset & (Align - 1))) //perfectly aligned?
{
CListItemReference* pItemPrev = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
if (!pItemPrev)
{
return 0;
}
const size_t OrgSize = pItem->MemSize();
m_Items.AddBefore(pItemPrev, pItem);
pItemPrev->Data(pItem->Data());
pItem->Data(reinterpret_cast<uint8*>(Offset));
pItemPrev->MemSize(OrgSize - Size);
pItem->MemSize(Size);
pItemPrev->Free();
return pItem;
}
//last resort, fragment it into 3 parts
//Size +=Offset&(Align-1); //adjust size to fit required alignment
Offset -= Offset & (Align - 1);
CListItemReference* pItemPrev = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
CListItemReference* pItemNext = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
if (!pItemPrev || !pItemNext)
{
return 0;
}
const size_t OrgSize = pItem->MemSize();
m_Items.AddBefore(pItemPrev, pItem);
m_Items.AddBehind(pItemNext, pItem);
pItemPrev->Data(pItem->Data());
pItem->Data(reinterpret_cast<uint8*>(Offset));
pItemNext->Data(pItem->Data() + Size);
pItemPrev->MemSize(pItem->Data() - pItemPrev->Data());
pItemNext->MemSize(OrgSize - pItemPrev->MemSize() - Size);
pItem->MemSize(Size);
pItemPrev->Free();
pItemNext->Free();
return pItem;
}
ILINE void Merge(CListItemReference* pItem)
{
m_Items.Validate(pItem);
//merge with next if possible
CListItemReference* pItemNext = pItem->Next();
if (pItemNext && pItemNext->IsFree())
{
if (m_pEmpty == pItemNext)
{
m_pEmpty = pItem;
}
const size_t OrgSize = pItem->MemSize();
const size_t NextSize = pItemNext->MemSize();
m_Items.Remove(pItemNext);
pItem->MemSize(OrgSize + NextSize);
m_NodePool.Free(pItemNext);
}
//merge with prev if possible
CListItemReference* pItemPrev = pItem->Prev();
if (pItemPrev && pItemPrev->IsFree())
{
if (m_pEmpty == pItem)
{
m_pEmpty = pItemPrev;
}
const size_t OrgSize = pItem->MemSize();
const size_t PrevSize = pItemPrev->MemSize();
m_Items.Remove(pItem);
pItemPrev->MemSize(PrevSize + OrgSize);
m_NodePool.Free(pItem);
}
}
template<class T>
ILINE T Resolve(const uint32 ID)
{
CPA_ASSERT(ID); //0 is invalid
return reinterpret_cast<T>(Item(ID)->Data());
}
ILINE uint32 AddressToHandle(void* pData)
{
for (CListItemReference* pItem = m_Items.First(); pItem; pItem = pItem->Next())
{
if (pItem->Data() == pData)
{
return Handle(pItem);
}
}
return 0;
}
template<class T>
ILINE size_t Size(T ID) const
{
CPA_ASSERT(ID); //0 is invalid
return Item(ID)->MemSize();
}
template<class T>
bool InBounds([[maybe_unused]] T ID, [[maybe_unused]] const bool Check) const
{
//boundscheck doesn't work for Referenced containers
return true;
}
template<class T>
ILINE bool Free(T ID, bool ForceBoundsCheck = false)
{
IF (!ID, false)
{
return true;
}
IF (!InBounds(ID, BoundsCheck | ForceBoundsCheck), false)
{
return false;
}
CListItemReference* pItem = Item(ID);
FreedMemory(pItem->MemSize());
pItem->Free();
Merge(pItem);
return true;
}
ILINE bool Beat(){return false; }//dummy beat in case no defragmentator is wraping
ILINE size_t MemFree() const{return TMemory::MemSize() - m_Allocated; }
ILINE size_t MemSize() const{return TMemory::MemSize(); }
ILINE uint32 Handle(CListItemReference* pItem) const
{
return static_cast<uint32>(pItem - &m_NodePool[0]);
}
ILINE CListItemReference* Item(uint32 ID)
{
return &m_NodePool[ID];
}
ILINE const CListItemReference* Item(uint32 ID) const
{
return &m_NodePool[ID];
}
ILINE static bool Defragmentable(){return true; }
template<class T>
ILINE bool ReSize(T* pData, size_t SizeNew)
{
CListItemReference* pItem = Item(*pData);
const size_t SizeOld = pItem->MemSize();
//reduction
if (SizeOld > SizeNew)
{
if (pItem->Next()->IsFree())
{
CListItemReference* pNext = pItem->Next();
const size_t NextSize = pNext->MemSize();
pNext->Data(pNext->Data() + SizeNew - SizeOld);
pNext->MemSize(NextSize - SizeNew + SizeOld);
pItem->MemSize(SizeNew);
return true;
}
//split
CListItemReference* pItemNext = reinterpret_cast<CListItemReference*>(m_NodePool.Allocate(1, 1));
m_Items.AddBehind(pItemNext, pItem);
pItemNext->Data(pItem->Data() + SizeNew);
pItem->MemSize(SizeNew);
pItemNext->MemSize(SizeOld - SizeNew);
pItemNext->Free();
return true;
}
//SizeOld<SizeNew grow
CListItemReference* pNext = pItem->Next();
const size_t SizeNext = pNext->IsFree() ? pNext->MemSize() : 0;
if (SizeNew <= SizeNext + SizeOld)
{
if (SizeNew == SizeNext + SizeOld)
{
m_Items.Remove(pNext);
m_NodePool.Free(pNext);
}
else
{
pNext->Data(pNext->Data() + SizeNew - SizeOld);
pNext->MemSize(SizeNext - SizeNew + SizeOld);
}
pItem->MemSize(SizeNew);
return true;
}
return false; //no further in-place realloc possible
}
};
}
#endif // CRYINCLUDE_CRYPOOL_CONTAINER_H
-65
View File
@@ -1,65 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_DEFRAG_H
#define CRYINCLUDE_CRYPOOL_DEFRAG_H
#pragma once
namespace NCryPoolAlloc
{
template<class T>
class CDefragStacked
: public T
{
template<class TItem>
ILINE bool DefragElement(TItem* pItem)
{
T::m_Items.Validate();
if (pItem)
{
for (; pItem->Next(); pItem = pItem->Next())
{
if (!pItem->IsFree())
{
continue;
}
if (pItem->Next()->Locked())
{
continue;
}
if (!pItem->Available(pItem->Next()->Align(), pItem->Next()->Align()))
{
continue;
}
T::m_Items.Validate(pItem);
Stack(pItem);
T::m_Items.Validate(pItem);
Merge(pItem);
T::m_Items.Validate();
return true;
}
}
return false;
}
public:
ILINE bool Beat()
{
return T::Defragmentable() && DefragElement(T::m_Items.First());
};
};
}
#endif // CRYINCLUDE_CRYPOOL_DEFRAG_H
@@ -1,81 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_FALLBACK_H
#define CRYINCLUDE_CRYPOOL_FALLBACK_H
#pragma once
namespace NCryPoolAlloc
{
enum EFallbackMode
{
EFM_DISABLED,
EFM_ENABLED,
EFM_ALWAYS
};
template<class TAllocator>
class CFallback
: public TAllocator
{
EFallbackMode m_Fallback;
public:
ILINE CFallback()
: m_Fallback(EFM_DISABLED)
{
}
template<class T>
ILINE T Allocate(size_t Size, size_t Align = 1)
{
if (EFM_ALWAYS == m_Fallback)
{
return reinterpret_cast<T>(CPA_ALLOC(Align, Size));
}
T pRet = TAllocator::template Allocate<T>(Size, Align);
if (!pRet && EFM_ENABLED == m_Fallback)
{
return reinterpret_cast<T>(CPA_ALLOC(Align, Size));
}
return pRet;
}
template<class T>
ILINE bool Free(T Handle)
{
if (!Handle)
{
return true;
}
if (EFM_ALWAYS == m_Fallback)
{
CPA_FREE(Handle);
return true;
}
if (EFM_ENABLED == m_Fallback && TAllocator::InBounds(Handle, true))
{
CPA_FREE(Handle);
return true;
}
return TAllocator::template Free<T>(Handle);
}
void FallbackMode(EFallbackMode M){m_Fallback = M; }
EFallbackMode FallbaclMode() const{return m_Fallback; }
};
}
#endif // CRYINCLUDE_CRYPOOL_FALLBACK_H
@@ -1,203 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_INSPECTOR_H
#define CRYINCLUDE_CRYPOOL_INSPECTOR_H
#pragma once
namespace NCryPoolAlloc
{
template<class TAllocator>
class CInspector
: public TAllocator
{
enum
{
EITableSize = 30
};
size_t m_Allocations[EITableSize];
size_t m_Alignment[EITableSize];
char m_LogFileName[1024];
size_t m_AllocCount;
size_t m_FreeCount;
size_t m_ResizeCount;
size_t m_FailAllocCount;
size_t m_FailFreeCount;
size_t m_FailResizeCount;
void WriteOut(const char* pFileName, uint32 Stack, const char* pFormat, ...) const
{
/*
if(!pFileName)
{
if(!*m_LogFileName)
return;
pFileName = m_LogFileName;
}
FILE* File = fopen(pFileName,"a");
if(File)
{
char Buffer[1024];
for(uint32 a=0;a<Stack;a++)
Buffer[a]=' ';
va_list args;
va_start(args,pFormat);
vsprintf(Buffer+Stack,pFormat,args);
fwrite(Buffer,1,strlen(Buffer),File);
fclose(File);
va_end(args);
}
*/
}
size_t Bit(size_t C) const
{
size_t Count = 0;
C >>= 1;
while (C)
{
Count++;
C >>= 1;
}
return Count >= EITableSize ? EITableSize - 1 : Count;
}
public:
CInspector()
{
for (size_t a = 0; a < EITableSize; a++)
{
m_Allocations[a] = m_Alignment[a] = 0;
}
m_LogFileName[0] = 0;
m_AllocCount = 0;
m_FreeCount = 0;
m_ResizeCount = 0;
m_FailAllocCount = 0;
m_FailFreeCount = 0;
m_FailResizeCount = 0;
}
bool LogFileName(const char* pFileName)
{
const size_t Size = strlen(pFileName) + 1;
if (Size > sizeof(m_LogFileName))
{
m_LogFileName[0] = 0;
return false;
}
memcpy(m_LogFileName, pFileName, Size);
WriteOut(0, "[log start]\n");
return true;
}
void SaveStats(const char* pFileName) const
{
WriteOut(pFileName, 0, "stats:\n");
WriteOut(pFileName, 1, "Counter calls|fails\n");
WriteOut(pFileName, 2, "Alloc: %6d|%6d\n", m_AllocCount, m_FailAllocCount);
WriteOut(pFileName, 2, "Free: %6d|%6d\n", m_FreeCount, m_FailFreeCount);
WriteOut(pFileName, 2, "Resize:%6d|%6d\n", m_ResizeCount, m_FailResizeCount);
WriteOut(pFileName, 1, "Allocations:\n");
for (size_t a = 0; a < EITableSize; a++)
{
WriteOut(pFileName, 2, "%9dByte: %8d\n", 1 << a, m_Allocations[a]);
}
WriteOut(pFileName, 1, "Alignment:\n");
for (size_t a = 0; a < EITableSize; a++)
{
WriteOut(pFileName, 2, "%9dByte: %8d\n", 1 << a, m_Alignment[a]);
}
}
template<class T>
ILINE T Allocate(size_t Size, size_t Align = 1)
{
m_AllocCount++;
m_Allocations[Bit(Size)]++;
m_Alignment[Bit(Align)]++;
T pData = TAllocator::template Allocate<T>(Size, Align);
WriteOut(0, 0, "[A|%d|%d|%d]", (int)pData, Size, Align);
if (!pData)
{
m_FailAllocCount++;
WriteOut(0, 0, "[failed]", Size, Align);
}
return pData;
}
template<class T>
ILINE bool Free(T pData, bool ForceBoundsCheck = false)
{
m_FreeCount++;
const bool Ret = TAllocator::Free(pData, ForceBoundsCheck);
WriteOut(0, 0, "[F|%d|%d|%d]", (int)pData, (int)ForceBoundsCheck, (int)Ret);
m_FailFreeCount += !Ret;
return Ret;
}
//template<class T>
//ILINE bool Free(T pData)
// {
// m_FreeCount++;
// const bool Ret = TAllocator::Free(pData);
// WriteOut(0,0,"[F|%d|%d|%d]",(int)pData,(int)-1,(int)Ret);
// m_FailFreeCount+=!Ret;
// return Ret;
// }
template<class T>
ILINE bool Resize(T** pData, size_t Size, size_t Alignment)
{
m_ResizeCount++;
const bool Ret = TAllocator::Resize(pData, Size, Alignment);
WriteOut(0, 0, "[R|%d|%d|%d]", (int)*pData, (int)-1, (int)Ret);
m_FailResizeCount += !Ret;
return Ret;
}
template<class T>
ILINE size_t FindBiggest(const T* pItem)
{
size_t Biggest = 0;
while (pItem)
{
if (pItem->IsFree() && pItem->MemSize() > Biggest)
{
Biggest = pItem->MemSize();
}
pItem = pItem->Next();
}
return Biggest;
}
ILINE size_t BiggestFreeBlock()
{
return FindBiggest(TAllocator::m_Items.First());
}
ILINE uint8* FirstItem()
{
return TAllocator::m_Items.First()->Data();
}
};
}
#endif // CRYINCLUDE_CRYPOOL_INSPECTOR_H
-366
View File
@@ -1,366 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_LIST_H
#define CRYINCLUDE_CRYPOOL_LIST_H
#pragma once
namespace NCryPoolAlloc
{
class CListItemInPlace;
class CListItemReference;
template<typename TItem>
class CListItem
{
TItem* m_pPrev;
TItem* m_pNext;
public:
ILINE TItem* Prev(){return m_pPrev; }
ILINE TItem* Next(){return m_pNext; }
ILINE const TItem* Prev() const{return m_pPrev; }
ILINE const TItem* Next() const{return m_pNext; }
ILINE void Prev(TItem* pPrev){ m_pPrev = pPrev; }
ILINE void Next(TItem* pNext){ m_pNext = pNext; }
//debugging
void Validate();
};
template<typename TItem>
class CListItemFlagged
: public CListItem<TItem>
{
enum
{
ELIF_INUSE = (1 << 0),
ELIF_LOCKED = (1 << 1),
};
uint32 m_Flags : 8;
uint32 m_Align : 24;
public:
ILINE CListItemFlagged()
: m_Flags(0)
{
}
ILINE bool IsFree() const{return (m_Flags & ELIF_INUSE) != ELIF_INUSE; }
ILINE void Free(){m_Flags &= ~ELIF_INUSE; }
ILINE void InUse(uint32 A){m_Flags |= ELIF_INUSE; m_Align = A; }
ILINE bool Locked() const{return ELIF_LOCKED == (m_Flags & ELIF_LOCKED); }
ILINE void Lock(){m_Flags |= ELIF_LOCKED; }
ILINE void Unlock(){m_Flags &= ~ELIF_LOCKED; }
ILINE uint32 Align() const{return m_Align; }
};
class CListItemInPlace
: public CListItemFlagged<CListItemInPlace>
{
public:
ILINE void Init([[maybe_unused]] uint8* pData, [[maybe_unused]] size_t Size, CListItemInPlace* pPrev, CListItemInPlace* pNext)
{
Prev(pPrev);
Next(pNext);
CPA_ASSERT(Size == MemSize());
}
ILINE bool Available(size_t Size, size_t Align) const
{
size_t Offset = reinterpret_cast<size_t>(Data());
if (Offset & (Align - 1)) //not aligned?
{
Size += sizeof(CListItemInPlace) + Align - 1; //then an intermedian node needs to fit
}
return Size <= MemSize() && IsFree();
}
ILINE uint8* Data(){return reinterpret_cast<uint8*>(this) + sizeof(CListItemInPlace); }
ILINE const uint8* Data() const{return reinterpret_cast<const uint8*>(this) + sizeof(CListItemInPlace); }
ILINE size_t MemSize() const
{
const uint8* pNext = reinterpret_cast<const uint8*>(Next());
const uint8* pThis = reinterpret_cast<const uint8*>(this);
const size_t ESize = sizeof(CListItemInPlace);
size_t Delta = pNext - pThis;
Delta -= ESize;
return Delta;
}
};
class CListItemReference
: public CListItemFlagged<CListItemReference>
{
uint8* m_pData;
// size_t m_Size;
public:
ILINE void Init(uint8* pData, size_t Size, CListItemReference* pPrev, CListItemReference* pNext)
{
Data(pData);
Prev(pPrev);
Next(pNext);
MemSize(Size);
}
ILINE bool Available(size_t Size, size_t Align) const
{
size_t Offset = reinterpret_cast<size_t>(Data());
if ((Offset & (Align - 1)))
{
Size += Align - (Offset & (Align - 1));
}
return Size <= MemSize() && IsFree();
}
ILINE void Data(uint8* pData){m_pData = pData; }
ILINE uint8* Data(size_t Align)
{
Align--;
size_t Offset = reinterpret_cast<size_t>(m_pData);
Offset = (Offset + Align) & ~Align;
return reinterpret_cast<uint8*>(Offset);
}
ILINE uint8* Data(){return m_pData; }
ILINE const uint8* Data() const{return m_pData; }
ILINE void MemSize([[maybe_unused]] size_t Size) { }
ILINE size_t MemSize() const
{
const size_t T = reinterpret_cast<size_t>(Data());
const size_t N = Next() ? reinterpret_cast<size_t>(Next()->Data()) : T;
return N - T;
}
//ILINE void MemSize(size_t Size){m_Size=Size;}
//ILINE size_t MemSize()const{return m_Size;}
};
template<class TItem, bool VALIDATE = false>
class CList
{
TItem* m_pFirst;
TItem* m_pLast;
size_t m_Count;
public:
ILINE CList()
: m_pFirst(0)
, m_pLast(0)
, m_Count(0)
{
}
ILINE void First(TItem* pItem){m_pFirst = pItem; }
ILINE TItem* First(){return m_pFirst; }
ILINE void Last(TItem* pItem){m_pLast = pItem; }
ILINE TItem* Last(){return m_pLast; }
ILINE bool Empty() const{return m_pFirst == 0; }
ILINE TItem* PopFirst()
{
Validate();
if (!m_pFirst)
{
return 0;
}
TItem* pRet = m_pFirst;
m_pFirst = m_pFirst->Next();
if (m_pFirst) //if any element exists
{
m_pFirst->Prev(0); //set prev ptr of this element to 0
}
else
{
m_pLast = 0; //set ptr to last element to 0 if ptr to first is zero as well
}
Validate();
m_Count--;
return pRet;
}
ILINE TItem* PopLast()
{
Validate();
if (!m_pLast)
{
return 0;
}
TItem* pRet = m_pLast;
m_pLast = m_pLast->Prev();
if (m_pLast) //if any element exists
{
m_pLast->Next(0); //set prev ptr of this element to 0
}
else
{
m_pFirst = 0; //set ptr to last element to 0 if ptr to first is zero as well
}
Validate();
m_Count--;
return pRet;
}
ILINE void AddFirst(TItem* pItem)
{
CPA_ASSERT(pItem); //ERROR AddFirst got 0 pointer
Validate();
pItem->Prev(0);
pItem->Next(m_pFirst);
if (!m_pFirst)
{
m_pLast = pItem;
}
else
{
m_pFirst->Prev(pItem);
}
m_pFirst = pItem;
m_Count++;
Validate();
}
ILINE void AddLast(TItem* pItem)
{
CPA_ASSERT(pItem); //ERROR AddLast got 0 pointer
Validate();
pItem->Prev(m_pLast);
pItem->Next(0);
if (!m_pLast)
{
m_pFirst = pItem;
}
else
{
m_pLast->Next(pItem);
}
m_pLast = pItem;
m_Count++;
Validate();
}
ILINE void AddBefore(TItem* pItem, TItem* pItemSuccessor)
{
CPA_ASSERT(pItem);
CPA_ASSERT(pItemSuccessor);
Validate();
pItem->Next(pItemSuccessor);
pItem->Prev(pItemSuccessor->Prev());
pItemSuccessor->Prev(pItem);
if (pItemSuccessor == m_pFirst)
{
m_pFirst = pItem;
}
else
{
pItem->Prev()->Next(pItem);
}
m_Count++;
Validate();
}
ILINE void AddBehind(TItem* pItem, TItem* pItemPredecessor)
{
CPA_ASSERT(pItem);
CPA_ASSERT(pItemPredecessor);
Validate();
pItem->Next(pItemPredecessor->Next());
pItem->Prev(pItemPredecessor);
pItemPredecessor->Next(pItem);
if (pItemPredecessor == m_pLast)
{
m_pLast = pItem;
}
else
{
pItem->Next()->Prev(pItem);
}
m_Count++;
Validate();
}
ILINE void Remove(TItem* pItem)
{
CPA_ASSERT(pItem); //ERROR releasing empty item
if (pItem == m_pFirst)
{
PopFirst();
return;
}
if (pItem == m_pLast)
{
PopLast();
return;
}
Validate(pItem);
pItem->Prev()->Next(pItem->Next());
pItem->Next()->Prev(pItem->Prev());
m_Count--;
Validate();
}
//debug
ILINE void Validate(TItem* pReferenceItem = 0)
{
if (!VALIDATE)
{
return;
}
//one-sided empty?
CPA_ASSERT((!First() && !Last()) || (First() && Last())); //ERROR validating item-list, just one end is 0
// endles linking?
TItem* pPrev = 0;
TItem* pItem = First();
while (pItem)
{
if (pReferenceItem == pItem)
{
pReferenceItem = 0;
}
CPA_ASSERT(pPrev == pItem->Prev()); //ERROR validating item-list, endless linking NULL
pPrev = pItem;
pItem = pItem->Next();
}
CPA_ASSERT(pPrev == Last()); //ERROR validating item-list, broken list, does not end at specified Last item
CPA_ASSERT(!pReferenceItem); //ERROR reference item not found in the item-list
}
ILINE size_t Count() const{return m_Count; }
};
}
#endif // CRYINCLUDE_CRYPOOL_LIST_H
-70
View File
@@ -1,70 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_MEMORY_H
#define CRYINCLUDE_CRYPOOL_MEMORY_H
#pragma once
namespace NCryPoolAlloc
{
class CMemoryDynamic
{
size_t m_Size;
uint8* m_pData;
protected:
ILINE CMemoryDynamic()
: m_Size(0)
, m_pData(0){}
public:
ILINE void InitMem(const size_t S, uint8* pData)
{
m_Size = S;
m_pData = pData;
CPA_ASSERT(S);
CPA_ASSERT(pData);
}
ILINE size_t MemSize() const{return m_Size; }
ILINE uint8* Data(){return m_pData; }
ILINE const uint8* Data() const{return m_pData; }
};
template<size_t TSize>
class CMemoryStatic
{
uint8 m_Data[TSize];
protected:
ILINE CMemoryStatic()
{
}
public:
ILINE void InitMem(const size_t S, uint8* pData)
{
}
ILINE size_t MemSize() const{return TSize; }
ILINE uint8* Data(){return m_Data; }
ILINE const uint8* Data() const{return m_Data; }
};
}
#endif // CRYINCLUDE_CRYPOOL_MEMORY_H
@@ -1,55 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#pragma once
#if defined(POOLALLOCTESTSUIT)
//cheat just for unit testing on windows
#include "BaseTypes.h"
#define ILINE inline
#endif
// Traits
#if defined(AZ_RESTRICTED_PLATFORM)
#include AZ_RESTRICTED_FILE(CryPool/PoolAlloc_h)
#elif defined(APPLE) || defined(LINUX)
#define POOLALLOC_H_TRAIT_USE_MEMALIGN 1
#endif
#if POOLALLOC_H_TRAIT_USE_MEMALIGN
#define CPA_ALLOC memalign
#define CPA_FREE free
#else
#define CPA_ALLOC _aligned_malloc
#define CPA_FREE _aligned_free
#endif
#define CPA_ASSERT assert
#define CPA_ASSERT_STATIC(X) {uint8 assertdata[(X) ? 0 : 1]; }
#define CPA_BREAK __debugbreak()
#include "List.h"
#include "Memory.h"
#include "Container.h"
#include "Allocator.h"
#include "Defrag.h"
#include "STLWrapper.h"
#include "Inspector.h"
#include "Fallback.h"
#if !defined(POOLALLOCTESTSUIT)
#include "ThreadSafe.h"
#endif
#undef CPA_ASSERT
#undef CPA_ASSERT_STATIC
#undef CPA_BREAK
@@ -1,148 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_STLWRAPPER_H
#define CRYINCLUDE_CRYPOOL_STLWRAPPER_H
#pragma once
namespace NCryPoolAlloc
{
//namespace CSTLPoolAllocWrapperHelper
//{
// inline void destruct(char *) {}
// inline void destruct(wchar_t*) {}
// template <typename T>
// inline void destruct(T *t) {t->~T();}
//}
//template <size_t S, class L, size_t A, typename T>
//struct CSTLPoolAllocWrapperStatic
//{
// static PoolAllocator<S, L, A> * allocator;
//};
//template <class T, class L, size_t A>
//struct CSTLPoolAllocWrapperKungFu : public CSTLPoolAllocWrapperStatic<sizeof(T),L,A,T>
//{
//};
template <class T, class TCont>
class CSTLPoolAllocWrapper
{
private:
static TCont* m_pContainer;
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
static TCont* Container(){return m_pContainer; }
static void Container(TCont* pContainer){m_pContainer = pContainer; }
template <class U>
struct rebind
{
typedef CSTLPoolAllocWrapper<T, TCont> other;
};
CSTLPoolAllocWrapper() throw()
{
}
CSTLPoolAllocWrapper(const CSTLPoolAllocWrapper&) throw()
{
}
template <class TTemp, class TTempCont>
CSTLPoolAllocWrapper(const CSTLPoolAllocWrapper<TTemp, TTempCont>&) throw()
{
}
~CSTLPoolAllocWrapper() throw()
{
}
pointer address(reference x) const
{
return &x;
}
const_pointer address(const_reference x) const
{
return &x;
}
pointer allocate(size_type n = 1, const_pointer hint = 0)
{
TCont* pContainer = Container();
uint8* pData = pContainer->TCont::template Allocate<uint8*>(n * sizeof(T), sizeof(T));
return pContainer->TCont::template Resolve<pointer>(pData);
// return Container()?Container()->Allocate<void*>(n*sizeof(T),sizeof(T)):0
}
void deallocate(pointer p, size_type n = 1)
{
if (Container())
{
Container()->Free(p);
}
}
size_type max_size() const throw()
{
return Container() ? Container()->MemSize() : 0;
}
void construct(pointer p, const T& val)
{
new(static_cast<void*>(p))T(val);
}
void construct(pointer p)
{
new(static_cast<void*>(p))T();
}
void destroy(pointer p)
{
p->~T();
}
pointer new_pointer()
{
return new(allocate())T();
}
pointer new_pointer(const T& val)
{
return new(allocate())T(val);
}
void delete_pointer(pointer p)
{
p->~T();
deallocate(p);
}
bool operator==(const CSTLPoolAllocWrapper&) {return true; }
bool operator!=(const CSTLPoolAllocWrapper&) {return false; }
};
}
#endif // CRYINCLUDE_CRYPOOL_STLWRAPPER_H
@@ -1,58 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_THREADSAFE_H
#define CRYINCLUDE_CRYPOOL_THREADSAFE_H
#pragma once
#include <CryThread.h>
namespace NCryPoolAlloc
{
template<class TAllocator>
class CThreadSafe
: public TAllocator
{
CryCriticalSection m_Mutex;
public:
template<class T>
ILINE T Allocate(size_t Size, size_t Align = 1)
{
CryAutoLock<CryCriticalSection> lock(m_Mutex);
return TAllocator::template Allocate<T>(Size, Align);
}
template<class T>
ILINE bool Free(T pData, bool ForceBoundsCheck = false)
{
CryAutoLock<CryCriticalSection> lock(m_Mutex);
return TAllocator::Free(pData, ForceBoundsCheck);
}
template<class T>
ILINE bool Resize(T** pData, size_t Size, size_t Alignment)
{
CryAutoLock<CryCriticalSection> lock(m_Mutex);
return TAllocator::Resize(pData, Size, Alignment);
}
};
}
#endif // CRYINCLUDE_CRYPOOL_THREADSAFE_H
-287
View File
@@ -1,287 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYPOOL_EXAMPLE_H
#define CRYINCLUDE_CRYPOOL_EXAMPLE_H
#pragma once
//The documentation is split up into 3 main parts, so strg+f for
// -Theory
// -Building blocks
// -Usage
// -FAQ
// -Realloc/Resize
/////////////////////////////////////////////////////////////////////////
// -Theory
/////////////////////////////////////////////////////////////////////////
//this includes the 3 major parts of the allocate suite
//1. the memory location templates
//2. container types
//3. some allocator version
//addtional you get
//4. a simple stack based defragmentation template
//5. helper
//1. memory location templates
// There are two types of them, static and dynamic
//1.1 CMemoryStatic<size> allows you do define on compile time what size
// it should have, suitable for pool you know that they won't grow or
// shrink
//1.2 CMemoryDynamic, this one has no template parameter, it has just one
// indirection via ptr to the memory location and size, that you will
// set during initialization.
//2. Container types
// We have also two container types, one so called "In Place"
// and one "Referenced".
//2.1 "In Place" means that a header is placed above every allocation,
// this is the usual way most allocators work.
//2.2 "Referenced", has an extra pool of headers that point to the actual
// memory. This is suitable for
// - external memory locations that are not directly accessable by the
// cpu. E.g. pools on disk, networks, rsx memory..
// - defragmentation, because you don't save a ptr to the real memory
// location, just a "handle" of the referencing item.
// - big alignments, having 4kb of alignment would waste also
// - 4kb for ever "In Place" header, you might not want that.
//3. Allocators
// This time we have 3 of them, "BestFit", "WorstFit" and "FirstFit"
//3.1 FirstFit just seeks for any location big enought to fit your
// requested size of memory. Internally it also saves the last used
// free memory area to speed up allocations.
// Use this also if you have just one particular allocation size.
//3.2 WorstFit, although it might sound illogical, WorstFit can reduce
// memory fragmentation in a cases with very random allocation sizes,
// because it gives smaller free blocks the chance to concatenate to
// bigger free blocks again while filling up those previously
// generated big blocks. The bad side is that it takes quite some time
// to find the biggest block as this needs to be done every time you
// allocate, so use this just when having a low amount of allocations
// or you're really desperately looking for mem.
//3.3 BestFit, it's best used if you don't have just one allocation size,
// but still very few varying sizes. Previously released blocks of
// the currently allocating sizes will be seeked and reused, this
// strongly helps to reduce fragmentation. While this might be slow
// in some cases, it can save you from doing any defragmentation.
//4. Defragmentation
// At the moment just one defragmentation algorithm is implemented:
// "Stack defragmentator"
// If you don't want some block to be moved, "Lock" it using your
// memory handle.
//4.1 Stack based
// To reduce fragmentation, holes are filled up with the next used,
// memory area. This defragmentation sheme is useful when you have
// some long living locations as well as very short living ones.
// At some point all long live memory will end up at the bottom of
// the stack, while leaving empty memory areas at the top for short
// living allocations.
//5. Helper
// this should be filled up with some handy helper tools for this
// pool suite.
// The first tool is a wrapper for the usage with stl
//5.1 Wrapper for STL
// As you know, you can pass your own allocator as the last
// parameter of stl containers, with this helper you can use a pool
// created with this suite and wrap it for the stl.
/////////////////////////////////////////////////////////////////////////
// -Building blocks
/////////////////////////////////////////////////////////////////////////
//That's the theory, so how does it work?
//It's pretty simple, you compose the pool of your dreams by cascading
//templates.
//Lets start with an exmaple
//Per level you want to allocate a fixed amount of memory for your
//textures.
CMemoryDynamic
//- They are placed in some memory you can access directly with the cpu:
CInPlace
//- and you don't want to defragmentate, so you prefer an allocation
// sheme that reduces fragmentation.
CBestFit
//now you combine them
typedef CBestFit<CInPlace<CMemoryDynamic>, CListItemInPlace> TMyOwnPool;
//Yes, it's that simple.
//ok, ok, texture memory is usually nothing you want to access directly
//with your cpu, so let's create a referencing pool. Therefor you need
//to also specify how many nodes that can reference your pool will have.
//We won't have more than 4000 textures, so let's start with
{
enum TEXTURE_NODE_COUNT = 4096
};
//and now our referencing pool
typedef CBestFit < CReferenced<CMemoryDynamic, TEXTURE_NODE_COUNT> TMyOwnPool;
//But yeah, you're right, texture memory has also a fixed size, lets
//assume it's 128MB.
{
enum TEXTURE_MEMORY_SIZE = 128 * 1024 * 1024
};
//and our fixed sized memory pool
typedef CBestFit < CReferenced<CMemoryStatic<TEXTURE_MEMORY_SIZE>, TEXTURE_NODE_COUNT> TMyOwnPool;
//ok, but you don't trust the best fit allocator in all cases, you prefer
//a fast one and you accept the slow down for defragmentation incase the
//allocation fails.
//So lets created a straight First Fit allocator with defragmentation:
typedef CDefragStacked < CFirstFit<CReferenced<CMemoryStatic<TEXTURE_MEMORY_SIZE>, TEXTURE_NODE_COUNT> > TMyOwnPool;
//here you see how simple you can add defragmentation, but be careful, it
//works of course just on Reference based memory containers, if you have
//Direct pointers to In Place allocation, we cannot shuffle them around.
/////////////////////////////////////////////////////////////////////////
// -Usage
/////////////////////////////////////////////////////////////////////////
//it all starts by including the meain header
#include "PoolAlloc.h"
//Define your dream allocator, preferably using a typedef (or macro)
typedef CBestFit<CInPlace<CMemoryDynamic>, CListItemInPlace> TMyOwnPool;
//also typedef (or macro) your handle
typedef uint8* TMyHandle; //in case of "In Place" allocations
typedef uint32 TMyHandle; //in case of "Referenced"
//Instantiate it
TMyOwnPool g_MyMemory;
//now you need to initialize it,
g_MyMemory.InitMem(pMemoryArea, MemorySize); //in case you use "CMemoryDynamic"
g_MyMemory.InitMem(); //in case you use "CmemoryStatic,
//altough you could pass the same
//parameters, they'd be ignored.
//Use this also to flush the pool
//quickly
//now allocate
TMyHandle MemID = g_MyMemory.Allocate<TMyHandle>(Size);
//optionally alignment can be passed as 2nd parameter
TMyHandle MemID = g_MyMemory.Allocate<TMyHandle>(Size, Align);
//free it simply by calling
g_Memory.Free(MemID);
//you might want to call the beat function to defragment the memory
//on regular base
g_Memory.Beat();
//you might also want to call it just when an allocation failed to
//defragmentate the memory as good as possible
if (!(MemID = g_Memoery.Allocate<TMyHandle>(Size)))
{
while (g_Memory.Beat())
{
;
}
MemID = g_Memoery.Allocate<TMyHandle>(Size);
}
//To acquire the pointer to your data, you need to resolve the handle
MyObject* pObject = g_Memory.Resolve<MyOBject*>(MemID);
/////////////////////////////////////////////////////////////////////////
// -Realloc/Resize
/////////////////////////////////////////////////////////////////////////
// The Containers provide a "resize" function. This one does nothing else
// than the name suggest, it is freeing some memory at the end of your
// allocation or, if free memory is available, allocates some memory to
// the end of your buffer. But it may also fail, if not enough memory
// available to allocate.
// "Realloc" on the other side requires an extra template that you wrap
// around your existing one like:
typedef CReallocator<TMyOwnPool> TMyOwnPoolWithReallocation;
// This one will first try to use resize, but in case it fails, it will
// allocate a seperate memory area, copy the data and free the old one.
//
// But this may fail as well, therefor the result is not a pointer to the
// allocation, but true/false.
// There for you need to pass a pointer to your pointer to the memory area
// or handle you deal with.
Handle = rMemory.Allocate<TPtr>(10, 1);
if (!rMemory.Reallocate<TPtr>(&Handles, 11, 1))
{
//handle realloc failure
}
/////////////////////////////////////////////////////////////////////////
// -FAQ
/////////////////////////////////////////////////////////////////////////
//"DO I HAVE TO ALWAYS RESOLVE?"
//if you use "In Place" memory, not at all, all resolve does is to
//cast your handle to your object ptr and returns it.
//if you use "Referenced" memory and you don't defragmentate, you
//can do it once and keep the ptr, but you also need to keep the
//handle to free the memory later on.
//"any reason I should resolve?"
//Yes, first of all, it makes it very easy to switch between various
//pool configuration for testing, you simply change some params of
//your typedef (or macro) and it should work out of the box.
//second, for defragmentation it's the only way to go and for future
//things it might be needed as well
//"but isn't resolving just overhead?"
//in case of "In Place": no, the resolve function just returns the
//pointer, casting to your wanted type
//in case of "Referenced": it cost you one indirection.
//"How do I flush the whole pool without freeing all items?"
g_Memory.InitMem()
//yes, you can call "InitMem" once again, you need to pass the mem
//ptr and size if using CMemoryDynamic e.g.
g_Memory.Init(g_Memory.Size(), g_Memory.Data());
//"How do I lock the allocated memory to avoid any reallocation"
g_Memory.Item(ptr)->Lock();
//"How do I get the size of a memory block?"
g_Memory.Item(ptr)->MemSize();
//"Is there any example?"
//for a real life example check PAUnitTest.cpp used to validate all
//functions of this pool.
//bug reports? questions? support?
//just ask me :) (michael kopietz)
#endif // CRYINCLUDE_CRYPOOL_EXAMPLE_H
-6
View File
@@ -49,12 +49,6 @@ public:
//! ISystem has shut down.
virtual void OnCrySystemPostShutdown() {}
//! Engine pre physics update.
virtual void OnCrySystemPrePhysicsUpdate() {}
//! Engine post physics update.
virtual void OnCrySystemPostPhysicsUpdate() {}
//! Sent when a new level is being created.
virtual void OnCryEditorBeginCreate() {}
-3
View File
@@ -37,9 +37,6 @@ enum CryLockType
#define CRYLOCK_HAVE_FASTLOCK 1
void CryThreadSetName(threadID nThreadId, const char* sThreadName);
const char* CryThreadGetName(threadID nThreadId);
/////////////////////////////////////////////////////////////////////////////
//
// Primitive locks and conditions.
-19
View File
@@ -31,22 +31,3 @@
#else
// Put other platform specific includes here!
#endif
#include <IThreadTask.h>
void CryThreadSetName(threadID dwThreadId, const char* sThreadName)
{
if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager())
{
gEnv->pSystem->GetIThreadTaskManager()->SetThreadName(dwThreadId, sThreadName);
}
}
const char* CryThreadGetName(threadID dwThreadId)
{
if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager())
{
return gEnv->pSystem->GetIThreadTaskManager()->GetThreadName(dwThreadId);
}
return "";
}
@@ -13,8 +13,6 @@
#pragma once
//#include <IThreadTask.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
@@ -249,10 +249,6 @@ public:
void SetName(const char* Name)
{
m_name = Name;
if (m_threadId)
{
CryThreadSetName(m_threadId, m_name);
}
}
const char* GetName() { return m_name; }
@@ -289,11 +285,6 @@ private:
self->m_bIsStarted = true;
self->m_bIsRunning = true;
if (!self->m_name.empty())
{
CryThreadSetName(-1, self->m_name);
}
self->m_Runnable->Run();
self->m_bIsRunning = false;
self->m_bCreatedThread = false;
@@ -311,11 +302,6 @@ private:
self->m_bIsStarted = true;
self->m_bIsRunning = true;
if (!self->m_name.empty())
{
CryThreadSetName(-1, self->m_name);
}
self->Run();
self->m_bIsRunning = false;
self->m_bCreatedThread = false;
@@ -1,34 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "EngineSettingsBackend.h"
#ifdef CRY_ENABLE_RC_HELPER
CEngineSettingsBackend::CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName)
: m_parent(parent)
, m_moduleName()
{
if (moduleName != nullptr)
{
m_moduleName = moduleName;
}
}
CEngineSettingsBackend::~CEngineSettingsBackend()
{
}
#endif // CRY_ENABLE_RC_HELPER
@@ -1,65 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H
#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H
#pragma once
#include "ProjectDefines.h"
#ifdef CRY_ENABLE_RC_HELPER
#include "SettingsManagerHelpers.h"
#include <string>
class CEngineSettingsManager;
class CEngineSettingsBackend
{
public:
CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL);
virtual ~CEngineSettingsBackend();
virtual std::wstring GetModuleFilePath() const = 0;
virtual bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) = 0;
virtual bool GetModuleSpecificIntEntry(const char* key, int& value) = 0;
virtual bool GetModuleSpecificBoolEntry(const char* key, bool& value) = 0;
virtual bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) = 0;
virtual bool SetModuleSpecificIntEntry(const char* key, const int& value) = 0;
virtual bool SetModuleSpecificBoolEntry(const char* key, const bool& value) = 0;
virtual bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) = 0;
virtual void LoadEngineSettingsFromRegistry() = 0;
virtual bool StoreEngineSettingsToRegistry() = 0;
protected:
CEngineSettingsManager* parent() const
{
return m_parent;
}
const std::wstring& moduleName() const
{
return m_moduleName;
}
private:
std::wstring m_moduleName;
CEngineSettingsManager* m_parent;
};
#endif // CRY_ENABLE_RC_HELPER
#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H
@@ -1,486 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "EngineSettingsBackendApple.h"
#ifdef CRY_ENABLE_RC_HELPER
#include "AzCore/PlatformDef.h"
#if AZ_TRAIT_OS_PLATFORM_APPLE
#include "EngineSettingsManager.h"
#include "SettingsManagerHelpers.h"
#include "platform.h"
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <mach-o/nlist.h>
#include <cassert>
#include <codecvt>
#include <cstdlib>
#include <fstream>
#include <map>
#include <string>
using namespace SettingsManagerHelpers;
static const char gDefaultRegistryLocation[] = "/EngineSettings.reg";
#define REG_SOFTWARE L"Software\\"
#define REG_COMPANY_NAME L"Amazon\\"
#define REG_PRODUCT_NAME L"Lumberyard\\"
#define REG_SETTING L"Settings\\"
#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING
//////////////////////////////////////////////////////////////////////////
class SimpleRegistry
{
typedef std::map< std::wstring, std::wstring > WStringMap;
std::map< std::wstring, WStringMap * > m_modules;
public:
SimpleRegistry();
~SimpleRegistry();
void setBoolValue(const std::wstring& module, const std::wstring& key, bool value);
void setIntValue(const std::wstring& module, const std::wstring& key, int value);
void setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value);
bool getBoolValue(const std::wstring& module, const std::wstring& key, bool& value);
bool getIntValue(const std::wstring& module, const std::wstring& key, int& value);
bool getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value);
bool loadFromFile(const char* fileName);
bool saveToFile(const char* fileName);
protected:
void clear();
private:
static const wchar_t gSimpleMagic[];
static const size_t gMetaCharCount;
};
const wchar_t SimpleRegistry::gSimpleMagic[] = L"FR0";
const size_t SimpleRegistry::gMetaCharCount = sizeof(size_t) / sizeof(wchar_t);
SimpleRegistry::SimpleRegistry()
{
}
SimpleRegistry::~SimpleRegistry()
{
clear();
}
void SimpleRegistry::setBoolValue(const std::wstring& module, const std::wstring& key, bool value)
{
return setStrValue(module, key, value ? L"true" : L"false");
}
void SimpleRegistry::setIntValue(const std::wstring& module, const std::wstring& key, int value)
{
return setStrValue(module, key, std::to_wstring(value));
}
void SimpleRegistry::setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value)
{
WStringMap *map = nullptr;
auto i = m_modules.find(module);
if (i == m_modules.end())
{
map = new WStringMap;
m_modules.emplace(module, map);
}
else
{
map = i->second;
}
assert(map);
(*map)[key] = value;
}
bool SimpleRegistry::getBoolValue(const std::wstring& module, const std::wstring& key, bool& value)
{
std::wstring str;
if (!getStrValue(module, key, str))
{
return false;
}
value = (0 == str.compare(L"true"));
return true;
}
bool SimpleRegistry::getIntValue(const std::wstring& module, const std::wstring& key, int& value)
{
std::wstring str;
if (!getStrValue(module, key, str))
{
return false;
}
value = std::stoi(str);
return true;
}
bool SimpleRegistry::getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value)
{
WStringMap *map = nullptr;
auto mi = m_modules.find(module);
if (mi == m_modules.end())
{
return false;
}
map = mi->second;
assert(map);
auto ki = map->find(key);
if (ki == map->end())
{
return false;
}
value = ki->second;
return true;
}
bool SimpleRegistry::loadFromFile(const char* fileName)
{
clear();
std::wifstream file(fileName, std::ios_base::in|std::ios_base::binary);
file.imbue(std::locale(file.getloc(), new std::codecvt_utf16<wchar_t>));
if (!file.is_open())
{
AZ_Warning("EngineSettings", false, "Failed to open registry settings file: %s", fileName);
return false;
}
std::wstring module;
std::wstring key;
std::wstring value;
wchar_t buffer[512];
size_t size;
wchar_t meta[gMetaCharCount];
/* magic number */
if(!file.read(buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) ||
wcsncmp(gSimpleMagic, buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) != 0)
{
file.close();
AZ_Warning("EngineSettings", false, "Failed to load registry settings from file: %s", fileName);
return false;
}
while (file.good())
{
file.read(meta, gMetaCharCount);
if (!file.good())
{
break;
}
memcpy(&size, meta, sizeof(size));
file.read(buffer, size);
buffer[file.gcount()] = L'\0';
module = buffer;
file.read(meta, gMetaCharCount);
memcpy(&size, meta, sizeof(size));
file.read(buffer, size);
buffer[file.gcount()] = L'\0';
key = buffer;
file.read(meta, gMetaCharCount);
memcpy(&size, meta, sizeof(size));
file.read(buffer, size);
buffer[file.gcount()] = L'\0';
value = buffer;
setStrValue(module, key, value);
}
file.close();
return true;
}
bool SimpleRegistry::saveToFile(const char* fileName)
{
std::wofstream file(fileName, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary);
file.imbue(std::locale(file.getloc(), new std::codecvt_utf16<wchar_t>));
if (!file.is_open())
{
return false;
}
std::wstring module;
size_t size;
wchar_t meta[gMetaCharCount];
/* magic number */
file.write(gSimpleMagic, sizeof(gSimpleMagic) / sizeof(wchar_t));
for (auto j : m_modules)
{
module = j.first;
for (auto i : *j.second)
{
size = module.size();
memcpy(meta, &size, sizeof(meta));
file.write(meta, gMetaCharCount);
file.write(module.c_str(), size);
size = i.first.size();
memcpy(meta, &size, sizeof(meta));
file.write(meta, gMetaCharCount);
file.write(i.first.c_str(), size);
size = i.second.size();
memcpy(meta, &size, sizeof(meta));
file.write(meta, gMetaCharCount);
file.write(i.second.c_str(), size);
}
}
file.close();
return true;
}
void SimpleRegistry::clear()
{
for (auto pair : m_modules)
{
delete pair.second;
}
m_modules.clear();
}
//////////////////////////////////////////////////////////////////////////
CEngineSettingsBackendApple::CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName)
: CEngineSettingsBackend(parent, moduleName)
, m_registry(new SimpleRegistry)
, m_registryFilePath()
{
std::string rootValue = gEnv->pFileIO->GetAlias("@root@");
if (rootValue.empty())
{
AZ_Warning("EngineSettings", false, "Could not get engine root.");
return;
}
rootValue.append(gDefaultRegistryLocation);
m_registryFilePath = rootValue;
}
CEngineSettingsBackendApple::~CEngineSettingsBackendApple()
{
delete m_registry, m_registry = nullptr;
}
std::wstring CEngineSettingsBackendApple::GetModuleFilePath() const
{
std::string path;
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string module = converter.to_bytes(moduleName());
void* handle = ::dlopen(module.c_str(), RTLD_LAZY);
if (handle)
{
const int c = _dyld_image_count();
for (int i = 0; i < c; ++i)
{
const char* image = _dyld_get_image_name(i);
const void* altHandle = dlopen(image, RTLD_LAZY);
if (handle == altHandle)
{
char absImage[PATH_MAX];
realpath(image, absImage);
char *ext = rindex(absImage, '.');
if (ext)
{
*ext = '\0';
}
path.append(absImage);
path.append(".ini");
break;
}
}
}
return converter.from_bytes(path);
}
bool CEngineSettingsBackendApple::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wkey = converter.from_bytes(key);
std::wstring str;
if (!m_registry->getStrValue(moduleName(), wkey, str))
{
return false;
}
std::wcscpy(wbuffer.getPtr(), str.c_str());
return true;
}
bool CEngineSettingsBackendApple::GetModuleSpecificIntEntry(const char* key, int& value)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wkey = converter.from_bytes(key);
return m_registry->getIntValue(moduleName(), wkey, value);
}
bool CEngineSettingsBackendApple::GetModuleSpecificBoolEntry(const char* key, bool& value)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wkey = converter.from_bytes(key);
return m_registry->getBoolValue(moduleName(), wkey, value);
}
bool CEngineSettingsBackendApple::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wkey = converter.from_bytes(key);
m_registry->setStrValue(moduleName(), wkey, str);
return true;
}
bool CEngineSettingsBackendApple::SetModuleSpecificIntEntry(const char* key, const int& value)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wkey = converter.from_bytes(key);
m_registry->setIntValue(moduleName(), wkey, value);
return true;
}
bool CEngineSettingsBackendApple::SetModuleSpecificBoolEntry(const char* key, const bool& value)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wkey = converter.from_bytes(key);
m_registry->setBoolValue(moduleName(), wkey, value);
return true;
}
bool CEngineSettingsBackendApple::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path)
{
return false;
}
bool CEngineSettingsBackendApple::StoreEngineSettingsToRegistry()
{
bool bRet = true;
wchar_t buffer[1024];
// ResourceCompiler Specific
if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
const bool b = wcscmp(buffer, L"true") == 0;
m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", b);
}
if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
const bool b = wcscmp(buffer, L"true") == 0;
m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", b);
}
if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
m_registry->setStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", buffer);
}
if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
const bool b = wcscmp(buffer, L"true") == 0;
m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", b);
}
bRet &= m_registry->saveToFile(m_registryFilePath.c_str());
return bRet;
}
void CEngineSettingsBackendApple::LoadEngineSettingsFromRegistry()
{
if (!m_registry->loadFromFile(m_registryFilePath.c_str()))
{
return;
}
std::wstring wStrResult;
bool bResult;
if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RootPath", wStrResult))
{
parent()->SetKey("ENG_RootPath", wStrResult.c_str());
}
// Engine Specific
if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"ENG_RootPath", wStrResult))
{
parent()->SetKey("ENG_RootPath", wStrResult.c_str());
}
// ResourceCompiler Specific
if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", bResult))
{
parent()->SetKey("RC_ShowWindow", bResult);
}
if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", bResult))
{
parent()->SetKey("RC_HideCustom", bResult);
}
if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", wStrResult))
{
parent()->SetKey("RC_Parameters", wStrResult.c_str());
}
if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", bResult))
{
parent()->SetKey("RC_EnableSourceControl", bResult);
}
}
#endif // AZ_TRAIT_OS_PLATFORM_APPLE
#endif // CRY_ENABLE_RC_HELPER
@@ -1,51 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H
#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H
#pragma once
#include "EngineSettingsBackend.h"
#ifdef CRY_ENABLE_RC_HELPER
class CEngineSettingsManager;
class SimpleRegistry;
class CEngineSettingsBackendApple : public CEngineSettingsBackend
{
public:
CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL);
~CEngineSettingsBackendApple();
std::wstring GetModuleFilePath() const override;
bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override;
bool GetModuleSpecificIntEntry(const char* key, int& value) override;
bool GetModuleSpecificBoolEntry(const char* key, bool& value) override;
bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override;
bool SetModuleSpecificIntEntry(const char* key, const int& value) override;
bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override;
bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override;
void LoadEngineSettingsFromRegistry() override;
bool StoreEngineSettingsToRegistry() override;
private:
SimpleRegistry *m_registry;
std::string m_registryFilePath;
};
#endif // CRY_ENABLE_RC_HELPER
#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H
@@ -1,431 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "EngineSettingsBackendWin32.h"
#ifdef CRY_ENABLE_RC_HELPER
#include "AzCore/PlatformDef.h"
#ifdef AZ_PLATFORM_WINDOWS
#include "EngineSettingsManager.h"
#include "platform.h"
#include <windows.h>
#define REG_SOFTWARE L"Software\\"
#define REG_COMPANY_NAME L"Amazon\\"
#define REG_PRODUCT_NAME L"Open 3D Engine\\"
#define REG_SETTING L"Settings\\"
#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
using namespace SettingsManagerHelpers;
static bool g_bWindowQuit;
static CEngineSettingsManager* g_pThis = 0;
static const unsigned int IDC_hEditRootPath = 100;
static const unsigned int IDC_hBtnBrowse = 101;
namespace
{
class RegKey
{
public:
RegKey(const wchar_t* key, bool writeable);
~RegKey();
void* pKey;
};
RegKey::RegKey(const wchar_t* key, bool writeable)
{
HKEY hKey;
LONG result;
if (writeable)
{
result = RegCreateKeyExW(HKEY_CURRENT_USER, key, 0, 0, 0, KEY_WRITE, 0, &hKey, 0);
}
else
{
result = RegOpenKeyExW(HKEY_CURRENT_USER, key, 0, KEY_READ, &hKey);
}
pKey = hKey;
}
RegKey::~RegKey()
{
RegCloseKey((HKEY)pKey);
}
}
CEngineSettingsBackendWin32::CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName)
: CEngineSettingsBackend(parent, moduleName)
{
}
std::wstring CEngineSettingsBackendWin32::GetModuleFilePath() const
{
wchar_t szFilename[_MAX_PATH];
GetModuleFileNameW((HINSTANCE)&__ImageBase, szFilename, _MAX_PATH);
wchar_t drive[_MAX_DRIVE];
wchar_t dir[_MAX_DIR];
wchar_t fname[_MAX_FNAME];
wchar_t ext[1] = L"";
_wsplitpath_s(szFilename, drive, dir, fname, ext);
_wmakepath_s(szFilename, drive, dir, fname, L"ini");
return szFilename;
}
bool CEngineSettingsBackendWin32::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer)
{
CFixedString<wchar_t, 256> s = REG_BASE_SETTING_KEY;
s.append(moduleName().c_str());
RegKey superKey(s.c_str(), false);
if (!superKey.pKey)
{
wbuffer[0] = 0;
return false;
}
if (!GetRegValue(superKey.pKey, key, wbuffer))
{
wbuffer[0] = 0;
return false;
}
return true;
}
bool CEngineSettingsBackendWin32::GetModuleSpecificIntEntry(const char* key, int& value)
{
CFixedString<wchar_t, 256> s = REG_BASE_SETTING_KEY;
s.append(moduleName().c_str());
RegKey superKey(s.c_str(), false);
if (!superKey.pKey)
{
return false;
}
if (!GetRegValue(superKey.pKey, key, value))
{
value = 0;
return false;
}
return true;
}
bool CEngineSettingsBackendWin32::GetModuleSpecificBoolEntry(const char* key, bool& value)
{
CFixedString<wchar_t, 256> s = REG_BASE_SETTING_KEY;
s.append(moduleName().c_str());
RegKey superKey(s.c_str(), false);
if (!superKey.pKey)
{
return false;
}
if (!GetRegValue(superKey.pKey, key, value))
{
value = false;
return false;
}
return true;
}
bool CEngineSettingsBackendWin32::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str)
{
CFixedString<wchar_t, 256> s = REG_BASE_SETTING_KEY;
s.append(moduleName().c_str());
RegKey superKey(s.c_str(), true);
if (superKey.pKey)
{
return SetRegValue(superKey.pKey, key, str);
}
return false;
}
bool CEngineSettingsBackendWin32::SetModuleSpecificIntEntry(const char* key, const int& value)
{
CFixedString<wchar_t, 256> s = REG_BASE_SETTING_KEY;
s.append(moduleName().c_str());
RegKey superKey(s.c_str(), true);
if (superKey.pKey)
{
return SetRegValue(superKey.pKey, key, value);
}
return false;
}
bool CEngineSettingsBackendWin32::SetModuleSpecificBoolEntry(const char* key, const bool& value)
{
CFixedString<wchar_t, 256> s = REG_BASE_SETTING_KEY;
s.append(moduleName().c_str());
RegKey superKey(s.c_str(), true);
if (superKey.pKey)
{
return SetRegValue(superKey.pKey, key, value);
}
return false;
}
bool CEngineSettingsBackendWin32::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path)
{
RegKey key(REG_BASE_SETTING_KEY L"O3DEExport\\ProjectBuilds", false);
if (key.pKey)
{
DWORD type;
DWORD nameSizeInBytes = DWORD(name.getSizeInBytes());
DWORD pathSizeInBytes = DWORD(path.getSizeInBytes());
LONG result = RegEnumValueW((HKEY)key.pKey, index, name.getPtr(), &nameSizeInBytes, NULL, &type, (BYTE*)path.getPtr(), &pathSizeInBytes);
if (result == ERROR_SUCCESS)
{
return true;
}
}
return false;
}
bool CEngineSettingsBackendWin32::StoreEngineSettingsToRegistry()
{
// make sure the path in registry exists
{
RegKey key0(REG_SOFTWARE REG_COMPANY_NAME, true);
if (!key0.pKey)
{
RegKey software(REG_SOFTWARE, true);
HKEY hKey;
RegCreateKeyW((HKEY)software.pKey, REG_COMPANY_NAME, &hKey);
if (!hKey)
{
return false;
}
}
RegKey key1(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true);
if (!key1.pKey)
{
RegKey softwareCompany(REG_SOFTWARE REG_COMPANY_NAME, true);
HKEY hKey;
RegCreateKeyW((HKEY)softwareCompany.pKey, REG_COMPANY_NAME, &hKey);
if (!hKey)
{
return false;
}
}
RegKey key2(REG_BASE_SETTING_KEY, true);
if (!key2.pKey)
{
RegKey softwareCompanyProduct(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true);
HKEY hKey;
RegCreateKeyW((HKEY)key2.pKey, REG_SETTING, &hKey);
if (!hKey)
{
return false;
}
}
}
bool bRet = true;
RegKey key(REG_BASE_SETTING_KEY, true);
if (!key.pKey)
{
bRet = false;
}
else
{
wchar_t buffer[1024];
// ResourceCompiler Specific
if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
const bool b = wcscmp(buffer, L"true") == 0;
SetRegValue(key.pKey, "RC_ShowWindow", b);
}
if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
const bool b = wcscmp(buffer, L"true") == 0;
SetRegValue(key.pKey, "RC_HideCustom", b);
}
if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
SetRegValue(key.pKey, "RC_Parameters", buffer);
}
if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
const bool b = wcscmp(buffer, L"true") == 0;
SetRegValue(key.pKey, "RC_EnableSourceControl", b);
}
}
return bRet;
}
void CEngineSettingsBackendWin32::LoadEngineSettingsFromRegistry()
{
wchar_t buffer[1024];
bool bResult;
// Engine Specific (Deprecated value)
RegKey key(REG_BASE_SETTING_KEY, false);
if (key.pKey)
{
if (GetRegValue(key.pKey, "RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
parent()->SetKey("ENG_RootPath", buffer);
}
// Engine Specific
if (GetRegValue(key.pKey, "ENG_RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
parent()->SetKey("ENG_RootPath", buffer);
}
// ResourceCompiler Specific
if (GetRegValue(key.pKey, "RC_ShowWindow", bResult))
{
parent()->SetKey("RC_ShowWindow", bResult);
}
if (GetRegValue(key.pKey, "RC_HideCustom", bResult))
{
parent()->SetKey("RC_HideCustom", bResult);
}
if (GetRegValue(key.pKey, "RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
parent()->SetKey("RC_Parameters", buffer);
}
if (GetRegValue(key.pKey, "RC_EnableSourceControl", bResult))
{
parent()->SetKey("RC_EnableSourceControl", bResult);
}
}
}
bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, const wchar_t* value)
{
CFixedString<wchar_t, 256> name;
name.appendAscii(valueName);
size_t const sizeInBytes = (wcslen(value) + 1) * sizeof(value[0]);
return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_SZ, (BYTE*)value, DWORD(sizeInBytes)));
}
bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, bool value)
{
CFixedString<wchar_t, 256> name;
name.appendAscii(valueName);
DWORD dwVal = value;
return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal)));
}
bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, int value)
{
CFixedString<wchar_t, 256> name;
name.appendAscii(valueName);
DWORD dwVal = value;
return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal)));
}
bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, CWCharBuffer wbuffer)
{
if (wbuffer.getSizeInElements() <= 0)
{
return false;
}
CFixedString<wchar_t, 256> name;
name.appendAscii(valueName);
DWORD type;
DWORD sizeInBytes = DWORD(wbuffer.getSizeInBytes());
if (ERROR_SUCCESS != RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)wbuffer.getPtr(), &sizeInBytes))
{
wbuffer[0] = 0;
return false;
}
const size_t sizeInElements = sizeInBytes / sizeof(wbuffer[0]);
if (sizeInElements > wbuffer.getSizeInElements()) // paranoid check
{
wbuffer[0] = 0;
return false;
}
// According to MSDN documentation for RegQueryValueEx(), strings returned by the function
// are not zero-terminated sometimes, so we need to terminate them by ourselves.
if (wbuffer[sizeInElements - 1] != 0)
{
if (sizeInElements >= wbuffer.getSizeInElements())
{
// No space left to put terminating zero character
wbuffer[0] = 0;
return false;
}
wbuffer[sizeInElements] = 0;
}
return true;
}
bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, bool& value)
{
CFixedString<wchar_t, 256> name;
name.appendAscii(valueName);
// Open the appropriate registry key
DWORD type, dwVal = 0, size = sizeof(dwVal);
bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size));
if (res)
{
value = (dwVal != 0);
}
else
{
wchar_t buffer[100];
res = GetRegValue(key, valueName, CWCharBuffer(buffer, sizeof(buffer)));
if (res)
{
value = (wcscmp(buffer, L"true") == 0);
}
}
return res;
}
bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, int& value)
{
CFixedString<wchar_t, 256> name;
name.appendAscii(valueName);
// Open the appropriate registry key
DWORD type, dwVal = 0, size = sizeof(dwVal);
bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size));
if (res)
{
value = dwVal;
}
return res;
}
#endif // AZ_PLATFORM_WINDOWS
#endif // CRY_ENABLE_RC_HELPER
@@ -1,53 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H
#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H
#pragma once
#include "EngineSettingsBackend.h"
#ifdef CRY_ENABLE_RC_HELPER
class CEngineSettingsManager;
class CEngineSettingsBackendWin32 : public CEngineSettingsBackend
{
public:
CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL);
std::wstring GetModuleFilePath() const override;
bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override;
bool GetModuleSpecificIntEntry(const char* key, int& value) override;
bool GetModuleSpecificBoolEntry(const char* key, bool& value) override;
bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override;
bool SetModuleSpecificIntEntry(const char* key, const int& value) override;
bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override;
bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override;
void LoadEngineSettingsFromRegistry() override;
bool StoreEngineSettingsToRegistry() override;
protected:
bool SetRegValue(void* key, const char* valueName, const wchar_t* value);
bool SetRegValue(void* key, const char* valueName, bool value);
bool SetRegValue(void* key, const char* valueName, int value);
bool GetRegValue(void* key, const char* valueName, SettingsManagerHelpers::CWCharBuffer wbuffer);
bool GetRegValue(void* key, const char* valueName, bool& value);
bool GetRegValue(void* key, const char* valueName, int& value);
};
#endif // CRY_ENABLE_RC_HELPER
#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H
@@ -1,479 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "ProjectDefines.h"
#include "EngineSettingsManager.h"
#if defined(CRY_ENABLE_RC_HELPER)
#include <assert.h> // assert()
#include "EngineSettingsBackend.h"
#include "AzCore/PlatformDef.h"
#include "platform.h"
#if defined(AZ_PLATFORM_WINDOWS)
#include "EngineSettingsBackendWin32.h"
#include <AzCore/PlatformIncl.h>
#elif AZ_TRAIT_OS_PLATFORM_APPLE
#include "EngineSettingsBackendApple.h"
#endif
#include <climits>
#include <cstdio>
#define INFOTEXT L"Please specify the directory of your CryENGINE installation (RootPath):"
using namespace SettingsManagerHelpers;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CEngineSettingsManager::CEngineSettingsManager(const wchar_t* moduleName, const wchar_t* iniFileName)
: m_hWndParent(0)
, m_backend(NULL)
{
m_sModuleName.clear();
#if defined(AZ_PLATFORM_WINDOWS)
m_backend = new CEngineSettingsBackendWin32(this, moduleName);
#elif AZ_TRAIT_OS_PLATFORM_APPLE
m_backend = new CEngineSettingsBackendApple(this, moduleName);
#endif
assert(m_backend);
// std initialization
RestoreDefaults();
// try to load content from INI file
if (moduleName != NULL)
{
m_sModuleName = moduleName;
if (iniFileName == NULL)
{
// find INI filename located in module path
m_sModuleFileName = m_backend->GetModuleFilePath().c_str();
}
else
{
m_sModuleFileName = iniFileName;
}
if (LoadValuesFromConfigFile(m_sModuleFileName.c_str()))
{
m_bGetDataFromBackend = false;
return;
}
}
m_bGetDataFromBackend = true;
// load basic content from registry
LoadEngineSettingsFromRegistry();
}
//////////////////////////////////////////////////////////////////////////
CEngineSettingsManager::~CEngineSettingsManager()
{
delete m_backend, m_backend = NULL;
}
//////////////////////////////////////////////////////////////////////////
void CEngineSettingsManager::RestoreDefaults()
{
// Engine
SetKey("ENG_RootPath", L"");
// RC
SetKey("RC_ShowWindow", false);
SetKey("RC_HideCustom", false);
SetKey("RC_Parameters", L"");
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer)
{
if (wbuffer.getSizeInElements() <= 0)
{
return false;
}
if (!m_bGetDataFromBackend)
{
if (!HasKey(key))
{
wbuffer[0] = 0;
return false;
}
if (!GetValueByRef(key, wbuffer))
{
wbuffer[0] = 0;
return false;
}
}
else
{
assert(m_backend);
return m_backend->GetModuleSpecificStringEntryUtf16(key, wbuffer);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer)
{
if (buffer.getSizeInElements() <= 0)
{
return false;
}
wchar_t wBuffer[1024];
if (!GetModuleSpecificStringEntryUtf16(key, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer))))
{
buffer[0] = 0;
return false;
}
SettingsManagerHelpers::ConvertUtf16ToUtf8(wBuffer, buffer);
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::GetModuleSpecificIntEntry(const char* key, int& value)
{
value = 0;
if (!m_bGetDataFromBackend)
{
if (!HasKey(key))
{
return false;
}
if (!GetValueByRef(key, value))
{
return false;
}
}
else
{
assert(m_backend);
return m_backend->GetModuleSpecificIntEntry(key, value);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::GetModuleSpecificBoolEntry(const char* key, bool& value)
{
value = false;
if (!m_bGetDataFromBackend)
{
if (!HasKey(key))
{
return false;
}
if (!GetValueByRef(key, value))
{
return false;
}
}
else
{
assert(m_backend);
return m_backend->GetModuleSpecificBoolEntry(key, value);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str)
{
SetKey(key, str);
if (!m_bGetDataFromBackend)
{
return StoreData();
}
assert(m_backend);
return m_backend->SetModuleSpecificStringEntryUtf16(key, str);
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::SetModuleSpecificIntEntry(const char* key, const int& value)
{
SetKey(key, value);
if (!m_bGetDataFromBackend)
{
return StoreData();
}
assert(m_backend);
return m_backend->SetModuleSpecificIntEntry(key, value);
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::SetModuleSpecificBoolEntry(const char* key, const bool& value)
{
SetKey(key, value);
if (!m_bGetDataFromBackend)
{
return StoreData();
}
assert(m_backend);
return m_backend->SetModuleSpecificBoolEntry(key, value);
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf8(const char* key, const char* str)
{
wchar_t wbuffer[512];
SettingsManagerHelpers::ConvertUtf8ToUtf16(str, SettingsManagerHelpers::CWCharBuffer(wbuffer, sizeof(wbuffer)));
return SetModuleSpecificStringEntryUtf16(key, wbuffer);
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::HasKey(const char* key)
{
return m_keyValueArray.find(key) != 0;
}
//////////////////////////////////////////////////////////////////////////
void CEngineSettingsManager::SetKey(const char* key, const wchar_t* value)
{
m_keyValueArray.set(key, value);
}
//////////////////////////////////////////////////////////////////////////
void CEngineSettingsManager::SetKey(const char* key, bool value)
{
m_keyValueArray.set(key, (value ? L"true" : L"false"));
}
//////////////////////////////////////////////////////////////////////////
void CEngineSettingsManager::SetKey(const char* key, int value)
{
m_keyValueArray.set(key, std::to_wstring(value).c_str());
}
bool CEngineSettingsManager::GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path)
{
assert(m_backend);
return m_backend->GetInstalledBuildRootPathUtf16(index, name, path);
}
//////////////////////////////////////////////////////////////////////////
void CEngineSettingsManager::SetParentDialog(size_t window)
{
m_hWndParent = window;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::StoreData()
{
if (m_bGetDataFromBackend)
{
bool res = StoreEngineSettingsToRegistry();
if (!res)
{
#ifdef AZ_PLATFORM_WINDOWS
MessageBoxA(reinterpret_cast<HWND>(m_hWndParent), "Could not store data to registry.", "Error", MB_OK | MB_ICONERROR);
#endif
}
return res;
}
// store data to INI file
FILE* file;
#ifdef AZ_PLATFORM_WINDOWS
_wfopen_s(&file, m_sModuleFileName.c_str(), L"wb");
#else
char fname[MAX_PATH];
memset(fname, 0, MAX_PATH);
wcstombs(fname, m_sModuleFileName.c_str(), MAX_PATH);
file = fopen(fname, "wb");
#endif
if (file == NULL)
{
return false;
}
char buffer[2048];
for (size_t i = 0; i < m_keyValueArray.size(); ++i)
{
const SKeyValue& kv = m_keyValueArray[i];
fprintf_s(file, kv.key.c_str());
fprintf_s(file, " = ");
if (kv.value.length() > 0)
{
SettingsManagerHelpers::ConvertUtf16ToUtf8(kv.value.c_str(), SettingsManagerHelpers::CCharBuffer(buffer, sizeof(buffer)));
fprintf_s(file, "%s", buffer);
}
fprintf_s(file, "\r\n");
}
fclose(file);
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::LoadValuesFromConfigFile(const wchar_t* szFileName)
{
m_keyValueArray.clear();
// read file to memory
FILE* file;
#ifdef AZ_PLATFORM_WINDOWS
_wfopen_s(&file, szFileName, L"rb");
#else
char fname[MAX_PATH];
memset(fname, 0, MAX_PATH);
wcstombs(fname, szFileName, MAX_PATH);
file = fopen(fname, "rb");
#endif
if (file == NULL)
{
return false;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
char* data = new char[size + 1];
fread_s(data, size, 1, size, file);
fclose(file);
wchar_t wBuffer[1024];
// parse file for root path
int start = 0, end = 0;
while (end < size)
{
while (end < size && data[end] != '\n')
{
end++;
}
memcpy(data, &data[start], end - start);
data[end - start] = 0;
start = end = end + 1;
CFixedString<char, 2048> line(data);
size_t equalsOfs;
for (equalsOfs = 0; equalsOfs < line.length(); ++equalsOfs)
{
if (line[equalsOfs] == '=')
{
break;
}
}
if (equalsOfs < line.length())
{
CFixedString<char, 256> key;
CFixedString<wchar_t, 1024> value;
key.appendAscii(line.c_str(), equalsOfs);
key.trim();
SettingsManagerHelpers::ConvertUtf8ToUtf16(line.c_str() + equalsOfs + 1, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer)));
value.append(wBuffer);
value.trim();
m_keyValueArray.set(key.c_str(), value.c_str());
}
}
delete[] data;
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::StoreEngineSettingsToRegistry()
{
assert(m_backend);
return m_backend->StoreEngineSettingsToRegistry();
}
//////////////////////////////////////////////////////////////////////////
void CEngineSettingsManager::LoadEngineSettingsFromRegistry()
{
assert(m_backend);
m_backend->LoadEngineSettingsFromRegistry();
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const
{
if (wbuffer.getSizeInElements() <= 0)
{
return false;
}
const SKeyValue* p = m_keyValueArray.find(key);
if (!p || (p->value.length() + 1) > wbuffer.getSizeInElements())
{
wbuffer[0] = 0;
return false;
}
azwcscpy(wbuffer.getPtr(), wbuffer.getSizeInElements(), p->value.c_str());
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::GetValueByRef(const char* key, bool& value) const
{
wchar_t buffer[100];
if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
return false;
}
value = (wcscmp(buffer, L"true") == 0);
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEngineSettingsManager::GetValueByRef(const char* key, int& value) const
{
wchar_t buffer[100];
if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))))
{
return false;
}
value = wcstol(buffer, 0, 10);
return true;
}
#endif //(CRY_ENABLE_RC_HELPER)
@@ -1,89 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H
#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H
#pragma once
#include "ProjectDefines.h"
#if defined(CRY_ENABLE_RC_HELPER)
#include "SettingsManagerHelpers.h"
class CEngineSettingsBackend;
//////////////////////////////////////////////////////////////////////////
// Manages storage and loading of all information for tools and CryENGINE, by either registry or an INI file.
// Information can be read and set by key-to-value functions.
// Specific information can be set by a dialog application called by this class.
// If the engine root path is not found, a fall-back dialog is opened.
class CEngineSettingsManager
{
public:
// prepares CEngineSettingsManager to get requested information either from registry or an INI file,
// if existent as a file with name an directory equal to the module, or from registry.
CEngineSettingsManager(const wchar_t* moduleName = NULL, const wchar_t* iniFileName = NULL);
~CEngineSettingsManager();
void RestoreDefaults();
// stores/loads user specific information for modules to/from registry or INI file
bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer);
bool GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer);
bool GetModuleSpecificIntEntry(const char* key, int& value);
bool GetModuleSpecificBoolEntry(const char* key, bool& value);
bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str);
bool SetModuleSpecificStringEntryUtf8(const char* key, const char* str);
bool SetModuleSpecificIntEntry(const char* key, const int& value);
bool SetModuleSpecificBoolEntry(const char* key, const bool& value);
bool GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const;
bool GetValueByRef(const char* key, bool& value) const;
bool GetValueByRef(const char* key, int& value) const;
void SetKey(const char* key, const wchar_t* value);
void SetKey(const char* key, bool value);
void SetKey(const char* key, int value);
bool StoreData();
bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path);
void SetParentDialog(size_t window);
private:
bool HasKey(const char* key);
void LoadEngineSettingsFromRegistry();
bool StoreEngineSettingsToRegistry();
// parses a file and stores all flags in a private key-value-map
bool LoadValuesFromConfigFile(const wchar_t* szFileName);
private:
CEngineSettingsBackend *m_backend;
SettingsManagerHelpers::CFixedString<wchar_t, 256> m_sModuleName; // name to store key-value pairs of modules in (registry) or to identify INI file
SettingsManagerHelpers::CFixedString<wchar_t, 256> m_sModuleFileName; // used in case of data being loaded from INI file
bool m_bGetDataFromBackend;
SettingsManagerHelpers::CKeyValueArray<30> m_keyValueArray;
void* m_hBtnBrowse;
size_t m_hWndParent;
};
#endif // CRY_ENABLE_RC_HELPER
#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H
@@ -1,202 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H
#define CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H
#pragma once
#include "CryExtension/CryGUID.h"
#if !defined(LINUX)
#pragma pack(push)
#pragma pack(1)
#define PACK_GCC
#else
#define PACK_GCC __attribute__ ((packed))
#endif
namespace GeomCacheFile
{
// Important: The enums are serialized, don't change the values
// without increasing the file version, conversion code etc!
typedef Vec3_tpl<uint16> Position;
typedef Vec2_tpl<int16> Texcoords;
typedef Vec4_tpl<int16> QTangent;
typedef uint8 Color;
// ASCII "CAXCACHE"
const uint64 kFileSignature = 0x4548434143584143ull;
// The smallest 'UVmax' we'll support - this avoids division by zero when encoding/decoding UVs
const float kMinUVrange = .01f;
// Bit Precision of tangents quaternions
const uint kTangentQuatPrecision = 10;
// Current file version GUID. Files with other GUIDs will not be loaded by the engine.
const CryGUID kCurrentVersion = MAKE_CRYGUID(0x1641defe440af501, 0x7ec5e9164c8c2d1c);
// Mesh prediction look back array size
const uint kMeshPredictorLookBackMaxDist = 4096;
// Number of frames between index frames. Needs to be <= g_kMaxBufferedFrames.
const uint kMaxIFrameDistance = 30;
enum EFileHeaderFlags
{
eFileHeaderFlags_PlaybackFromMemory = BIT(0),
eFileHeaderFlags_32BitIndices = BIT(1)
};
enum EBlockCompressionFormat
{
eBlockCompressionFormat_None = 0,
eBlockCompressionFormat_Deflate = 1, // zlib
eBlockCompressionFormat_LZ4HC = 2, // LZ4 HC
eBlockCompressionFormat_ZSTD = 3, //ZStandard
};
enum EStreams
{
eStream_Indices = BIT(0),
eStream_Positions = BIT(1),
eStream_Texcoords = BIT(2),
eStream_QTangents = BIT(3),
eStream_Colors = BIT(4)
};
enum ETransformType
{
eTransformType_Constant,
eTransformType_Animated
};
enum ENodeType
{
eNodeType_Transform = 0, // Transforms all sub nodes
eNodeType_Mesh = 1,
eNodeType_PhysicsGeometry = 2,
};
// Common frame
enum EFrameType
{
eFrameType_IFrame = 0,
eFrameType_BFrame = 1
};
// Common frame flags
enum EFrameFlags
{
eFrameFlags_Hidden = BIT(0)
};
// Flags for mesh index frames
enum EMeshIFrameFlags
{
eMeshIFrameFlags_UsePredictor = BIT(1)
};
struct SHeader
{
SHeader()
: m_signature(0)
, m_version(kCurrentVersion)
, m_blockCompressionFormat(0)
, m_flags(0)
, m_numFrames(0) {}
uint64 m_signature;
CryGUID m_version;
uint16 m_blockCompressionFormat;
uint32 m_flags;
uint32 m_numFrames;
uint64 m_totalUncompressedAnimationSize;
float m_aabbMin[3];
float m_aabbMax[3];
} PACK_GCC;
struct SFrameInfo
{
uint32 m_frameType;
uint32 m_frameSize;
uint64 m_frameOffset;
float m_frameTime;
} PACK_GCC;
struct SCompressedBlockHeader
{
uint32 m_uncompressedSize;
uint32 m_compressedSize;
} PACK_GCC;
struct SFrameHeader
{
uint32 m_nodeDataOffset;
float m_frameAABBMin[3];
float m_frameAABBMax[3];
uint32 m_padding;
} PACK_GCC;
struct STemporalPredictorControl
{
uint8 m_acceleration;
uint8 m_indexFrameLerpFactor;
uint8 m_combineFactor;
uint8 m_padding;
} PACK_GCC;
struct SMeshFrameHeader
{
uint32 m_flags;
STemporalPredictorControl m_positionStreamPredictorControl;
STemporalPredictorControl m_texcoordStreamPredictorControl;
STemporalPredictorControl m_qTangentStreamPredictorControl;
STemporalPredictorControl m_colorStreamPredictorControl[4];
} PACK_GCC;
struct SMeshInfo
{
uint8 m_constantStreams;
uint8 m_animatedStreams;
uint8 m_positionPrecision[3];
float m_uvMax;
uint8 m_padding;
uint16 m_numMaterials;
uint32 m_numVertices;
uint32 m_flags;
float m_aabbMin[3];
float m_aabbMax[3];
uint32 m_nameLength;
uint64 m_hash;
} PACK_GCC;
struct SNodeInfo
{
uint8 m_type;
uint8 m_bVisible;
uint16 m_transformType;
uint32 m_meshIndex;
uint32 m_numChildren;
uint32 m_nameLength;
} PACK_GCC;
}
#undef PACK_GCC
#if !defined(LINUX)
#pragma pack(pop)
#endif
#endif // CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H
-53
View File
@@ -1,53 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Defines the extension interface for the CryEngine modules.
#ifndef CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H
#define CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H
#pragma once
#include <CryExtension/ICryUnknown.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Console/Console.h>
#include <AzCore/Console/ConsoleFunctor.h>
struct SSystemInitParams;
// Base Interface for all engine module extensions
struct IEngineModule
: public ICryUnknown
{
CRYINTERFACE_DECLARE(IEngineModule, 0xf899cf661df04f61, 0xa341a8a7ffdf9de4);
// <interfuscator:shuffle>
// Retrieve name of the extension module.
virtual const char* GetName() const = 0;
// Retrieve category for the extension module (CryEngine for standard modules).
virtual const char* GetCategory() const = 0;
// This is called to initialize the new module.
virtual bool Initialize(SSystemGlobalEnvironment& env, const SSystemInitParams& initParams) = 0;
// </interfuscator:shuffle>
// This is called to register any AZ console vars declared within this engine module
virtual void RegisterConsoleVars()
{
AZ::ConsoleFunctorBase*& deferredHead = AZ::ConsoleFunctorBase::GetDeferredHead();
AZ::Interface<AZ::IConsole>::Get()->LinkDeferredFunctors(deferredHead);
}
};
#endif // CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H
-228
View File
@@ -1,228 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_IFLARES_H
#define CRYINCLUDE_CRYCOMMON_IFLARES_H
#pragma once
#include <IFuncVariable.h> // <> required for Interfuscator
#include <IXml.h> // <> required for Interfuscator
#include "smartptr.h"
struct IShader;
class CCamera;
class __MFPA
{
};
class __MFPB
{
};
#define MFP_SIZE_ENFORCE : public __MFPA, public __MFPB
enum EFlareType
{
eFT__Base__,
eFT_Root,
eFT_Group,
eFT_Ghost,
eFT_MultiGhosts,
eFT_Glow,
eFT_ChromaticRing,
eFT_IrisShafts,
eFT_CameraOrbs,
eFT_ImageSpaceShafts,
eFT_Streaks,
eFT_Reference,
eFT_Proxy,
eFT_Max
};
#define FLARE_LIBS_PATH "libs/flares/"
#define FLARE_EXPORT_FILE "LensFlareList.xml"
#define FLARE_EXPORT_FILE_VERSION "1"
struct FlareInfo
{
EFlareType type;
const char* name;
#if defined(FLARES_SUPPORT_EDITING)
const char* imagename;
#endif
};
#if defined(FLARES_SUPPORT_EDITING)
# define ADD_FLARE_INFO(type, name, imagename) {type, name, imagename}
#else
# define ADD_FLARE_INFO(type, name, imagename) {type, name}
#endif
class FlareInfoArray
{
public:
struct Props
{
const FlareInfo* p;
size_t size;
};
static const Props Get()
{
static const FlareInfo flareInfoArray[] =
{
ADD_FLARE_INFO(eFT__Base__, "__Base__", NULL),
ADD_FLARE_INFO(eFT_Root, "Root", NULL),
ADD_FLARE_INFO(eFT_Group, "Group", NULL),
ADD_FLARE_INFO(eFT_Ghost, "Ghost", "EngineAssets/Textures/flares/icons/ghost.dds"),
ADD_FLARE_INFO(eFT_MultiGhosts, "Multi Ghost", "EngineAssets/Textures/flares/icons/multi_ghost.dds"),
ADD_FLARE_INFO(eFT_Glow, "Glow", "EngineAssets/Textures/flares/icons/glow.dds"),
ADD_FLARE_INFO(eFT_ChromaticRing, "ChromaticRing", "EngineAssets/Textures/flares/icons/ring.dds"),
ADD_FLARE_INFO(eFT_IrisShafts, "IrisShafts", "EngineAssets/Textures/flares/icons/iris_shafts.dds"),
ADD_FLARE_INFO(eFT_CameraOrbs, "CameraOrbs", "EngineAssets/Textures/flares/icons/orbs.dds"),
ADD_FLARE_INFO(eFT_ImageSpaceShafts, "Vol Shafts", "EngineAssets/Textures/flares/icons/vol_shafts.dds"),
ADD_FLARE_INFO(eFT_Streaks, "Streaks", "EngineAssets/Textures/flares/icons/iris_shafts.dds")
};
Props ret;
ret.p = flareInfoArray;
ret.size = sizeof(flareInfoArray) / sizeof(flareInfoArray[0]);
return ret;
}
private:
FlareInfoArray();
~FlareInfoArray();
};
struct SLensFlareRenderParam
{
SLensFlareRenderParam()
: pCamera(NULL)
, pShader(NULL)
{
}
~SLensFlareRenderParam(){}
bool IsValid() const
{
return pCamera && pShader;
}
CCamera* pCamera;
IShader* pShader;
};
class ISoftOcclusionQuery
{
public:
// <interfuscator:shuffle>
virtual ~ISoftOcclusionQuery() {}
virtual void AddRef() = 0;
virtual void Release() = 0;
// </interfuscator:shuffle>
};
class IOpticsElementBase MFP_SIZE_ENFORCE
{
public:
IOpticsElementBase()
: m_nRefCount(0)
{
}
void AddRef()
{
CryInterlockedIncrement(&m_nRefCount);
}
void Release()
{
if (CryInterlockedDecrement(&m_nRefCount) <= 0)
{
delete this;
}
}
// <interfuscator:shuffle>
virtual EFlareType GetType() = 0;
virtual bool IsGroup() const = 0;
virtual string GetName() const = 0;
virtual void SetName(const char* ch_name) = 0;
virtual void Load(IXmlNode* pNode) = 0;
virtual IOpticsElementBase* GetParent() const = 0;
virtual ~IOpticsElementBase() {
}
virtual bool IsEnabled() const = 0;
virtual void AddElement(IOpticsElementBase* pElement) = 0;
virtual void InsertElement(int nPos, IOpticsElementBase* pElement) = 0;
virtual void Remove(int i) = 0;
virtual void RemoveAll() = 0;
virtual int GetElementCount() const = 0;
virtual IOpticsElementBase* GetElementAt(int i) const = 0;
virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0;
virtual void Invalidate() = 0;
virtual void Render(SLensFlareRenderParam* pParam, const Vec3& vPos) = 0;
virtual void SetOpticsReference([[maybe_unused]] IOpticsElementBase* pReference) {}
virtual IOpticsElementBase* GetOpticsReference() const { return NULL; }
// </interfuscator:shuffle>
#if defined(FLARES_SUPPORT_EDITING)
virtual AZStd::vector<FuncVariableGroup> GetEditorParamGroups() = 0;
#endif
///Basic Setters///////////////////////////////////////////////////////////////
virtual void SetEnabled(bool enabled) { (void)enabled; }
virtual void SetSize(float size) { (void)size; }
virtual void SetPerspectiveFactor(float perspectiveFactor) { (void)perspectiveFactor; }
virtual void SetDistanceFadingFactor(float distanceFadingFactor) { (void)distanceFadingFactor; }
virtual void SetBrightness(float brightness) { (void)brightness; }
virtual void SetColor(ColorF color) { (void)color; }
virtual void SetMovement(Vec2 movement) { (void)movement; }
virtual void SetTransform(const Matrix33& xform) { (void)xform; }
virtual void SetOccBokehEnabled(bool occBokehEnabled) { (void)occBokehEnabled; }
virtual void SetOrbitAngle(float orbitAngle) { (void)orbitAngle; }
virtual void SetSensorSizeFactor(float sizeFactor) { (void)sizeFactor; }
virtual void SetSensorBrightnessFactor(float brightnessFactor) { (void)brightnessFactor; }
virtual void SetAutoRotation(bool autoRotation) { (void)autoRotation; }
virtual void SetAspectRatioCorrection(bool aspectRatioCorrection) { (void)aspectRatioCorrection; }
////////////////////////////////////////////////////////////////////////////////
private:
volatile int m_nRefCount;
};
class IOpticsManager
{
public:
// <interfuscator:shuffle>
virtual ~IOpticsManager(){}
virtual void Reset() = 0;
virtual IOpticsElementBase* Create(EFlareType type) const = 0;
virtual bool Load(const char* fullFlareName, int& nOutIndex, bool forceReload = false) = 0;
virtual bool Load(XmlNodeRef& rootNode, int& nOutIndex) = 0;
virtual IOpticsElementBase* GetOptics(int nIndex) = 0;
virtual bool AddOptics(IOpticsElementBase* pOptics, const char* name, int& nOutNewIndex, bool allowReplace = false) = 0;
virtual bool Rename(const char* fullFlareName, const char* newFullFlareName) = 0;
virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0;
virtual void Invalidate() = 0;
// </interfuscator:shuffle>
};
typedef _smart_ptr<IOpticsElementBase> IOpticsElementBasePtr;
#endif // CRYINCLUDE_CRYCOMMON_IFLARES_H
-504
View File
@@ -1,504 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Interface to the Material Effects System
#ifndef CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H
#define CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H
#pragma once
#if !defined(_RELEASE)
#define MATERIAL_EFFECTS_DEBUG
#endif
#include "CryFixedArray.h"
struct IRenderNode;
struct ISurfaceType;
//////////////////////////////////////////////////////////////////////////
enum EMFXPlayFlags
{
eMFXPF_Disable_Delay = BIT(0),
eMFXPF_Audio = BIT(1),
eMFXPF_Decal = BIT(2),
eMFXPF_Particles = BIT(3),
eMFXPF_Deprecated0 = BIT(4), // formerly eMFXPF_Flowgraph
eMFXPF_ForceFeedback = BIT(5),
eMFXPF_All = (eMFXPF_Audio | eMFXPF_Decal | eMFXPF_Particles | eMFXPF_Deprecated0 | eMFXPF_ForceFeedback),
};
#define MFX_INVALID_ANGLE (gf_PI2 + 1)
//////////////////////////////////////////////////////////////////////////
struct SMFXAudioEffectRtpc
{
SMFXAudioEffectRtpc()
{
rtpcName = "";
rtpcValue = 0.0f;
}
const char* rtpcName;
float rtpcValue;
};
//////////////////////////////////////////////////////////////////////////
struct SMFXRunTimeEffectParams
{
static const int MAX_AUDIO_RTPCS = 4;
SMFXRunTimeEffectParams()
: playSoundFP(false)
, playflags(eMFXPF_All)
, fLastTime(0.0f)
, srcSurfaceId(0)
, trgSurfaceId(0)
, srcRenderNode(0)
, trgRenderNode(0)
, partID(0)
, pos(ZERO)
, decalPos(ZERO)
, normal(0.0f, 0.0f, 1.0f)
, angle(MFX_INVALID_ANGLE)
, scale(1.0f)
, audioComponentOffset(ZERO)
, numAudioRtpcs(0)
, fDecalPlacementTestMaxSize(1000.f)
{
dir[0].Set(0.0f, 0.0f, -1.0f);
dir[1].Set(0.0f, 0.0f, 1.0f);
}
bool AddAudioRtpc(const char* name, float val)
{
if (numAudioRtpcs < MAX_AUDIO_RTPCS)
{
audioRtpcs[numAudioRtpcs].rtpcName = name;
audioRtpcs[numAudioRtpcs].rtpcValue = val;
++numAudioRtpcs;
return true;
}
return false;
}
void ResetAudioRtpcs()
{
numAudioRtpcs = 0;
}
public:
uint16 playSoundFP; // Sets 1p/3p audio switch
uint16 playflags; // See EMFXPlayFlags
float fLastTime; // Last time this effect was played
float fDecalPlacementTestMaxSize;
int srcSurfaceId;
int trgSurfaceId;
IRenderNode* srcRenderNode;
IRenderNode* trgRenderNode;
int partID;
Vec3 pos;
Vec3 decalPos;
Vec3 dir[2];
Vec3 normal;
float angle;
float scale;
// audio related
Vec3 audioComponentOffset; // in case of audio component, uses this offset
SMFXAudioEffectRtpc audioRtpcs[MAX_AUDIO_RTPCS];
uint32 numAudioRtpcs;
};
struct SMFXBreakageParams
{
enum EBreakageRequestFlags
{
eBRF_Matrix = BIT(0),
eBRF_HitPos = BIT(1),
eBRF_HitImpulse = BIT(2),
eBRF_Velocity = BIT(3),
eBRF_ExplosionImpulse = BIT(4),
eBRF_Mass = BIT(5),
eBFR_Entity = BIT(6),
};
SMFXBreakageParams()
: m_flags(0)
, m_worldTM(IDENTITY)
, m_vHitPos(ZERO)
, m_vHitImpulse(IDENTITY)
, m_vVelocity(ZERO)
, m_fExplosionImpulse(1.0f)
, m_fMass(0.0f)
{
}
// Matrix
void SetMatrix(const Matrix34& worldTM)
{
m_worldTM = worldTM;
SetFlag(eBRF_Matrix);
}
const Matrix34& GetMatrix() const
{
return m_worldTM;
}
// HitPos
void SetHitPos(const Vec3& vHitPos)
{
m_vHitPos = vHitPos;
SetFlag(eBRF_HitPos);
}
const Vec3& GetHitPos() const
{
return m_vHitPos;
}
// HitImpulse
void SetHitImpulse(const Vec3& vHitImpulse)
{
m_vHitImpulse = vHitImpulse;
SetFlag(eBRF_HitImpulse);
}
const Vec3& GetHitImpulse() const
{
return m_vHitImpulse;
}
// Velocity
void SetVelocity(const Vec3& vVelocity)
{
m_vVelocity = vVelocity;
SetFlag(eBRF_Velocity);
}
const Vec3& GetVelocity() const
{
return m_vVelocity;
}
// Explosion Impulse
void SetExplosionImpulse(float fExplosionImpulse)
{
m_fExplosionImpulse = fExplosionImpulse;
SetFlag(eBRF_ExplosionImpulse);
}
float GetExplosionImpulse() const
{
return m_fExplosionImpulse;
}
// Mass
void SetMass(float fMass)
{
m_fMass = fMass;
SetFlag(eBRF_Mass);
}
float GetMass() const
{
return m_fMass;
}
// Checking for flags
bool CheckFlag(EBreakageRequestFlags flag) const
{
return (m_flags & flag) != 0;
}
protected:
void SetFlag(EBreakageRequestFlags flag)
{
m_flags |= flag;
}
void ClearFlag(EBreakageRequestFlags flag)
{
m_flags &= ~flag;
}
uint32 m_flags;
Matrix34 m_worldTM;
Vec3 m_vHitPos;
Vec3 m_vHitImpulse;
Vec3 m_vVelocity;
float m_fExplosionImpulse;
float m_fMass;
};
class IMFXParticleParams
{
public:
IMFXParticleParams()
: name(NULL)
, userdata(NULL)
, scale(1.0f)
{
}
const char* name;
const char* userdata;
float scale;
};
class SMFXParticleListNode
{
public:
static SMFXParticleListNode* Create();
void Destroy();
static void FreePool();
IMFXParticleParams m_particleParams;
SMFXParticleListNode* pNext;
private:
SMFXParticleListNode()
{
pNext = NULL;
}
~SMFXParticleListNode() {}
};
class IMFXAudioParams
{
const static uint MAX_SWITCH_DATA_ELEMENTS = 4;
public:
struct SSwitchData
{
SSwitchData()
: switchName(NULL)
, switchStateName(NULL)
{
}
const char* switchName;
const char* switchStateName;
};
IMFXAudioParams()
: triggerName(NULL)
{
}
const char* triggerName;
CryFixedArray<SSwitchData, MAX_SWITCH_DATA_ELEMENTS> triggerSwitches;
};
class SMFXAudioListNode
{
public:
static SMFXAudioListNode* Create();
void Destroy();
static void FreePool();
IMFXAudioParams m_audioParams;
SMFXAudioListNode* pNext;
private:
SMFXAudioListNode()
: pNext(NULL)
{
}
~SMFXAudioListNode()
{
}
};
class IMFXDecalParams
{
public:
IMFXDecalParams()
{
filename = 0;
material = 0;
minscale = 1.f;
maxscale = 1.f;
rotation = -1.f;
lifetime = 10.0f;
assemble = false;
forceedge = false;
}
const char* filename;
const char* material;
float minscale;
float maxscale;
float rotation;
float lifetime;
bool assemble;
bool forceedge;
};
class SMFXDecalListNode
{
public:
static SMFXDecalListNode* Create();
void Destroy();
static void FreePool();
IMFXDecalParams m_decalParams;
SMFXDecalListNode* pNext;
private:
SMFXDecalListNode()
{
pNext = 0;
}
~SMFXDecalListNode() {}
};
class IMFXForceFeedbackParams
{
public:
IMFXForceFeedbackParams()
: forceFeedbackEventName (NULL)
, intensityFallOffMinDistanceSqr(0.0f)
, intensityFallOffMaxDistanceSqr(0.0f)
{
}
const char* forceFeedbackEventName;
float intensityFallOffMinDistanceSqr;
float intensityFallOffMaxDistanceSqr;
};
class SMFXForceFeedbackListNode
{
public:
static SMFXForceFeedbackListNode* Create();
void Destroy();
static void FreePool();
IMFXForceFeedbackParams m_forceFeedbackParams;
SMFXForceFeedbackListNode* pNext;
private:
SMFXForceFeedbackListNode()
: pNext(NULL)
{
}
~SMFXForceFeedbackListNode() {}
};
struct SMFXResourceList;
typedef _smart_ptr<SMFXResourceList> SMFXResourceListPtr;
struct SMFXResourceList
{
public:
SMFXParticleListNode* m_particleList;
SMFXAudioListNode* m_audioList;
SMFXDecalListNode* m_decalList;
SMFXForceFeedbackListNode* m_forceFeedbackList;
void AddRef() { ++m_refs; }
void Release()
{
if (--m_refs <= 0)
{
Destroy();
}
}
static SMFXResourceListPtr Create();
static void FreePool();
private:
int m_refs;
virtual void Destroy();
SMFXResourceList()
: m_refs(0)
{
m_particleList = 0;
m_audioList = 0;
m_decalList = 0;
m_forceFeedbackList = 0;
}
virtual ~SMFXResourceList()
{
while (m_particleList != 0)
{
SMFXParticleListNode* next = m_particleList->pNext;
m_particleList->Destroy();
m_particleList = next;
}
while (m_audioList != 0)
{
SMFXAudioListNode* next = m_audioList->pNext;
m_audioList->Destroy();
m_audioList = next;
}
while (m_decalList != 0)
{
SMFXDecalListNode* next = m_decalList->pNext;
m_decalList->Destroy();
m_decalList = next;
}
while (m_forceFeedbackList != 0)
{
SMFXForceFeedbackListNode* next = m_forceFeedbackList->pNext;
m_forceFeedbackList->Destroy();
m_forceFeedbackList = next;
}
}
};
typedef uint16 TMFXEffectId;
static const TMFXEffectId InvalidEffectId = 0;
struct SMFXCustomParamValue
{
float fValue;
};
//////////////////////////////////////////////////////////////////////////
struct IMaterialEffects
{
// <interfuscator:shuffle>
virtual ~IMaterialEffects(){}
virtual void LoadFXLibraries() = 0;
virtual void Reset(bool bCleanup) = 0;
virtual void ClearDelayedEffects() = 0;
virtual TMFXEffectId GetEffectIdByName(const char* libName, const char* effectName) = 0;
virtual TMFXEffectId GetEffectId(int surfaceIndex1, int surfaceIndex2) = 0;
virtual TMFXEffectId GetEffectId(const char* customName, int surfaceIndex2) = 0;
virtual SMFXResourceListPtr GetResources(TMFXEffectId effectId) const = 0;
virtual void PreLoadAssets() = 0;
virtual bool ExecuteEffect(TMFXEffectId effectId, SMFXRunTimeEffectParams& runtimeParams) = 0;
virtual int GetDefaultSurfaceIndex() = 0;
virtual int GetDefaultCanopyIndex() = 0;
virtual bool PlayBreakageEffect(ISurfaceType* pSurfaceType, const char* breakageType, const SMFXBreakageParams& mfxBreakageParams) = 0;
virtual void SetCustomParameter(TMFXEffectId effectId, const char* customParameter, const SMFXCustomParamValue& customParameterValue) = 0;
virtual void CompleteInit() = 0;
// </interfuscator:shuffle>
};
#endif // CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H
@@ -1,147 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H
#define CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H
#pragma once
// Constants
#define NN_CHANNEL_NAME_LENGTH_MAX 16
struct INotificationNetworkClient;
// User Interfaces
struct INotificationNetworkListener
{
// <interfuscator:shuffle>
virtual ~INotificationNetworkListener(){}
// Called upon receiving data from the Channel the Listener is binded to.
virtual void OnNotificationNetworkReceive(const void* pBuffer, size_t length) = 0;
// </interfuscator:shuffle>
};
struct INotificationNetworkConnectionCallback
{
// <interfuscator:shuffle>
virtual ~INotificationNetworkConnectionCallback(){}
virtual void OnConnect(INotificationNetworkClient* pClient, bool bSucceeded) = 0;
virtual void OnDisconnected(INotificationNetworkClient* pClient) = 0;
// </interfuscator:shuffle>
};
// Interfaces
struct INotificationNetworkClient
{
// <interfuscator:shuffle>
virtual ~INotificationNetworkClient(){}
virtual void Release() = 0;
// Binds a Listener to the given Notification Channel.
// Each Listener can be binded only to one Channel, calling the method
// again with an already added Listener and a different Channel will rebind it.
// The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars.
virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0;
// If it exist, removes the given Listener form the Notification Network.
virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0;
// Sends arbitrary data to the Notification Network the Client is connected to.
virtual bool Send(const char* channelName, const void* pBuffer, size_t length) = 0;
// Checks if the current client is connected.
// Returns true if it is connected, false otherwise.
virtual bool IsConnected() = 0;
// Checks if the connection attempt failed.
// Returns true if it failed to connect by any reason (such as timeout).
virtual bool IsFailedToConnect() const = 0;
// Start the connection request for this particular client.
// Parameters:
// address - Is the host name or ipv4 (for now) address string to which
// we want to connect.
// port - Is the TCP port to which we want to connect.
// Remarks: Port 9432 is being used by the live preview already.
virtual bool Connect(const char* address, uint16 port) = 0;
// Tries to register a callback listener object.
// A callback listener object will receive events from the client element,
// such as connection result information.
// Parameters:
// - pConnectionCallback - Is a pointer to an object implementing interface
// INotificationNetworkConnectionCallback which will be called when
// the events happen, such as connection, disconnection and failed attempt
// to connect.
// Return Value:
// - It will return true if registered the callback object successfully.
// - It will return false when there the callback object is already
// registered.
virtual bool RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0;
// Tries to unregister a callback listener object.
// A callback listener object will receive events from the client element,
// such as connection result information.
// Parameters:
// - pConnectionCallback - Is a pointer to an object implementing interface
// INotificationNetworkConnectionCallback which will be called when
// the events happen, such as connection, disconnection and failed attempt
// to connect and that we want to unregister.
// Return Value:
// - It will return true if unregistered the callback object successfully.
// - It will return false when no object matching the one requested is found
// int the object.
virtual bool UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0;
// </interfuscator:shuffle>
};
struct INotificationNetwork
{
// <interfuscator:shuffle>
virtual ~INotificationNetwork(){}
virtual void Release() = 0;
// Creates a disconnected client.
virtual INotificationNetworkClient* CreateClient() = 0;
// Attempts to connect to the Notification Network at the given address,
// returns a Client interface if communication is possible.
virtual INotificationNetworkClient* Connect(const char* address, uint16 port) = 0;
// Returns the Connection count of the given Channel. If NULL is passed
// instead of a valid Channel name the total count of all Connections is
// returned.
virtual size_t GetConnectionCount(const char* channelName = NULL) = 0;
// Has to be called from the main thread to process received notifications.
virtual void Update() = 0;
// Binds a Listener to the given Notification Channel.
// Each Listener can be binded only to one Channel, calling the method
// again with an already added Listener and a different Channel will rebind it.
// The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars.
virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0;
// If it exist, removes the given Listener form the Notification Network.
virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0;
// Sends arbitrary data to all the Connections listening to the given Channel.
virtual uint32 Send(const char* channel, const void* pBuffer, size_t length) = 0;
// </interfuscator:shuffle>
};
#endif // CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H
-763
View File
@@ -1,763 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Service network interface
#ifndef CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H
#define CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H
#pragma once
#include <CryString.h>
#include <BaseTypes.h>
//-----------------------------------------------------------------------------
// Helpers for writing/reading command data stream from network message packets.
// Those interfaces automatically handle byteswapping for big endian systems.
// The native format for data inside the messages is little endian.
//-----------------------------------------------------------------------------
/// Write stream interface
struct IDataWriteStream
{
public:
virtual ~IDataWriteStream() {};
public:
// Virtualized write method for general data buffer
virtual void Write(const void* pData, const uint32 size) = 0;
// Virtualized write method for types with size 8 (support byteswapping, a little bit faster than general case)
virtual void Write8(const void* pData) = 0;
// Virtualized write method for types with size 4 (support byteswapping, a little bit faster than general case)
virtual void Write4(const void* pData) = 0;
// Virtualized write method for types with size 2 (support byteswapping, a little bit faster than general case)
virtual void Write2(const void* pData) = 0;
// Virtualized write method for types with size 1 (a little bit faster than general case)
virtual void Write1(const void* pData) = 0;
// Get number of bytes written
virtual const uint32 GetSize() const = 0;
// Convert to service network message
virtual struct IServiceNetworkMessage* BuildMessage() const = 0;
// Save the data from this writer stream to the provided buffer
virtual void CopyToBuffer(void* pData) const = 0;
// Destroy object (if dynamically created)
virtual void Delete() = 0;
public:
IDataWriteStream& operator<<(const uint8& val)
{
Write1(&val);
return *this;
}
IDataWriteStream& operator<<(const uint16& val)
{
Write2(&val);
return *this;
}
IDataWriteStream& operator<<(const uint32& val)
{
Write4(&val);
return *this;
}
IDataWriteStream& operator<<(const uint64& val)
{
Write8(&val);
return *this;
}
IDataWriteStream& operator<<(const int8& val)
{
Write1(&val);
return *this;
}
IDataWriteStream& operator<<(const int16& val)
{
Write2(&val);
return *this;
}
IDataWriteStream& operator<<(const int32& val)
{
Write4(&val);
return *this;
}
IDataWriteStream& operator<<(const int64& val)
{
Write8(&val);
return *this;
}
IDataWriteStream& operator<<(const float& val)
{
Write4(&val);
return *this;
}
// Bool is saved by writing an 8 bit value to make it portable
IDataWriteStream& operator<<(const bool& val)
{
const uint8 uVal = val ? 1 : 0;
Write1(&uVal);
return *this;
}
public:
// Write C string to stream
void WriteString(const char* str);
// Write string to stream
void WriteString(const string& str);
// Write int8 value to stream
void WriteInt8(const int8 val)
{
Write1(&val);
}
// Write int16 value to stream
void WriteInt16(const int16 val)
{
Write2(&val);
}
// Write int32 value to stream
void WriteInt32(const int32 val)
{
Write4(&val);
}
// Write int64 value to stream
void WriteInt64(const int64 val)
{
Write8(&val);
}
// Write uint8 value to stream
void WriteUint8(const uint8 val)
{
Write1(&val);
}
// Write uint16 value to stream
void WriteUint16(const uint16 val)
{
Write2(&val);
}
// Write uint32 value to stream
void WriteUint32(const uint32 val)
{
Write4(&val);
}
// Write uint64 value to stream
void WriteUint64(const uint64 val)
{
Write8(&val);
}
// Write float value to stream
void WriteFloat(const float val)
{
Write4(&val);
}
};
//-----------------------------------------------------------------------------
/// Read stream interface
/// This interface should support endianess swapping
struct IDataReadStream
{
public:
virtual ~IDataReadStream() {};
public:
// Destroy object (if dynamically created)
virtual void Delete() = 0;
// Skip given amount of data without reading it
virtual void Skip(const uint32 size) = 0;
// Virtualized read method (for general buffers)
virtual void Read(void* pData, const uint32 size) = 0;
// Virtualized read method for types with size 8 (a little bit faster than general method, supports byte swapping for BE systems)
virtual void Read8(void* pData) = 0;
// Virtualized read method for types with size 4 (a little bit faster than general method, supports byte swapping for BE systems)
virtual void Read4(void* pData) = 0;
// Virtualized read method for types with size 2 (a little bit faster than general method, supports byte swapping for BE systems)
virtual void Read2(void* pData) = 0;
// Virtualized read method for types with size 1 (a little bit faster than general method, supports byte swapping for BE systems)
virtual void Read1(void* pData) = 0;
// Optimization case - get direct pointer to the underlying buffer
virtual const void* GetPointer() = 0;
public:
IDataReadStream& operator<<(uint8& val)
{
Read1(&val);
return *this;
}
IDataReadStream& operator<<(uint16& val)
{
Read2(&val);
return *this;
}
IDataReadStream& operator<<(uint32& val)
{
Read4(&val);
return *this;
}
IDataReadStream& operator<<(uint64& val)
{
Read8(&val);
return *this;
}
IDataReadStream& operator<<(int8& val)
{
Read1(&val);
return *this;
}
IDataReadStream& operator<<(int16& val)
{
Read2(&val);
return *this;
}
IDataReadStream& operator<<(int32& val)
{
Read4(&val);
return *this;
}
IDataReadStream& operator<<(int64& val)
{
Read8(&val);
return *this;
}
IDataReadStream& operator<<(float& val)
{
Read4(&val);
return *this;
}
// Bool is saved by writing an 8 bit value to make it portable
IDataReadStream& operator<<(bool& val)
{
uint8 uVal = 0;
Read1(&uVal);
val = (uVal != 0);
return *this;
}
public:
// Read string from stream
string ReadString();
// Skip string data in a stream without loading the data
void SkipString();
// Read int8 from stream
int8 ReadInt8()
{
int8 val = 0;
Read1(&val);
return val;
}
// Read int16 from stream
int16 ReadInt16()
{
int16 val = 0;
Read2(&val);
return val;
}
// Read int32 from stream
int32 ReadInt32()
{
int32 val = 0;
Read4(&val);
return val;
}
// Read int64 from stream
int64 ReadInt64()
{
int64 val = 0;
Read8(&val);
return val;
}
// Read uint8 from stream
uint8 ReadUint8()
{
uint8 val = 0;
Read1(&val);
return val;
}
// Read uint16 from stream
uint16 ReadUint16()
{
uint16 val = 0;
Read2(&val);
return val;
}
// Read uint32 from stream
uint32 ReadUint32()
{
uint32 val = 0;
Read4(&val);
return val;
}
// Read int64 from stream
uint64 ReadUint64()
{
uint64 val = 0;
Read8(&val);
return val;
}
// Read float from stream
float ReadFloat()
{
float val = 0.0f;
Read4(&val);
return val;
}
};
//-----------------------------------------------------------------------------
/// Remote command class info (simple RTTI)
struct IRemoteCommandClass
{
public:
virtual ~IRemoteCommandClass() {};
// Get class name
virtual const char* GetName() const = 0;
// Create command instance
virtual struct IRemoteCommand* CreateObject() = 0;
};
/// Remote command interface
struct IRemoteCommand
{
protected:
virtual ~IRemoteCommand() {};
public:
// Get command class
virtual IRemoteCommandClass* GetClass() const = 0;
// Save to data stream
virtual void SaveToStream(struct IDataWriteStream& writeStream) const = 0;
// Load from data stream
virtual void LoadFromStream(struct IDataReadStream& readStream) = 0;
// Execute (remote call) = 0;
virtual void Execute() = 0;
// Delete the command object (can be allocated from different heap)
virtual void Delete() = 0;
};
//-----------------------------------------------------------------------------
// This is a implementation of a synchronous listener (limited to the engine tick rate)
// that processes and responds to the raw messages received from clients.
struct IRemoteCommandListenerSync
{
public:
virtual ~IRemoteCommandListenerSync() {};
// Process a raw message and optionally provide an answer to the request, return true if you have processed the message.
// Messages is accessible via the data reader. Response can be written to a data writer.
virtual bool OnRawMessageSync(const class ServiceNetworkAddress& remoteAddress, struct IDataReadStream& msg, struct IDataWriteStream& response) = 0;
};
//-----------------------------------------------------------------------------
// This is a implementation of a asynchronous listener (called from network thread)
// that processes and responds to the raw messages received from clients.
struct IRemoteCommandListenerAsync
{
public:
virtual ~IRemoteCommandListenerAsync() {};
// Process a raw message and optionally provide an answer to the request, return true if you have processed the message.
// Messages is accessible via the data reader. Response can be written to a data writer.
virtual bool OnRawMessageAsync(const class ServiceNetworkAddress& remoteAddress, struct IDataReadStream& msg, struct IDataWriteStream& response) = 0;
};
//-----------------------------------------------------------------------------
/// Remote command server
struct IRemoteCommandServer
{
protected:
virtual ~IRemoteCommandServer() {};
public:
// Execute all of the received pending commands
// This should be called from a safe place (main thread)
virtual void FlushCommandQueue() = 0;
// Suppress command execution
virtual void SuppressCommands() = 0;
// Resume command execution
virtual void ResumeCommands() = 0;
// Register/Unregister synchronous message listener (limited to tick rate)
virtual void RegisterSyncMessageListener(IRemoteCommandListenerSync* pListener) = 0;
virtual void UnregisterSyncMessageListener(IRemoteCommandListenerSync* pListener) = 0;
// Register/Unregister asynchronous message listener (called from network thread)
virtual void RegisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) = 0;
virtual void UnregisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) = 0;
// Broadcast a message to all connected clients
virtual void Broadcast(IServiceNetworkMessage* pMessage) = 0;
// Do we have any clients connected ?
virtual bool HasConnectedClients() const = 0;
// Delete the client
virtual void Delete() = 0;
};
//-----------------------------------------------------------------------------
/// Connection to remote command server
struct IRemoteCommandConnection
{
protected:
virtual ~IRemoteCommandConnection() {};
public:
// Are we connected ?
// This returns false when the underlying network connection has failed (sockets error).
// Also, this returns false if the remote connection was closed by remote peer.
virtual bool IsAlive() const = 0;
// Get address of remote command server
// This returns the full address of the endpoint (with valid port)
virtual const ServiceNetworkAddress& GetRemoteAddress() const = 0;
// Send raw message to the other side of this connection.
// Raw messages are not buffer and are sent right away,
// they also have precedence over internal command traffic.
// The idea is that you need some kind of bidirectional signaling
// channel to extend the rather one-directional nature of commands.
// Returns true if message was added to the send queue.
virtual bool SendRawMessage(IServiceNetworkMessage* pMessage) = 0;
// See if there's a raw message waiting for us and if it is, get it
// Be aware that messages are reference counted.
virtual IServiceNetworkMessage* ReceiveRawMessage() = 0;
// Close connection
// - pending commands are not sent
// - pending raw messages are sent or not (depending on the flag)
virtual void Close(bool bFlushQueueBeforeClosing = false) = 0;
// Add internal reference to object (Refcounting interface)
virtual void AddRef() = 0;
// Release internal reference to object (Refcounting interface)
virtual void Release() = 0;
};
//-----------------------------------------------------------------------------
/// Remote command client
struct IRemoteCommandClient
{
protected:
virtual ~IRemoteCommandClient() {};
public:
// Connect to remote server, returns true on success, false on failure
virtual IRemoteCommandConnection* ConnectToServer(const class ServiceNetworkAddress& serverAddress) = 0;
// Schedule command to be executed on the all of the remote servers
virtual bool Schedule(const IRemoteCommand& command) = 0;
// Delete the client object
virtual void Delete() = 0;
};
//-----------------------------------------------------------------------------
/// Remote command manager
struct IRemoteCommandManager
{
public:
virtual ~IRemoteCommandManager() {};
// Set debug message verbose level
virtual void SetVerbosityLevel(const uint32 level) = 0;
// Create local server for executing remote commands on given local port
virtual IRemoteCommandServer* CreateServer(uint16 localPort) = 0;
// Create client interface for executing remote commands on remote servers
virtual IRemoteCommandClient* CreateClient() = 0;
// Register command class (will be accessible by both clients and server)
virtual void RegisterCommandClass(IRemoteCommandClass& commandClass) = 0;
};
//-----------------------------------------------------------------------------
/// Class RTTI wrapper for remote command classes
template< typename T >
class CRemoteCommandClass
: public IRemoteCommandClass
{
private:
const char* m_szName;
public:
CRemoteCommandClass(const char* szName)
: m_szName(szName)
{}
virtual const char* GetName() const
{
return m_szName;
}
virtual struct IRemoteCommand* CreateObject()
{
return new T();
}
};
#define DECLARE_REMOTE_COMMAND(x) \
public: static IRemoteCommandClass& GetStaticClass() { \
static IRemoteCommandClass* theClass = new CRemoteCommandClass<x>(#x); return *theClass; } \
public: virtual IRemoteCommandClass* GetClass() const { return &GetStaticClass(); } \
public: virtual void Delete() { delete this; } \
public: virtual void SaveToStream(IDataWriteStream & writeStream) const { const_cast<x*>(this)->Serialize<IDataWriteStream>(writeStream); } \
public: virtual void LoadFromStream(IDataReadStream & readStream) { Serialize<IDataReadStream>(readStream); }
//-----------------------------------------------------------------------------
/// CryString serialization helper (read)
inline IDataReadStream& operator<<(IDataReadStream& stream, string& outString)
{
const uint32 kMaxTempString = 256;
// read length
uint32 length = 0;
stream << length;
// load string
if (length > 0)
{
if (length < kMaxTempString)
{
// load the string into temporary buffer
char temp[kMaxTempString];
stream.Read(&temp, length);
temp[length] = 0;
// set the string with new value
outString = temp;
}
else
{
// allocate temporary memory and load the string
std::vector<char> temp;
temp.resize(length + 1, 0);
stream.Read(&temp[0], length);
// set the string with new value
outString = &temp[0];
}
}
else
{
// empty string
outString.clear();
}
return stream;
}
/// CryString serialization helper (write)
inline IDataWriteStream& operator<<(IDataWriteStream& stream, const string& str)
{
// write length
const uint32 length = static_cast<uint32>(str.length());
stream << length;
// write string data
if (length > 0)
{
stream.Write(str.c_str(), length);
}
return stream;
}
//------------------------------------------------------------------------
/// Vector serialization helper (reading)
template< class T >
IDataReadStream& operator<<(IDataReadStream& ar, std::vector<T>& outVector)
{
// Load item count
uint32 count = 0;
ar << count;
// Adapt the vector size (exact fit)
outVector.resize(count);
// Load items
for (uint32 i = 0; i < count; ++i)
{
ar << outVector[i];
}
return ar;
}
/// Vector serialization helper (writing)
template< class T >
IDataWriteStream& operator<<(IDataWriteStream& ar, const std::vector<T>& vec)
{
// Save item count
const uint32 count = vec.size();
ar << count;
// Save items
for (uint32 i = 0; i < count; ++i)
{
ar << const_cast<T&>(vec[i]);
}
return ar;
}
//------------------------------------------------------------------------
inline void IDataWriteStream::WriteString(const char* str)
{
string tempString(str);
*this << tempString;
}
inline void IDataWriteStream::WriteString(const string& str)
{
*this << str;
}
inline string IDataReadStream::ReadString()
{
string ret;
*this << ret;
return ret;
}
inline void IDataReadStream::SkipString()
{
// read length
uint32 length = 0;
*this << length;
Skip(length);
}
//------------------------------------------------------------------------
// Helper class for using the data reader and writer classes
// The only major differce betwen auto_ptr is that we call Delete() instead of operator delete
template<class T>
class TAutoDelete
{
public:
T* m_ptr;
public:
TAutoDelete(T* ptr)
: m_ptr(ptr)
{
}
~TAutoDelete()
{
if (NULL != m_ptr)
{
m_ptr->Delete();
m_ptr = NULL;
}
}
operator bool()
{
return (NULL != m_ptr);
}
operator T& ()
{
return *m_ptr;
}
T* operator->()
{
return m_ptr;
}
private:
TAutoDelete(const TAutoDelete& other)
: m_ptr(NULL){};
TAutoDelete& operator=(const TAutoDelete& other) { return *this; }
};
//------------------------------------------------------------------------
#endif // CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H
+3 -25
View File
@@ -16,12 +16,12 @@
#include "Cry_Geo.h"
#include "Cry_Camera.h"
#include "ITexture.h"
#include <IFlares.h> // <> required for Interfuscator
#include <IFuncVariable.h> // <> required for Interfuscator
#include <IXml.h> // <> required for Interfuscator
#include "smartptr.h"
#include <AzCore/Casting/numeric_cast.h>
#include <AzCore/std/containers/intrusive_slist.h>
#include "IResourceCompilerHelper.h" // for IResourceCompilerHelper::ERcCallResult
// forward declarations
struct SRenderingPassInfo;
struct SRTStack;
@@ -95,7 +95,6 @@ struct IFFont;
struct IFFont_RenderProxy;
struct STextDrawContext;
struct IRenderMesh;
class IOpticsManager;
struct ShadowFrustumMGPUCache;
struct IAsyncTextureCompileListener;
struct IClipVolume;
@@ -955,25 +954,6 @@ protected:
virtual ~ITextureStreamListener() {}
};
#if defined(CRY_ENABLE_RC_HELPER)
////////////////////////////////////////////////////////////////////////////
// Listener for asynchronous texture compilation.
// Connects the listener to the task-queue of pending compilation requests.
enum ERcExitCode;
struct IAsyncTextureCompileListener
{
public:
virtual void OnCompilationStarted(const char* source, const char* target, int nPending) = 0;
virtual void OnCompilationFinished(const char* source, const char* target, IResourceCompilerHelper::ERcCallResult nReturnCode) = 0;
virtual void OnCompilationQueueTriggered(int nPending) = 0;
virtual void OnCompilationQueueDepleted() = 0;
protected:
virtual ~IAsyncTextureCompileListener() {}
};
#endif
enum eDolbyVisionMode
{
eDVM_Disabled,
@@ -1869,8 +1849,6 @@ struct IRenderer
virtual SDepthTexture* CreateDepthSurface(int nWidth, int nHeight, bool shaderResourceView = false) = 0;
virtual void DestroyDepthSurface(SDepthTexture* pDepthSurf) = 0;
virtual IOpticsElementBase* CreateOptics(EFlareType type) const = 0;
// Note:
// Used for pausing timer related stuff.
// Example:
@@ -1,378 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "IResourceCompilerHelper.h"
#include <AzCore/base.h>
// DO NOT USE AZSTD.
#include <string> // std string used here.
#include <memory>
#include <cstring>
// the following block is for _mkdir on windows and mkdir on other platforms.
#if defined(_WIN32)
# include <direct.h>
#else
# include <sys/stat.h>
# include <sys/types.h>
#endif
namespace RCPathUtil
{
const char* GetExt(const char* filepath)
{
const char* str = filepath;
size_t len = strlen(filepath);
for (const char* p = str + len - 1; p >= str; --p)
{
switch (*p)
{
case ':':
case '/':
case '\\':
// we've reached a path separator - it means there's no extension in this name
return "";
case '.':
// there's an extension in this file name
return p + 1;
}
}
return "";
}
const char* GetFile(const char* filepath)
{
const size_t len = strlen(filepath);
for (const char* p = filepath + len - 1; p >= filepath; --p)
{
switch (*p)
{
case ':':
case '/':
case '\\':
return p + 1;
}
}
return filepath;
}
//! Replace extension for given file.
std::string RemoveExtension(const char* filepath)
{
std::string filepathstr = filepath;
const char* str = filepathstr.c_str();
for (const char* p = str + filepathstr.length() - 1; p >= str; --p)
{
switch (*p)
{
case ':':
case '/':
case '\\':
// we've reached a path separator - it means there's no extension in this name
return filepathstr;
case '.':
// there's an extension in this file name
filepathstr.erase(p - str);
return filepathstr;
}
}
// it seems the file name is a pure name, without path or extension
return filepathstr;
}
std::string ReplaceExtension(const char* filepath, const char* ext)
{
std::string str = filepath;
if (ext != 0)
{
str = RemoveExtension(str.c_str());
if (ext[0] != 0 && ext[0] != '.')
{
str += ".";
}
str += ext;
}
return str;
}
std::string GetPath(const char* filepath)
{
std::string filepathstr = filepath;
const char* str = filepathstr.c_str();
for (const char* p = str + filepathstr.length() - 1; p >= str; --p)
{
switch (*p)
{
case ':':
case '/':
case '\\':
// we've reached a path separator - it means there's no extension in this name
return filepathstr.substr(0, p - str);
}
}
// it seems the file name is a pure name, without path
return "";
}
//////////////////////////////////////////////////////////////////////////
bool IsRelativePath(const char* p)
{
if (!p || !p[0])
{
return true;
}
return p[0] != '/' && p[0] != '\\' && !strchr(p, ':');
}
}
const char* IResourceCompilerHelper::SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE] = { "tif", "bmp", "gif", "jpg", "jpeg", "jpe", "tga", "png" };
const char* IResourceCompilerHelper::SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" };
const char* IResourceCompilerHelper::EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE] = { "dds" };
const char* IResourceCompilerHelper::EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE] = { ".dds" };
IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::ConvertResourceCompilerExitCodeToResultCode(int exitCode)
{
switch (exitCode)
{
case eRcExitCode_Success:
case eRcExitCode_UserFixing:
return eRcCallResult_success;
case eRcExitCode_Error:
return eRcCallResult_error;
case eRcExitCode_FatalError:
return eRcCallResult_error;
case eRcExitCode_Crash:
return eRcCallResult_crash;
}
return eRcCallResult_error;
}
//////////////////////////////////////////////////////////////////////////
const char* IResourceCompilerHelper::GetCallResultDescription(IResourceCompilerHelper::ERcCallResult result)
{
switch (result)
{
case eRcCallResult_success:
return "Success.";
case eRcCallResult_notFound:
return "ResourceCompiler executable was not found.";
case eRcCallResult_error:
return "ResourceCompiler exited with an error.";
case eRcCallResult_crash:
return "ResourceCompiler crashed! Please report this. Include source asset and this log in the report.";
default:
return "Unexpected failure in ResultCompilerHelper.";
}
}
// Arguments:
// szFilePath - could be source or destination filename
void IResourceCompilerHelper::GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes)
{
if (IResourceCompilerHelper::IsSourceImageFormatSupported(szFilePath))
{
std::string newString = RCPathUtil::ReplaceExtension(szFilePath, "dds");
azstrncpy(buffer, bufferSizeInBytes, newString.c_str(), bufferSizeInBytes - 1);
return;
}
azstrncpy(buffer, bufferSizeInBytes, szFilePath, bufferSizeInBytes - 1);
}
IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog)
{
const char* szDstFileName = RCPathUtil::GetFile(szDstFilePath);
std::string pathOnly = RCPathUtil::GetPath(szDstFilePath);
const int maxStringSize = 512;
char szRemoteCmdLine[maxStringSize] = { 0 };
char szFullPathToSourceFile[maxStringSize] = { 0 };
if (RCPathUtil::IsRelativePath(szSrcFilePath))
{
azstrcat(szFullPathToSourceFile, maxStringSize, "#ENGINEROOT#");
azstrcat(szFullPathToSourceFile, maxStringSize, "\\");
}
azstrcat(szFullPathToSourceFile, maxStringSize, szSrcFilePath);
azstrcat(szRemoteCmdLine, maxStringSize, " /targetroot=\"");
azstrcat(szRemoteCmdLine, maxStringSize, pathOnly.c_str());
azstrcat(szRemoteCmdLine, maxStringSize, "\"");
azstrcat(szRemoteCmdLine, maxStringSize, " /overwritefilename=\"");
azstrcat(szRemoteCmdLine, maxStringSize, szDstFileName);
azstrcat(szRemoteCmdLine, maxStringSize, "\"");
return CallResourceCompiler(szFullPathToSourceFile, szRemoteCmdLine, nullptr, true, false, !bUserDialog);
}
unsigned int IResourceCompilerHelper::GetNumSourceImageFormats()
{
return NUM_SOURCE_IMAGE_TYPE;
}
const char* IResourceCompilerHelper::GetSourceImageFormat(unsigned int index, bool bWithDot)
{
if (index >= GetNumSourceImageFormats())
{
return nullptr;
}
if (bWithDot)
{
return SourceImageFormatExtsWithDot[index];
}
else
{
return SourceImageFormatExts[index];
}
}
unsigned int IResourceCompilerHelper::GetNumEngineImageFormats()
{
return NUM_ENGINE_IMAGE_TYPE;
}
const char* IResourceCompilerHelper::GetEngineImageFormat(unsigned int index, bool bWithDot)
{
if (index >= GetNumEngineImageFormats())
{
return nullptr;
}
if (bWithDot)
{
return EngineImageFormatExtsWithDot[index];
}
else
{
return EngineImageFormatExts[index];
}
}
bool IResourceCompilerHelper::IsSourceImageFormatSupported(const char* szFileNameOrExtension)
{
if (!szFileNameOrExtension) // if this hits, might want to check the call site
{
return false;
}
//check the string length
size_t len = strlen(szFileNameOrExtension);
if (len < 3)//no point in going on if the smallest valid ext is 3 characters
{
return false;
}
//find the ext by starting at the last character and moving backward to first he first '.'
const char* szExtension = nullptr;
size_t cur = len - 1;
while (cur && !szExtension)
{
if (szFileNameOrExtension[cur] == '.')
{
szExtension = &szFileNameOrExtension[cur];
}
cur--;
}
if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters
{
return false;
}
//if we didn't find a '.' it could still be valid, they may not have
//passed it in. i.e. "dds" instead of ".dds" which is still valid
if (!szExtension)
{
//with no '.' the largest ext is currently 4 characters
//no point in going on if it is larger
if (len > 4)
{
return false;
}
szExtension = szFileNameOrExtension;
}
//loop over all the valid exts and see if it is one of them
for (unsigned int i = 0; i < GetNumSourceImageFormats(); ++i)
{
if (!azstricmp(szExtension, GetSourceImageFormat(i, szExtension[0] == '.')))
{
return true;
}
}
return false;
}
bool IResourceCompilerHelper::IsGameImageFormatSupported(const char* szFileNameOrExtension)
{
if (!szFileNameOrExtension) // if this hits, might want to check the call site
{
return false;
}
//check the string length
size_t len = strlen(szFileNameOrExtension);
if (len < 3)//no point in going on if the smallest valid ext is 3 characters
{
return false;
}
//find the ext by starting at the last character and moving backward to first he first '.'
const char* szExtension = nullptr;
size_t cur = len - 1;
while (cur && !szExtension)
{
if (szFileNameOrExtension[cur] == '.')
{
szExtension = &szFileNameOrExtension[cur];
}
cur--;
}
if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters
{
return false;
}
//if we didn't find a '.' it could still be valid, they may not have
//passed it in. i.e. "dds" instead of ".dds" which is still valid
if (!szExtension)
{
//with no '.' the largest ext is currently 4 characters
//no point in going on if it is larger
if (len > 4)
{
return false;
}
szExtension = szFileNameOrExtension;
}
//loop over all the valid exts and see if it is one of them
for (unsigned int i = 0; i < GetNumEngineImageFormats(); ++i)
{
if (!azstricmp(szExtension, GetEngineImageFormat(i, szExtension[0] == '.')))
{
return true;
}
}
return false;
}
@@ -1,167 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#ifndef CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H
#define CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H
#pragma once
// DO NOT USE AZSTD
#include <string>
// IResourceCompilerHelper exists to define an interface that allows
// remote or local compilation of resources through the "resource Compiler" executable
// in most tools it will be implemented as a local execution. However, in the engine
// it will be substituted for a remote RC invocation through the Asset Processor if
// that system is enabled (via con var and define)
// DO NOT USE CRYSTRING or CRY ALLOCATORS HERE. This is used in maya plugins, that kind of thing.
// the following path utils are special versions of these functions which take pains
// to not use crystring.
// the functions in this interface must be cross platform.
namespace RCPathUtil
{
// given a full path, return the extension (it will be a pointer into the existing string)
const char* GetExt(const char* filepath);
// given a full path, return the file only (it will be a pointer into the existing string)
const char* GetFile(const char* filepath);
// given a filepath, get only the path.
std::string GetPath(const char* filepath);
std::string ReplaceExtension(const char* filepath, const char* ext);
bool IsRelativePath(const char* p);
}
class IResourceCompilerListener;
enum ERcExitCode
{
eRcExitCode_Success = 0, // must be 0
eRcExitCode_Error = 1,
eRcExitCode_FatalError = 100,
eRcExitCode_Crash = 101,
eRcExitCode_UserFixing = 200,
eRcExitCode_Pending = 666,
};
/// A pure virtual interface to the RC Helper system
/// the RC helper system allows you to make requests to a remote process in order to process
/// an asset for you.
class IResourceCompilerHelper
{
public:
virtual ~IResourceCompilerHelper() {}
// defines the result of a call via this API to the RC system
enum ERcCallResult
{
eRcCallResult_success, // everything is OK
eRcCallResult_notFound, // the RC executable is not found
eRcCallResult_error, // the RC executable returned an error
eRcCallResult_crash, // the RC executable did not finish
};
//
// Arguments:
// szFileName null terminated ABSOLUTE file path or 0 can be used to test for rc.exe existence
// relative path needs to be relative to rc_plugins directory
// szAdditionalSettings - 0 or e.g. "/refresh" or "/refresh /xyz=56"
//
// this is a SYNCHRONOUS, BLOCKING call and will return once the process is complete
virtual ERcCallResult CallResourceCompiler(
const char* szFileName = 0,
const char* szAdditionalSettings = 0,
IResourceCompilerListener* listener = 0,
bool bMayShowWindow = true,
bool bSilent = false,
bool bNoUserDialog = false,
const wchar_t* szWorkingDirectory = 0,
const wchar_t* szRootPath = 0) = 0;
// InvokeResourceCompiler - a utility that calls the above CallResourceCompiler function
// but generates appropriate settings so you don't have to specify each option.
// This is a BLOCKING call
// the srcFile can be relative to the project root or an absolute path
// the dstFilePath MUST be relative to the same folder as the Src File path
// this will output dstFilePath in the same folder as srcFile.
virtual ERcCallResult InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog);
// --------------------- utility functions ---------------------------------
// given a RC.EXE process exit code like 101, convert it to the above ERcCallResult
ERcCallResult ConvertResourceCompilerExitCodeToResultCode(int exitCode);
// given a ERcCallResult, convert it to a simple english string for debugging.
static const char* GetCallResultDescription(ERcCallResult result);
// given a filename such as "blah.tif" convert it to the appropriate output name "blah.dds" for example
static void GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes);
//////////////////////////////////////////////////////////////////////////
enum SourceImageTypes
{
SOURCE_IMAGE_TYPE_TIF,
SOURCE_IMAGE_TYPE_BMP,
SOURCE_IMAGE_TYPE_GIF,
SOURCE_IMAGE_TYPE_JPG,
SOURCE_IMAGE_TYPE_JPEG,
SOURCE_IMAGE_TYPE_JPE,
SOURCE_IMAGE_TYPE_TGA,
SOURCE_IMAGE_TYPE_PNG,
NUM_SOURCE_IMAGE_TYPE
};
enum EngineImageTypes
{
ENGINE_IMAGE_TYPE_DDS,
NUM_ENGINE_IMAGE_TYPE
};
private:
static const char* SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE];
static const char* SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE];
static const char* EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE];
static const char* EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE];
public:
static unsigned int GetNumSourceImageFormats();
static const char* GetSourceImageFormat(unsigned int index, bool bWithDot);
static unsigned int GetNumEngineImageFormats();
static const char* GetEngineImageFormat(unsigned int index, bool bWithDot);
static bool IsSourceImageFormatSupported(const char* szExtension);
static bool IsGameImageFormatSupported(const char* szExtension);
};
////////////////////////////////////////////////////////////////////////////
// Listener for synchronous resource-compilation.
// Connects the listener to the output of the RC process.
class IResourceCompilerListener
{
public:
// FbxImportDialog relies on this enum being in the order from most verbose to least verbose
enum MessageSeverity
{
MessageSeverity_Debug = 0,
MessageSeverity_Info,
MessageSeverity_Warning,
MessageSeverity_Error
};
virtual void OnRCMessage(MessageSeverity /*severity*/, const char* /*text*/) {}
virtual ~IResourceCompilerListener() {}
};
#endif // CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H
-344
View File
@@ -1,344 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Service network interface
#ifndef CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H
#define CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H
#pragma once
#include <CryExtension/CryGUID.h>
//-----------------------------------------------------------------------------
//
// Service network is a simple abstract interface for connecting between instances
// of the editor and game running on various platforms. It implements it's own
// small message based communication layer and shall not be used for raw communication
// with anything else.
//
// Features currently implemented by the service network:
// - Completely thread safe (so can be used from within other threads)
// - Completely asynchronous (only one thread)
// - Message based approach (both on the send and receive ends)
// - Automatic and transparent reconnection
// - Debug-friendly (will not time-out easily when one of the endpoints is being debugged)
// - Easy to use
//
// Usage case (server)
// - Create listener (IServiceListener) on some pre-defined port
// - Poll the incoming connections by calling Accept() method
// - Service the traffic by calling connection's ReceiveMessage()/SendMessage() methods
// - Close() and Release() connections
// - Close() and Release() listener
//
// Usage case (client)
// - Connect to a remote listener by calling Connect() method
// - Service the traffic by calling connection's ReceiveMessage()/SendMessage() methods
// - Close() and Release() connection
//
// Both sending and receiving is asynchronous. Calling the SendMessage()/ReceiveMessage() methods
// only pushes/pops the message buffers to/from the queue.
// NOTE: Message buffers are internally reference counted by the network system and they are kept around
// untill they are sent (in case of outgoing traffic) or untill they are polled by ReceiveMessage().
// Be aware that this can cause memory spikes, especially when incoming traffic is not serviced fast enough.
// There are customizable limits (around 1MB) on the amount of data that can be buffered internally by
// the service network before the new messages are rejected.
// It's up to the higher layer to ensure damage control in such situation.
//
// NOTE: connection is also a reference counted object, make sure to call Close() before calling Release().
//
//-----------------------------------------------------------------------------
/// Network address abstraction
class ServiceNetworkAddress
{
public:
struct StringAddress
{
char m_data[32];
ILINE const char* c_str() const
{
return m_data;
}
};
struct Address
{
uint8 m_ip0;
uint8 m_ip1;
uint8 m_ip2;
uint8 m_ip3;
uint16 m_port;
ILINE Address()
: m_ip0(0)
, m_ip1(0)
, m_ip2(0)
, m_ip3(0)
, m_port(0)
{}
};
private:
Address m_address;
public:
// By default creates ("invalid address")
ILINE ServiceNetworkAddress()
{
}
// Copy (with optional port change)
ILINE ServiceNetworkAddress(const ServiceNetworkAddress& other, uint16 newPort = 0)
: m_address(other.m_address)
{
if (newPort != 0)
{
m_address.m_port = newPort;
}
}
// Initialize from ip:host pattern (if you want to initialize from host name use the DebugNetwork interface)
ILINE ServiceNetworkAddress(uint8 ip0, uint8 ip1, uint8 ip2, uint8 ip3, uint16 port)
{
m_address.m_ip0 = ip0;
m_address.m_ip1 = ip1;
m_address.m_ip2 = ip2;
m_address.m_ip3 = ip3;
m_address.m_port = port;
}
// Set new port value
ILINE void SetPort(uint16 port)
{
m_address.m_port = port;
}
// Is this a valid address
ILINE bool IsValid() const
{
return (m_address.m_ip0 != 0) &&
(m_address.m_ip1 != 1) &&
(m_address.m_ip2 != 1) &&
(m_address.m_ip3 != 1) &&
(m_address.m_port != 0);
}
// Convert to human readable string
ILINE StringAddress ToString() const
{
// format the string buffer
StringAddress ret;
sprintf_s(ret.m_data, sizeof(ret.m_data),
"%d.%d.%d.%d:%d",
m_address.m_ip0, m_address.m_ip1, m_address.m_ip2, m_address.m_ip3,
m_address.m_port);
// return as managed string
return ret;
}
// Get the literal data
ILINE const Address& GetAddress() const
{
return m_address;
}
public:
// Compare base address (IP only) of two connections
static bool CompareBaseAddress(const ServiceNetworkAddress& a, const ServiceNetworkAddress& b)
{
return (a.m_address.m_ip0 == b.m_address.m_ip0) &&
(a.m_address.m_ip1 == b.m_address.m_ip1) &&
(a.m_address.m_ip2 == b.m_address.m_ip2) &&
(a.m_address.m_ip3 == b.m_address.m_ip3);
}
// Compare full address (IP+port) of two connections
static bool CompareFullAddress(const ServiceNetworkAddress& a, const ServiceNetworkAddress& b)
{
return (a.m_address.m_ip0 == b.m_address.m_ip0) &&
(a.m_address.m_ip1 == b.m_address.m_ip1) &&
(a.m_address.m_ip2 == b.m_address.m_ip2) &&
(a.m_address.m_ip3 == b.m_address.m_ip3) &&
(a.m_address.m_port == b.m_address.m_port);
}
};
//-----------------------------------------------------------------------------
/// Message buffer used by the network system
struct IServiceNetworkMessage
{
protected:
IServiceNetworkMessage() {};
virtual ~IServiceNetworkMessage() {};
public:
// Get unique message ID (message ID is used just once)
virtual uint32 GetId() const = 0;
// Get the size of message buffer
virtual uint32 GetSize() const = 0;
// Get pointer to the message data
virtual void* GetPointer() = 0;
// Get pointer to the message data
virtual const void* GetPointer() const = 0;
// Create reader interface for reading message data, returned object is not
// reference counted but it will hold a reference to the message.
virtual struct IDataReadStream* CreateReader() const = 0;
// Add reference (buffer is internally refcounted)
virtual void AddRef() = 0;
// Release reference
virtual void Release() = 0;
};
//-----------------------------------------------------------------------------
/// General network TCP/IP connection
struct IServiceNetworkConnection
{
protected:
IServiceNetworkConnection() {};
virtual ~IServiceNetworkConnection() {};
public:
static const uint32 kDefaultFlushTime = 10000; // ms
// Get the unique connection ID (is shared between host and client)
virtual const CryGUID& GetGUID() const = 0;
// Get remote endpoint address
virtual const ServiceNetworkAddress& GetRemoteAddress() const = 0;
// Get local endpoint address
virtual const ServiceNetworkAddress& GetLocalAddress() const = 0;
// Add a message buffer to the connection send queue.
// Connection can refuse to send the buffer if it's full or invalid.
// If a message is rejected this function returns false.
virtual bool SendMsg(IServiceNetworkMessage* message) = 0;
// Get a message from connection receive queue.
// If there are no pending messages a NULL is returned.
// Since message is a ref-counted you need to call Release() when you are done with the buffer.
virtual IServiceNetworkMessage* ReceiveMsg() = 0;
// Checks if connection is still alive.
// Returns false only if connection has been damaged beyond repair.
virtual bool IsAlive() const = 0;
// Get number of messages sent by this connection so far
virtual uint32 GetMessageSendCount() const = 0;
// Get number of messages received by this connection so far
virtual uint32 GetMessageReceivedCount() const = 0;
// Get size of data sent by this connection so far
virtual uint64 GetMessageSendDataSize() const = 0;
// Get size of data received by this connection so far
virtual uint64 GetMessageReceivedDataSize() const = 0;
// Request connection to be closed but not before sending out all of the pending messages. Incoming messages are ignored.
// Processing and sending the messages is done on the networking thread so this function will not block.
// As an option, connection can be forcefully closed after given amount of time (in ms).
virtual void FlushAndClose(const uint32 timeoutMs = kDefaultFlushTime) = 0;
// Synchronous wait for the connection to send all outgoing messages
virtual void FlushAndWait() = 0;
// Request connection to be closed now. All pending messages are discarded.
virtual void Close() = 0;
// Add reference (connection is an internally reference counted object)
virtual void AddRef() = 0;
// Release reference
virtual void Release() = 0;
};
//-----------------------------------------------------------------------------
/// General listening socket (async)
struct IServiceNetworkListener
{
protected:
IServiceNetworkListener() {};
virtual ~IServiceNetworkListener() {};
public:
// Get the local address
virtual const ServiceNetworkAddress& GetLocalAddress() const = 0;
// Get number of active connections handled by this listener
virtual uint GetConnectionCount() const = 0;
// Accept incoming connection (asynchronously)
// Will return NULL if there's nothing to accept
// Will return new IDebugNetworkConnection if something was received
virtual IServiceNetworkConnection* Accept() = 0;
// Is listener able to accept connections ?
virtual bool IsAlive() const = 0;
// Request listener to be closed (closes the socket)
virtual void Close() = 0;
// Add reference (listener is an internally reference counted object)
virtual void AddRef() = 0;
// Release reference
virtual void Release() = 0;
};
//-----------------------------------------------------------------------------
/// General service (background) network interface
struct IServiceNetwork
{
public:
virtual ~IServiceNetwork() {};
// Set verbosity level of debug messages that got printed to log, levels 0-3 are commonly used
virtual void SetVerbosityLevel(const uint32 level) = 0;
// Allocate empty message buffer of given size, message buffer is a reference counted object
virtual IServiceNetworkMessage* AllocMessageBuffer(const uint32 size) = 0;
// Create general message writer stream, object is not reference counted
virtual struct IDataWriteStream* CreateMessageWriter() = 0;
// Create general message reader stream and initialize it with data
virtual struct IDataReadStream* CreateMessageReader(const void* pData, const uint32 dataSize) = 0;
// Translate host address (string:port) to network address
virtual ServiceNetworkAddress GetHostAddress(const string& addressString, uint16 optionalPort = 0) const = 0;
// Create network listener on given local port, listening and accepting connections is done on network thread
virtual IServiceNetworkListener* CreateListener(uint16 localPort) = 0;
// Connect to remote address (will block until connection is made or refused)
virtual IServiceNetworkConnection* Connect(const ServiceNetworkAddress& remoteAddress) = 0;
};
//-----------------------------------------------------------------------------
#endif // CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H
+3 -39
View File
@@ -24,7 +24,9 @@
#endif
#include "smartptr.h"
#include <IFlares.h> // <> required for Interfuscator
#include <IFuncVariable.h> // <> required for Interfuscator
#include <IXml.h> // <> required for Interfuscator
#include "smartptr.h"
#include "VertexFormats.h"
#include <Vertex.h>
#include <AzCore/Casting/numeric_cast.h>
@@ -2828,7 +2830,6 @@ struct SRenderLight
m_ObjMatrix.SetIdentity();
m_BaseObjMatrix.SetIdentity();
m_sName = "";
m_pSoftOccQuery = NULL;
m_pLightAnim = NULL;
m_fAreaWidth = 1;
m_fAreaHeight = 1;
@@ -2884,11 +2885,6 @@ struct SRenderLight
return m_pLightImage ? m_pLightImage : NULL;
}
IOpticsElementBase* GetLensOpticsElement() const
{
return m_pLensOpticsElement;
}
void SetOpticsParams(const SOpticsInstanceParameters& params)
{
m_opticsParams = params;
@@ -2899,24 +2895,6 @@ struct SRenderLight
return m_opticsParams;
}
void SetLensOpticsElement(IOpticsElementBase* pOptics)
{
if (m_pLensOpticsElement == pOptics)
{
return;
}
if (pOptics && pOptics->GetType() != eFT_Root)
{
return;
}
SAFE_RELEASE(m_pLensOpticsElement);
m_pLensOpticsElement = pOptics;
if (m_pLensOpticsElement)
{
m_pLensOpticsElement->AddRef();
}
}
void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*LATER*/}
void AcquireResources()
@@ -2937,14 +2915,6 @@ struct SRenderLight
{
m_pSpecularCubemap->AddRef();
}
if (m_pLensOpticsElement)
{
m_pLensOpticsElement->AddRef();
}
if (m_pSoftOccQuery)
{
m_pSoftOccQuery->AddRef();
}
if (m_pLightAnim)
{
m_pLightAnim->AddRef();
@@ -2961,8 +2931,6 @@ struct SRenderLight
SAFE_RELEASE(m_pLightImage);
SAFE_RELEASE(m_pDiffuseCubemap);
SAFE_RELEASE(m_pSpecularCubemap);
SAFE_RELEASE(m_pLensOpticsElement);
SAFE_RELEASE(m_pSoftOccQuery);
SAFE_RELEASE(m_pLightAnim);
SAFE_RELEASE(m_pLightAttenMap);
}
@@ -3046,8 +3014,6 @@ struct SRenderLight
const char* m_sName; // Optional name of the light source.
SShaderItem m_Shader; // Shader item
CRenderObject* m_pObject[MAX_RECURSION_LEVELS]; // Object for light coronas and light flares.
IOpticsElementBase* m_pLensOpticsElement; // Optics element for this shader instance
ISoftOcclusionQuery* m_pSoftOccQuery;
ILightAnimWrapper* m_pLightAnim;
Matrix34 m_BaseObjMatrix;
@@ -3146,9 +3112,7 @@ public:
m_fShadowSlopeBias = dl.m_fShadowSlopeBias;
m_fShadowResolutionScale = dl.m_fShadowResolutionScale;
m_fHDRDynamic = dl.m_fHDRDynamic;
m_pLensOpticsElement = dl.m_pLensOpticsElement;
m_LensOpticsFrustumAngle = dl.m_LensOpticsFrustumAngle;
m_pSoftOccQuery = dl.m_pSoftOccQuery;
m_fLightFrustumAngle = dl.m_fLightFrustumAngle;
m_fProjectorNearPlane = dl.m_fProjectorNearPlane;
m_Flags = dl.m_Flags;
-276
View File
@@ -1,276 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Interface to manage SoftCode module loading and patching
#ifndef CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H
#define CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H
#pragma once
// Provides the generic interface for exchanging member values between SoftCode modules,
struct IExchangeValue
{
// <interfuscator:shuffle>
virtual ~IExchangeValue() {}
// Allocates a new IExchangeValue with the underlying type
virtual IExchangeValue* Clone() const = 0;
// Returns the size of the underlying type (to check compatibility)
virtual size_t GetSizeOf() const = 0;
// </interfuscator:shuffle>
};
template <typename T>
struct ExchangeValue
: public IExchangeValue
{
ExchangeValue(T& value)
: m_value(value)
{}
virtual IExchangeValue* Clone() const { return new ExchangeValue(*this); }
virtual size_t GetSizeOf() const { return sizeof(m_value); }
T m_value;
};
template <typename T, size_t S>
struct ExchangeArray
: public IExchangeValue
{
ExchangeArray(T* pArr)
{
for (size_t i = 0; i < S; ++i)
{
m_array[i] = pArr[i];
}
}
virtual IExchangeValue* Clone() const { return new ExchangeArray(*this); }
virtual size_t GetSizeOf() const { return sizeof(m_array); }
T m_array[S];
};
/*
This is a non-intrusive support function for types where default construction does no initialization.
SoftCoding relies on default construction to initialize object state correctly.
For most types this works as expected but for some types (typically things like vectors or matrices)
default initialization would be too costly and is therefore not implemented.
This function allows a specialized implementation to be used for such types that will perform
initialization on the newly constructed instance. For example:
inline void DefaultInitialize(Matrix34& matrix)
{
matrix.SetIdentity();
}
*/
template <typename T>
void DefaultInitialize(T& t)
{
t = T();
}
// Vector support
template<class F>
struct Vec2_tpl;
template<typename T>
struct Vec3_tpl;
template <class F>
void DefaultInitialize(Vec2_tpl<F>& vec) { vec.zero(); }
template <typename T>
void DefaultInitialize(Vec3_tpl<T>& vec) { vec.zero(); }
// Matrix support
template<typename F>
struct Matrix33_tpl;
template<typename F>
struct Matrix34_tpl;
template<typename F>
struct Matrix44_tpl;
template <typename F>
void DefaultInitialize(Matrix33_tpl<F>& matrix) { matrix.SetIdentity(); }
template <typename F>
void DefaultInitialize(Matrix34_tpl<F>& matrix) { matrix.SetIdentity(); }
template <typename F>
void DefaultInitialize(Matrix44_tpl<F>& matrix) { matrix.SetIdentity(); }
// Quat support
template <typename F>
struct Quat_tpl;
template <typename F>
void DefaultInitialize(Quat_tpl<F>& quat) { quat.SetIdentity(); }
// Interface for performing an exchange of instance data
struct IExchanger
{
// <interfuscator:shuffle>
virtual ~IExchanger() {}
// True if data is being read from instance members
virtual bool IsLoading() const = 0;
virtual size_t InstanceCount() const = 0;
virtual bool BeginInstance(void* pInstance) = 0;
virtual bool SetValue(const char* name, IExchangeValue& value) = 0;
virtual IExchangeValue* GetValue(const char* name, void* pTarget, size_t targetSize) = 0;
// </interfuscator:shuffle>
template <typename T>
void Visit(const char* name, T& instance);
template <typename T, size_t S>
void Visit(const char* name, T (&arr)[S]);
};
template <typename T>
void IExchanger::Visit(const char* name, T& value)
{
if (IsLoading())
{
IExchangeValue* pValue = GetValue(name, &value, sizeof(value));
if (pValue)
{
ExchangeValue<T>* pTypedValue = static_cast<ExchangeValue<T>*>(pValue);
value = pTypedValue->m_value;
}
}
else // Saving
{
// If this member is stored
if (SetValue(name, ExchangeValue<T>(value)))
{
// Set the original value to the default state (to allow safe destruction)
DefaultInitialize(value);
}
}
}
template <typename T, size_t S>
void IExchanger::Visit(const char* name, T (&arr)[S])
{
if (IsLoading())
{
IExchangeValue* pValue = GetValue(name, &arr, sizeof(arr));
if (pValue)
{
ExchangeArray<T, S>* pTypedArray = static_cast<ExchangeArray<T, S>*>(pValue);
// TODO: Accommodate array resizing? Complex however...
for (size_t i = 0; i < S; ++i)
{
arr[i] = pTypedArray->m_array[i];
}
}
}
else // Saving
{
// If this member is stored
if (SetValue(name, ExchangeArray<T, S>(arr)))
{
T defaultValue;
DefaultInitialize(defaultValue);
// Set the original value to the default value (to allow safe destruction)
for (size_t i = 0; i < S; ++i)
{
arr[i] = defaultValue;
}
}
}
}
struct InstanceTracker;
struct ITypeRegistrar
{
// <interfuscator:shuffle>
virtual ~ITypeRegistrar() {}
virtual const char* GetName() const = 0;
// Creates an instance of the type
virtual void* CreateInstance() = 0;
// </interfuscator:shuffle>
#ifdef SOFTCODE_ENABLED
// How many active instances exist of this type?
virtual size_t InstanceCount() const = 0;
// Used to remove a tracked instance from the Registrar
virtual void RemoveInstance(InstanceTracker* pTracker) = 0;
// Exchanges the instance state with the given exchanger data set
virtual bool ExchangeInstances(IExchanger& exchanger) = 0;
// Destroys all tracked instances of this type
virtual bool DestroyInstances() = 0;
// Returns true if pInstance is of this type (linear search)
virtual bool HasInstance(void* pInstance) const = 0;
#endif
};
struct ITypeLibrary
{
// <interfuscator:shuffle>
virtual ~ITypeLibrary() {}
virtual const char* GetName() = 0;
virtual void* CreateInstanceVoid(const char* typeName) = 0;
// </interfuscator:shuffle>
#ifdef SOFTCODE_ENABLED
virtual void SetOverride(ITypeLibrary* pOverrideLib) = 0;
// Fills in the supplied type list if large enough, and sets count to number of types
virtual size_t GetTypes(ITypeRegistrar** ppRegistrar, size_t& count) const = 0;
#endif
};
struct ISoftCodeListener
{
// <interfuscator:shuffle>
virtual ~ISoftCodeListener() {}
// Called when an instance is replaced to allow managing systems to fixup pointers
virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) = 0;
// </interfuscator:shuffle>
};
/// Interface for ...
struct ISoftCodeMgr
{
// <interfuscator:shuffle>
virtual ~ISoftCodeMgr() {}
// Used to register built-in libraries on first use
virtual void RegisterLibrary(ITypeLibrary* pLib) = 0;
// Loads any new SoftCode modules
virtual void LoadNewModules() = 0;
virtual void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) = 0;
virtual void RemoveListener(const char* libraryName, ISoftCodeListener* pListener) = 0;
// To be called regularly to poll for library updates
virtual void PollForNewModules() = 0;
// Stops thread execution until a new SoftCode instance is available
virtual void* WaitForUpdate(void* pInstance) = 0;
/// Frees this instance from memory
//virtual void Release() = 0;
// </interfuscator:shuffle>
};
#endif // CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H
-1
View File
@@ -34,7 +34,6 @@
#include <list>
#include "smartptr.h"
#include <IThreadTask.h> // <> required for Interfuscator
#include "CryThread.h"
#include "IStreamEngineDefs.h"
+3 -346
View File
@@ -49,19 +49,15 @@
#include <ILog.h> // <> required for Interfuscator
#include "CryVersion.h"
#include "smartptr.h"
#include <ISystemScheduler.h> // <> required for Interfuscator
#include <memory> // shared_ptr
#include <CrySystemBus.h>
struct ISystem;
struct ILog;
struct IProfileLogSystem;
namespace AZ::IO
{
struct IArchive;
}
struct IKeyboard;
struct IMouse;
struct IConsole;
struct IRemoteConsole;
struct IRenderer;
@@ -79,32 +75,21 @@ struct SFileVersion;
struct INameTable;
struct ILevelSystem;
struct IViewSystem;
struct IMaterialEffects;
class IOpticsManager;
class ICrySizer;
class IXMLBinarySerializer;
struct IReadWriteXMLSink;
struct IThreadTaskManager;
struct IResourceManager;
struct ITextModeConsole;
struct IAVI_Reader;
class CPNoise3;
struct IVisualLog;
struct ILocalizationManager;
struct ICryFactoryRegistry;
struct ISoftCodeMgr;
struct IZLibCompressor;
struct IZLibDecompressor;
struct ILZ4Decompressor;
class IZStdDecompressor;
struct IOutputPrintSink;
struct IThreadManager;
struct IServiceNetwork;
struct IRemoteCommandManager;
struct IWindowMessageHandler;
struct IImageHandler;
class IResourceCompilerHelper;
class ILmbrAWS;
namespace AZ
{
@@ -114,12 +99,6 @@ namespace AZ
}
}
class IResourceCompilerHelper;
namespace Serialization {
struct IArchiveHost;
}
typedef void* WIN_HWND;
class CCamera;
@@ -127,39 +106,13 @@ struct CLoadingTimeProfiler;
class ICmdLine;
struct INotificationNetwork;
class ILyShine;
namespace JobManager {
struct IJobManager;
}
#define PROC_MENU 1
#define PROC_3DENGINE 2
// Summary:
// IDs for script userdata typing.
// Remarks:
// Maybe they should be moved into the game.dll .
//##@{
#define USER_DATA_SOUND 1
#define USER_DATA_TEXTURE 2
#define USER_DATA_OBJECT 3
#define USER_DATA_LIGHT 4
#define USER_DATA_BONEHANDLER 5
#define USER_DATA_POINTER 6
//##@}
enum ESystemUpdateFlags
{
ESYSUPDATE_IGNORE_PHYSICS = 0x0002,
// Summary:
// Special update mode for editor.
ESYSUPDATE_EDITOR = 0x0004,
ESYSUPDATE_MULTIPLAYER = 0x0008,
ESYSUPDATE_EDITOR_AI_PHYSICS = 0x0010,
ESYSUPDATE_EDITOR_ONLY = 0x0020,
ESYSUPDATE_UPDATE_VIEW_ONLY = 0x0040
ESYSUPDATE_EDITOR = 0x0004
};
// Description:
@@ -192,29 +145,6 @@ enum ESystemConfigPlatform
END_CONFIG_PLATFORM_ENUM, // MUST BE LAST VALUE. USED FOR ERROR CHECKING.
};
enum ESubsystem
{
ESubsys_3DEngine = 0,
ESubsys_AI = 1,
ESubsys_Physics = 2,
ESubsys_Renderer = 3,
ESubsys_Script = 4
};
// Summary:
// Collates cycles taken per update.
struct sUpdateTimes
{
uint32 PhysYields;
uint64 SysUpdateTime;
uint64 PhysStepTime;
uint64 RenderTime;
//extended yimes info
uint64 physWaitTime;
uint64 streamingWaitTime;
uint64 animationWaitTime;
};
enum ESystemGlobalState
{
ESYSTEM_GLOBAL_STATE_UNKNOWN,
@@ -571,33 +501,6 @@ struct IErrorObserver
// </interfuscator:shuffle>
};
enum ESystemProtectedFunctions
{
eProtectedFunc_Save = 0,
eProtectedFunc_Load = 1,
eProtectedFuncsLast = 10,
};
struct SCvarsDefault
{
SCvarsDefault()
{
sz_r_DriverDef = NULL;
}
const char* sz_r_DriverDef;
};
#if defined(CVARS_WHITELIST)
struct ICVarsWhitelist
{
// <interfuscator:shuffle>
virtual ~ICVarsWhitelist() {};
virtual bool IsWhiteListed(const string& command, bool silent) = 0;
// </interfuscator:shuffle>
};
#endif // defined(CVARS_WHITELIST)
#if defined(AZ_RESTRICTED_PLATFORM)
#define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_3
#include AZ_RESTRICTED_FILE(ISystem_h)
@@ -619,9 +522,6 @@ struct SSystemInitParams
{
void* hInstance; //
void* hWnd; //
void* hWndForInputSystem; // the HWND for the input devices, distinct from the hWnd, which the rendering system overrides anyways
bool remoteResourceCompiler;
ILog* pLog; // You can specify your own ILog to be used by System.
ILogCallback* pLogCallback; // You can specify your own ILogCallback to be added on log creation (used by Editor).
@@ -636,33 +536,14 @@ struct SSystemInitParams
bool bPreview; // When running in Preview mode (Minimal initialization).
bool bTestMode; // When running in Automated testing mode.
bool bDedicatedServer; // When running a dedicated server.
bool bExecuteCommandLine; // can be switched of to suppress the feature or do it later during the initialization.
bool bSkipFont; // Don't load CryFont.dll
bool bSkipConsole; // Don't create console
bool bSkipNetwork; // Don't create Network
bool bSkipWebsocketServer; // Don't create the WebSocket server
bool bMinimal; // Don't load banks
bool bTesting; // CryUnit
bool bNoRandom; //use fixed generator init/seed
bool bUnattendedMode; // When running as part of a build on build-machines: Prevent popping up of any dialog
bool bSkipMovie; // Don't load movie
bool bSkipAnimation; // Don't load animation
bool bToolMode; // System is running inside a tool. Will not create USER directory or anything else that the game needs to do
bool bSkipPhysics; // Don't initialize CryPhysics.
ISystem* pSystem; // Pointer to existing ISystem interface, it will be reused if not NULL.
typedef void* (*ProtectedFunction)(void* param1, void* param2);
ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions.
SCvarsDefault* pCvarsDefault; // to override the default value of some cvar
#if defined(CVARS_WHITELIST)
ICVarsWhitelist* pCVarsWhitelist; // CVars whitelist callback
#endif // defined(CVARS_WHITELIST)
SharedEnvironmentInstance* pSharedEnvironment;
// Summary:
@@ -671,16 +552,10 @@ struct SSystemInitParams
{
hInstance = NULL;
hWnd = NULL;
hWndForInputSystem = NULL;
remoteResourceCompiler = false;
pLog = NULL;
pLogCallback = NULL;
pUserCallback = NULL;
#if defined(CVARS_WHITELIST)
pCVarsWhitelist = NULL;
#endif // defined(CVARS_WHITELIST)
sLogFileName = NULL;
autoBackupLogs = true;
pValidator = NULL;
@@ -691,32 +566,13 @@ struct SSystemInitParams
bPreview = false;
bTestMode = false;
bDedicatedServer = false;
bExecuteCommandLine = true;
bExecuteCommandLine = true;
bSkipFont = false;
bSkipConsole = false;
bSkipNetwork = false;
#if defined(WIN32) || defined(WIN64)
// create websocket server by default. bear in mind that USE_HTTP_WEBSOCKETS is not defined in release.
bSkipWebsocketServer = false;
#else
// CTCPStreamSocket only seems to fully support Win32 and 64
bSkipWebsocketServer = true;
#endif
bMinimal = false;
bTesting = false;
bNoRandom = false;
bUnattendedMode = false;
bSkipMovie = false;
bSkipAnimation = false;
bToolMode = false;
bSkipPhysics = false;
pSystem = NULL;
memset(pProtectedFunctions, 0, sizeof(pProtectedFunctions));
pCvarsDefault = NULL;
pSharedEnvironment = nullptr;
}
};
@@ -785,8 +641,6 @@ struct SSystemGlobalEnvironment
{
AZ::IO::IArchive* pCryPak;
AZ::IO::FileIOBase* pFileIO;
IProfileLogSystem* pProfileLogSystem;
IOpticsManager* pOpticsManager;
ITimer* pTimer;
ICryFont* pCryFont;
::IConsole* pConsole;
@@ -794,83 +648,27 @@ struct SSystemGlobalEnvironment
ILog* pLog;
IMovieSystem* pMovieSystem;
INameTable* pNameTable;
IVisualLog* pVisualLog;
IRenderer* pRenderer;
IMaterialEffects* pMaterialEffects;
ISoftCodeMgr* pSoftCodeMgr;
IServiceNetwork* pServiceNetwork;
IRemoteCommandManager* pRemoteCommandManager;
ILyShine* pLyShine;
IResourceCompilerHelper* pResourceCompilerHelper;
SharedEnvironmentInstance* pSharedEnvironment;
IThreadManager* pThreadManager;
#if defined(AZ_RESTRICTED_PLATFORM)
#define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_4
#include AZ_RESTRICTED_FILE(ISystem_h)
#endif
ISystemScheduler* pSystemScheduler;
threadID mMainThreadId; //The main thread ID is used in multiple systems so should be stored globally
//////////////////////////////////////////////////////////////////////////
uint32 nMainFrameID;
//////////////////////////////////////////////////////////////////////////
const char* szCmdLine; // Startup command line.
//////////////////////////////////////////////////////////////////////////
// Generic debug string which can be easily updated by any system and output by the debug handler
enum
{
MAX_DEBUG_STRING_LENGTH = 128
};
char szDebugStatus[MAX_DEBUG_STRING_LENGTH];
//////////////////////////////////////////////////////////////////////////
// Used to tell if this is a server/multiplayer instance
bool bServer;
bool bMultiplayer;
bool bHostMigrating;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Indicate Editor status.
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Used by CRY_ASSERT
bool bIgnoreAllAsserts;
bool bNoAssertDialog;
bool bTesting;
//////////////////////////////////////////////////////////////////////////
bool bNoRandomSeed;
SPlatformInfo pi;
// Protected functions.
SSystemInitParams::ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions.
//////////////////////////////////////////////////////////////////////////
// Flag to able to print out of memory conditon
bool bIsOutOfMemory;
bool bIsOutOfVideoMemory;
bool bToolMode;
int retCode = 0;
ILINE const bool IsClient() const
{
#if defined(CONSOLE)
return true;
#else
return bClient;
#endif
}
ILINE const bool IsDedicated() const
{
#if defined(CONSOLE)
@@ -900,11 +698,6 @@ struct SSystemGlobalEnvironment
{
bDedicated = isDedicated;
}
ILINE void SetIsClient(bool isClient)
{
bClient = isClient;
}
#endif
//this way the compiler can strip out code for consoles
@@ -944,26 +737,6 @@ struct SSystemGlobalEnvironment
#endif
}
ILINE const bool IsFMVPlaying() const
{
return m_isFMVPlaying;
}
ILINE void SetFMVIsPlaying(const bool isPlaying)
{
m_isFMVPlaying = isPlaying;
}
ILINE const bool IsCutscenePlaying() const
{
return m_isCutscenePlaying;
}
ILINE void SetCutsceneIsPlaying(const bool isPlaying)
{
m_isCutscenePlaying = isPlaying;
}
ILINE bool IsInToolMode() const
{
return bToolMode;
@@ -974,35 +747,17 @@ struct SSystemGlobalEnvironment
bToolMode = bNewToolMode;
}
ILINE void SetDynamicMergedMeshGenerationEnabled(bool mmgenEnable)
{
m_bDynamicMergedMeshGenerationEnabled = mmgenEnable;
}
ILINE const bool IsDynamicMergedMeshGenerationEnabled() const
{
return m_bDynamicMergedMeshGenerationEnabled;
}
#if !defined(CONSOLE)
private:
bool bClient;
bool bEditor; // Engine is running under editor.
bool bEditorGameMode; // Engine is in editor game mode.
bool bEditorSimulationMode; // Engine is in editor simulation mode.
bool bDedicated; // Engine is in dedicated
#endif
bool m_isFMVPlaying;
bool m_isCutscenePlaying;
bool m_bDynamicMergedMeshGenerationEnabled;
public:
SSystemGlobalEnvironment()
: pSystemScheduler(nullptr)
, szCmdLine("")
, bToolMode(false)
, m_bDynamicMergedMeshGenerationEnabled(false)
: bToolMode(false)
{
};
};
@@ -1040,37 +795,11 @@ struct IProfilingSystem
// Initialize and dispatch all engine's subsystems.
struct ISystem
{
struct ILoadingProgressListener
{
// <interfuscator:shuffle>
virtual ~ILoadingProgressListener() {}
virtual void OnLoadingProgress(int steps) = 0;
// </interfuscator:shuffle>
};
#ifndef _RELEASE
enum LevelLoadOrigin
{
eLLO_Unknown,
eLLO_NewLevel,
eLLO_Level2Level,
eLLO_Resumed,
eLLO_MapCmd,
};
struct ICheckpointData
{
int m_totalLoads;
LevelLoadOrigin m_loadOrigin;
};
#endif
// <interfuscator:shuffle>
virtual ~ISystem() {}
// Summary:
// Releases ISystem.
virtual void Release() = 0;
virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const = 0; // will return NULL if no whitelisting
// Summary:
// Returns pointer to the global environment structure.
@@ -1099,9 +828,6 @@ struct ISystem
virtual void DoWorkDuringOcclusionChecks() = 0;
virtual bool NeedDoWorkDuringOcclusionChecks() = 0;
//! Update screen and call some important tick functions during loading.
virtual void SynchronousLoadingTick(const char* pFunc, int line) = 0;
// Summary:
// Returns the current used memory.
virtual uint32 GetUsedMemory() = 0;
@@ -1175,7 +901,6 @@ struct ISystem
virtual IZLibDecompressor* GetIZLibDecompressor() = 0;
virtual ILZ4Decompressor* GetLZ4Decompressor() = 0;
virtual IZStdDecompressor* GetZStdDecompressor() = 0;
virtual INotificationNetwork* GetINotificationNetwork() = 0;
virtual IViewSystem* GetIViewSystem() = 0;
virtual ILevelSystem* GetILevelSystem() = 0;
virtual INameTable* GetINameTable() = 0;
@@ -1192,24 +917,10 @@ struct ISystem
// Returns:
// Can be NULL, because it only exists when running through the editor, not in pure game mode.
virtual IResourceManager* GetIResourceManager() = 0;
virtual IThreadTaskManager* GetIThreadTaskManager() = 0;
virtual IProfilingSystem* GetIProfilingSystem() = 0;
virtual ISystemEventDispatcher* GetISystemEventDispatcher() = 0;
virtual IVisualLog* GetIVisualLog() = 0;
virtual ITimer* GetITimer() = 0;
virtual IThreadManager* GetIThreadManager() = 0;
virtual void SetLoadingProgressListener(ILoadingProgressListener* pListener) = 0;
virtual ISystem::ILoadingProgressListener* GetLoadingProgressListener() const = 0;
// Summary:
// Game is created after System init, so has to be set explicitly.
virtual void SetIMaterialEffects(IMaterialEffects* pMaterialEffects) = 0;
virtual void SetIOpticsManager(IOpticsManager* pOpticsManager) = 0;
virtual void SetIVisualLog(IVisualLog* pVisualLog) = 0;
//virtual const char *GetGamePath()=0;
virtual void DebugStats(bool checkpoint, bool leaks) = 0;
virtual void DumpWinHeaps() = 0;
@@ -1224,7 +935,6 @@ struct ISystem
virtual bool WasInDevMode() const = 0;
virtual bool IsDevMode() const = 0;
virtual bool IsMODValid(const char* szMODName) const = 0;
virtual bool IsMinimalMode() const = 0;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
@@ -1244,10 +954,6 @@ struct ISystem
// Retrieves access to XML utilities interface.
virtual IXmlUtils* GetXmlUtils() = 0;
// Summary:
// Interface to access different implementations of Serialization::IArchive in a centralized way.
virtual Serialization::IArchiveHost* GetArchiveHost() const = 0;
virtual void SetViewCamera(CCamera& Camera) = 0;
virtual CCamera& GetViewCamera() = 0;
@@ -1343,12 +1049,6 @@ struct ISystem
// Detects and set optimal spec.
virtual void AutoDetectSpec(bool detectResolution) = 0;
// Summary:
// Thread management for subsystems
// Return Value:
// Non-0 if the state was indeed changed, 0 if already in that state.
virtual int SetThreadState(ESubsystem subsys, bool bActive) = 0;
// Summary:
// Query if system is now paused.
// Pause flag is set when calling system update with pause mode.
@@ -1368,10 +1068,6 @@ struct ISystem
// Retrieves system update counter.
virtual uint64 GetUpdateCounter() = 0;
// Summary:
// Gets access to all registered factories.
virtual ICryFactoryRegistry* GetCryFactoryRegistry() const = 0;
//////////////////////////////////////////////////////////////////////////
// Error callback handling
@@ -1419,14 +1115,6 @@ struct ISystem
// Get log index of the currently running Open 3D Engine application. (0 = first instance, 1 = second instance, etc)
virtual int GetApplicationLogInstance(const char* logFilePath) = 0;
// Summary:
// Retrieves the current stats for systems to update the respective time taken
virtual sUpdateTimes& GetCurrentUpdateTimeStats() = 0;
// Summary:
// Retrieves the array of update times and the number of entries
virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&) = 0;
// Summary:
// Clear all currently logged and drawn on screen error messages
virtual void ClearErrorMessages() = 0;
@@ -1471,17 +1159,6 @@ struct ISystem
virtual void AsyncMemcpy(void* dst, const void* src, size_t size, int nFlags, volatile int* sync) = 0;
// </interfuscator:shuffle>
#if defined(CVARS_WHITELIST)
virtual ICVarsWhitelist* GetCVarsWhiteList() const = 0;
#endif // defined(CVARS_WHITELIST)
#ifndef _RELEASE
virtual void GetCheckpointData(ICheckpointData& data) = 0;
virtual void IncreaseCheckpointLoadCount() = 0;
virtual void SetLoadOrigin(LevelLoadOrigin origin) = 0;
#endif
#if !defined(_RELEASE)
virtual bool IsSavingResourceList() const = 0;
#endif
@@ -1491,15 +1168,6 @@ struct ISystem
virtual const IImageHandler* GetImageHandler() const = 0;
// Summary:
// Loads a dynamic library, creates and initializes an instance of the module class
virtual bool InitializeEngineModule(const char* dllName, const char* moduleClassName, const SSystemInitParams& initParams) = 0;
// Summary:
// Unloads a dynamic library as well as the corresponding instance of the module class
virtual bool UnloadEngineModule(const char* dllName, const char* moduleClassName) = 0;
// Summary:
// Gets the root window message handler function
// The returned pointer is platform-specific:
@@ -1535,11 +1203,6 @@ struct ISystem
using CrySystemNotificationBus = AZ::EBus<CrySystemNotifications>;
};
//JAT - this is a very important function for the dedicated server - it lets us run >1000 players per piece of server hardware
//JAT - this saves us lots of money on the dedicated server hardware
#define SYNCHRONOUS_LOADING_TICK() do { if (gEnv && gEnv->pSystem) {gEnv->pSystem->SynchronousLoadingTick(__FUNC__, __LINE__); } \
} while (0)
#if defined(USE_DISK_PROFILER)
struct DiskOperationInfo
@@ -1616,7 +1279,7 @@ typedef ISystem* (*PFNCREATESYSTEMINTERFACE)(SSystemInitParams& initParams);
//////////////////////////////////////////////////////////////////////////
// Global environment variable.
//////////////////////////////////////////////////////////////////////////
extern SC_API SSystemGlobalEnvironment* gEnv;
extern SSystemGlobalEnvironment* gEnv;
// Summary:
@@ -1635,11 +1298,6 @@ inline ISystem* GetISystem()
}
return systemInterface;
};
inline ISystemScheduler* GetISystemScheduler(void)
{
return gEnv->pSystemScheduler;
};
//////////////////////////////////////////////////////////////////////////
// Description:
@@ -1662,7 +1320,6 @@ void* GetDetachEnvironmentSymbol();
extern bool g_bProfilerEnabled;
extern int g_iTraceAllocations;
// Summary:
// Interface of the DLL.
@@ -1,63 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H
#define CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H
#pragma once
#if defined(__cplusplus)
#define SLICE_AND_SLEEP() do { if (GetISystemScheduler()) { GetISystemScheduler()->SliceAndSleep(__FUNC__, __LINE__); } \
} while (0)
#define SLICE_SCOPE_DEFINE() CSliceLoadingMonitor sliceScope
#else
extern void SliceAndSleep(const char* pFunc, int line);
#define SLICE_AND_SLEEP() SliceAndSleep(__FILE__, __LINE__)
#endif
struct ISystemScheduler
{
virtual ~ISystemScheduler(){}
// <interfuscator:shuffle>
// Map load slicing functionality support
virtual void SliceAndSleep(const char* sliceName, int line) = 0;
virtual void SliceLoadingBegin() = 0;
virtual void SliceLoadingEnd() = 0;
virtual void SchedulingSleepIfNeeded(void) = 0;
// </interfuscator:shuffle>
};
ISystemScheduler* GetISystemScheduler(void);
class CSliceLoadingMonitor
{
public:
CSliceLoadingMonitor()
{
if (GetISystemScheduler())
{
GetISystemScheduler()->SliceLoadingBegin();
}
}
~CSliceLoadingMonitor()
{
if (GetISystemScheduler())
{
GetISystemScheduler()->SliceLoadingEnd();
}
}
};
#endif // CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H
-111
View File
@@ -1,111 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#pragma once
class IThreadConfigManager;
enum EJoinMode
{
eJM_TryJoin,
eJM_Join,
};
class IThread
{
public:
// <interfuscator:shuffle>
virtual ~IThread()
{
}
//! Entry functions for code executed on thread.
virtual void ThreadEntry() = 0;
// </interfuscator:shuffle>
};
enum EFPE_Severity
{
eFPE_None, //!< No Floating Point Exceptions.
eFPE_Basic, //!< Invalid operation, Div by 0.
eFPE_All, //!< Invalid operation, Div by 0, Denormalized operand, Overflow, Underflow, Inexact.
eFPE_LastEntry
};
//temp disable CRY DX12
//#define SCOPED_ENABLE_FLOAT_EXCEPTIONS(eFPESeverity) CScopedFloatingPointException scopedSetFloatExceptionMask(eFPESeverity)
//#define SCOPED_DISABLE_FLOAT_EXCEPTIONS() CScopedFloatingPointException scopedSetFloatExceptionMask(eFPE_None)
struct IThreadManager
{
public:
// <interfuscator:shuffle>
virtual ~IThreadManager()
{
}
//! Get thread config manager.
virtual IThreadConfigManager* GetThreadConfigManager() = 0;
//! Spawn a new thread and apply thread config settings at thread beginning.
virtual bool SpawnThread(IThread* pThread, const char* sThreadName, ...) = 0;
//! Wait on another thread to exit (Blocking).
//! Use eJM_TryJoin if you cannot be sure that the target thread is awake.
//! \retval true if target thread has not been started yet or has already exited.
//! \retval false if target thread is still running and therefore not in a state to exit.
virtual bool JoinThread(IThread* pThreadTask, EJoinMode joinStatus) = 0;
//! Register 3rd party thread with the thread manager.
//! Applies thread config for thread if found.
//! \param pThreadHandle If NULL, the current thread handle will be used.
virtual bool RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) = 0;
//! Unregister 3rd party thread with the thread manager.
virtual bool UnRegisterThirdPartyThread(const char* sThreadName, ...) = 0;
//! Get Thread Name.
//! Returns "" if thread not found.
virtual const char* GetThreadName(threadID nThreadId) = 0;
//! Get ThreadID.
virtual threadID GetThreadId(const char* sThreadName, ...) = 0;
//! Execute function for each other thread but this one.
typedef void (* ThreadModifFunction)(threadID nThreadId, void* pData);
virtual void ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData = 0) = 0;
virtual void EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId = 0) = 0;
virtual void EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) = 0;
virtual uint GetFloatingPointExceptionMask() = 0;
virtual void SetFloatingPointExceptionMask(uint nMask) = 0;
// </interfuscator:shuffle>
};
/*TEMP DISABLE CRY DX12
class CScopedFloatingPointException
{
public:
CScopedFloatingPointException(EFPE_Severity eFPESeverity)
{
oldMask = gEnv->pThreadManager->GetFloatingPointExceptionMask();
gEnv->pThreadManager->EnableFloatExceptions(eFPESeverity);
}
~CScopedFloatingPointException()
{
gEnv->pThreadManager->SetFloatingPointExceptionMask(oldMask);
}
private:
uint oldMask;
};
*/
-166
View File
@@ -1,166 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "BitFiddling.h"
#ifndef CRYINCLUDE_CRYCOMMON_ITHREADTASK_H
#define CRYINCLUDE_CRYCOMMON_ITHREADTASK_H
#pragma once
#include <smartptr.h>
// forward declarations
struct SThreadTaskInfo;
enum EThreadTaskFlags
{
THREAD_TASK_BLOCKING = BIT(0), // Blocking tasks will be allocated on their own thread.
THREAD_TASK_ASSIGN_TO_POOL = BIT(1), // Task can be assigned to any thread in the group of threads
};
class IThreadTask_Thread
{
public:
// <interfuscator:shuffle>
virtual ~IThreadTask_Thread() {};
virtual void AddTask(SThreadTaskInfo* pTaskInfo) = 0;
virtual void RemoveTask(SThreadTaskInfo* pTaskInfo) = 0;
virtual void RemoveAllTasks() = 0;
virtual void SingleUpdate() = 0;
// </interfuscator:shuffle>
};
typedef int ThreadPoolHandle;
struct SThreadTaskParams
{
uint32 nFlags; // Task flags. @see ETaskFlags
union
{
int nPreferedThread; // Preferred Thread index (0,1,2,3...)
ThreadPoolHandle nThreadsGroupId; // Id of group of threads(useful only if THREAD_TASK_ASSIGN_TO_POOL is set)
};
int16 nPriorityOff; // If THREAD_TASK_BLOCKING, this will adjust the priority of the thread
int16 nStackSizeKB; // If THREAD_TASK_BLOCKING, this will adjust the stack size of the thread
const char* name; // Name for this task (thread for the blocking task will be named using this string)
SThreadTaskParams()
: nFlags(0)
, nPreferedThread(-1)
, nPriorityOff(0)
, name("")
, nStackSizeKB(SIMPLE_THREAD_STACK_SIZE_KB) {}
};
//////////////////////////////////////////////////////////////////////////
// Tasks must implement this interface.
//////////////////////////////////////////////////////////////////////////
struct IThreadTask
{
// <interfuscator:shuffle>
// The function to be called on every update for non bocking tasks.
// Or will be called only once for the blocking threads.
virtual void OnUpdate() = 0;
// Called to indicate that this task must quit.
// Warning! can be called from different thread then OnUpdate call.
virtual void Stop() = 0;
// Returns task info
virtual struct SThreadTaskInfo* GetTaskInfo() = 0;
virtual ~IThreadTask() {}
// </interfuscator:shuffle>
};
struct SThreadTaskInfo
: public CMultiThreadRefCount
{
IThreadTask_Thread* m_pThread;
IThreadTask* m_pTask;
SThreadTaskParams m_params;
SThreadTaskInfo()
: m_pThread(NULL)
, m_pTask(NULL) { m_params.nFlags = 0; m_params.nPreferedThread = -1; }
};
// Might be changed to uint64 etc in the future
typedef uint32 ThreadPoolAffinityMask;
#define INVALID_AFFINITY 0
//////////////////////////////////////////////////////////////////////////
// Description of thread pool to create
//////////////////////////////////////////////////////////////////////////
struct ThreadPoolDesc
{
ThreadPoolAffinityMask AffinityMask; // number of bits means number of threads. affinity overlapping is prohibited
string sPoolName;
int32 nThreadPriority;
int32 nThreadStackSizeKB;
ThreadPoolDesc()
: AffinityMask(INVALID_AFFINITY)
, sPoolName("UnnamedPool")
, nThreadPriority(-1)
, nThreadStackSizeKB(-1) { }
ILINE bool CreateThread(ThreadPoolAffinityMask affinityMask)
{
if (this->AffinityMask & affinityMask)
{
return false;
}
this->AffinityMask |= affinityMask;
return true;
}
ILINE uint32 GetThreadCount() const
{
return CountBits(AffinityMask);
}
};
//////////////////////////////////////////////////////////////////////////
// Task manager.
//////////////////////////////////////////////////////////////////////////
struct IThreadTaskManager
{
// <interfuscator:shuffle>
virtual ~IThreadTaskManager(){}
// Register new task to the manager.
virtual void RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options) = 0;
virtual void UnregisterTask(IThreadTask* pTask) = 0;
// Limit number of threads to this amount.
virtual void SetMaxThreadCount(int nMaxThreads) = 0;
// Create a pool of threads
virtual ThreadPoolHandle CreateThreadsPool(const ThreadPoolDesc& desc) = 0;
virtual const bool DestroyThreadsPool(const ThreadPoolHandle& handle) = 0;
virtual const bool GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const = 0;
virtual const bool SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask) = 0;
virtual void SetThreadName(threadID dwThreadId, const char* sThreadName) = 0;
virtual const char* GetThreadName(threadID dwThreadId) = 0;
// Return thread handle by thread name
virtual threadID GetThreadByName(const char* sThreadName) = 0;
// if bMark=true the calling thread will dump its stack during crashes
virtual void MarkThisThreadForDebugging(const char* name, bool bDump) = 0;
// </interfuscator:shuffle>
};
#endif // CRYINCLUDE_CRYCOMMON_ITHREADTASK_H
@@ -13,7 +13,6 @@
#define CRYINCLUDE_CRYCOMMON_ICONSOLEMOCK_H
#pragma once
#include <IRemoteCommand.h>
#include <IConsole.h>
#include <AzTest/AzTest.h>
@@ -1,43 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <CryMemoryManager.h>
class MemoryManagerMock
: public IMemoryManager
{
public:
MOCK_METHOD1(GetProcessMemInfo,
bool(SProcessMemInfo& minfo));
MOCK_METHOD3(TraceDefineHeap,
HeapHandle(const char* heapName, size_t size, const void* pBase));
MOCK_METHOD6(TraceHeapAlloc,
void(HeapHandle heap, void* mem, size_t size, size_t blockSize, const char* sUsage, const char* sNameHint));
MOCK_METHOD3(TraceHeapFree,
void(HeapHandle heap, void* mem, size_t blockSize));
MOCK_METHOD1(TraceHeapSetColor,
void(uint32 color));
MOCK_METHOD0(TraceHeapGetColor,
uint32());
MOCK_METHOD1(TraceHeapSetLabel,
void(const char* sLabel));
MOCK_METHOD1(CreateCustomMemoryHeapInstance,
ICustomMemoryHeap* const (EAllocPolicy const eAllocPolicy));
MOCK_METHOD3(CreateGeneralExpandingMemoryHeap,
IGeneralMemoryHeap* (size_t upperLimit, size_t reserveSize, const char* sUsage));
MOCK_METHOD3(CreateGeneralMemoryHeap,
IGeneralMemoryHeap* (void* base, size_t sz, const char* sUsage));
MOCK_METHOD2(ReserveAddressRange,
IMemoryAddressRange* (size_t capacity, const char* sName));
MOCK_METHOD2(CreatePageMappingHeap,
IPageMappingHeap* (size_t addressSpace, const char* sName));
};
@@ -1,47 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
struct NetworkMock : public INetwork
{
NetworkMock() : m_gridMate(nullptr)
{
}
GridMate::IGridMate* m_gridMate;
void Release() override {}
void GetMemoryStatistics([[maybe_unused]] ICrySizer* pSizer) override {}
void GetBandwidthStatistics([[maybe_unused]] SBandwidthStats* const pStats) override {}
void GetPerformanceStatistics([[maybe_unused]] SNetworkPerformance* pSizer) override {}
void GetProfilingStatistics([[maybe_unused]] SNetworkProfilingStats* const pStats) override {}
void SyncWithGame([[maybe_unused]] ENetworkGameSync syncType) override {}
const char* GetHostName() override { return "testhostname"; }
GridMate::IGridMate* GetGridMate() override
{
return m_gridMate;
}
ChannelId GetChannelIdForSessionMember([[maybe_unused]] GridMate::GridMember* member) const override { return ChannelId(); }
ChannelId GetServerChannelId() const override { return ChannelId(); }
ChannelId GetLocalChannelId() const override { return ChannelId(); }
CTimeValue GetSessionTime() override { return CTimeValue(); }
void ChangedAspects([[maybe_unused]] EntityId id, [[maybe_unused]] NetworkAspectType aspectBits) override {}
void SetDelegatableAspectMask([[maybe_unused]] NetworkAspectType aspectBits) override {}
void SetObjectDelegatedAspectMask([[maybe_unused]] EntityId entityId, [[maybe_unused]] NetworkAspectType aspects, [[maybe_unused]] bool set) override {}
void DelegateAuthorityToClient([[maybe_unused]] EntityId entityId, [[maybe_unused]] ChannelId clientChannelId) override {}
void InvokeActorRMI([[maybe_unused]] EntityId entityId, [[maybe_unused]] uint8 actorExtensionId, [[maybe_unused]] ChannelId targetChannelFilter, [[maybe_unused]] IActorRMIRep& rep) override {}
void InvokeScriptRMI([[maybe_unused]] ISerializable* serializable, [[maybe_unused]] bool isServerRMI, [[maybe_unused]] ChannelId toChannelId = kInvalidChannelId, [[maybe_unused]] ChannelId avoidChannelId = kInvalidChannelId) override {}
void RegisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {}
void UnregisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {}
EntityId LocalEntityIdToServerEntityId([[maybe_unused]] EntityId localId) const override { return EntityId(); }
EntityId ServerEntityIdToLocalEntityId([[maybe_unused]] EntityId serverId, [[maybe_unused]] bool allowForcedEstablishment = false) const override { return EntityId(); }
};
@@ -585,8 +585,6 @@ public:
SDepthTexture * (int, int, bool));
MOCK_METHOD1(DestroyDepthSurface,
void(SDepthTexture * pDepthSurf));
MOCK_CONST_METHOD1(CreateOptics,
IOpticsElementBase * (EFlareType type));
MOCK_METHOD1(PauseTimer,
void(bool bPause));
MOCK_METHOD0(CreateShaderPublicParams,
@@ -23,8 +23,6 @@ class SystemMock
public:
MOCK_METHOD0(Release,
void());
MOCK_CONST_METHOD0(GetCVarsWhiteListConfigSink,
ILoadConfigurationEntrySink * ());
MOCK_METHOD0(GetGlobalEnvironment,
SSystemGlobalEnvironment * ());
MOCK_METHOD2(UpdatePreTickBus,
@@ -37,8 +35,6 @@ public:
void());
MOCK_METHOD0(NeedDoWorkDuringOcclusionChecks,
bool());
MOCK_METHOD2(SynchronousLoadingTick,
void(const char* pFunc, int line));
MOCK_METHOD0(RenderStatistics,
void());
MOCK_METHOD0(GetUsedMemory,
@@ -84,8 +80,6 @@ public:
ILZ4Decompressor * ());
MOCK_METHOD0(GetZStdDecompressor,
IZStdDecompressor * ());
MOCK_METHOD0(GetINotificationNetwork,
INotificationNetwork * ());
MOCK_METHOD0(GetIViewSystem,
IViewSystem * ());
MOCK_METHOD0(GetILevelSystem,
@@ -116,28 +110,12 @@ public:
IRemoteConsole * ());
MOCK_METHOD0(GetIResourceManager,
IResourceManager * ());
MOCK_METHOD0(GetIThreadTaskManager,
IThreadTaskManager * ());
MOCK_METHOD0(GetIProfilingSystem,
IProfilingSystem * ());
MOCK_METHOD0(GetISystemEventDispatcher,
ISystemEventDispatcher * ());
MOCK_METHOD0(GetIVisualLog,
IVisualLog * ());
MOCK_METHOD0(GetITimer,
ITimer * ());
MOCK_METHOD0(GetIThreadManager,
IThreadManager * ());
MOCK_METHOD1(SetLoadingProgressListener,
void(ILoadingProgressListener * pListener));
MOCK_CONST_METHOD0(GetLoadingProgressListener,
ISystem::ILoadingProgressListener * ());
MOCK_METHOD1(SetIMaterialEffects,
void(IMaterialEffects * pMaterialEffects));
MOCK_METHOD1(SetIOpticsManager,
void(IOpticsManager * pOpticsManager));
MOCK_METHOD1(SetIVisualLog,
void(IVisualLog * pVisualLog));
MOCK_METHOD2(DebugStats,
void(bool checkpoint, bool leaks));
MOCK_METHOD0(DumpWinHeaps,
@@ -154,8 +132,6 @@ public:
bool());
MOCK_CONST_METHOD1(IsMODValid,
bool(const char* szMODName));
MOCK_CONST_METHOD0(IsMinimalMode,
bool());
MOCK_METHOD3(CreateXmlNode,
XmlNodeRef(const char*, bool, bool));
MOCK_METHOD4(LoadXmlFromBuffer,
@@ -164,8 +140,6 @@ public:
XmlNodeRef(const char*, bool));
MOCK_METHOD0(GetXmlUtils,
IXmlUtils * ());
MOCK_CONST_METHOD0(GetArchiveHost,
Serialization::IArchiveHost * ());
MOCK_METHOD1(SetViewCamera,
void(CCamera & Camera));
MOCK_METHOD0(GetViewCamera,
@@ -211,8 +185,6 @@ public:
void(ESystemConfigPlatform platform));
MOCK_METHOD1(AutoDetectSpec,
void(bool detectResolution));
MOCK_METHOD2(SetThreadState,
int(ESubsystem subsys, bool bActive));
MOCK_CONST_METHOD0(IsPaused,
bool());
MOCK_METHOD0(GetLocalizationManager,
@@ -223,8 +195,6 @@ public:
CPNoise3 * ());
MOCK_METHOD0(GetUpdateCounter,
uint64());
MOCK_CONST_METHOD0(GetCryFactoryRegistry,
ICryFactoryRegistry * ());
MOCK_METHOD1(RegisterErrorObserver,
bool(IErrorObserver * errorObserver));
MOCK_METHOD1(UnregisterErrorObserver,
@@ -243,10 +213,6 @@ public:
int());
MOCK_METHOD1(GetApplicationLogInstance,
int(const char* logFilePath));
MOCK_METHOD0(GetCurrentUpdateTimeStats,
sUpdateTimes & ());
MOCK_METHOD2(GetUpdateTimeStats,
const sUpdateTimes * (uint32 &, uint32 &));
MOCK_METHOD0(ClearErrorMessages,
void());
MOCK_METHOD2(debug_GetCallStack,
@@ -264,20 +230,6 @@ public:
MOCK_METHOD5(AsyncMemcpy,
void(void* dst, const void* src, size_t size, int nFlags, volatile int* sync));
#if defined(CVARS_WHITELIST)
MOCK_CONST_METHOD0(GetCVarsWhiteList,
ICVarsWhitelist * ());
#endif
#ifndef _RELEASE
MOCK_METHOD1(GetCheckpointData,
void(ICheckpointData & data));
MOCK_METHOD0(IncreaseCheckpointLoadCount,
void());
MOCK_METHOD1(SetLoadOrigin,
void(LevelLoadOrigin origin));
#endif
#if !defined(_RELEASE)
MOCK_CONST_METHOD0(IsSavingResourceList,
bool());
@@ -287,10 +239,6 @@ public:
bool());
MOCK_CONST_METHOD0(GetImageHandler,
const IImageHandler * ());
MOCK_METHOD3(InitializeEngineModule,
bool(const char* dllName, const char* moduleClassName, const SSystemInitParams&initParams));
MOCK_METHOD2(UnloadEngineModule,
bool(const char* dllName, const char* moduleClassName));
MOCK_METHOD0(GetRootWindowMessageHandler,
void*());
MOCK_METHOD1(RegisterWindowMessageHandler,
@@ -1,29 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzTest/AzTest.h>
#include <CGFContent.h>
class MockIAssetWriter
: public IAssetWriter
{
public:
~MockIAssetWriter() override = default;
MOCK_METHOD1(WriteCGF,
bool(CContentCGF* content));
MOCK_METHOD2(WriteCHR,
bool(CContentCGF* content, IConvertContext* convertContext));
MOCK_METHOD3(WriteSKIN,
bool(CContentCGF* content, IConvertContext* convertContext, bool exportMorphTargets));
};
@@ -1,11 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
@@ -1,14 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
../../WinBase.cpp
)
@@ -1,13 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
)
@@ -1,11 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
@@ -1,13 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
)
@@ -1,11 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
@@ -1,14 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
../../WinBase.cpp
)
@@ -1,15 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
../../EngineSettingsBackendApple.cpp
../../EngineSettingsBackendApple.h
)
@@ -1,11 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
@@ -1,14 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
../../WinBase.cpp
)
@@ -1,15 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
../../EngineSettingsBackendWin32.cpp
../../EngineSettingsBackendWin32.h
)
@@ -1,11 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
@@ -1,13 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
)
@@ -1,13 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
)
@@ -1,11 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
@@ -1,14 +0,0 @@
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or the license accompanying this file. Do not
# remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
set(FILES
../../WinBase.cpp
)
-70
View File
@@ -1,70 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_PROFILELOG_H
#define CRYINCLUDE_CRYCOMMON_PROFILELOG_H
#pragma once
#include <ISystem.h> // <> required for Interfuscator
#include <ITimer.h> // <> required for Interfuscator
struct ILogElement
{
virtual ~ILogElement(){}
virtual ILogElement* Log (const char* name, const char* message) = 0;
virtual ILogElement* SetTime (float time) = 0;
virtual void Flush (stack_string& indent) = 0;
};
struct IProfileLogSystem
{
virtual ~IProfileLogSystem(){}
virtual ILogElement* Log (const char* name, const char* msg) = 0;
virtual void SetTime (ILogElement* pElement, float time) = 0;
virtual void Release () = 0;
};
struct SHierProfileLogItem
{
SHierProfileLogItem(const char* name, const char* msg, int inbDoLog)
: m_pLogElement(NULL)
, m_bDoLog(inbDoLog)
{
if (m_bDoLog)
{
m_pLogElement = gEnv->pProfileLogSystem->Log(name, msg);
m_startTime = gEnv->pTimer->GetAsyncTime();
}
}
~SHierProfileLogItem()
{
if (m_bDoLog)
{
CTimeValue endTime = gEnv->pTimer->GetAsyncTime();
gEnv->pProfileLogSystem->SetTime(m_pLogElement, (endTime - m_startTime).GetMilliSeconds());
}
}
private:
int m_bDoLog;
CTimeValue m_startTime;
ILogElement* m_pLogElement;
};
#define HPROFILE_BEGIN(msg1, msg2, doLog) { SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog);
#define HPROFILE_END() }
#define HPROFILE(msg1, msg2, doLog) SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog);
#endif // CRYINCLUDE_CRYCOMMON_PROFILELOG_H
-33
View File
@@ -78,9 +78,6 @@ typedef uint32 vtx_idx;
#if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS
#define RELEASE_LOGGING
//#if defined(_RELEASE)
//#define CVARS_WHITELIST
//#endif // defined(_RELEASE)
#endif
#if defined(_RELEASE) && !defined(RELEASE_LOGGING)
@@ -181,32 +178,6 @@ typedef uint32 vtx_idx;
#define SHADER_REFLECT_TEXTURE_SLOTS 0
#endif
#if (defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC)) && (!defined(AZ_MONOLITHIC_BUILD) || defined(RESOURCE_COMPILER))
#define CRY_ENABLE_RC_HELPER 1
#endif
#if !defined(_RELEASE) && PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM
#define SOFTCODE_SYSTEM_ENABLED
#endif
// Is SoftCoding enabled for this module? Usually set by the SoftCode AddIn in conjunction with a SoftCode.props file.
#ifdef SOFTCODE_ENABLED
// Is this current compilation unit part of a SOFTCODE build?
#ifdef SOFTCODE
// Import any SC functions from the host module
#define SC_API __declspec(dllimport)
#else
// Export any SC functions from the host module
#define SC_API __declspec(dllexport)
#endif
#else // SoftCode disabled
#define SC_API
#endif
// these enable and disable certain net features to give compatibility between PCs and consoles / profile and performance builds
#define PC_CONSOLE_NET_COMPATIBLE 0
#define PROFILE_PERFORMANCE_NET_COMPATIBLE 0
@@ -292,10 +263,6 @@ typedef uint32 vtx_idx;
# define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined
#endif
#if defined(SOFTCODE_ENABLED)
#error "SoftCode currently relies on CryMemoryManager being enabled. Either build without SoftCode support, or enable CryMemoryManager."
#endif
#if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER)
#define GPU_PARTICLES 1
#else
@@ -1,639 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "ProjectDefines.h"
#if defined(CRY_ENABLE_RC_HELPER)
#include "ResourceCompilerHelper.h"
#include "EngineSettingsManager.h"
// When complining CryTiffPlugin the mayaAssert.h is included that defined
// Assert as _Assert. This wreaks havoc with AZ_Assert since under the covers
// it calls AzCore::Debug::Trace::Assert, which gets transformed bo
// Trace::_Assert, which does not exist. Gotta love macros. Undefine Assert
// before we include semaphore so that it can compile correctly
#if defined(Assert)
#undef Assert
#endif
#include <AzCore/std/parallel/semaphore.h>
#include <AzCore/std/smart_ptr/shared_ptr.h>
#include <AzCore/std/string/string_view.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Utils/Utils.h>
#if defined(AZ_PLATFORM_WINDOWS)
#include <windows.h>
#include <shellapi.h> // ShellExecuteW()
#endif
#if AZ_TRAIT_OS_PLATFORM_APPLE
#include "AppleSpecific.h"
#include <CoreFoundation/CoreFoundation.h>
#else
#undef RC_EXECUTABLE
#define RC_EXECUTABLE "rc.exe"
#endif
#include <assert.h>
#include <string> // lawsonn - we use std::string internally
#include <sstream>
namespace
{
class LineStreamBuffer
{
public:
template <typename T>
LineStreamBuffer(T* object, void (T::* method)(const char* line))
: m_charCount(0)
, m_bTruncated(false)
{
m_target = new Target<T>(object, method);
}
~LineStreamBuffer()
{
Flush();
delete m_target;
}
void HandleText(const char* text, int length)
{
const char* pos = text;
while (pos - text < length)
{
const char* start = pos;
while (pos - text < length && *pos != '\n' && *pos != '\r')
{
++pos;
}
size_t n = pos - start;
if (m_charCount + n > kMaxCharCount)
{
n = kMaxCharCount - m_charCount;
m_bTruncated = true;
}
memcpy(&m_buffer[m_charCount], start, n);
m_charCount += n;
if (pos - text < length)
{
Flush();
while (pos - text < length && (*pos == '\n' || *pos == '\r'))
{
++pos;
}
}
}
}
void Flush()
{
if (m_charCount > 0)
{
m_buffer[m_charCount] = 0;
m_target->Call(m_buffer);
m_charCount = 0;
}
}
bool IsTruncated() const
{
return m_bTruncated;
}
private:
struct ITarget
{
virtual ~ITarget() {}
virtual void Call(const char* line) = 0;
};
template <typename T>
struct Target
: public ITarget
{
public:
Target(T* object, void (T::* method)(const char* line))
: object(object)
, method(method) {}
virtual void Call(const char* line)
{
(object->*method)(line);
}
private:
T* object;
void (T::* method)(const char* line);
};
ITarget* m_target;
size_t m_charCount;
static const size_t kMaxCharCount = 2047;
char m_buffer[kMaxCharCount + 1];
bool m_bTruncated;
};
#if !defined(AZ_PLATFORM_WINDOWS)
void MessageBoxW(int, const wchar_t* header, const wchar_t* message, unsigned long)
{
#if AZ_TRAIT_OS_PLATFORM_APPLE
CFStringEncoding encoding = (CFByteOrderLittleEndian == CFByteOrderGetCurrent()) ?
kCFStringEncodingUTF32LE : kCFStringEncodingUTF32BE;
CFStringRef header_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast<const UInt8*>(header), wcslen(header) * sizeof(wchar_t), encoding, false);
CFStringRef message_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast<const UInt8*>(message), wcslen(message) * sizeof(wchar_t), encoding, false);
CFOptionFlags result; //result code from the message box
CFUserNotificationDisplayAlert(0, kCFUserNotificationStopAlertLevel, 0, 0, 0, header_ref, message_ref, 0, 0, 0, &result);
CFRelease(header_ref);
CFRelease(message_ref);
#endif
}
#endif
}
namespace
{
class RcLock
{
public:
RcLock()
: m_cs(0u, 1u)
{
m_cs.release();
}
~RcLock()
{
}
void Lock()
{
m_cs.acquire();
}
void Unlock()
{
m_cs.release();
}
private:
AZStd::semaphore m_cs;
};
template<class LockClass>
class RcAutoLock
{
public:
RcAutoLock(LockClass& lock)
: m_lock(lock)
{
m_lock.Lock();
}
~RcAutoLock()
{
m_lock.Unlock();
}
private:
RcAutoLock();
RcAutoLock(const RcAutoLock<LockClass>&);
RcAutoLock<LockClass>& operator =(const RcAutoLock<LockClass>&);
private:
LockClass& m_lock;
};
HANDLE s_rcProcessHandle = 0;
RcLock s_rcProcessHandleLock;
}
//////////////////////////////////////////////////////////////////////////
static void ShowMessageBoxRcNotFound([[maybe_unused]] const wchar_t* const szCmdLine, [[maybe_unused]] const wchar_t* const szDir)
{
SettingsManagerHelpers::CFixedString<wchar_t, MAX_PATH* 4 + 150> tmp;
tmp.append(L"The resource compiler (RC.EXE) was not found.");
MessageBoxW(0, tmp.c_str(), L"Error", MB_ICONERROR | MB_OK);
}
//////////////////////////////////////////////////////////////////////////
namespace
{
class ResourceCompilerLineHandler
{
public:
ResourceCompilerLineHandler(IResourceCompilerListener* listener)
: m_listener(listener)
{
}
void HandleLine(const char* line)
{
if (!m_listener || !line)
{
return;
}
// check the first three characters to see if it's a warning or error.
bool bHasPrefix;
IResourceCompilerListener::MessageSeverity severity;
if ((line[0] == 'E') && (line[1] == ':') && (line[2] == ' '))
{
bHasPrefix = true;
severity = IResourceCompilerListener::MessageSeverity_Error;
line += 3; // skip the prefix
}
else if ((line[0] == 'W') && (line[1] == ':') && (line[2] == ' '))
{
bHasPrefix = true;
severity = IResourceCompilerListener::MessageSeverity_Warning;
line += 3; // skip the prefix
}
else if ((line[0] == ' ') && (line[1] == ' ') && (line[2] == ' '))
{
bHasPrefix = true;
severity = IResourceCompilerListener::MessageSeverity_Info;
line += 3; // skip the prefix
}
else
{
bHasPrefix = false;
severity = IResourceCompilerListener::MessageSeverity_Info;
}
if (bHasPrefix)
{
// skip thread info "%d>", if present
{
const char* p = line;
while (*p == ' ')
{
++p;
}
if (isdigit(*p))
{
while (isdigit(*p))
{
++p;
}
if (*p == '>')
{
line = p + 1;
}
}
}
// skip time info "%d:%d", if present
{
const char* p = line;
while (*p == ' ')
{
++p;
}
if (isdigit(*p))
{
while (isdigit(*p))
{
++p;
}
if (*p == ':')
{
++p;
if (isdigit(*p))
{
while (isdigit(*p))
{
++p;
}
while (*p == ' ')
{
++p;
}
line = p;
}
}
}
}
}
m_listener->OnRCMessage(severity, line);
}
private:
IResourceCompilerListener* m_listener;
};
// we now support macros like #ENGINEROOT# in the string:
void replaceAllInStringInPlace(std::string& inOut, const char* findValue, const char* replaceValue)
{
if (!findValue)
{
return;
}
if (!replaceValue)
{
return;
}
std::string::size_type pos = std::string::npos;
std::string::size_type replaceLen = strlen(findValue);
while ((pos = inOut.find(findValue)) != std::string::npos)
{
inOut.replace(pos, replaceLen, replaceValue);
}
}
// given a string that contains macros (like #ENGINEROOT#), eliminate the macros and replace them with the real data.
// note that in the 'remote' implementation, these macros are sent to the remote RC. It can then expand them for its own environment
// but in a local RC, these macros are expanded by the local environment.
void expandMacros(const char* inputString, char* outputString, std::size_t bufferSize)
{
if (!inputString)
{
return;
}
if (!outputString)
{
return;
}
AZStd::string_view rootFolder;
AZ::ComponentApplicationBus::BroadcastResult(rootFolder, &AZ::ComponentApplicationRequests::GetAppRoot);
std::string finalString(inputString);
const AZStd::string rootFolderStr = rootFolder.data();
replaceAllInStringInPlace(finalString, "#ENGINEROOT#", rootFolderStr.c_str());
// put additional replacements here.
azstrcpy(outputString, bufferSize, finalString.c_str());
}
}
//////////////////////////////////////////////////////////////////////////
IResourceCompilerHelper::ERcCallResult CResourceCompilerHelper::CallResourceCompiler(
const char* szFileName,
const char* szAdditionalSettings,
IResourceCompilerListener* listener,
bool bMayShowWindow,
bool bSilent,
bool bNoUserDialog,
const wchar_t* szWorkingDirectory,
[[maybe_unused]] const wchar_t* szRootPath)
{
#if defined(AZ_PLATFORM_WINDOWS)
HANDLE hChildStdOutRd = INVALID_HANDLE_VALUE, hChildStdOutWr = INVALID_HANDLE_VALUE;
HANDLE hChildStdInRd = INVALID_HANDLE_VALUE, hChildStdInWr = INVALID_HANDLE_VALUE;
PROCESS_INFORMATION pi;
#else
FILE* hChildStdOutRd;
#endif
{
RcAutoLock<RcLock> lock(s_rcProcessHandleLock);
// make command for execution
SettingsManagerHelpers::CFixedString<wchar_t, MAX_PATH* 3> wRemoteCmdLine;
if (!szAdditionalSettings)
{
szAdditionalSettings = "";
}
// expand the additioanl settings.
char szActualFileName[512] = {0};
char szActualAdditionalSettings[512] = {0};
expandMacros(szFileName, szActualFileName, 512);
expandMacros(szAdditionalSettings, szActualAdditionalSettings, 512);
CSettingsManagerTools smTools = CSettingsManagerTools(); // moved this line to after macro expansion to avoid multiple of these existing at once.
AZStd::string_view exeFolderName;
AZ::ComponentApplicationBus::BroadcastResult(exeFolderName, &AZ::ComponentApplicationRequests::GetExecutableFolder);
wchar_t szRegSettingsBuffer[1024];
smTools.GetEngineSettingsManager()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(szRegSettingsBuffer, sizeof(szRegSettingsBuffer)));
bool enableSourceControl = true;
smTools.GetEngineSettingsManager()->GetValueByRef("RC_EnableSourceControl", enableSourceControl);
wRemoteCmdLine.appendAscii("\"");
wRemoteCmdLine.appendAscii(exeFolderName.data(), exeFolderName.size());
wRemoteCmdLine.appendAscii("/");
wRemoteCmdLine.appendAscii(RC_EXECUTABLE);
wRemoteCmdLine.appendAscii("\"");
if (!enableSourceControl)
{
wRemoteCmdLine.appendAscii(" -nosourcecontrol ");
}
if (!szFileName)
{
wRemoteCmdLine.appendAscii(" -userdialog=0 ");
wRemoteCmdLine.appendAscii(szActualAdditionalSettings);
wRemoteCmdLine.appendAscii(" ");
wRemoteCmdLine.append(szRegSettingsBuffer);
}
else
{
wRemoteCmdLine.appendAscii(" \"");
wRemoteCmdLine.appendAscii(szActualFileName);
wRemoteCmdLine.appendAscii("\"");
wRemoteCmdLine.appendAscii(bNoUserDialog ? " -userdialog=0 " : " -userdialog=1 ");
wRemoteCmdLine.appendAscii(szActualAdditionalSettings);
wRemoteCmdLine.appendAscii(" ");
wRemoteCmdLine.append(szRegSettingsBuffer);
}
// Create a pipe to read the stdout of the RC.
SECURITY_ATTRIBUTES saAttr;
if (listener)
{
#if defined(AZ_PLATFORM_WINDOWS)
ZeroMemory(&saAttr, sizeof(saAttr));
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = 0;
CreatePipe(&hChildStdOutRd, &hChildStdOutWr, &saAttr, 0);
SetHandleInformation(hChildStdOutRd, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN
CreatePipe(&hChildStdInRd, &hChildStdInWr, &saAttr, 0);
SetHandleInformation(hChildStdInWr, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN
#endif
}
#if defined(AZ_PLATFORM_WINDOWS)
STARTUPINFOW si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwX = 100;
si.dwY = 100;
if (listener)
{
si.hStdError = hChildStdOutWr;
si.hStdOutput = hChildStdOutWr;
si.hStdInput = hChildStdInRd;
si.dwFlags = STARTF_USEPOSITION | STARTF_USESTDHANDLES;
}
else
{
si.dwFlags = STARTF_USEPOSITION;
}
ZeroMemory(&pi, sizeof(pi));
#endif
bool bShowWindow;
if (bMayShowWindow)
{
wchar_t buffer[20];
smTools.GetEngineSettingsManager()->GetValueByRef("ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)));
bShowWindow = (wcscmp(buffer, L"true") == 0);
}
else
{
bShowWindow = false;
}
#if defined(AZ_PLATFORM_WINDOWS)
const wchar_t* szStartingDirectory = szWorkingDirectory;
if (!szStartingDirectory)
{
char currentDirectory[MAX_PATH];
AZ::Utils::GetExecutableDirectory(currentDirectory, MAX_PATH);
SettingsManagerHelpers::CFixedString<wchar_t, MAX_PATH> wCurrentDirectory;
wCurrentDirectory.appendAscii(currentDirectory);
szStartingDirectory = wCurrentDirectory.c_str();
}
if (!CreateProcessW(
NULL, // No module name (use command line).
const_cast<wchar_t*>(wRemoteCmdLine.c_str()), // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
TRUE, // Set handle inheritance to TRUE.
bShowWindow ? 0 : CREATE_NO_WINDOW, // creation flags.
NULL, // Use parent's environment block.
szStartingDirectory, // Set starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi)) // Pointer to PROCESS_INFORMATION structure.
{
// The following code block is commented out instead of being deleted
// because it's good to have at hand for a debugging session.
#if 0
const size_t charsInMessageBuffer = 32768; // msdn about FormatMessage(): "The output buffer cannot be larger than 64K bytes."
wchar_t szMessageBuffer[charsInMessageBuffer] = L"";
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, szMessageBuffer, charsInMessageBuffer, NULL);
GetCurrentDirectoryW(charsInMessageBuffer, szMessageBuffer);
#endif
if (!bSilent)
{
ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szStartingDirectory);
}
return eRcCallResult_notFound;
}
s_rcProcessHandle = pi.hProcess;
#else
int fd = open(".", O_RDONLY);
char remoteCmdLineUtf8[MAX_PATH * 8];
char workingDirectory[MAX_PATH * 8];
ConvertUtf16ToUtf8(wRemoteCmdLine.c_str(), SettingsManagerHelpers::CCharBuffer(remoteCmdLineUtf8, MAX_PATH * 8));
if (szWorkingDirectory)
{
ConvertUtf16ToUtf8(szWorkingDirectory, SettingsManagerHelpers::CCharBuffer(workingDirectory, MAX_PATH * 8));
chdir(workingDirectory);
}
hChildStdOutRd = popen(remoteCmdLineUtf8, "r");
fchdir(fd);
if (hChildStdOutRd == nullptr)
{
if (!bSilent)
{
ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szWorkingDirectory);
}
return eRcCallResult_notFound;
}
#endif
}
bool bFailedToReadOutput = false;
if (listener)
{
#if defined(AZ_PLATFORM_WINDOWS)
// Close the pipe that writes to the child process, since we don't actually have any input for it.
CloseHandle(hChildStdInWr);
// Read all the output from the child process.
CloseHandle(hChildStdOutWr);
#endif
ResourceCompilerLineHandler lineHandler(listener);
LineStreamBuffer lineBuffer(&lineHandler, &ResourceCompilerLineHandler::HandleLine);
for (;; )
{
char buffer[2048];
DWORD bytesRead;
#if defined(AZ_PLATFORM_WINDOWS)
if (!ReadFile(hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, NULL) || (bytesRead == 0))
#else
if (fgets(buffer, sizeof(buffer), hChildStdOutRd) == nullptr || (bytesRead = strlen(buffer) == 0))
#endif
{
break;
}
lineBuffer.HandleText(buffer, bytesRead);
}
bFailedToReadOutput = lineBuffer.IsTruncated();
}
#if defined(AZ_PLATFORM_WINDOWS)
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
#else
DWORD exitCode = pclose(hChildStdOutRd);
#endif
#if defined(AZ_PLATFORM_WINDOWS)
RcAutoLock<RcLock> lock(s_rcProcessHandleLock);
s_rcProcessHandle = 0;
DWORD exitCode = eRcExitCode_Error;
if (bFailedToReadOutput || GetExitCodeProcess(pi.hProcess, &exitCode) == 0)
{
exitCode = eRcExitCode_Error;
}
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
#endif
return ConvertResourceCompilerExitCodeToResultCode(exitCode);
}
#endif //(CRY_ENABLE_RC_HELPER)
@@ -1,46 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H
#define CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H
#pragma once
#if defined(CRY_ENABLE_RC_HELPER)
#include "IResourceCompilerHelper.h"
//////////////////////////////////////////////////////////////////////////
// Provides settings and functions to make calls to RC.
// calls RC locally. only works on windows, does not exist on other platforms
// note: You shouldn't be calling this directly
// instead, you should be calling it via the IResourceCompilerHelper interface.
// since it may be replaced with a custom RC for your platform or a remote invocation
class CResourceCompilerHelper
: public IResourceCompilerHelper
{
public:
virtual ERcCallResult CallResourceCompiler(
const char* szFileName = 0,
const char* szAdditionalSettings = 0,
IResourceCompilerListener* listener = 0,
bool bMayShowWindow = true,
bool bSilent = false,
bool bNoUserDialog = false,
const wchar_t* szWorkingDirectory = 0,
const wchar_t* szRootPath = 0) override;
};
#endif // CRY_ENABLE_RC_HELPER
#endif // CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H
@@ -1,46 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H
#pragma once
#ifdef SERIALIZATION_STANDALONE
#include <assert.h>
#else
#include <platform.h>
#endif
#ifdef YASLI_ASSERT
# undef YASLI_ASSERT
#endif
#ifdef YASLI_VERIFY
# undef YASLI_VERIFY
#endif
#ifdef YASLI_ESCAPE
# undef YASLI_ESCAPE
#endif
#ifdef SERIALIZATION_STANDALONE
#define YASLI_ASSERT(x) assert(x)
#define YASLI_ASSERT_STR(x, str) assert(x && str)
#define YASLI_ESCAPE(x, action) if (!(x)) { YASLI_ASSERT(0 && #x); action; };
#else
#define YASLI_ASSERT(x) CRY_ASSERT(x)
#define YASLI_ASSERT_STR(x, str) CRY_ASSERT_MESSAGE(x, str)
#define YASLI_ESCAPE(x, action) if (!(x)) { YASLI_ASSERT(0 && #x); action; };
#endif // SERIALIZATION_STANDALONE
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H
@@ -1,39 +0,0 @@
// Copyright (c) 2012 Crytek GmbH
// Authors: Evgeny Andreeshchev, Alexander Kotliar
// Based on: Yasli - the serialization library.
// Modifications copyright Amazon.com, Inc. or its affiliates
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H
#pragma once
namespace Serialization{
class IArchive;
template<class Enum>
class BitVector
{
public:
BitVector(int value = 0) : value_(value) {}
operator int&() { return value_; }
operator int() const { return value_; }
BitVector& operator|= (Enum value) { value_ |= value; return *this; }
BitVector& operator|= (int value) { value_ |= value; return *this; }
BitVector& operator&= (int value) { value_ &= value; return *this; }
void Serialize(IArchive& ar);
private:
int value_;
};
template<class Enum>
bool Serialize(Serialization::IArchive& ar, Serialization::BitVector<Enum>& value, const char* name, const char* label);
}
#include "BitVectorImpl.h"
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H
@@ -1,88 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H
#pragma once
#include "Serialization/BitVector.h"
#include "Serialization/IArchive.h"
#include "Serialization/Enum.h"
namespace Serialization {
struct BitVectorWrapper
{
int* valuePointer;
int value;
const CEnumDescription* description;
explicit BitVectorWrapper(int* _value = 0, const CEnumDescription* _description = 0)
: valuePointer(_value)
, description(_description)
{
if (valuePointer)
{
value = *valuePointer;
}
}
BitVectorWrapper(const BitVectorWrapper& _rhs)
: value(_rhs.value)
, description(0)
, valuePointer(0)
{
}
~BitVectorWrapper()
{
if (valuePointer)
{
* valuePointer = value;
}
}
BitVectorWrapper& operator=(const BitVectorWrapper& rhs)
{
value = rhs.value;
return *this;
}
void Serialize(IArchive& ar)
{
ar(value, "value", "Value");
}
};
template<class Enum>
void BitVector<Enum>::Serialize(IArchive& ar)
{
ar(value_, "value", "Value");
}
}
template<class Enum>
bool Serialize(Serialization::IArchive& ar, Serialization::BitVector<Enum>& value, const char* name, const char* label)
{
using namespace Serialization;
CEnumDescription& desc = getEnumDescription<Enum>();
if (ar.IsEdit())
{
return ar(BitVectorWrapper(&static_cast<int&>(value), &desc), name, label);
}
else
{
return desc.serializeBitVector(ar, static_cast<int&>(value), name, label);
}
}
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H
@@ -1,93 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H
#pragma once
#include <stdlib.h> // for malloc and free
namespace Serialization
{
// Black box is used to store opaque data blobs in a format internal to
// specific Archive. For example it can be used to store sections of the JSON
// or binary archive.
//
// This is useful for the Editor to store portions of files with unfamiliar
// structure.
//
// We store deallocation function here so we can safely pass the blob
// across DLLs with different memory allocators.
struct SBlackBox
{
const char* format;
void* data;
size_t size;
typedef void(* FreeFunction)(void*);
FreeFunction freeFunction;
SBlackBox()
: format("")
, data(0)
, size(0)
, freeFunction(0)
{
}
SBlackBox(const SBlackBox& rhs)
: format("")
, data(0)
, size(0)
, freeFunction(0)
{
*this = rhs;
}
void set(const char* _format, const void* _data, size_t _size)
{
if (_data && freeFunction)
{
freeFunction(this->data);
this->data = 0;
this->size = 0;
freeFunction = 0;
}
this->format = _format;
if (_data && _size)
{
this->data = CryModuleMalloc(_size);
memcpy(this->data, _data, _size);
this->size = _size;
freeFunction = &Free;
}
}
SBlackBox& operator=(const SBlackBox& rhs)
{
set(rhs.format, rhs.data, rhs.size);
return *this;
}
~SBlackBox()
{
set("", 0, 0);
}
static void Free(void* ptr)
{
CryModuleFree(ptr);
}
};
}
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H
@@ -1,102 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#pragma once
#include <Serialization/Serializer.h>
#include "ClassFactory.h"
template <class T>
class BoostSharedPtrSerializer
: public Serialization::IPointer
{
public:
BoostSharedPtrSerializer(AZStd::shared_ptr<T>& ptr)
: m_ptr(ptr)
{
}
const char* registeredTypeName() const override
{
if (m_ptr)
{
return factoryOverride().getRegisteredTypeName(m_ptr.get());
}
else
{
return "";
}
}
void create(const char* registeredTypeName) const override
{
CRY_ASSERT(!m_ptr || m_ptr.use_count() == 1);
if (registeredTypeName && registeredTypeName[0] != '\0')
{
m_ptr.reset(factoryOverride().create(registeredTypeName));
}
else
{
m_ptr.reset();
}
}
Serialization::TypeID baseType() const override
{
return Serialization::TypeID::get<T>();
}
virtual Serialization::SStruct serializer() const override
{
return Serialization::SStruct(*m_ptr);
}
void* get() const
{
return reinterpret_cast<void*>(m_ptr.get());
}
const void* handle() const
{
return &m_ptr;
}
Serialization::TypeID pointerType() const override
{
return Serialization::TypeID::get<AZStd::shared_ptr<T> >();
}
Serialization::ClassFactory<T>* factory() const override
{
return &factoryOverride();
}
virtual Serialization::ClassFactory<T>& factoryOverride() const
{
return Serialization::ClassFactory<T>::the();
}
protected:
AZStd::shared_ptr<T>& m_ptr;
};
namespace AZStd
{
template <class T>
bool Serialize(Serialization::IArchive& ar, AZStd::shared_ptr<T>& ptr, const char* name, const char* label)
{
BoostSharedPtrSerializer<T> serializer(ptr);
return ar(static_cast<Serialization::IPointer&>(serializer), name, label);
}
}
@@ -1,30 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H
#pragma once
template <uint32 StoreStrings, typename THash>
struct SCRCRef;
namespace Serialization
{
class IArchive;
}
template <uint32 StoreStrings, typename THash>
bool Serialize(Serialization::IArchive& ar, SCRCRef<StoreStrings, THash>& crcRef, const char* name, const char* label);
#include "CRCRefImpl.h"
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H
@@ -1,100 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H
#pragma once
#include "IArchive.h"
#include "Serializer.h"
template <typename TCRCRef>
class CRCRefSerializer
: public Serialization::IString
{
public:
CRCRefSerializer(TCRCRef& crcRef)
: m_crcRef(crcRef)
{
}
virtual void set(const char* value)
{
m_crcRef.SetByString(value);
}
virtual const char* get() const
{
return m_crcRef.c_str();
}
const void* handle() const
{
return &m_crcRef;
}
Serialization::TypeID type() const
{
return Serialization::TypeID::get<TCRCRef>();
}
TCRCRef& m_crcRef;
};
template <uint32 StoreStrings, typename THash>
class CCRCRefSerializerNoStrings
{
public:
CCRCRefSerializerNoStrings(struct SCRCRef<StoreStrings, THash>& crcRef)
: crc(crcRef.crc)
{
}
bool Serialize(Serialization::IArchive& ar)
{
return ar(crc, "CRC", "CRC");
}
typedef typename THash::TInt TInt;
TInt& crc;
};
template <uint32 StoreStrings, typename THash>
bool Serialize(Serialization::IArchive& ar, struct SCRCRef<StoreStrings, THash>& crcRef, const char* name, const char* label)
{
if (StoreStrings == 0)
{
if (ar.IsInput())
{
SCRCRef<StoreStrings, THash> crcCopy;
ar(CCRCRefSerializerNoStrings<StoreStrings, THash>(crcCopy), name, label);
if (crcCopy.crc != THash::INVALID)
{
crcRef = crcCopy;
return true;
}
}
else if (ar.IsOutput())
{
return ar(CCRCRefSerializerNoStrings<StoreStrings, THash>(crcRef), name, label);
}
}
CRCRefSerializer<SCRCRef<StoreStrings, THash> > crcRefSerializer(crcRef);
return ar(static_cast<Serialization::IString&>(crcRefSerializer), name, label);
}
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H
@@ -1,184 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H
#pragma once
#include <AzCore/std/functional.h>
namespace Serialization
{
struct ICallback
{
virtual bool SerializeValue(IArchive& ar, const char* name, const char* value) = 0;
virtual ICallback* Clone() = 0;
virtual void Release() = 0;
virtual TypeID Type() const = 0;
typedef AZStd::function<void(void*, const TypeID&)> ApplyFunction;
virtual void Call(const ApplyFunction&) = 0;
};
template<class T, class Decorator = T>
struct CallbackSimple
: ICallback
{
typedef AZStd::function<void(const T&)> CallbackFunction;
T* value;
T oldValue;
CallbackFunction callback;
CallbackSimple(T* value, const T& oldValue, const AZStd::function<void(const T&)>& callback)
: value(value)
, oldValue(oldValue)
, callback(callback)
{
}
ICallback* Clone() { return new CallbackSimple<T>(0, oldValue, callback); }
void Release() { delete this; }
bool SerializeValue(IArchive& ar, const char* name, const char* label) { return ar(*value, name, label); }
TypeID Type() const{ return TypeID::get<T>(); }
void Call(const ApplyFunction& applyFunction)
{
T newValue;
applyFunction((void*)&newValue, TypeID::get<T>());
if (oldValue != newValue)
{
callback(newValue);
oldValue = newValue;
}
}
};
template<class T, class Decorator = T>
struct CallbackWithDecorator
: ICallback
{
typedef AZStd::function<void(const T&)> CallbackFunction;
typedef AZStd::function<Decorator (T&)> DecoratorFunction;
T oldValue;
T* value;
CallbackFunction callback;
DecoratorFunction decorator;
CallbackWithDecorator(T* value,
const T& oldValue,
const CallbackFunction& callback,
const DecoratorFunction& decorator)
: value(value)
, oldValue(oldValue)
, callback(callback)
, decorator(decorator)
{
}
ICallback* Clone() { return new CallbackWithDecorator<T, Decorator>(0, oldValue, callback, decorator); }
void Release() { delete this; }
bool SerializeValue(IArchive& ar, const char* name, const char* label) { return ar(decorator(*value), name, label); }
TypeID Type() const{ return TypeID::get<Decorator>(); }
void Call(const ApplyFunction& applyFunction)
{
T newValue;
Decorator dec = decorator(newValue);
applyFunction((void*)&dec, TypeID::get<Decorator>());
if (oldValue != newValue)
{
callback(newValue);
oldValue = newValue;
}
}
};
namespace Detail
{
template <typename T>
struct MethodReturnType
{
typedef void type;
};
template <typename ClassType, typename ReturnType, typename Arg0>
struct MethodReturnType<ReturnType(ClassType::*)(Arg0) const>
{
typedef ReturnType type;
};
template<class T>
struct OperatorBracketsReturnType
{
typedef typename MethodReturnType<decltype(& T::operator())>::type Type;
};
}
template<class T, class CallbackFunc>
CallbackSimple<T>
Callback(T& value, const CallbackFunc& callback)
{
return CallbackSimple<T>(&value, value, AZStd::function<void(const T&)>(callback));
}
template<class T, class CallbackFunc, class DecoratorFunc>
CallbackWithDecorator<T, typename Detail::OperatorBracketsReturnType<DecoratorFunc>::Type>
Callback(T& value, const CallbackFunc& callback, const DecoratorFunc& decorator)
{
typedef typename Detail::OperatorBracketsReturnType<DecoratorFunc>::Type Decorator;
return CallbackWithDecorator<T, Decorator>(&value, value,
AZStd::function<void(const T&)>(callback),
AZStd::function<Decorator(T&)>(decorator));
}
template<class T>
bool Serialize(IArchive& ar, CallbackSimple<T>& callback, const char* name, const char* label)
{
if (ar.IsEdit())
{
return ar(static_cast<ICallback&>(callback), name, label);
}
else
{
if (!ar(*callback.value, name, label))
{
return false;
}
return true;
}
}
template<class T, class Decorator>
bool Serialize(IArchive& ar, CallbackWithDecorator<T, Decorator>& callback, const char* name, const char* label)
{
if (ar.IsEdit())
{
return ar(static_cast<ICallback&>(callback), name, label);
}
else
{
if (!ar(*callback.value, name, label))
{
return false;
}
return true;
}
}
}
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H
@@ -1,376 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H
#pragma once
#include <map>
#include <vector>
#include "Serialization/Assert.h"
#include "Serialization/IClassFactory.h"
#include "Serialization/TypeID.h"
namespace Serialization {
class IArchive;
class ClassFactoryManager
{
public:
static ClassFactoryManager& the()
{
static ClassFactoryManager factoryManager;
return factoryManager;
}
const IClassFactory* find(TypeID baseType) const
{
lazyRegisterFactories();
Factories::const_iterator it = factories_.find(baseType);
if (it == factories_.end())
{
return 0;
}
else
{
return it->second;
}
}
void registerFactory([[maybe_unused]] TypeID type, IClassFactory* factory)
{
factory->m_next = m_head;
m_head = factory;
}
protected:
void lazyRegisterFactories() const
{
if (m_head)
{
IClassFactory* factory = m_head;
while (factory)
{
const_cast<ClassFactoryManager*>(this)->factories_[factory->baseType_] = factory;
factory = factory->m_next;
}
const_cast<ClassFactoryManager*>(this)->m_head = nullptr;
}
}
typedef AZStd::unordered_map<TypeID, const IClassFactory*, AZStd::hash<TypeID>, AZStd::equal_to<TypeID>, AZ::StdLegacyAllocator> Factories;
Factories factories_;
IClassFactory* m_head = nullptr;
};
template<class BaseType>
class ClassFactory
: public IClassFactory
{
public:
static ClassFactory& the()
{
static AZStd::aligned_storage_for_t<ClassFactory> storage;
if (s_instance != (decltype(s_instance))&storage)
{
s_instance = new(&storage) ClassFactory();
}
return *s_instance;
}
static void destroy()
{
if (s_instance)
{
s_instance->~ClassFactory();
s_instance = nullptr;
}
}
class CreatorBase
{
public:
virtual ~CreatorBase() {}
virtual BaseType* create() const = 0;
virtual const TypeDescription& description() const{ return *description_; }
virtual void* vptr() const { return vptr_; }
virtual TypeID typeID() const = 0;
protected:
const TypeDescription* description_ = nullptr;
void* vptr_ = nullptr;
public:
CreatorBase* next;
};
static void* extractVPtr(BaseType* ptr)
{
return *((void**)ptr);
}
template<class Derived>
struct Annotation
{
Annotation(IClassFactory* factory, const char* name, const char* value) { static_cast<ClassFactory<BaseType>*>(factory)->addAnnotation<Derived>(name, value); }
};
template<class Derived>
class Creator
: public CreatorBase
{
public:
Creator(const TypeDescription* description, ClassFactory* factory = nullptr)
{
this->description_ = description;
if (!factory)
{
factory = &ClassFactory::the();
}
factory->registerCreator(this);
}
void* vptr() const override
{
if (!this->vptr_)
{
Derived vptrProbe;
const_cast<Creator*>(this)->vptr_ = extractVPtr(&vptrProbe);
}
return this->vptr_;
}
BaseType* create() const override { return new Derived(); }
TypeID typeID() const override { return Serialization::TypeID::get<Derived>(); }
};
ClassFactory()
: IClassFactory(TypeID::get<BaseType>())
{
ClassFactoryManager::the().registerFactory(baseType_, this);
}
~ClassFactory()
{
m_data->~Data();
m_data = nullptr;
}
typedef AZStd::unordered_map<string, const CreatorBase*, AZStd::hash<string>, AZStd::equal_to<string>, AZ::StdLegacyAllocator> TypeToCreatorMap;
typedef AZStd::unordered_map<void*, CreatorBase*, AZStd::hash<void*>, AZStd::equal_to<void*>, AZ::StdLegacyAllocator> VPtrToCreatorMap;
typedef AZStd::unordered_map<string, TypeID, AZStd::hash<string>, AZStd::equal_to<string>, AZ::StdLegacyAllocator> RegisteredNameToTypeID;
typedef AZStd::unordered_map<TypeID, std::vector<std::pair<const char*, const char*> >, AZStd::hash<TypeID>, AZStd::equal_to<TypeID>, AZ::StdLegacyAllocator> AnnotationMap;
virtual BaseType* create(const char* registeredName) const
{
lazyRegisterCreators();
if (!registeredName)
{
return 0;
}
if (registeredName[0] == '\0')
{
return 0;
}
typename TypeToCreatorMap::const_iterator it = m_data->typeToCreatorMap_.find(registeredName);
if (it != m_data->typeToCreatorMap_.end())
{
return it->second->create();
}
else
{
return 0;
}
}
virtual const char* getRegisteredTypeName(BaseType* ptr) const
{
lazyRegisterCreators();
if (ptr == 0)
{
return "";
}
void* vptr = extractVPtr(ptr);
typename VPtrToCreatorMap::const_iterator it = m_data->vptrToCreatorMap_.find(vptr);
if (it == m_data->vptrToCreatorMap_.end())
{
return "";
}
return it->second->description().name();
}
BaseType* createByIndex(int index) const
{
lazyRegisterCreators();
YASLI_ASSERT(size_t(index) < m_data->creators_.size());
return m_data->creators_[index]->create();
}
void serializeNewByIndex(IArchive& ar, int index, const char* name, const char* label)
{
lazyRegisterCreators();
YASLI_ESCAPE(size_t(index) < m_data->creators_.size(), return );
BaseType* ptr = m_data->creators_[index]->create();
ar(*ptr, name, label);
delete ptr;
}
// from ClassFactoryInterface:
size_t size() const{ return m_data->creators_.size(); }
const TypeDescription* descriptionByIndex(int index) const override
{
lazyRegisterCreators();
if (size_t(index) >= int(m_data->creators_.size()))
{
return 0;
}
return &m_data->creators_[index]->description();
}
const TypeDescription* descriptionByRegisteredName(const char* name) const override
{
lazyRegisterCreators();
const size_t numCreators = m_data->creators_.size();
for (size_t i = 0; i < numCreators; ++i)
{
if (strcmp(m_data->creators_[i]->description().name(), name) == 0)
{
return &m_data->creators_[i]->description();
}
}
return 0;
}
// ^^^
TypeID typeIDByRegisteredName(const char* registeredTypeName) const
{
lazyRegisterCreators();
RegisteredNameToTypeID::const_iterator it = m_data->registeredNameToTypeID_.find(registeredTypeName);
if (it == m_data->registeredNameToTypeID_.end())
{
return TypeID();
}
return it->second;
}
const char* findAnnotation(const char* registeredTypeName, const char* name) const
{
lazyRegisterCreators();
TypeID typeID = typeIDByRegisteredName(registeredTypeName);
AnnotationMap::const_iterator it = m_data->annotations_.find(typeID);
if (it == m_data->annotations_.end())
{
return "";
}
for (size_t i = 0; i < it->second.size(); ++i)
{
if (strcmp(it->second[i].first, name) == 0)
{
return it->second[i].second;
}
}
return "";
}
void unregisterCreator(const TypeDescription& typeDescription)
{
auto creator = m_data->typeToCreatorMap_.find(typeDescription.name());
if (creator != m_data->typeToCreatorMap_.end())
{
m_data->creators_.erase(std::find(m_data->creators_.begin(), m_data->creators_.end(), m_data->creator->second));
m_data->vptrToCreatorMap_.erase(m_data->vptrToCreatorMap_.find(creator->second->vptr()));
m_data->typeToCreatorMap_.erase(creator);
}
}
protected:
virtual void registerCreator(CreatorBase* creator)
{
creator->next = creatorsList;
creatorsList = creator;
}
void lazyRegisterCreators() const
{
if (!m_data)
{
const_cast<ClassFactory*>(this)->m_data = ::new((void*)&m_dataStorage) Data();
for (CreatorBase* creator = creatorsList; creator; creator = creator->next)
{
if (!const_cast<ClassFactory*>(this)->m_data->typeToCreatorMap_.insert(AZStd::make_pair(creator->description().name(), creator)).second)
{
YASLI_ASSERT(0 && "Type registered twice in the same factory. Was SERIALIZATION_CLASS_NAME put into header file by mistake?");
}
const_cast<ClassFactory*>(this)->m_data->creators_.push_back(creator);
const_cast<ClassFactory*>(this)->m_data->registeredNameToTypeID_[creator->description().name()] = creator->typeID();
const_cast<ClassFactory*>(this)->m_data->vptrToCreatorMap_[creator->vptr()] = creator;
}
}
}
template<class T>
void addAnnotation(const char* name, const char* value)
{
addAnnotation(Serialization::TypeID::get<T>(), name, value);
}
virtual void addAnnotation(const Serialization::TypeID& id, const char* name, const char* value)
{
lazyRegisterCreators();
m_data->annotations_[id].push_back(std::make_pair(name, value));
}
CreatorBase* creatorsList = nullptr;
static ClassFactory* s_instance;
struct Data
{
TypeToCreatorMap typeToCreatorMap_;
AZStd::vector<CreatorBase*, AZ::StdLegacyAllocator> creators_;
VPtrToCreatorMap vptrToCreatorMap_;
RegisteredNameToTypeID registeredNameToTypeID_;
AnnotationMap annotations_;
};
Data* m_data = nullptr;
AZStd::aligned_storage_for_t<Data> m_dataStorage;
};
template <class T>
ClassFactory<T>* ClassFactory<T>::s_instance = nullptr;
}
#define SERIALIZATION_CLASS_NULL(BaseType, name) \
namespace { \
bool BaseType##_NullRegistered = Serialization::ClassFactory<BaseType>::the().setNullLabel(name); \
}
#define SERIALIZATION_CLASS_NAME(BaseType, Type, name, label) \
static const Serialization::TypeDescription Type##BaseType##_DerivedDescription(name, label); \
static Serialization::ClassFactory<BaseType>::Creator<Type> Type##BaseType##_Creator(&Type##BaseType##_DerivedDescription); \
int dummyForType_##Type##BaseType;
#define SERIALIZATION_CLASS_NAME_FOR_FACTORY(Factory, BaseType, Type, name, label) \
static const Serialization::TypeDescription Type##BaseType##_DerivedDescription(name, label); \
static Serialization::ClassFactory<BaseType>::Creator<Type> Type##BaseType##_Creator(&Type##BaseType##_DerivedDescription, &(Factory));
#define SERIALIZATION_CLASS_ANNOTATION(BaseType, Type, attributeName, attributeValue) \
static Serialization::ClassFactory<BaseType>::Annotation<Type> Type##BaseType##_Annotation(&Serialization::ClassFactory<BaseType>::the(), attributeName, attributeValue);
#define SERIALIZATION_CLASS_ANNOTATION_FOR_FACTORY(factory, BaseType, Type, attributeName, attributeValue) \
static Serialization::ClassFactory<BaseType>::Annotation<Type> Type##BaseType##_Annotation(&factory, attributeName, attributeValue);
#define SERIALIZATION_FORCE_CLASS(BaseType, Type) \
extern int dummyForType_##Type##BaseType; \
int* dummyForTypePtr_##Type##BaseType = &dummyForType_##Type##BaseType + 1;
#include "ClassFactoryImpl.h"
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H
@@ -1,47 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H
#pragma once
#include "IArchive.h"
#include "IClassFactory.h"
#include "STL.h"
#include "ClassFactory.h"
#include "Strings.h"
namespace Serialization {
inline bool Serialize(Serialization::IArchive& ar, Serialization::TypeNameWithFactory& value, const char* name, [[maybe_unused]] const char* label)
{
if (!ar(value.registeredName, name))
{
return false;
}
if (ar.IsInput())
{
const TypeDescription* desc = value.factory->descriptionByRegisteredName(value.registeredName.c_str());
if (!desc)
{
ar.Error(value, "Unable to read TypeID: unregistered type name: \'%s\'", value.registeredName.c_str());
value.registeredName.clear();
return false;
}
}
return true;
}
}
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H
@@ -1,55 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H
#pragma once
#include <Serialization/IArchive.h>
#include <Serialization/Decorators/Range.h>
template<typename T>
inline bool Serialize(Serialization::IArchive& ar, Color_tpl<T>& c, const char* name, const char* label);
namespace Serialization
{
struct Vec3AsColor
{
Vec3& v;
Vec3AsColor(Vec3& v)
: v(v) {}
void Serialize(Serialization::IArchive& ar)
{
ar(Range(v.x, 0.0f, 1.0f), "r", "^");
ar(Range(v.y, 0.0f, 1.0f), "g", "^");
ar(Range(v.z, 0.0f, 1.0f), "b", "^");
}
};
inline bool Serialize(Serialization::IArchive& ar, Vec3AsColor& c, const char* name, const char* label)
{
if (ar.IsEdit())
{
return ar(Serialization::SStruct(c), name, label);
}
else
{
typedef float (* Array)[3];
return ar(*((Array) & c.v.x), name, label);
}
}
}
#include "ColorImpl.h"
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H
@@ -1,53 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H
#pragma once
#include "Color.h"
//////////////////////////////////////////////////////////////////////////
template<typename T>
struct SerializableColor_tpl
: Color_tpl<T>
{
static float ColorRangeMin(float) { return 0.0f; }
static float ColorRangeMax(float) { return 1.0f; }
static unsigned char ColorRangeMin(unsigned char) { return 0; }
static unsigned char ColorRangeMax(unsigned char) { return 255; }
void Serialize(Serialization::IArchive& ar)
{
ar(Serialization::Range(Color_tpl<T>::r, ColorRangeMin(Color_tpl<T>::r), ColorRangeMax(Color_tpl<T>::r)), "r", "^");
ar(Serialization::Range(Color_tpl<T>::g, ColorRangeMin(Color_tpl<T>::g), ColorRangeMax(Color_tpl<T>::g)), "g", "^");
ar(Serialization::Range(Color_tpl<T>::b, ColorRangeMin(Color_tpl<T>::b), ColorRangeMax(Color_tpl<T>::b)), "b", "^");
ar(Serialization::Range(Color_tpl<T>::a, ColorRangeMin(Color_tpl<T>::a), ColorRangeMax(Color_tpl<T>::a)), "a", "^");
}
};
template<typename T>
bool Serialize(Serialization::IArchive& ar, Color_tpl<T>& c, const char* name, const char* label)
{
if (ar.IsEdit())
{
return Serialize(ar, static_cast<SerializableColor_tpl<T>&>(c), name, label);
}
else
{
typedef T (& Array)[4];
return ar((Array)c, name, label);
}
}
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H
@@ -1,44 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H
#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H
#pragma once
#ifdef GetClassName
#undef GetClassName
#endif
#include <CryExtension/ICryFactory.h>
namespace Serialization
{
// Allows to have AZStd::shared_ptr<TPointer> but serialize it by
// interface-casting to TSerializable, i.e. implementing Serialization through
// separate interface.
template<class TPointer, class TSerializable = TPointer>
struct CryExtensionPointer
{
AZStd::shared_ptr<TPointer>& ptr;
CryExtensionPointer(AZStd::shared_ptr<TPointer>& _ptr)
: ptr(_ptr) {}
void Serialize(Serialization::IArchive& ar);
};
}
// This function treats T as a type derived from CryUnknown type.
template<class T>
bool Serialize(Serialization::IArchive& ar, AZStd::shared_ptr<T>& ptr, const char* name, const char* label);
#include "CryExtensionImpl.h"
#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H

Some files were not shown because too many files have changed in this diff Show More